From 620730325bd1491aeff6bb241b29e280297c4369 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sat, 14 Nov 2026 17:16:17 +0100 Subject: [PATCH 01/86] chore: add pyproject, tooling config and package skeleton Python 3.11+ package with FastAPI, Pydantic v2, httpx, Pillow, NumPy and APScheduler. Ruff, mypy (strict) and pytest are configured in pyproject.toml. Providers, processor and clients packages are created as documented placeholders for upcoming milestones. Co-Authored-By: Claude Opus 5.5 --- .gitattributes | 10 +++++ README.md | 44 +++++++++++++++++++ app/__init__.py | 5 +++ app/api/__init__.py | 1 + app/api/routes/__init__.py | 1 + app/clients/__init__.py | 5 +++ app/core/__init__.py | 1 + app/processor/__init__.py | 6 +++ app/providers/__init__.py | 7 +++ app/py.typed | 0 pyproject.toml | 90 ++++++++++++++++++++++++++++++++++++++ 11 files changed, 170 insertions(+) create mode 100644 .gitattributes create mode 100644 README.md create mode 100644 app/__init__.py create mode 100644 app/api/__init__.py create mode 100644 app/api/routes/__init__.py create mode 100644 app/clients/__init__.py create mode 100644 app/core/__init__.py create mode 100644 app/processor/__init__.py create mode 100644 app/providers/__init__.py create mode 100644 app/py.typed create mode 100644 pyproject.toml diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..c7ab696 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,10 @@ +# Normalize text files to LF in the repository and in Linux containers. +* text=auto eol=lf + +# Binary assets +*.png binary +*.jpg binary +*.jpeg binary +*.webp binary +*.gif binary +*.bin binary diff --git a/README.md b/README.md new file mode 100644 index 0000000..6ab20de --- /dev/null +++ b/README.md @@ -0,0 +1,44 @@ +# Smart Frame Engine + +Self-hosted web app and REST API that fetches images from modular sources (Immich, +TMDB movie/TV posters, direct URLs), optimizes them for a color eInk panel (Spectra 6), +and pushes them to a [Fraimic](https://fraimic.com) picture frame. Home Assistant +friendly, runs standalone in Docker. + +> **Status:** early development (`v0.x`). The core service, configuration, security and +> container packaging are in place; image providers, the eInk pipeline and the web UI +> are being added milestone by milestone. + +## Quickstart + +```bash +cp .env.example .env # then fill in your values +mkdir -p data # must be writable by PUID:PGID (default 1000:1000) +docker compose up -d +``` + +- API docs: `http://:8000/docs` +- Health: `http://:8000/api/health` + +Runtime settings are stored in `./data/config.json` and can be edited with +`GET`/`PUT /api/config`. Values saved there take precedence over `.env`, which in turn +takes precedence over built-in defaults. `POST /api/config/reset` removes saved values. + +## Development + +```bash +python -m venv .venv +source .venv/bin/activate # Windows: .venv\Scripts\activate +pip install -e ".[dev]" +ruff check . && ruff format --check . && mypy app && pytest +DATA_DIR=./data python -m app # serve on http://localhost:8000 +``` + +## Credits + +The `.bin` encoding follows the official +[Fraimic Bin Converter](https://github.com/Fraimic/fraimic_bin_converter) (MIT). + +## License + +[MIT](LICENSE) diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000..385be7b --- /dev/null +++ b/app/__init__.py @@ -0,0 +1,5 @@ +"""Smart Frame Engine: modular image sources -> color eInk pipeline -> Fraimic frame.""" + +__version__ = "0.1.0" + +__all__ = ["__version__"] diff --git a/app/api/__init__.py b/app/api/__init__.py new file mode 100644 index 0000000..a56f35b --- /dev/null +++ b/app/api/__init__.py @@ -0,0 +1 @@ +"""HTTP API layer (FastAPI routers and dependencies).""" diff --git a/app/api/routes/__init__.py b/app/api/routes/__init__.py new file mode 100644 index 0000000..0c1ed1d --- /dev/null +++ b/app/api/routes/__init__.py @@ -0,0 +1 @@ +"""FastAPI routers grouped by concern.""" diff --git a/app/clients/__init__.py b/app/clients/__init__.py new file mode 100644 index 0000000..dca1c2f --- /dev/null +++ b/app/clients/__init__.py @@ -0,0 +1,5 @@ +"""Outbound device clients. + +The Fraimic HTTP client and its power-mode aware upload queue (``continuous`` +and ``deepsleep``) are added in the ``feat/eink-fraimic`` milestone. +""" diff --git a/app/core/__init__.py b/app/core/__init__.py new file mode 100644 index 0000000..d24d234 --- /dev/null +++ b/app/core/__init__.py @@ -0,0 +1 @@ +"""Core infrastructure: settings, persistence, security, auth and logging.""" diff --git a/app/processor/__init__.py b/app/processor/__init__.py new file mode 100644 index 0000000..9303ead --- /dev/null +++ b/app/processor/__init__.py @@ -0,0 +1,6 @@ +"""Image processing pipeline. + +Fit modes (``smart_crop``, ``contain``), eInk enhancement, Spectra 6 dithering +and Fraimic ``.bin`` packing live here. They are added in the +``feat/eink-fraimic`` milestone. +""" diff --git a/app/providers/__init__.py b/app/providers/__init__.py new file mode 100644 index 0000000..7c95856 --- /dev/null +++ b/app/providers/__init__.py @@ -0,0 +1,7 @@ +"""Image source providers. + +Every provider subclasses ``BaseImageProvider`` and returns a standardized +``ImageAsset`` (raw bytes, metadata, recommended fit mode, regions of interest). +Providers (Immich, TMDB media posters, direct URLs) are added in the +``feat/providers-api`` milestone. +""" diff --git a/app/py.typed b/app/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..a20ea33 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,90 @@ +[build-system] +requires = ["setuptools>=77", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "smart-frame-engine" +version = "0.1.0" +description = "Fetch photos and posters from modular sources, optimize them for color eInk, and push them to a Fraimic frame." +readme = "README.md" +license = "MIT" +license-files = ["LICENSE"] +requires-python = ">=3.11" +authors = [{ name = "ant1fr" }] +classifiers = [ + "Framework :: FastAPI", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Typing :: Typed", +] +dependencies = [ + "fastapi>=0.115", + "uvicorn[standard]>=0.30", + "pydantic>=2.7", + "pydantic-settings>=2.4", + "httpx>=0.27", + "pillow>=10.4", + "numpy>=1.26", + "apscheduler>=3.10,<4", + "jinja2>=3.1", + "python-multipart>=0.0.9", + "tzdata>=2024.1", +] + +[project.optional-dependencies] +dev = [ + "pytest>=8.2", + "httpx2>=2.0", + "pytest-asyncio>=0.24", + "respx>=0.21", + "ruff>=0.6", + "mypy>=1.11", +] + +[project.urls] +Homepage = "https://github.com/ant1fr/Smart-Frame-Engine" +Issues = "https://github.com/ant1fr/Smart-Frame-Engine/issues" + +[tool.setuptools.packages.find] +include = ["app*"] + +[tool.setuptools.package-data] +app = ["py.typed", "templates/*.html"] + +# --- Ruff ----------------------------------------------------------------------- +[tool.ruff] +target-version = "py311" +line-length = 100 +extend-exclude = ["fraimic-docs"] + +[tool.ruff.lint] +select = ["E", "F", "W", "I", "UP", "B", "SIM", "S", "ANN", "RUF"] +ignore = [ + "ANN401", # `Any` is legitimate for JSON payloads and ASGI plumbing. +] + +[tool.ruff.lint.per-file-ignores] +"tests/**" = ["S101", "S105", "S106", "ANN"] + +[tool.ruff.lint.isort] +known-first-party = ["app"] + +# --- Pytest --------------------------------------------------------------------- +[tool.pytest.ini_options] +testpaths = ["tests"] +asyncio_mode = "auto" +asyncio_default_fixture_loop_scope = "function" +addopts = "-ra" + +# --- Mypy ----------------------------------------------------------------------- +[tool.mypy] +python_version = "3.11" +strict = true +plugins = ["pydantic.mypy"] +exclude = ["fraimic-docs/", "build/"] + +[tool.pydantic-mypy] +init_forbid_extra = true +init_typed = true +warn_required_dynamic_aliases = true From 2841f492203c1f7b2a2efcf664a390854917d84e Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sat, 14 Nov 2026 17:16:17 +0100 Subject: [PATCH 02/86] feat: add environment settings and runtime config models EnvSettings holds infrastructure settings (data dir, API key, proxy, CORS, limits) and optional runtime seeds read from .env. RuntimeConfig groups the UI-editable sections (immich, tmdb, fraimic, display, eink, scheduler). Defaults follow the official Fraimic converter: 13.3" panel, Atkinson dithering, brightness 1.1 / contrast 1.2 / saturation 1.2, /api/image upload and /api/info status endpoints. Co-Authored-By: Claude Opus 5.5 --- app/core/config_models.py | 353 ++++++++++++++++++++++++++++++++++++++ app/core/settings.py | 207 ++++++++++++++++++++++ 2 files changed, 560 insertions(+) create mode 100644 app/core/config_models.py create mode 100644 app/core/settings.py diff --git a/app/core/config_models.py b/app/core/config_models.py new file mode 100644 index 0000000..7950f66 --- /dev/null +++ b/app/core/config_models.py @@ -0,0 +1,353 @@ +"""Runtime configuration models (editable from the UI and ``/api/config``). + +The effective configuration is resolved by :class:`app.core.config_store.ConfigStore` +with the precedence ``built-in defaults <- environment (.env) <- /data/config.json``. + +The schema is intentionally two levels deep (``section.field``) so that overrides, +value sources and resets can be addressed with simple dotted paths. +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from typing import Any, Final, Literal +from urllib.parse import urlsplit +from zoneinfo import ZoneInfo, ZoneInfoNotFoundError + +from pydantic import ( + BaseModel, + ConfigDict, + Field, + JsonValue, + SecretStr, + field_validator, + model_validator, +) + +PanelModel = Literal["133", "315"] +Orientation = Literal["portrait", "landscape"] +FitMode = Literal["smart_crop", "contain"] +DitherAlgorithm = Literal["atkinson", "floyd_steinberg"] +PowerMode = Literal["continuous", "deepsleep"] + + +@dataclass(frozen=True, slots=True) +class PanelSpec: + """Physical characteristics of a Fraimic Spectra 6 panel (native portrait).""" + + key: PanelModel + label: str + width: int + height: int + bin_size: int + + +PANEL_SPECS: Final[dict[PanelModel, PanelSpec]] = { + "133": PanelSpec("133", 'Spectra 6 13.3" (EL133UF1)', 1200, 1600, 960_000), + "315": PanelSpec("315", 'Spectra 6 31.5" (EL315)', 1440, 2560, 2_304_000), +} + +_HHMM_RE: Final = re.compile(r"^(?:[01]\d|2[0-3]):[0-5]\d$") +_LANGUAGE_RE: Final = re.compile(r"^[a-z]{2}-[A-Z]{2}$") + + +def _normalize_http_base_url(value: str) -> str: + """Validate an optional ``http(s)://host[:port][/path]`` base URL. + + An empty string means "not configured". Trailing slashes are removed so that + API paths can be appended safely. + """ + value = value.strip() + if not value: + return "" + parts = urlsplit(value) + if parts.scheme not in {"http", "https"} or not parts.hostname: + raise ValueError("must be an absolute http:// or https:// URL") + if parts.username or parts.password: + raise ValueError("must not embed credentials; use the API key field instead") + if parts.query or parts.fragment: + raise ValueError("must not contain a query string or fragment") + return value.rstrip("/") + + +class _Section(BaseModel): + """Base class for configuration sections: strict keys, validated assignment.""" + + model_config = ConfigDict(extra="forbid", validate_assignment=True) + + +class ImmichConfig(_Section): + """Connection and default selection filters for the Immich provider.""" + + url: str = Field(default="", description="Immich base URL, e.g. http://immich.local:2283") + api_key: SecretStr = Field(default=SecretStr(""), description="Immich API key") + persons: list[str] = Field(default_factory=list, description="Default person names filter") + match_mode: Literal["any", "all"] = Field( + default="any", description="Match photos containing any or all of the persons" + ) + album: str = Field(default="", description="Default album name filter (empty = all)") + favorites_only: bool = Field(default=False, description="Only pick favorite assets") + exclude_archived: bool = Field(default=True, description="Skip archived assets") + anti_repeat_days: int = Field( + default=30, ge=0, le=3650, description="Do not show the same photo again within N days" + ) + + @field_validator("url") + @classmethod + def _validate_url(cls, value: str) -> str: + return _normalize_http_base_url(value) + + @field_validator("persons") + @classmethod + def _clean_persons(cls, value: list[str]) -> list[str]: + cleaned: list[str] = [] + for name in value: + stripped = name.strip() + if stripped and stripped not in cleaned: + cleaned.append(stripped) + return cleaned + + +class TmdbConfig(_Section): + """TMDB (The Movie Database) settings for HD movie and TV posters.""" + + api_key: SecretStr = Field(default=SecretStr(""), description="TMDB API key (v3)") + language: str = Field( + default="en-US", description="Preferred poster/metadata language, e.g. fr-FR or en-US" + ) + image_size: Literal["w1280", "original"] = Field( + default="original", description="Poster resolution to download" + ) + + @field_validator("language") + @classmethod + def _validate_language(cls, value: str) -> str: + value = value.strip() + if not _LANGUAGE_RE.match(value): + raise ValueError("must look like 'en-US' or 'fr-FR'") + return value + + +class FraimicConfig(_Section): + """Fraimic frame connection, panel model and power management.""" + + host: str = Field( + default="fraimic.local", + description="Frame hostname, IP or base URL (http:// is assumed when omitted)", + ) + power_mode: PowerMode = Field( + default="continuous", + description="continuous = always reachable; deepsleep = queue until the frame wakes up", + ) + panel: PanelModel = Field(default="133", description='Panel model: 133 (13.3") or 315 (31.5")') + upload_path: str = Field(default="/api/image", description="Frame endpoint receiving .bin") + status_path: str = Field(default="/api/info", description="Frame endpoint used as ping") + poll_interval_s: int = Field( + default=30, ge=5, le=3600, description="Deepsleep: seconds between availability checks" + ) + request_timeout_s: float = Field( + default=60.0, gt=0, le=600, description="HTTP timeout for frame requests" + ) + + @field_validator("host") + @classmethod + def _validate_host(cls, value: str) -> str: + value = value.strip().rstrip("/") + if not value: + return "" + candidate = value if "://" in value else f"http://{value}" + parts = urlsplit(candidate) + if parts.scheme not in {"http", "https"} or not parts.hostname: + raise ValueError("must be a hostname, an IP address or an http(s) base URL") + if parts.username or parts.password or parts.query or parts.fragment: + raise ValueError("must not contain credentials, a query string or a fragment") + return value + + @field_validator("upload_path", "status_path") + @classmethod + def _validate_path(cls, value: str) -> str: + value = value.strip() + if not value.startswith("/") or "://" in value or any(c in value for c in "?#"): + raise ValueError("must be an absolute path such as /api/info") + return value + + @property + def base_url(self) -> str: + """Frame base URL including scheme, or an empty string when unset.""" + if not self.host: + return "" + return self.host if "://" in self.host else f"http://{self.host}" + + @property + def spec(self) -> PanelSpec: + """Physical specification of the configured panel.""" + return PANEL_SPECS[self.panel] + + +class DisplayConfig(_Section): + """How the frame is hung and how images are fitted into it.""" + + orientation: Orientation = Field(default="portrait", description="How the frame is hung") + landscape_rotation: Literal[90, 270] = Field( + default=90, + description="Landscape only: degrees (counter-clockwise) to rotate the composed image " + "into the panel's native portrait buffer; use 270 if the image appears upside down", + ) + default_fit: FitMode = Field( + default="smart_crop", description="Fit mode for photos (posters always use contain)" + ) + contain_background: Literal["blur", "black", "white"] = Field( + default="blur", description="Padding style used by the contain fit mode" + ) + + +class EinkConfig(_Section): + """Color eInk optimization. Defaults mirror the official Fraimic converter.""" + + brightness: float = Field(default=1.1, ge=0.1, le=3.0, description="1.0 = unchanged") + contrast: float = Field(default=1.2, ge=0.1, le=3.0, description="1.0 = unchanged") + saturation: float = Field(default=1.2, ge=0.0, le=3.0, description="1.0 = unchanged") + sharpness: float = Field(default=1.0, ge=0.0, le=3.0, description="1.0 = unchanged") + edge_filters: bool = Field( + default=True, description="Apply the official edge-enhance / smooth / sharpen chain" + ) + dither: DitherAlgorithm = Field( + default="atkinson", + description="atkinson = tuned color metric (official default); floyd_steinberg = classic", + ) + + +class SourceRule(BaseModel): + """The last source request, replayed by ``/api/refresh`` and the scheduler.""" + + model_config = ConfigDict(extra="forbid") + + kind: Literal["immich", "media", "url"] + params: dict[str, JsonValue] = Field(default_factory=dict) + + +class SchedulerConfig(_Section): + """Autonomous periodic refresh with an optional quiet-hours window.""" + + enabled: bool = Field(default=False, description="Enable autonomous periodic refresh") + interval_hours: float = Field( + default=6.0, ge=0.25, le=168, description="Hours between automatic refreshes" + ) + quiet_hours_start: str | None = Field( + default=None, description="HH:MM start of the no-refresh window (local time)" + ) + quiet_hours_end: str | None = Field( + default=None, description="HH:MM end of the no-refresh window (local time)" + ) + timezone: str = Field(default="UTC", description="IANA timezone, e.g. Europe/Paris") + source_rule: SourceRule | None = Field( + default=None, description="Source rule replayed on refresh (set by display actions)" + ) + + @field_validator("quiet_hours_start", "quiet_hours_end") + @classmethod + def _validate_hhmm(cls, value: str | None) -> str | None: + if value is None or not value.strip(): + return None + value = value.strip() + if not _HHMM_RE.match(value): + raise ValueError("must use 24h HH:MM format") + return value + + @field_validator("timezone") + @classmethod + def _validate_timezone(cls, value: str) -> str: + value = value.strip() + try: + ZoneInfo(value) + except (ZoneInfoNotFoundError, ValueError) as exc: + raise ValueError(f"unknown IANA timezone {value!r}") from exc + return value + + @model_validator(mode="after") + def _quiet_hours_pair(self) -> SchedulerConfig: + if (self.quiet_hours_start is None) != (self.quiet_hours_end is None): + raise ValueError("quiet_hours_start and quiet_hours_end must be set together") + return self + + +class RuntimeConfig(BaseModel): + """Complete runtime configuration persisted (sparsely) to ``/data/config.json``.""" + + model_config = ConfigDict(extra="forbid") + + immich: ImmichConfig = Field(default_factory=ImmichConfig) + tmdb: TmdbConfig = Field(default_factory=TmdbConfig) + fraimic: FraimicConfig = Field(default_factory=FraimicConfig) + display: DisplayConfig = Field(default_factory=DisplayConfig) + eink: EinkConfig = Field(default_factory=EinkConfig) + scheduler: SchedulerConfig = Field(default_factory=SchedulerConfig) + + @property + def frame_size(self) -> tuple[int, int]: + """Composition size ``(width, height)`` honoring the frame orientation.""" + spec = self.fraimic.spec + if self.display.orientation == "landscape": + return spec.height, spec.width + return spec.width, spec.height + + +SECTION_NAMES: Final[tuple[str, ...]] = tuple(RuntimeConfig.model_fields) + + +def section_model(section: str) -> type[BaseModel]: + """Return the Pydantic model class of a configuration section. + + Raises: + KeyError: If ``section`` is not a known section. + """ + annotation = RuntimeConfig.model_fields[section].annotation + if not isinstance(annotation, type) or not issubclass(annotation, BaseModel): + raise TypeError(f"{section!r} is not a configuration section") + return annotation + + +def section_fields(section: str) -> tuple[str, ...]: + """Return the field names of a configuration section.""" + return tuple(section_model(section).model_fields) + + +def secret_field_paths() -> tuple[tuple[str, str], ...]: + """Return ``(section, field)`` pairs whose values are secrets.""" + return tuple( + (section, name) + for section in SECTION_NAMES + for name, field in section_model(section).model_fields.items() + if field.annotation is SecretStr + ) + + +def dump_config(config: RuntimeConfig, *, reveal_secrets: bool) -> dict[str, dict[str, Any]]: + """Serialize a config to plain JSON-compatible data. + + Args: + config: Configuration to serialize. + reveal_secrets: When ``False``, secret values are replaced by :func:`mask_secret`. + """ + data: dict[str, dict[str, Any]] = config.model_dump(mode="json") + for section, name in secret_field_paths(): + secret: SecretStr = getattr(getattr(config, section), name) + raw = secret.get_secret_value() + data[section][name] = raw if reveal_secrets else mask_secret(raw) + return data + + +MASK_PREFIX: Final = "•" * 8 + + +def mask_secret(value: str) -> str: + """Mask a secret for display. Empty stays empty; long keys keep their last 4 chars.""" + if not value: + return "" + return MASK_PREFIX + (value[-4:] if len(value) >= 16 else "") + + +def is_masked(value: object) -> bool: + """Return ``True`` if ``value`` is a masked placeholder produced by :func:`mask_secret`.""" + return isinstance(value, str) and value.startswith(MASK_PREFIX) diff --git a/app/core/settings.py b/app/core/settings.py new file mode 100644 index 0000000..63e928f --- /dev/null +++ b/app/core/settings.py @@ -0,0 +1,207 @@ +"""Environment settings (``.env`` / container environment). + +Two kinds of values live here: + +* **Infrastructure settings** (data directory, auth key, reverse proxy, CORS, limits). + They are read once at startup, are never editable through the API, and require a + restart to change. ``APP_API_KEY`` in particular can never be changed by the API it + protects. +* **Runtime seeds** (``IMMICH_URL``, ``TMDB_API_KEY``, ``FRAIMIC_HOST``...). They provide + fallback values for :class:`app.core.config_models.RuntimeConfig`; anything saved to + ``/data/config.json`` from the UI or API takes precedence over them. +""" + +from __future__ import annotations + +from functools import lru_cache +from pathlib import Path +from typing import Any, Literal + +from pydantic import Field, SecretStr, field_validator +from pydantic_settings import BaseSettings, SettingsConfigDict + +LogLevel = Literal["CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG"] + + +def _split_csv(raw: str) -> list[str]: + return [item.strip() for item in raw.split(",") if item.strip()] + + +class EnvSettings(BaseSettings): + """Process-level settings loaded from environment variables and an optional ``.env``.""" + + model_config = SettingsConfigDict( + env_file=".env", + env_file_encoding="utf-8", + extra="ignore", + frozen=True, + ) + + # --- Infrastructure ------------------------------------------------------- + data_dir: Path = Field(default=Path("/data"), description="Persistent data directory") + host: str = Field(default="0.0.0.0", description="Bind address") # noqa: S104 + port: int = Field(default=8000, ge=1, le=65535, description="Bind port") + log_level: LogLevel = Field(default="INFO", description="Python log level") + + app_api_key: SecretStr = Field( + default=SecretStr(""), + description="When set, mutating routes and /api/config require X-API-Key", + ) + public_image_endpoints: bool = Field( + default=True, + description="Serve /api/current.jpg and /api/current.bin without an API key", + ) + + root_path: str = Field(default="", description="Sub-path when behind a reverse proxy") + cors_origins: str = Field(default="*", description="Comma-separated allowed CORS origins") + forwarded_allow_ips: str = Field( + default="*", description="Proxy IPs trusted for X-Forwarded-* headers" + ) + + max_upload_mb: int = Field(default=20, ge=1, le=200, description="Max image size in MB") + block_private_urls: bool = Field( + default=False, + description="Reject external URLs resolving to private/loopback/link-local addresses", + ) + url_allowlist: str = Field( + default="", + description="Comma-separated hosts or CIDRs exempt from BLOCK_PRIVATE_URLS", + ) + + # --- Runtime seeds (fallbacks for config.json) ---------------------------- + immich_url: str | None = None + immich_api_key: SecretStr | None = None + tmdb_api_key: SecretStr | None = None + tmdb_language: str | None = None + fraimic_host: str | None = None + fraimic_power_mode: str | None = None + fraimic_panel: str | None = None + orientation: str | None = None + scheduler_enabled: bool | None = None + refresh_interval_hours: float | None = None + tz: str | None = None + + @field_validator("root_path") + @classmethod + def _normalize_root_path(cls, value: str) -> str: + value = value.strip().strip("/") + return f"/{value}" if value else "" + + @field_validator("log_level", mode="before") + @classmethod + def _upper_log_level(cls, value: object) -> object: + return value.strip().upper() if isinstance(value, str) else value + + @field_validator( + "immich_url", + "tmdb_language", + "fraimic_host", + "fraimic_power_mode", + "fraimic_panel", + "orientation", + "tz", + mode="before", + ) + @classmethod + def _blank_to_none(cls, value: object) -> object: + if isinstance(value, str) and not value.strip(): + return None + return value.strip() if isinstance(value, str) else value + + @field_validator("immich_api_key", "tmdb_api_key", mode="before") + @classmethod + def _blank_secret_to_none(cls, value: object) -> object: + if isinstance(value, str) and not value.strip(): + return None + return value + + @field_validator("scheduler_enabled", "refresh_interval_hours", mode="before") + @classmethod + def _blank_scalar_to_none(cls, value: object) -> object: + if isinstance(value, str) and not value.strip(): + return None + return value + + # --- Derived values ---------------------------------------------------------- + @property + def api_key(self) -> str: + """The configured API key (empty string when authentication is disabled).""" + return self.app_api_key.get_secret_value().strip() + + @property + def auth_enabled(self) -> bool: + """Whether API key authentication is enforced.""" + return bool(self.api_key) + + @property + def cors_origin_list(self) -> list[str]: + """Parsed ``CORS_ORIGINS`` (``["*"]`` when empty).""" + return _split_csv(self.cors_origins) or ["*"] + + @property + def url_allowlist_entries(self) -> list[str]: + """Parsed ``URL_ALLOWLIST`` entries.""" + return _split_csv(self.url_allowlist) + + @property + def max_upload_bytes(self) -> int: + """Upload/download size limit in bytes.""" + return self.max_upload_mb * 1024 * 1024 + + @property + def config_path(self) -> Path: + """Location of the runtime configuration overrides file.""" + return self.data_dir / "config.json" + + @property + def history_path(self) -> Path: + """Location of the display history file.""" + return self.data_dir / "history.json" + + @property + def cache_dir(self) -> Path: + """Directory holding ``current.jpg`` and ``current.bin``.""" + return self.data_dir / "cache" + + def secret_values(self) -> list[str]: + """All secret values provided through the environment (for log masking).""" + values = [self.api_key] + for secret in (self.immich_api_key, self.tmdb_api_key): + if secret is not None: + values.append(secret.get_secret_value()) + return [value for value in values if value] + + def runtime_seed(self) -> dict[str, dict[str, Any]]: + """Environment-provided fallbacks shaped like ``RuntimeConfig`` overrides. + + Only variables that are actually set are included, so unset variables fall back + to the built-in defaults. + """ + candidates: dict[tuple[str, str], Any] = { + ("immich", "url"): self.immich_url, + ("immich", "api_key"): ( + self.immich_api_key.get_secret_value() if self.immich_api_key else None + ), + ("tmdb", "api_key"): ( + self.tmdb_api_key.get_secret_value() if self.tmdb_api_key else None + ), + ("tmdb", "language"): self.tmdb_language, + ("fraimic", "host"): self.fraimic_host, + ("fraimic", "power_mode"): self.fraimic_power_mode, + ("fraimic", "panel"): self.fraimic_panel, + ("display", "orientation"): self.orientation, + ("scheduler", "enabled"): self.scheduler_enabled, + ("scheduler", "interval_hours"): self.refresh_interval_hours, + ("scheduler", "timezone"): self.tz, + } + seed: dict[str, dict[str, Any]] = {} + for (section, name), value in candidates.items(): + if value is not None: + seed.setdefault(section, {})[name] = value + return seed + + +@lru_cache(maxsize=1) +def get_env_settings() -> EnvSettings: + """Return the process-wide :class:`EnvSettings` (cached after the first call).""" + return EnvSettings() From fb41e3c2bd2eab3a5ad2f4f1e51de48465102f3e Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sat, 14 Nov 2026 17:16:17 +0100 Subject: [PATCH 03/86] feat: add atomic JSON persistence for config and history ConfigStore resolves defaults <- .env <- /data/config.json, persists only explicitly saved values, masks secrets for clients, supports reset to .env/defaults and drops stale or invalid saved entries on load. HistoryStore keeps a pruned display log for anti-repeat rules. Writes use a temp file + fsync + os.replace; corrupt files are moved aside. Co-Authored-By: Claude Opus 5.5 --- app/core/config_store.py | 321 ++++++++++++++++++++++++++++++++++++++ app/core/history_store.py | 120 ++++++++++++++ app/core/json_store.py | 75 +++++++++ 3 files changed, 516 insertions(+) create mode 100644 app/core/config_store.py create mode 100644 app/core/history_store.py create mode 100644 app/core/json_store.py diff --git a/app/core/config_store.py b/app/core/config_store.py new file mode 100644 index 0000000..2b2aff1 --- /dev/null +++ b/app/core/config_store.py @@ -0,0 +1,321 @@ +"""Runtime configuration store with sparse JSON persistence. + +Resolution order (later wins):: + + built-in defaults <- environment seeds (.env) <- /data/config.json overrides + +``config.json`` only contains values the user explicitly changed, addressed as +``{"section": {"field": value}}``. Fields that were never saved keep following the +environment (or the built-in defaults), and ``reset`` removes overrides so the value +falls back again. +""" + +from __future__ import annotations + +import asyncio +import copy +import logging +from collections.abc import Awaitable, Callable, Iterable, Mapping +from pathlib import Path +from typing import Any, Literal + +from pydantic import ValidationError + +from app.core.config_models import ( + SECTION_NAMES, + RuntimeConfig, + dump_config, + is_masked, + secret_field_paths, + section_fields, +) +from app.core.json_store import atomic_write_json, read_json + +logger = logging.getLogger(__name__) + +Overrides = dict[str, dict[str, Any]] +ValueSource = Literal["default", "env", "config"] +ConfigListener = Callable[[RuntimeConfig], Awaitable[None]] + +_MAX_PRUNE_PASSES = 32 + + +class ConfigError(ValueError): + """Base class for configuration errors that are safe to report to API clients.""" + + def __init__(self, message: str, errors: list[dict[str, Any]] | None = None) -> None: + super().__init__(message) + self.message = message + self.errors: list[dict[str, Any]] = errors or [] + + +class ConfigValidationError(ConfigError): + """The resulting configuration failed validation. ``errors`` never echoes input values.""" + + @classmethod + def from_pydantic(cls, exc: ValidationError) -> ConfigValidationError: + errors = [ + {"loc": [str(part) for part in err["loc"]], "msg": err["msg"], "type": err["type"]} + for err in exc.errors(include_url=False, include_input=False, include_context=False) + ] + return cls("Invalid configuration", errors) + + +class UnknownConfigPathError(ConfigError): + """A patch or reset referenced a section or field that does not exist.""" + + +def _merge(*layers: Mapping[str, Mapping[str, Any]]) -> Overrides: + """Merge ``section -> field -> value`` layers; later layers win per field.""" + merged: Overrides = {} + for layer in layers: + for section, fields in layer.items(): + target = merged.setdefault(section, {}) + for name, value in fields.items(): + target[name] = copy.deepcopy(value) + return merged + + +def _parse_path(path: str) -> tuple[str, str | None]: + """Split ``"section"`` or ``"section.field"`` and check it exists.""" + section, _, name = path.strip().partition(".") + if section not in SECTION_NAMES: + raise UnknownConfigPathError(f"Unknown configuration section: {section!r}") + if name and name not in section_fields(section): + raise UnknownConfigPathError(f"Unknown configuration field: {path!r}") + return section, name or None + + +class ConfigStore: + """Holds the effective :class:`RuntimeConfig` and persists user overrides.""" + + def __init__(self, path: Path, env_seed: Mapping[str, Mapping[str, Any]]) -> None: + """Create the store and validate built-in defaults merged with ``env_seed``. + + Args: + path: Location of ``config.json``. + env_seed: Environment fallbacks (see :meth:`EnvSettings.runtime_seed`). + + Raises: + ConfigValidationError: If an environment variable holds an invalid value. + """ + self._path = path + self._defaults: Overrides = dump_config(RuntimeConfig(), reveal_secrets=True) + self._env_seed: Overrides = _merge(env_seed) + self._overrides: Overrides = {} + self._lock = asyncio.Lock() + self._listeners: list[ConfigListener] = [] + try: + self._config = self._build({}) + except ConfigValidationError as exc: + details = "; ".join(f"{'.'.join(e['loc'])}: {e['msg']}" for e in exc.errors) + raise ConfigValidationError( + f"Invalid configuration from environment variables: {details}", exc.errors + ) from exc + + # --- Read access ----------------------------------------------------------------- + @property + def path(self) -> Path: + """Location of the overrides file.""" + return self._path + + @property + def config(self) -> RuntimeConfig: + """The current effective configuration.""" + return self._config + + @property + def overrides(self) -> Overrides: + """A copy of the values persisted in ``config.json``.""" + return copy.deepcopy(self._overrides) + + def sources(self) -> dict[str, ValueSource]: + """Where each ``section.field`` value currently comes from.""" + result: dict[str, ValueSource] = {} + for section in SECTION_NAMES: + for name in section_fields(section): + if name in self._overrides.get(section, {}): + result[f"{section}.{name}"] = "config" + elif name in self._env_seed.get(section, {}): + result[f"{section}.{name}"] = "env" + else: + result[f"{section}.{name}"] = "default" + return result + + def public_view(self) -> dict[str, Any]: + """Configuration safe to send to clients (secrets masked) plus value sources.""" + return { + "config": dump_config(self._config, reveal_secrets=False), + "sources": self.sources(), + } + + def secret_values(self) -> list[str]: + """Every non-empty secret currently in the effective configuration.""" + values: list[str] = [] + for section, name in secret_field_paths(): + raw = getattr(getattr(self._config, section), name).get_secret_value() + if raw: + values.append(raw) + return values + + def add_listener(self, listener: ConfigListener) -> None: + """Register a coroutine called with the new config after every change.""" + self._listeners.append(listener) + + # --- Lifecycle --------------------------------------------------------------------- + def load(self) -> RuntimeConfig: + """Load ``config.json`` from disk, dropping unknown or invalid entries. + + Invalid entries (e.g. left over from an older version) are logged and ignored in + memory; the file is rewritten without them on the next successful save. + """ + raw = read_json(self._path, dict) + overrides = self._sanitize_shape(raw) + overrides = self._prune_invalid(overrides) + self._overrides = overrides + self._config = self._build(overrides) + logger.info( + "Loaded runtime configuration (%d saved value(s)) from %s", + sum(len(fields) for fields in overrides.values()), + self._path, + ) + return self._config + + # --- Mutations --------------------------------------------------------------------- + async def update(self, patch: Mapping[str, Any]) -> RuntimeConfig: + """Validate and persist a partial update ``{"section": {"field": value}}``. + + * Masked secret placeholders (as returned by :meth:`public_view`) mean "unchanged". + * A value equal to the current effective value is only stored if the field is + already saved, so submitting a full settings form does not freeze fields that + currently follow the environment. + * Nothing is written when validation fails. + + Raises: + UnknownConfigPathError: If the patch references unknown sections or fields. + ConfigValidationError: If the resulting configuration is invalid. + """ + normalized = self._normalize_patch(patch) + async with self._lock: + candidate = _merge(self._overrides, normalized) + config = self._build(candidate) + canonical = dump_config(config, reveal_secrets=True) + current = dump_config(self._config, reveal_secrets=True) + + new_overrides = copy.deepcopy(self._overrides) + for section, fields in normalized.items(): + for name in fields: + already_saved = name in self._overrides.get(section, {}) + if not already_saved and canonical[section][name] == current[section][name]: + continue + new_overrides.setdefault(section, {})[name] = canonical[section][name] + await asyncio.to_thread(self._persist, new_overrides) + self._overrides = new_overrides + self._config = config + await self._notify(config) + return config + + async def reset(self, paths: Iterable[str] | None = None) -> RuntimeConfig: + """Remove saved overrides so values fall back to the environment or defaults. + + Args: + paths: ``"section"`` or ``"section.field"`` entries; ``None`` resets everything. + + Raises: + UnknownConfigPathError: If a path does not exist. + ConfigValidationError: If the fallback values form an invalid configuration + (e.g. resetting only one half of a quiet-hours window). + """ + targets = None if paths is None else [_parse_path(path) for path in paths] + async with self._lock: + new_overrides: Overrides = {} + if targets is not None: + new_overrides = copy.deepcopy(self._overrides) + for section, name in targets: + if name is None: + new_overrides.pop(section, None) + else: + new_overrides.get(section, {}).pop(name, None) + new_overrides = {s: f for s, f in new_overrides.items() if f} + config = self._build(new_overrides) + await asyncio.to_thread(self._persist, new_overrides) + self._overrides = new_overrides + self._config = config + await self._notify(config) + return config + + # --- Internals ----------------------------------------------------------------------- + def _build(self, overrides: Mapping[str, Mapping[str, Any]]) -> RuntimeConfig: + merged = _merge(self._defaults, self._env_seed, overrides) + try: + return RuntimeConfig.model_validate(merged) + except ValidationError as exc: + raise ConfigValidationError.from_pydantic(exc) from None + + def _persist(self, overrides: Overrides) -> None: + atomic_write_json(self._path, overrides, file_mode=0o600) + + async def _notify(self, config: RuntimeConfig) -> None: + for listener in list(self._listeners): + try: + await listener(config) + except Exception: + logger.exception("Configuration listener %r failed", listener) + + @staticmethod + def _normalize_patch(patch: Mapping[str, Any]) -> Overrides: + if not isinstance(patch, Mapping): + raise UnknownConfigPathError("Patch must be an object of sections") + normalized: Overrides = {} + for section, fields in patch.items(): + _parse_path(section) + if not isinstance(fields, Mapping): + raise UnknownConfigPathError(f"Section {section!r} must be an object of fields") + for name, value in fields.items(): + _parse_path(f"{section}.{name}") + if is_masked(value): + continue + normalized.setdefault(section, {})[name] = copy.deepcopy(value) + return normalized + + def _sanitize_shape(self, raw: Any) -> Overrides: + if not isinstance(raw, dict): + logger.warning("Ignoring %s: expected a JSON object", self._path) + return {} + overrides: Overrides = {} + for section, fields in raw.items(): + if section not in SECTION_NAMES or not isinstance(fields, dict): + logger.warning("Ignoring unknown configuration section %r", section) + continue + known = section_fields(section) + for name, value in fields.items(): + if name not in known: + logger.warning("Ignoring unknown configuration field %s.%s", section, name) + continue + overrides.setdefault(section, {})[name] = value + return overrides + + def _prune_invalid(self, overrides: Overrides) -> Overrides: + pruned = copy.deepcopy(overrides) + for _ in range(_MAX_PRUNE_PASSES): + try: + self._build(pruned) + return pruned + except ConfigValidationError as exc: + removed = False + for error in exc.errors: + loc = error["loc"] + section = loc[0] if loc else None + if section not in pruned: + continue + if len(loc) >= 2 and loc[1] in pruned[section]: + del pruned[section][loc[1]] + logger.warning("Ignoring invalid saved value %s.%s", section, loc[1]) + else: + del pruned[section] + logger.warning("Ignoring invalid saved section %r", section) + removed = True + pruned = {s: f for s, f in pruned.items() if f} + if not removed: + raise + return {} diff --git a/app/core/history_store.py b/app/core/history_store.py new file mode 100644 index 0000000..a9936ec --- /dev/null +++ b/app/core/history_store.py @@ -0,0 +1,120 @@ +"""Display history persisted to ``/data/history.json`` (used for anti-repeat rules).""" + +from __future__ import annotations + +import asyncio +import logging +from datetime import UTC, datetime, timedelta +from pathlib import Path +from typing import Any + +from pydantic import AwareDatetime, BaseModel, ConfigDict, Field, ValidationError + +from app.core.json_store import atomic_write_json, read_json + +logger = logging.getLogger(__name__) + +HISTORY_FORMAT_VERSION = 1 + + +class HistoryEntry(BaseModel): + """One image that was displayed on the frame.""" + + model_config = ConfigDict(frozen=True) + + asset_id: str = Field(min_length=1, description="Provider-specific asset identifier") + source: str = Field(min_length=1, description="Provider name, e.g. 'immich'") + shown_at: AwareDatetime = Field(description="When the image was displayed (UTC)") + + +class HistoryStore: + """Append-only display log with time- and size-based retention.""" + + def __init__( + self, + path: Path, + *, + max_age_days: int = 365, + max_entries: int = 5000, + ) -> None: + """Create the store. + + Args: + path: Location of ``history.json``. + max_age_days: Entries older than this are discarded. + max_entries: Hard cap on stored entries (oldest are discarded first). + """ + if max_age_days < 1 or max_entries < 1: + raise ValueError("max_age_days and max_entries must be positive") + self._path = path + self._max_age = timedelta(days=max_age_days) + self._max_entries = max_entries + self._entries: list[HistoryEntry] = [] + self._lock = asyncio.Lock() + + def load(self) -> None: + """Load the history from disk, skipping malformed entries.""" + raw = read_json(self._path, dict) + items: Any = raw.get("entries", []) if isinstance(raw, dict) else [] + entries: list[HistoryEntry] = [] + skipped = 0 + for item in items if isinstance(items, list) else []: + try: + entries.append(HistoryEntry.model_validate(item)) + except ValidationError: + skipped += 1 + if skipped: + logger.warning("Skipped %d malformed history entries in %s", skipped, self._path) + entries.sort(key=lambda entry: entry.shown_at) + self._entries = self._prune(entries, datetime.now(UTC)) + + async def record( + self, asset_id: str, source: str, shown_at: datetime | None = None + ) -> HistoryEntry: + """Append an entry and persist the history. + + Args: + asset_id: Provider-specific identifier of the displayed asset. + source: Provider name. + shown_at: Display time (timezone-aware); defaults to now. + """ + now = datetime.now(UTC) + entry = HistoryEntry( + asset_id=asset_id, source=source, shown_at=(shown_at or now).astimezone(UTC) + ) + async with self._lock: + entries = sorted([*self._entries, entry], key=lambda item: item.shown_at) + entries = self._prune(entries, now) + await asyncio.to_thread(self._persist, entries) + self._entries = entries + return entry + + def recent_ids(self, source: str, within_days: int) -> set[str]: + """Asset IDs from ``source`` displayed within the last ``within_days`` days.""" + if within_days <= 0: + return set() + cutoff = datetime.now(UTC) - timedelta(days=within_days) + return { + entry.asset_id + for entry in self._entries + if entry.source == source and entry.shown_at >= cutoff + } + + def entries(self, limit: int | None = None) -> list[HistoryEntry]: + """Entries, newest first, optionally limited.""" + newest_first = list(reversed(self._entries)) + return newest_first if limit is None else newest_first[: max(limit, 0)] + + def _prune(self, entries: list[HistoryEntry], now: datetime) -> list[HistoryEntry]: + cutoff = now - self._max_age + kept = [entry for entry in entries if entry.shown_at >= cutoff] + return kept[-self._max_entries :] + + def _persist(self, entries: list[HistoryEntry]) -> None: + atomic_write_json( + self._path, + { + "version": HISTORY_FORMAT_VERSION, + "entries": [entry.model_dump(mode="json") for entry in entries], + }, + ) diff --git a/app/core/json_store.py b/app/core/json_store.py new file mode 100644 index 0000000..1b7be68 --- /dev/null +++ b/app/core/json_store.py @@ -0,0 +1,75 @@ +"""Crash-safe JSON file helpers used by the configuration and history stores.""" + +from __future__ import annotations + +import contextlib +import json +import logging +import os +import tempfile +from collections.abc import Callable +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +logger = logging.getLogger(__name__) + + +def read_json(path: Path, default_factory: Callable[[], Any]) -> Any: + """Read a JSON document, tolerating a missing or corrupt file. + + A missing file returns ``default_factory()``. An unreadable or invalid file is + renamed to ``.corrupt-`` (so nothing is lost) and + ``default_factory()`` is returned. + + Args: + path: File to read. + default_factory: Builds the value returned when the file cannot be used. + """ + try: + raw = path.read_text(encoding="utf-8") + except FileNotFoundError: + return default_factory() + + try: + return json.loads(raw) + except (json.JSONDecodeError, UnicodeDecodeError) as exc: + stamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ") + backup = path.with_name(f"{path.name}.corrupt-{stamp}") + try: + os.replace(path, backup) + logger.warning("Corrupt JSON in %s (%s); moved it to %s", path, exc, backup.name) + except OSError: + logger.exception("Corrupt JSON in %s and it could not be moved aside", path) + return default_factory() + + +def atomic_write_json(path: Path, data: Any, *, file_mode: int | None = None) -> None: + """Write ``data`` as pretty JSON atomically (temp file + fsync + ``os.replace``). + + Readers never observe a partially written file, even if the process crashes or the + container is stopped mid-write. + + Args: + path: Destination file. Parent directories are created when missing. + data: JSON-serializable document. + file_mode: Optional POSIX permission bits (e.g. ``0o600``). Ignored where the + platform does not support ``chmod`` semantics. + """ + path.parent.mkdir(parents=True, exist_ok=True) + fd, tmp_name = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".tmp") + tmp_path = Path(tmp_name) + try: + with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as handle: + json.dump(data, handle, indent=2, ensure_ascii=False, sort_keys=False) + handle.write("\n") + handle.flush() + os.fsync(handle.fileno()) + if file_mode is not None: + with contextlib.suppress(OSError): + os.chmod(tmp_path, file_mode) + os.replace(tmp_path, path) + except BaseException: + with contextlib.suppress(OSError): + tmp_path.unlink() + raise From a63d4e5d128bd0620374f8c23f476eed60308e4e Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sat, 14 Nov 2026 17:16:17 +0100 Subject: [PATCH 04/86] feat: add API key auth, root path and log masking middleware Pure ASGI middleware enforces APP_API_KEY on mutating routes, /api/config and (optionally) the image endpoints, via X-API-Key or ?api_key=. Root path support works whether or not the proxy strips the prefix. A logging filter redacts known secrets and api_key query parameters, including in Uvicorn access logs. Co-Authored-By: Claude Opus 5.5 --- app/core/auth.py | 124 +++++++++++++++++++++++++++++++++++++ app/core/logging_config.py | 81 ++++++++++++++++++++++++ app/core/proxy.py | 37 +++++++++++ 3 files changed, 242 insertions(+) create mode 100644 app/core/auth.py create mode 100644 app/core/logging_config.py create mode 100644 app/core/proxy.py diff --git a/app/core/auth.py b/app/core/auth.py new file mode 100644 index 0000000..d9033c4 --- /dev/null +++ b/app/core/auth.py @@ -0,0 +1,124 @@ +"""Adaptive API key authentication (pure ASGI middleware). + +Rules when ``APP_API_KEY`` is set (no-op when it is empty): + +* ``POST``/``PUT``/``PATCH``/``DELETE`` on any route require the key. +* ``/api/config`` and everything below it require the key for every method. +* ``/api/current.jpg`` and ``/api/current.bin`` require the key only when + ``PUBLIC_IMAGE_ENDPOINTS=false``. +* Everything else (UI, ``/docs``, ``/openapi.json``, ``/api/health``, ``GET /api/status``) + stays public so the UI can load and prompt for the key. + +The key is accepted from the ``X-API-Key`` header or the ``api_key`` query parameter and +compared in constant time. +""" + +from __future__ import annotations + +import hmac +from typing import Final +from urllib.parse import parse_qsl + +from fastapi.security import APIKeyHeader +from starlette.responses import JSONResponse +from starlette.types import ASGIApp, Receive, Scope, Send + +API_KEY_HEADER: Final = "X-API-Key" +API_KEY_QUERY_PARAM: Final = "api_key" + +MUTATING_METHODS: Final = frozenset({"POST", "PUT", "PATCH", "DELETE"}) +PROTECTED_PREFIXES: Final = ("/api/config",) +IMAGE_ENDPOINTS: Final = frozenset({"/api/current.jpg", "/api/current.bin"}) + +#: OpenAPI-only security scheme so ``/docs`` offers an "Authorize" button. Enforcement +#: is done by :class:`APIKeyMiddleware`, never by this dependency. +api_key_scheme = APIKeyHeader( + name=API_KEY_HEADER, + auto_error=False, + description="Required for mutating routes and /api/config when APP_API_KEY is set.", +) + + +def route_path(scope: Scope) -> str: + """Request path relative to the application's ``root_path``. + + Works whether or not the reverse proxy strips the sub-path prefix. + """ + path: str = scope.get("path", "") + root_path: str = scope.get("root_path", "") + if not root_path or not path.startswith(root_path): + return path + if path == root_path: + return "/" + if path[len(root_path)] == "/": + return path[len(root_path) :] + return path + + +def requires_api_key(method: str, path: str, *, public_image_endpoints: bool) -> bool: + """Decide whether a request must carry a valid API key.""" + method = method.upper() + if method == "OPTIONS": + return False + if method in MUTATING_METHODS: + return True + normalized = path.rstrip("/") or "/" + if any(normalized == p or normalized.startswith(f"{p}/") for p in PROTECTED_PREFIXES): + return True + return normalized in IMAGE_ENDPOINTS and not public_image_endpoints + + +def extract_api_key(scope: Scope) -> str | None: + """Read the API key from the ``X-API-Key`` header or the ``api_key`` query param.""" + header_name = API_KEY_HEADER.lower().encode("latin-1") + for name, value in scope.get("headers", []): + if name.lower() == header_name: + return bytes(value).decode("latin-1").strip() + query: bytes = scope.get("query_string", b"") + if query: + for name, value in parse_qsl(query.decode("latin-1"), keep_blank_values=True): + if name == API_KEY_QUERY_PARAM: + return value.strip() + return None + + +def keys_match(provided: str | None, expected: str) -> bool: + """Constant-time comparison of a provided key against the expected key.""" + if not provided or not expected: + return False + return hmac.compare_digest(provided.encode("utf-8"), expected.encode("utf-8")) + + +class APIKeyMiddleware: + """Enforce :func:`requires_api_key` rules for HTTP requests.""" + + def __init__(self, app: ASGIApp, *, api_key: str, public_image_endpoints: bool) -> None: + """Wrap ``app``. + + Args: + app: Downstream ASGI application. + api_key: Expected key; an empty string disables authentication. + public_image_endpoints: Keep current.jpg/current.bin readable without a key. + """ + self.app = app + self.api_key = api_key + self.public_image_endpoints = public_image_endpoints + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + if scope["type"] != "http" or not self.api_key: + await self.app(scope, receive, send) + return + + method: str = scope.get("method", "GET") + if requires_api_key( + method, route_path(scope), public_image_endpoints=self.public_image_endpoints + ) and not keys_match(extract_api_key(scope), self.api_key): + response = JSONResponse( + {"detail": "Missing or invalid API key"}, + status_code=401, + headers={"WWW-Authenticate": f'APIKey header="{API_KEY_HEADER}"'}, + ) + await response(scope, receive, send) + return + + await self.app(scope, receive, send) diff --git a/app/core/logging_config.py b/app/core/logging_config.py new file mode 100644 index 0000000..1b57fe3 --- /dev/null +++ b/app/core/logging_config.py @@ -0,0 +1,81 @@ +"""Logging setup with secret masking. + +Every handler gets a :class:`SecretMaskingFilter` that redacts known secret values +(API keys from the environment and from ``config.json``) and any ``api_key=...`` query +parameter, which would otherwise leak through Uvicorn's access log. +""" + +from __future__ import annotations + +import logging +import re +import sys +import threading +from collections.abc import Iterable +from typing import Any, Final + +REDACTED: Final = "***" +_QUERY_KEY_RE: Final = re.compile(r"(?i)((?:api_key|apikey|api-key|token)=)[^&\s\"']+") +_MIN_SECRET_LENGTH: Final = 4 +_UVICORN_LOGGERS: Final = ("uvicorn", "uvicorn.error", "uvicorn.access") +LOG_FORMAT: Final = "%(asctime)s %(levelname)-8s %(name)s: %(message)s" + + +class SecretMaskingFilter(logging.Filter): + """Redact secrets from log records (message *and* formatting arguments).""" + + def __init__(self) -> None: + super().__init__() + self._lock = threading.Lock() + self._secrets: tuple[str, ...] = () + + def set_secrets(self, values: Iterable[str]) -> None: + """Replace the set of literal values to redact.""" + cleaned = {v for v in values if v and len(v) >= _MIN_SECRET_LENGTH} + with self._lock: + # Longest first so a secret containing another one is fully redacted. + self._secrets = tuple(sorted(cleaned, key=len, reverse=True)) + + def mask(self, text: str) -> str: + """Return ``text`` with every known secret and ``api_key=`` value redacted.""" + for secret in self._secrets: + if secret in text: + text = text.replace(secret, REDACTED) + return _QUERY_KEY_RE.sub(rf"\1{REDACTED}", text) + + def _mask_value(self, value: Any) -> Any: + return self.mask(value) if isinstance(value, str) else value + + def filter(self, record: logging.LogRecord) -> bool: + if isinstance(record.msg, str): + record.msg = self.mask(record.msg) + if isinstance(record.args, tuple): + record.args = tuple(self._mask_value(arg) for arg in record.args) + elif isinstance(record.args, dict): + record.args = {key: self._mask_value(val) for key, val in record.args.items()} + return True + + +#: Process-wide filter instance shared by all handlers. +masking_filter = SecretMaskingFilter() + + +def setup_logging(level: str = "INFO") -> None: + """Configure root logging once and attach the masking filter everywhere. + + Safe to call multiple times. When Uvicorn installed its own handlers (e.g. when run + as ``uvicorn --factory app.main:create_app``), the filter is attached to them too. + """ + root = logging.getLogger() + root.setLevel(level) + if not root.handlers: + stream_handler = logging.StreamHandler(sys.stdout) + stream_handler.setFormatter(logging.Formatter(LOG_FORMAT)) + root.addHandler(stream_handler) + + handlers: list[logging.Handler] = list(root.handlers) + for name in _UVICORN_LOGGERS: + handlers.extend(logging.getLogger(name).handlers) + for handler in handlers: + if masking_filter not in handler.filters: + handler.addFilter(masking_filter) diff --git a/app/core/proxy.py b/app/core/proxy.py new file mode 100644 index 0000000..85e88ac --- /dev/null +++ b/app/core/proxy.py @@ -0,0 +1,37 @@ +"""Reverse proxy sub-path support (``ROOT_PATH``). + +``RootPathMiddleware`` sets ``scope["root_path"]`` for every request, which is what +FastAPI's (now deprecated) ``FastAPI(root_path=...)`` argument did. FastAPI then serves +``/docs`` with the prefixed OpenAPI URL and advertises the prefix in ``servers``. + +Unlike Uvicorn's ``--root-path`` (which prepends the prefix to every incoming path and +therefore only works with proxies that strip it), this works with both proxy styles: + +* the proxy strips ``/fraimic`` and forwards ``/api/status``; +* the proxy keeps the prefix and forwards ``/fraimic/api/status``. + +Starlette's router removes the prefix when present before matching routes. +""" + +from __future__ import annotations + +from starlette.types import ASGIApp, Receive, Scope, Send + + +class RootPathMiddleware: + """Inject a fixed ``root_path`` into HTTP and WebSocket scopes.""" + + def __init__(self, app: ASGIApp, *, root_path: str) -> None: + """Wrap ``app``. + + Args: + app: Downstream ASGI application. + root_path: Normalized prefix such as ``/fraimic``; empty disables the middleware. + """ + self.app = app + self.root_path = root_path + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + if self.root_path and scope["type"] in {"http", "websocket"}: + scope = {**scope, "root_path": self.root_path} + await self.app(scope, receive, send) From aef4dc0105a21ad6f9c33a8dd927c9746cc115ca Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sat, 14 Nov 2026 17:16:17 +0100 Subject: [PATCH 05/86] feat: add app factory with config, health and status endpoints create_app() wires CORS, auth and root path middleware, initializes the stores in the lifespan and exposes GET /api/health, GET /api/status, GET/PUT /api/config, GET /api/config/schema and POST /api/config/reset. Validation errors never echo submitted values. python -m app runs Uvicorn with proxy headers and FORWARDED_ALLOW_IPS. Co-Authored-By: Claude Opus 5.5 --- app/__main__.py | 33 +++++++++ app/api/deps.py | 31 +++++++++ app/api/routes/config.py | 137 ++++++++++++++++++++++++++++++++++++++ app/api/routes/system.py | 95 ++++++++++++++++++++++++++ app/main.py | 140 +++++++++++++++++++++++++++++++++++++++ 5 files changed, 436 insertions(+) create mode 100644 app/__main__.py create mode 100644 app/api/deps.py create mode 100644 app/api/routes/config.py create mode 100644 app/api/routes/system.py create mode 100644 app/main.py diff --git a/app/__main__.py b/app/__main__.py new file mode 100644 index 0000000..8435256 --- /dev/null +++ b/app/__main__.py @@ -0,0 +1,33 @@ +"""Container entry point: ``python -m app``. + +Starts Uvicorn with reverse-proxy support (``X-Forwarded-Proto``/``X-Forwarded-For``) +using the ``HOST``, ``PORT``, ``LOG_LEVEL`` and ``FORWARDED_ALLOW_IPS`` settings. +""" + +from __future__ import annotations + +import uvicorn + +from app.core.logging_config import setup_logging +from app.core.settings import get_env_settings + + +def main() -> None: + """Configure logging and serve the application.""" + settings = get_env_settings() + setup_logging(settings.log_level) + uvicorn.run( + "app.main:create_app", + factory=True, + host=settings.host, + port=settings.port, + proxy_headers=True, + forwarded_allow_ips=settings.forwarded_allow_ips, + log_config=None, + log_level=settings.log_level.lower(), + server_header=False, + ) + + +if __name__ == "__main__": + main() diff --git a/app/api/deps.py b/app/api/deps.py new file mode 100644 index 0000000..db9da7d --- /dev/null +++ b/app/api/deps.py @@ -0,0 +1,31 @@ +"""FastAPI dependencies giving routes access to application-scoped services.""" + +from __future__ import annotations + +from typing import Annotated, cast + +from fastapi import Depends, Request + +from app.core.config_store import ConfigStore +from app.core.history_store import HistoryStore +from app.core.settings import EnvSettings + + +def get_settings(request: Request) -> EnvSettings: + """Environment settings the application was created with.""" + return cast(EnvSettings, request.app.state.settings) + + +def get_config_store(request: Request) -> ConfigStore: + """The runtime configuration store (initialized during app startup).""" + return cast(ConfigStore, request.app.state.config_store) + + +def get_history_store(request: Request) -> HistoryStore: + """The display history store (initialized during app startup).""" + return cast(HistoryStore, request.app.state.history_store) + + +SettingsDep = Annotated[EnvSettings, Depends(get_settings)] +ConfigStoreDep = Annotated[ConfigStore, Depends(get_config_store)] +HistoryStoreDep = Annotated[HistoryStore, Depends(get_history_store)] diff --git a/app/api/routes/config.py b/app/api/routes/config.py new file mode 100644 index 0000000..aafeada --- /dev/null +++ b/app/api/routes/config.py @@ -0,0 +1,137 @@ +"""Runtime configuration endpoints (always API-key protected when a key is set).""" + +from __future__ import annotations + +from typing import Annotated, Any + +from fastapi import APIRouter, Body, Security +from fastapi.responses import JSONResponse +from pydantic import BaseModel, Field + +from app.api.deps import ConfigStoreDep +from app.core.auth import api_key_scheme +from app.core.config_models import RuntimeConfig +from app.core.config_store import ConfigError, ConfigValidationError + +router = APIRouter( + prefix="/api/config", + tags=["config"], + dependencies=[Security(api_key_scheme)], +) + + +class ConfigView(BaseModel): + """Effective configuration with masked secrets and value provenance.""" + + config: dict[str, dict[str, Any]] = Field( + description="Effective configuration; secrets are masked" + ) + sources: dict[str, str] = Field( + description="Origin of each value: 'default', 'env' (.env) or 'config' (saved)" + ) + frame_size: tuple[int, int] = Field(description="Composition size (width, height)") + + +class ResetRequest(BaseModel): + """Paths to reset; omit or send ``null`` to reset everything.""" + + paths: list[str] | None = Field( + default=None, + description="Entries like 'immich' (whole section) or 'immich.url' (single field)", + examples=[["immich.url", "eink"]], + ) + + +class ConfigErrorResponse(BaseModel): + """Validation error payload (never echoes submitted values).""" + + detail: str + errors: list[dict[str, Any]] = Field(default_factory=list) + + +PATCH_EXAMPLES: dict[str, Any] = { + "fraimic": { + "summary": "Battery-powered frame", + "value": {"fraimic": {"host": "fraimic.local", "power_mode": "deepsleep"}}, + }, + "immich": { + "summary": "Immich defaults", + "value": {"immich": {"persons": ["Alice", "Bob"], "match_mode": "any"}}, + }, +} + + +def _view(store: ConfigStoreDep) -> ConfigView: + public = store.public_view() + return ConfigView( + config=public["config"], sources=public["sources"], frame_size=store.config.frame_size + ) + + +def _error_response(exc: ConfigError) -> JSONResponse: + status_code = 422 if isinstance(exc, ConfigValidationError) else 400 + payload = ConfigErrorResponse(detail=exc.message, errors=exc.errors) + return JSONResponse(payload.model_dump(), status_code=status_code) + + +_ERROR_RESPONSES: dict[int | str, dict[str, Any]] = { + 400: {"model": ConfigErrorResponse, "description": "Unknown section or field"}, + 422: {"model": ConfigErrorResponse, "description": "Resulting configuration is invalid"}, +} + + +@router.get("", response_model=ConfigView, summary="Read the runtime configuration") +async def read_config(store: ConfigStoreDep) -> ConfigView: + """Return the effective configuration (secrets masked) and where each value comes from.""" + return _view(store) + + +@router.get("/schema", summary="JSON Schema of the runtime configuration") +async def config_schema() -> dict[str, Any]: + """JSON Schema describing every section and field (used to render settings forms).""" + return RuntimeConfig.model_json_schema() + + +@router.put( + "", + response_model=ConfigView, + responses=_ERROR_RESPONSES, + summary="Update the runtime configuration", +) +async def update_config( + store: ConfigStoreDep, + patch: Annotated[ + dict[str, dict[str, Any]], + Body( + description="Partial update: {section: {field: value}}. Masked secrets are ignored.", + openapi_examples=PATCH_EXAMPLES, + ), + ], +) -> ConfigView | JSONResponse: + """Validate and save a partial update to ``/data/config.json``. + + Saved values take precedence over ``.env``. Nothing is written if validation fails. + """ + try: + await store.update(patch) + except ConfigError as exc: + return _error_response(exc) + return _view(store) + + +@router.post( + "/reset", + response_model=ConfigView, + responses=_ERROR_RESPONSES, + summary="Reset saved values to .env / defaults", +) +async def reset_config( + store: ConfigStoreDep, + request: Annotated[ResetRequest | None, Body()] = None, +) -> ConfigView | JSONResponse: + """Remove saved overrides so the values fall back to ``.env`` or built-in defaults.""" + try: + await store.reset(None if request is None else request.paths) + except ConfigError as exc: + return _error_response(exc) + return _view(store) diff --git a/app/api/routes/system.py b/app/api/routes/system.py new file mode 100644 index 0000000..7c552fa --- /dev/null +++ b/app/api/routes/system.py @@ -0,0 +1,95 @@ +"""Health and status endpoints.""" + +from __future__ import annotations + +import time +from typing import Literal + +from fastapi import APIRouter, Request +from pydantic import BaseModel, Field + +from app import __version__ +from app.api.deps import ConfigStoreDep, SettingsDep + +router = APIRouter(prefix="/api", tags=["system"]) + + +class HealthResponse(BaseModel): + """Liveness probe payload.""" + + status: Literal["ok"] = "ok" + version: str + + +class FrameStatus(BaseModel): + """Configured frame characteristics.""" + + panel: str = Field(description="Panel model key (133 or 315)") + panel_label: str + power_mode: str + orientation: str + frame_size: tuple[int, int] = Field(description="Composition size (width, height)") + configured: bool = Field(description="Whether a frame host is configured") + + +class SchedulerStatus(BaseModel): + """Configured autonomous refresh.""" + + enabled: bool + interval_hours: float + timezone: str + + +class ServiceConfigured(BaseModel): + """Whether each external service has the settings it needs.""" + + immich: bool + tmdb: bool + + +class StatusResponse(BaseModel): + """Overall system status.""" + + version: str + uptime_s: float + auth_enabled: bool + public_image_endpoints: bool + frame: FrameStatus + scheduler: SchedulerStatus + services: ServiceConfigured + + +@router.get("/health", response_model=HealthResponse, summary="Liveness probe") +async def health() -> HealthResponse: + """Return ``ok`` while the process is serving requests.""" + return HealthResponse(version=__version__) + + +@router.get("/status", response_model=StatusResponse, summary="System status") +async def status(request: Request, settings: SettingsDep, store: ConfigStoreDep) -> StatusResponse: + """Overall system status and configuration summary (no secrets).""" + config = store.config + started_at: float = request.app.state.started_at + return StatusResponse( + version=__version__, + uptime_s=round(time.monotonic() - started_at, 1), + auth_enabled=settings.auth_enabled, + public_image_endpoints=settings.public_image_endpoints, + frame=FrameStatus( + panel=config.fraimic.panel, + panel_label=config.fraimic.spec.label, + power_mode=config.fraimic.power_mode, + orientation=config.display.orientation, + frame_size=config.frame_size, + configured=bool(config.fraimic.base_url), + ), + scheduler=SchedulerStatus( + enabled=config.scheduler.enabled, + interval_hours=config.scheduler.interval_hours, + timezone=config.scheduler.timezone, + ), + services=ServiceConfigured( + immich=bool(config.immich.url and config.immich.api_key.get_secret_value()), + tmdb=bool(config.tmdb.api_key.get_secret_value()), + ), + ) diff --git a/app/main.py b/app/main.py new file mode 100644 index 0000000..8c7472f --- /dev/null +++ b/app/main.py @@ -0,0 +1,140 @@ +"""FastAPI application factory. + +Run with ``python -m app`` (recommended, honors ``PORT``/``FORWARDED_ALLOW_IPS``) or +``uvicorn --factory app.main:create_app``. +""" + +from __future__ import annotations + +import logging +import time +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +from typing import Any + +from fastapi import FastAPI, Request +from fastapi.encoders import jsonable_encoder +from fastapi.exceptions import RequestValidationError +from fastapi.middleware.cors import CORSMiddleware +from fastapi.responses import JSONResponse, RedirectResponse + +from app import __version__ +from app.api.routes import config as config_routes +from app.api.routes import system as system_routes +from app.core.auth import APIKeyMiddleware +from app.core.config_models import RuntimeConfig +from app.core.config_store import ConfigStore +from app.core.history_store import HistoryStore +from app.core.logging_config import masking_filter, setup_logging +from app.core.proxy import RootPathMiddleware +from app.core.settings import EnvSettings, get_env_settings + +logger = logging.getLogger(__name__) + +API_DESCRIPTION = """ +Fetch images from modular sources (Immich, TMDB posters, URLs), optimize them for a +color eInk panel and push them to a Fraimic frame. + +**Authentication:** when `APP_API_KEY` is set, every `POST`/`PUT`/`DELETE` route and +`/api/config` require the `X-API-Key` header (or `?api_key=`). Use **Authorize** above. +""" + + +def _prepare_data_dir(settings: EnvSettings) -> None: + for directory in (settings.data_dir, settings.cache_dir): + try: + directory.mkdir(parents=True, exist_ok=True) + except OSError as exc: + raise RuntimeError( + f"Data directory {directory} is not writable ({exc}). " + "Check the /data volume mount and its ownership (container runs as uid 1000)." + ) from exc + + +def create_app(settings: EnvSettings | None = None) -> FastAPI: + """Build the FastAPI application. + + Args: + settings: Environment settings; defaults to :func:`get_env_settings`. + """ + settings = settings or get_env_settings() + + @asynccontextmanager + async def lifespan(app: FastAPI) -> AsyncIterator[None]: + setup_logging(settings.log_level) + _prepare_data_dir(settings) + + config_store = ConfigStore(settings.config_path, settings.runtime_seed()) + config_store.load() + history_store = HistoryStore(settings.history_path) + history_store.load() + + def _refresh_masked_secrets() -> None: + masking_filter.set_secrets([*settings.secret_values(), *config_store.secret_values()]) + + async def _on_config_change(_: RuntimeConfig) -> None: + _refresh_masked_secrets() + + _refresh_masked_secrets() + config_store.add_listener(_on_config_change) + + app.state.config_store = config_store + app.state.history_store = history_store + + logger.info( + "Smart Frame Engine %s started (data_dir=%s, auth=%s, root_path=%r, panel=%s)", + __version__, + settings.data_dir, + "enabled" if settings.auth_enabled else "disabled", + settings.root_path, + config_store.config.fraimic.panel, + ) + yield + logger.info("Smart Frame Engine stopped") + + app = FastAPI( + title="Smart Frame Engine", + version=__version__, + description=API_DESCRIPTION, + lifespan=lifespan, + ) + app.state.settings = settings + app.state.started_at = time.monotonic() + + # Middleware added last runs first. Order (outermost first): RootPath -> CORS -> auth. + # CORS wraps auth so 401 responses keep CORS headers; RootPath must run before auth + # so protected paths are recognized under a sub-path. + app.add_middleware( + APIKeyMiddleware, + api_key=settings.api_key, + public_image_endpoints=settings.public_image_endpoints, + ) + origins = settings.cors_origin_list + app.add_middleware( + CORSMiddleware, + allow_origins=origins, + allow_credentials="*" not in origins, + allow_methods=["*"], + allow_headers=["*"], + ) + app.add_middleware(RootPathMiddleware, root_path=settings.root_path) + + @app.exception_handler(RequestValidationError) + async def _validation_handler(_: Request, exc: RequestValidationError) -> JSONResponse: + """Report request validation errors without echoing submitted values.""" + errors: list[dict[str, Any]] = [ + {"loc": list(err.get("loc", ())), "msg": err.get("msg", ""), "type": err.get("type")} + for err in exc.errors() + ] + return JSONResponse({"detail": jsonable_encoder(errors)}, status_code=422) + + app.include_router(system_routes.router) + app.include_router(config_routes.router) + + @app.get("/", include_in_schema=False) + async def index(request: Request) -> RedirectResponse: + """Redirect to the API docs (the web UI replaces this in a later milestone).""" + root_path: str = request.scope.get("root_path", "") + return RedirectResponse(url=f"{root_path}/docs", status_code=307) + + return app From ec685338f7eea313deac59ad20376b1b7579dedd Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sat, 14 Nov 2026 17:16:17 +0100 Subject: [PATCH 06/86] feat: add URL, upload size and image validation helpers validate_external_url enforces http(s), rejects embedded credentials and, when BLOCK_PRIVATE_URLS is enabled, blocks non-public resolved addresses unless allowlisted. read_limited/read_upload enforce the size limit while streaming and verify_image_bytes checks real image structure with Pillow. Co-Authored-By: Claude Opus 5.5 --- app/core/security.py | 222 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 222 insertions(+) create mode 100644 app/core/security.py diff --git a/app/core/security.py b/app/core/security.py new file mode 100644 index 0000000..4654ae0 --- /dev/null +++ b/app/core/security.py @@ -0,0 +1,222 @@ +"""Input hardening: SSRF-aware URL validation, size-limited reads, image verification.""" + +from __future__ import annotations + +import asyncio +import io +import ipaddress +import socket +from collections.abc import AsyncIterable, Iterable +from dataclasses import dataclass, field +from typing import Final, Protocol +from urllib.parse import urlsplit + +from PIL import Image, UnidentifiedImageError + +IPAddress = ipaddress.IPv4Address | ipaddress.IPv6Address +IPNetwork = ipaddress.IPv4Network | ipaddress.IPv6Network + +ALLOWED_IMAGE_FORMATS: Final = frozenset({"JPEG", "MPO", "PNG", "WEBP", "GIF", "TIFF", "BMP"}) +MAX_IMAGE_PIXELS: Final = 120_000_000 +UPLOAD_CHUNK_SIZE: Final = 64 * 1024 + + +class UnsafeURLError(ValueError): + """The URL is malformed, uses a forbidden scheme, or targets a blocked address.""" + + +class PayloadTooLargeError(ValueError): + """The payload exceeds the configured size limit.""" + + def __init__(self, limit: int) -> None: + super().__init__(f"Payload exceeds the {limit // (1024 * 1024)} MB limit") + self.limit = limit + + +class InvalidImageError(ValueError): + """The payload is not a supported, decodable image.""" + + +@dataclass(frozen=True, slots=True) +class URLPolicy: + """Outbound URL policy. + + Attributes: + block_private: Reject hosts resolving to non-public addresses. + networks: Networks exempt from ``block_private``. + hostnames: Hostnames (lower-case) exempt from ``block_private``. + """ + + block_private: bool = False + networks: tuple[IPNetwork, ...] = field(default_factory=tuple) + hostnames: frozenset[str] = field(default_factory=frozenset) + + @classmethod + def from_entries(cls, block_private: bool, entries: Iterable[str]) -> URLPolicy: + """Build a policy from allowlist entries (CIDRs, IPs or hostnames).""" + networks: list[IPNetwork] = [] + hostnames: set[str] = set() + for entry in entries: + entry = entry.strip() + if not entry: + continue + try: + networks.append(ipaddress.ip_network(entry, strict=False)) + except ValueError: + hostnames.add(entry.lower().rstrip(".")) + return cls(block_private, tuple(networks), frozenset(hostnames)) + + def allows_address(self, address: IPAddress) -> bool: + """Whether ``address`` may be contacted under this policy.""" + if not self.block_private: + return True + if isinstance(address, ipaddress.IPv6Address) and address.ipv4_mapped is not None: + address = address.ipv4_mapped + if any(address in network for network in self.networks): + return True + return is_public_address(address) + + +def is_public_address(address: IPAddress) -> bool: + """``True`` for globally routable unicast addresses only.""" + return not ( + address.is_private + or address.is_loopback + or address.is_link_local + or address.is_multicast + or address.is_reserved + or address.is_unspecified + or not address.is_global + ) + + +async def _resolve(host: str, port: int) -> list[IPAddress]: + loop = asyncio.get_running_loop() + try: + infos = await loop.getaddrinfo(host, port, type=socket.SOCK_STREAM) + except socket.gaierror as exc: + raise UnsafeURLError(f"Cannot resolve host {host!r}") from exc + addresses: list[IPAddress] = [] + for info in infos: + raw = str(info[4][0]).split("%", 1)[0] # drop IPv6 zone index + addresses.append(ipaddress.ip_address(raw)) + return addresses + + +async def validate_external_url(url: str, policy: URLPolicy) -> str: + """Validate a user-supplied URL before the server fetches it. + + Checks: ``http``/``https`` scheme, a host is present, no embedded credentials and, + when ``policy.block_private`` is enabled, every resolved address is public or + explicitly allowlisted. + + Note: + Resolution happens here, before the fetch; this narrows but cannot fully close + DNS-rebinding windows. Fetchers should also disable redirects to other hosts or + re-validate each redirect target. + + Returns: + The stripped URL. + + Raises: + UnsafeURLError: If the URL is rejected. + """ + url = url.strip() + try: + parts = urlsplit(url) + port = parts.port + except ValueError as exc: + raise UnsafeURLError("Malformed URL") from exc + if parts.scheme not in {"http", "https"}: + raise UnsafeURLError("Only http:// and https:// URLs are allowed") + host = (parts.hostname or "").rstrip(".").lower() + if not host: + raise UnsafeURLError("URL has no host") + if parts.username or parts.password: + raise UnsafeURLError("URLs with embedded credentials are not allowed") + if not policy.block_private or host in policy.hostnames: + return url + + try: + addresses = [ipaddress.ip_address(host)] + except ValueError: + addresses = await _resolve(host, port or (443 if parts.scheme == "https" else 80)) + if not addresses: + raise UnsafeURLError(f"Cannot resolve host {host!r}") + for address in addresses: + if not policy.allows_address(address): + raise UnsafeURLError(f"Host {host!r} resolves to a blocked address") + return url + + +async def read_limited( + chunks: AsyncIterable[bytes], max_bytes: int, *, declared_length: int | None = None +) -> bytes: + """Collect an async byte stream, aborting as soon as it exceeds ``max_bytes``. + + Args: + chunks: Async byte stream (e.g. ``httpx.Response.aiter_bytes()``). + max_bytes: Maximum accepted size. + declared_length: Optional ``Content-Length`` for early rejection. + + Raises: + PayloadTooLargeError: If the limit is exceeded. + """ + if declared_length is not None and declared_length > max_bytes: + raise PayloadTooLargeError(max_bytes) + buffer = bytearray() + async for chunk in chunks: + buffer.extend(chunk) + if len(buffer) > max_bytes: + raise PayloadTooLargeError(max_bytes) + return bytes(buffer) + + +class AsyncReadable(Protocol): + """Anything with an async ``read(size)`` (e.g. ``fastapi.UploadFile``).""" + + async def read(self, size: int = -1) -> bytes: ... + + +async def read_upload(file: AsyncReadable, max_bytes: int) -> bytes: + """Read an uploaded file in chunks, enforcing ``max_bytes``. + + Raises: + PayloadTooLargeError: If the upload is larger than ``max_bytes``. + """ + + async def _iterate() -> AsyncIterable[bytes]: + while chunk := await file.read(UPLOAD_CHUNK_SIZE): + yield chunk + + return await read_limited(_iterate(), max_bytes) + + +def verify_image_bytes(data: bytes, *, max_pixels: int = MAX_IMAGE_PIXELS) -> str: + """Check that ``data`` really is a supported image (magic bytes + structure). + + Returns: + The detected Pillow format name (e.g. ``"JPEG"``). + + Raises: + InvalidImageError: If the data is not a supported, structurally valid image or + its pixel count exceeds ``max_pixels``. + """ + if not data: + raise InvalidImageError("Empty file") + try: + with Image.open(io.BytesIO(data)) as image: + image_format = image.format or "" + width, height = image.size + if image_format not in ALLOWED_IMAGE_FORMATS: + raise InvalidImageError(f"Unsupported image format: {image_format or 'unknown'}") + if width * height > max_pixels: + raise InvalidImageError(f"Image too large: {width}x{height} pixels") + image.verify() + except InvalidImageError: + raise + except (UnidentifiedImageError, Image.DecompressionBombError) as exc: + raise InvalidImageError("Not a valid image") from exc + except (OSError, SyntaxError, ValueError) as exc: + raise InvalidImageError("Corrupt or truncated image") from exc + return image_format From 2dace0832fc69c3aa4a3ba9163e739fd3a7c7b15 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sat, 14 Nov 2026 17:16:17 +0100 Subject: [PATCH 07/86] test: cover settings, stores, auth, security and root path Co-Authored-By: Claude Opus 5.5 --- tests/__init__.py | 1 + tests/conftest.py | 55 ++++++++++++ tests/test_api.py | 114 +++++++++++++++++++++++++ tests/test_auth.py | 142 ++++++++++++++++++++++++++++++ tests/test_config_models.py | 154 +++++++++++++++++++++++++++++++++ tests/test_config_store.py | 166 ++++++++++++++++++++++++++++++++++++ tests/test_history_store.py | 79 +++++++++++++++++ tests/test_logging.py | 63 ++++++++++++++ tests/test_root_path.py | 67 +++++++++++++++ tests/test_security.py | 161 ++++++++++++++++++++++++++++++++++ tests/test_settings.py | 84 ++++++++++++++++++ 11 files changed, 1086 insertions(+) create mode 100644 tests/__init__.py create mode 100644 tests/conftest.py create mode 100644 tests/test_api.py create mode 100644 tests/test_auth.py create mode 100644 tests/test_config_models.py create mode 100644 tests/test_config_store.py create mode 100644 tests/test_history_store.py create mode 100644 tests/test_logging.py create mode 100644 tests/test_root_path.py create mode 100644 tests/test_security.py create mode 100644 tests/test_settings.py diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..b91eb13 --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1 @@ +"""Test suite for Smart Frame Engine.""" diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..443707a --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,55 @@ +"""Shared fixtures: isolated environment, temporary data dir, app/client factories.""" + +from __future__ import annotations + +from collections.abc import Callable, Iterator +from pathlib import Path +from typing import Any + +import pytest +from fastapi.testclient import TestClient + +from app.core.settings import EnvSettings +from app.main import create_app + +SettingsFactory = Callable[..., EnvSettings] +ClientFactory = Callable[..., TestClient] + + +@pytest.fixture(autouse=True) +def _isolate_env(monkeypatch: pytest.MonkeyPatch) -> None: + """Make sure the developer's shell environment never leaks into tests.""" + for name in EnvSettings.model_fields: + monkeypatch.delenv(name.upper(), raising=False) + + +@pytest.fixture +def data_dir(tmp_path: Path) -> Path: + return tmp_path / "data" + + +@pytest.fixture +def make_settings(data_dir: Path) -> SettingsFactory: + """Build settings from keyword overrides and the (monkeypatched) environment.""" + + def _make(**overrides: Any) -> EnvSettings: + overrides.setdefault("data_dir", data_dir) + return EnvSettings(_env_file=None, **overrides) + + return _make + + +@pytest.fixture +def make_client(make_settings: SettingsFactory) -> Iterator[ClientFactory]: + """Create started TestClients (lifespan executed); they are closed after the test.""" + clients: list[TestClient] = [] + + def _make(**overrides: Any) -> TestClient: + client = TestClient(create_app(make_settings(**overrides))) + client.__enter__() + clients.append(client) + return client + + yield _make + for client in clients: + client.__exit__(None, None, None) diff --git a/tests/test_api.py b/tests/test_api.py new file mode 100644 index 0000000..585e197 --- /dev/null +++ b/tests/test_api.py @@ -0,0 +1,114 @@ +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from app import __version__ +from app.core.config_models import MASK_PREFIX +from tests.conftest import ClientFactory + + +def test_health(make_client: ClientFactory) -> None: + response = make_client().get("/api/health") + assert response.status_code == 200 + assert response.json() == {"status": "ok", "version": __version__} + + +def test_status_summarizes_without_secrets( + make_client: ClientFactory, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("IMMICH_URL", "http://immich.local:2283") + monkeypatch.setenv("IMMICH_API_KEY", "immich-secret-value") + client = make_client(app_api_key="k") + response = client.get("/api/status") + assert response.status_code == 200 + body = response.json() + assert body["auth_enabled"] is True + assert body["frame"]["panel"] == "133" + assert body["frame"]["frame_size"] == [1200, 1600] + assert body["services"] == {"immich": True, "tmdb": False} + assert "immich-secret-value" not in response.text + + +def test_data_dir_is_created(make_client: ClientFactory, data_dir: Path) -> None: + make_client() + assert data_dir.is_dir() + assert (data_dir / "cache").is_dir() + + +def test_config_read_update_reset_flow(make_client: ClientFactory, data_dir: Path) -> None: + client = make_client(tmdb_api_key="tmdb-env-secret-abcd") + + view = client.get("/api/config").json() + assert view["config"]["tmdb"]["api_key"] == MASK_PREFIX + "abcd" + assert view["sources"]["tmdb.api_key"] == "env" + assert view["frame_size"] == [1200, 1600] + assert "tmdb-env-secret-abcd" not in json.dumps(view) + + updated = client.put( + "/api/config", + json={"display": {"orientation": "landscape"}, "tmdb": view["config"]["tmdb"]}, + ) + assert updated.status_code == 200 + assert updated.json()["frame_size"] == [1600, 1200] + assert updated.json()["sources"]["display.orientation"] == "config" + saved = json.loads((data_dir / "config.json").read_text(encoding="utf-8")) + assert saved == {"display": {"orientation": "landscape"}} + + reset = client.post("/api/config/reset", json={"paths": ["display.orientation"]}) + assert reset.status_code == 200 + assert reset.json()["frame_size"] == [1200, 1600] + + assert client.post("/api/config/reset").status_code == 200 + + +def test_config_validation_error_is_sanitized(make_client: ClientFactory) -> None: + client = make_client() + response = client.put( + "/api/config", json={"tmdb": {"api_key": "do-not-echo", "language": "klingon"}} + ) + assert response.status_code == 422 + body = response.json() + assert body["detail"] == "Invalid configuration" + assert body["errors"][0]["loc"] == ["tmdb", "language"] + assert "do-not-echo" not in response.text + assert "klingon" not in response.text + + +def test_config_unknown_path_returns_400(make_client: ClientFactory) -> None: + client = make_client() + assert client.put("/api/config", json={"nope": {"x": 1}}).status_code == 400 + assert client.post("/api/config/reset", json={"paths": ["eink.nope"]}).status_code == 400 + + +def test_request_validation_error_does_not_echo_input(make_client: ClientFactory) -> None: + client = make_client() + response = client.put("/api/config", json={"immich": "secret-looking-value"}) + assert response.status_code == 422 + assert "secret-looking-value" not in response.text + + +def test_config_schema(make_client: ClientFactory) -> None: + schema = make_client().get("/api/config/schema").json() + assert set(schema["properties"]) == { + "immich", + "tmdb", + "fraimic", + "display", + "eink", + "scheduler", + } + + +def test_openapi_documents_api_key_scheme(make_client: ClientFactory) -> None: + spec = make_client().get("/openapi.json").json() + assert "APIKeyHeader" in spec["components"]["securitySchemes"] + assert spec["paths"]["/api/config"]["put"]["security"] == [{"APIKeyHeader": []}] + + +def test_index_redirects_to_docs(make_client: ClientFactory) -> None: + response = make_client().get("/", follow_redirects=False) + assert response.status_code == 307 + assert response.headers["location"] == "/docs" diff --git a/tests/test_auth.py b/tests/test_auth.py new file mode 100644 index 0000000..b0108c6 --- /dev/null +++ b/tests/test_auth.py @@ -0,0 +1,142 @@ +from __future__ import annotations + +import pytest + +from app.core.auth import extract_api_key, keys_match, requires_api_key, route_path +from tests.conftest import ClientFactory + +KEY = "s3cret-key" + + +@pytest.mark.parametrize( + ("method", "path", "public_images", "expected"), + [ + ("GET", "/", True, False), + ("GET", "/docs", True, False), + ("GET", "/openapi.json", True, False), + ("GET", "/api/health", True, False), + ("GET", "/api/status", True, False), + ("GET", "/api/config", True, True), + ("GET", "/api/config/", True, True), + ("GET", "/api/config/schema", True, True), + ("GET", "/api/configuration", True, False), + ("POST", "/api/refresh", True, True), + ("PUT", "/api/config", True, True), + ("PATCH", "/api/anything", True, True), + ("DELETE", "/api/anything", True, True), + ("OPTIONS", "/api/config", True, False), + ("GET", "/api/current.jpg", True, False), + ("GET", "/api/current.bin", True, False), + ("HEAD", "/api/current.jpg", True, False), + ("GET", "/api/current.jpg", False, True), + ("GET", "/api/current.bin", False, True), + ], +) +def test_requires_api_key_rules( + method: str, path: str, public_images: bool, expected: bool +) -> None: + assert requires_api_key(method, path, public_image_endpoints=public_images) is expected + + +@pytest.mark.parametrize( + ("path", "root_path", "expected"), + [ + ("/api/config", "", "/api/config"), + ("/api/config", "/fraimic", "/api/config"), + ("/fraimic/api/config", "/fraimic", "/api/config"), + ("/fraimic", "/fraimic", "/"), + ("/fraimicx/api/config", "/fraimic", "/fraimicx/api/config"), + ], +) +def test_route_path(path: str, root_path: str, expected: str) -> None: + assert route_path({"type": "http", "path": path, "root_path": root_path}) == expected + + +def test_extract_api_key_header_wins_over_query() -> None: + scope = { + "type": "http", + "headers": [(b"x-api-key", b" header-key ")], + "query_string": b"api_key=query-key", + } + assert extract_api_key(scope) == "header-key" + assert extract_api_key({"type": "http", "headers": [], "query_string": b"a=1&api_key=q"}) == "q" + assert extract_api_key({"type": "http", "headers": [], "query_string": b""}) is None + + +def test_keys_match() -> None: + assert keys_match(KEY, KEY) + assert not keys_match("wrong", KEY) + assert not keys_match(None, KEY) + assert not keys_match("", "") + + +def test_no_key_configured_everything_open(make_client: ClientFactory) -> None: + client = make_client() + assert client.get("/api/config").status_code == 200 + assert client.put("/api/config", json={"eink": {"contrast": 1.3}}).status_code == 200 + + +def test_protected_routes_require_key(make_client: ClientFactory) -> None: + client = make_client(app_api_key=KEY) + + denied = client.get("/api/config") + assert denied.status_code == 401 + assert denied.json() == {"detail": "Missing or invalid API key"} + assert denied.headers["www-authenticate"].startswith("APIKey") + + assert client.get("/api/config", headers={"X-API-Key": "wrong"}).status_code == 401 + assert client.get("/api/config", headers={"X-API-Key": KEY}).status_code == 200 + assert client.get("/api/config", params={"api_key": KEY}).status_code == 200 + assert client.put("/api/config", json={"eink": {"contrast": 1.3}}).status_code == 401 + assert ( + client.put( + "/api/config", json={"eink": {"contrast": 1.3}}, headers={"X-API-Key": KEY} + ).status_code + == 200 + ) + # A POST to an unknown route is still rejected before routing (no route discovery). + assert client.post("/api/does-not-exist").status_code == 401 + + +def test_public_routes_stay_open_with_key(make_client: ClientFactory) -> None: + client = make_client(app_api_key=KEY) + assert client.get("/api/health").status_code == 200 + assert client.get("/api/status").status_code == 200 + assert client.get("/openapi.json").status_code == 200 + assert client.get("/docs").status_code == 200 + + +@pytest.mark.parametrize(("public", "expected"), [(True, 404), (False, 401)]) +def test_image_endpoints_follow_public_flag( + make_client: ClientFactory, public: bool, expected: int +) -> None: + # The image routes arrive in a later milestone: 404 proves the request was let through. + client = make_client(app_api_key=KEY, public_image_endpoints=public) + assert client.get("/api/current.jpg").status_code == expected + assert client.get("/api/current.jpg", params={"api_key": KEY}).status_code == 404 + + +def test_cors_preflight_and_headers_on_401(make_client: ClientFactory) -> None: + client = make_client(app_api_key=KEY) + preflight = client.options( + "/api/config", + headers={ + "Origin": "https://ha.example", + "Access-Control-Request-Method": "PUT", + "Access-Control-Request-Headers": "X-API-Key", + }, + ) + assert preflight.status_code == 200 + assert preflight.headers["access-control-allow-origin"] == "*" + + denied = client.get("/api/config", headers={"Origin": "https://ha.example"}) + assert denied.status_code == 401 + assert denied.headers["access-control-allow-origin"] == "*" + + +def test_cors_restricted_origins(make_client: ClientFactory) -> None: + client = make_client(cors_origins="https://ha.example") + allowed = client.get("/api/health", headers={"Origin": "https://ha.example"}) + assert allowed.headers["access-control-allow-origin"] == "https://ha.example" + blocked = client.get("/api/health", headers={"Origin": "https://evil.example"}) + assert "access-control-allow-origin" not in blocked.headers diff --git a/tests/test_config_models.py b/tests/test_config_models.py new file mode 100644 index 0000000..e229990 --- /dev/null +++ b/tests/test_config_models.py @@ -0,0 +1,154 @@ +from __future__ import annotations + +from typing import Any + +import pytest +from pydantic import SecretStr, ValidationError + +from app.core.config_models import ( + MASK_PREFIX, + PANEL_SPECS, + FraimicConfig, + ImmichConfig, + RuntimeConfig, + SchedulerConfig, + TmdbConfig, + dump_config, + is_masked, + mask_secret, + secret_field_paths, +) + + +def test_defaults_follow_official_converter() -> None: + config = RuntimeConfig() + assert config.fraimic.panel == "133" + assert config.fraimic.upload_path == "/api/image" + assert config.fraimic.status_path == "/api/info" + assert config.eink.dither == "atkinson" + assert (config.eink.brightness, config.eink.contrast, config.eink.saturation) == ( + 1.1, + 1.2, + 1.2, + ) + assert config.eink.edge_filters is True + + +@pytest.mark.parametrize( + ("panel", "orientation", "expected"), + [ + ("133", "portrait", (1200, 1600)), + ("133", "landscape", (1600, 1200)), + ("315", "portrait", (1440, 2560)), + ("315", "landscape", (2560, 1440)), + ], +) +def test_frame_size(panel: str, orientation: str, expected: tuple[int, int]) -> None: + config = RuntimeConfig.model_validate( + {"fraimic": {"panel": panel}, "display": {"orientation": orientation}} + ) + assert config.frame_size == expected + + +def test_panel_specs_match_bin_sizes() -> None: + for spec in PANEL_SPECS.values(): + assert spec.width * spec.height // 2 <= spec.bin_size + assert PANEL_SPECS["133"].bin_size == 960_000 + assert PANEL_SPECS["315"].bin_size == 2_304_000 + + +@pytest.mark.parametrize( + ("host", "base_url"), + [ + ("fraimic.local", "http://fraimic.local"), + ("192.168.1.50", "http://192.168.1.50"), + ("https://frame.example/", "https://frame.example"), + ("", ""), + ], +) +def test_fraimic_host_normalization(host: str, base_url: str) -> None: + assert FraimicConfig(host=host).base_url == base_url + + +@pytest.mark.parametrize("host", ["ftp://frame", "http://user:pw@frame", "http://frame/?x=1"]) +def test_fraimic_host_rejects_bad_values(host: str) -> None: + with pytest.raises(ValidationError): + FraimicConfig(host=host) + + +@pytest.mark.parametrize("path", ["api/info", "http://x/api", "/api?x=1"]) +def test_fraimic_paths_must_be_absolute(path: str) -> None: + with pytest.raises(ValidationError): + FraimicConfig(status_path=path) + + +def test_immich_url_and_persons_are_cleaned() -> None: + config = ImmichConfig(url=" http://immich.local:2283/ ", persons=[" Alice", "Bob", "Alice", ""]) + assert config.url == "http://immich.local:2283" + assert config.persons == ["Alice", "Bob"] + + +@pytest.mark.parametrize("url", ["immich.local", "file:///etc/passwd", "http://u:p@immich"]) +def test_immich_url_rejects_bad_values(url: str) -> None: + with pytest.raises(ValidationError): + ImmichConfig(url=url) + + +@pytest.mark.parametrize("language", ["fr-FR", "en-US", "de-DE"]) +def test_tmdb_language_accepts_locale_codes(language: str) -> None: + assert TmdbConfig(language=language).language == language + + +@pytest.mark.parametrize("language", ["fr", "FR-fr", "english"]) +def test_tmdb_language_rejects_other_formats(language: str) -> None: + with pytest.raises(ValidationError): + TmdbConfig(language=language) + + +def test_scheduler_quiet_hours_must_be_paired() -> None: + with pytest.raises(ValidationError): + SchedulerConfig(quiet_hours_start="22:00") + config = SchedulerConfig(quiet_hours_start="22:00", quiet_hours_end="07:30") + assert (config.quiet_hours_start, config.quiet_hours_end) == ("22:00", "07:30") + assert SchedulerConfig(quiet_hours_start="", quiet_hours_end=" ").quiet_hours_start is None + + +@pytest.mark.parametrize("value", ["24:00", "7:30", "12:60"]) +def test_scheduler_rejects_bad_times(value: str) -> None: + with pytest.raises(ValidationError): + SchedulerConfig(quiet_hours_start=value, quiet_hours_end="06:00") + + +def test_scheduler_timezone_validated() -> None: + assert SchedulerConfig(timezone="Europe/Paris").timezone == "Europe/Paris" + with pytest.raises(ValidationError): + SchedulerConfig(timezone="Mars/Olympus") + + +def test_unknown_fields_are_rejected() -> None: + payload: dict[str, Any] = {"immich": {"nope": 1}} + with pytest.raises(ValidationError): + RuntimeConfig.model_validate(payload) + + +def test_secret_masking() -> None: + assert mask_secret("") == "" + assert mask_secret("short") == MASK_PREFIX + assert mask_secret("0123456789abcdefWXYZ") == MASK_PREFIX + "WXYZ" + assert is_masked(mask_secret("anything")) + assert not is_masked("plain") + assert not is_masked(None) + + +def test_dump_config_reveals_or_masks_secrets() -> None: + config = RuntimeConfig( + immich=ImmichConfig(api_key=SecretStr("immich-secret-key-1234")), + tmdb=TmdbConfig(api_key=SecretStr("tmdb")), + ) + assert set(secret_field_paths()) == {("immich", "api_key"), ("tmdb", "api_key")} + revealed = dump_config(config, reveal_secrets=True) + masked = dump_config(config, reveal_secrets=False) + assert revealed["immich"]["api_key"] == "immich-secret-key-1234" + assert masked["immich"]["api_key"] == MASK_PREFIX + "1234" + assert masked["tmdb"]["api_key"] == MASK_PREFIX + assert RuntimeConfig.model_validate(revealed) == config diff --git a/tests/test_config_store.py b/tests/test_config_store.py new file mode 100644 index 0000000..36bcc97 --- /dev/null +++ b/tests/test_config_store.py @@ -0,0 +1,166 @@ +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from app.core.config_models import MASK_PREFIX, RuntimeConfig +from app.core.config_store import ConfigStore, ConfigValidationError, UnknownConfigPathError + + +@pytest.fixture +def config_path(tmp_path: Path) -> Path: + return tmp_path / "config.json" + + +def make_store(path: Path, seed: dict[str, dict[str, object]] | None = None) -> ConfigStore: + store = ConfigStore(path, seed or {}) + store.load() + return store + + +def saved(path: Path) -> object: + return json.loads(path.read_text(encoding="utf-8")) + + +async def test_precedence_default_env_config_and_reset(config_path: Path) -> None: + store = make_store(config_path, {"fraimic": {"host": "env-frame.lan"}}) + assert store.config.fraimic.host == "env-frame.lan" + assert store.sources()["fraimic.host"] == "env" + assert store.sources()["fraimic.panel"] == "default" + + await store.update({"fraimic": {"host": "ui-frame.lan"}}) + assert store.config.fraimic.host == "ui-frame.lan" + assert store.sources()["fraimic.host"] == "config" + assert saved(config_path) == {"fraimic": {"host": "ui-frame.lan"}} + + # A restart keeps the saved value over the environment. + restarted = make_store(config_path, {"fraimic": {"host": "env-frame.lan"}}) + assert restarted.config.fraimic.host == "ui-frame.lan" + + await restarted.reset(["fraimic.host"]) + assert restarted.config.fraimic.host == "env-frame.lan" + assert restarted.sources()["fraimic.host"] == "env" + assert saved(config_path) == {} + + +async def test_overrides_are_sparse_and_canonical(config_path: Path) -> None: + store = make_store(config_path) + await store.update({"immich": {"url": "http://immich.local:2283/", "persons": ["A", " A "]}}) + assert saved(config_path) == {"immich": {"url": "http://immich.local:2283", "persons": ["A"]}} + + +async def test_unchanged_values_do_not_freeze_env_fallback(config_path: Path) -> None: + store = make_store(config_path, {"fraimic": {"host": "env-frame.lan"}}) + full_form = store.public_view()["config"] + full_form["eink"]["contrast"] = 1.5 + await store.update(full_form) + assert saved(config_path) == {"eink": {"contrast": 1.5}} + assert store.sources()["fraimic.host"] == "env" + + +async def test_masked_secret_round_trip_keeps_value(config_path: Path) -> None: + store = make_store(config_path, {"immich": {"api_key": "env-immich-secret-0001"}}) + view = store.public_view() + assert view["config"]["immich"]["api_key"] == MASK_PREFIX + "0001" + + await store.update(view["config"]) + assert store.config.immich.api_key.get_secret_value() == "env-immich-secret-0001" + assert not config_path.exists() or saved(config_path) == {} + + await store.update({"immich": {"api_key": "new-key"}}) + assert store.config.immich.api_key.get_secret_value() == "new-key" + assert saved(config_path) == {"immich": {"api_key": "new-key"}} + assert "new-key" in store.secret_values() + + +async def test_invalid_update_is_not_persisted(config_path: Path) -> None: + store = make_store(config_path) + await store.update({"eink": {"contrast": 1.4}}) + with pytest.raises(ConfigValidationError) as info: + await store.update({"eink": {"contrast": 99}, "tmdb": {"api_key": "leak-me"}}) + assert info.value.errors[0]["loc"] == ["eink", "contrast"] + assert "leak-me" not in json.dumps(info.value.errors) + assert "99" not in json.dumps(info.value.errors) + assert store.config.eink.contrast == 1.4 + assert saved(config_path) == {"eink": {"contrast": 1.4}} + + +@pytest.mark.parametrize( + "patch", + [{"nope": {"x": 1}}, {"immich": {"nope": 1}}, {"immich": "not-a-section"}], +) +async def test_unknown_paths_rejected(config_path: Path, patch: dict[str, object]) -> None: + store = make_store(config_path) + with pytest.raises(UnknownConfigPathError): + await store.update(patch) + + +async def test_reset_section_and_all(config_path: Path) -> None: + store = make_store(config_path) + await store.update( + {"eink": {"contrast": 1.5, "saturation": 1.0}, "tmdb": {"language": "fr-FR"}} + ) + await store.reset(["eink"]) + assert store.overrides == {"tmdb": {"language": "fr-FR"}} + await store.reset() + assert store.overrides == {} + assert store.config == RuntimeConfig() + with pytest.raises(UnknownConfigPathError): + await store.reset(["eink.nope"]) + + +async def test_reset_that_breaks_validation_is_refused(config_path: Path) -> None: + store = make_store(config_path) + await store.update({"scheduler": {"quiet_hours_start": "22:00", "quiet_hours_end": "07:00"}}) + with pytest.raises(ConfigValidationError): + await store.reset(["scheduler.quiet_hours_start"]) + assert store.config.scheduler.quiet_hours_start == "22:00" + + +def test_invalid_environment_fails_fast(config_path: Path) -> None: + with pytest.raises(ConfigValidationError, match=r"fraimic\.panel"): + ConfigStore(config_path, {"fraimic": {"panel": "999"}}) + + +def test_corrupt_file_is_moved_aside(config_path: Path) -> None: + config_path.write_text("{not json", encoding="utf-8") + store = make_store(config_path) + assert store.config == RuntimeConfig() + assert not config_path.exists() + assert len(list(config_path.parent.glob("config.json.corrupt-*"))) == 1 + + +def test_stale_and_invalid_saved_values_are_ignored(config_path: Path) -> None: + config_path.write_text( + json.dumps( + { + "legacy": {"x": 1}, + "immich": {"removed_field": True, "album": "Family"}, + "eink": {"contrast": "very high", "saturation": 1.3}, + "scheduler": {"quiet_hours_start": "22:00"}, + } + ), + encoding="utf-8", + ) + store = make_store(config_path) + assert store.overrides == {"immich": {"album": "Family"}, "eink": {"saturation": 1.3}} + assert store.config.eink.contrast == 1.2 + + +async def test_listeners_are_notified(config_path: Path) -> None: + store = make_store(config_path) + seen: list[float] = [] + + async def listener(config: RuntimeConfig) -> None: + seen.append(config.eink.contrast) + + async def broken(_: RuntimeConfig) -> None: + raise RuntimeError("boom") + + store.add_listener(broken) + store.add_listener(listener) + await store.update({"eink": {"contrast": 1.7}}) + await store.reset() + assert seen == [1.7, 1.2] diff --git a/tests/test_history_store.py b/tests/test_history_store.py new file mode 100644 index 0000000..98c46bd --- /dev/null +++ b/tests/test_history_store.py @@ -0,0 +1,79 @@ +from __future__ import annotations + +import json +from datetime import UTC, datetime, timedelta +from pathlib import Path + +import pytest + +from app.core.history_store import HistoryStore + + +@pytest.fixture +def history_path(tmp_path: Path) -> Path: + return tmp_path / "history.json" + + +async def test_record_and_recent_ids(history_path: Path) -> None: + store = HistoryStore(history_path) + store.load() + now = datetime.now(UTC) + await store.record("a1", "immich", now - timedelta(days=40)) + await store.record("a2", "immich", now - timedelta(days=2)) + await store.record("p1", "media", now) + + assert store.recent_ids("immich", 30) == {"a2"} + assert store.recent_ids("immich", 60) == {"a1", "a2"} + assert store.recent_ids("immich", 0) == set() + assert [entry.asset_id for entry in store.entries()] == ["p1", "a2", "a1"] + assert [entry.asset_id for entry in store.entries(limit=1)] == ["p1"] + + +async def test_persistence_round_trip(history_path: Path) -> None: + store = HistoryStore(history_path) + store.load() + await store.record("a1", "immich") + + payload = json.loads(history_path.read_text(encoding="utf-8")) + assert payload["version"] == 1 + assert payload["entries"][0]["asset_id"] == "a1" + + reloaded = HistoryStore(history_path) + reloaded.load() + assert reloaded.recent_ids("immich", 1) == {"a1"} + + +async def test_retention_by_age_and_count(history_path: Path) -> None: + store = HistoryStore(history_path, max_age_days=10, max_entries=3) + store.load() + now = datetime.now(UTC) + await store.record("old", "immich", now - timedelta(days=11)) + for index in range(4): + await store.record(f"n{index}", "immich", now - timedelta(minutes=10 - index)) + assert [entry.asset_id for entry in store.entries()] == ["n3", "n2", "n1"] + + +def test_malformed_entries_are_skipped(history_path: Path) -> None: + now = datetime.now(UTC).isoformat() + history_path.write_text( + json.dumps( + { + "version": 1, + "entries": [ + {"asset_id": "ok", "source": "immich", "shown_at": now}, + {"asset_id": "", "source": "immich", "shown_at": now}, + {"asset_id": "naive", "source": "immich", "shown_at": "2026-01-01T00:00:00"}, + "garbage", + ], + } + ), + encoding="utf-8", + ) + store = HistoryStore(history_path) + store.load() + assert [entry.asset_id for entry in store.entries()] == ["ok"] + + +def test_invalid_limits_rejected(history_path: Path) -> None: + with pytest.raises(ValueError): + HistoryStore(history_path, max_entries=0) diff --git a/tests/test_logging.py b/tests/test_logging.py new file mode 100644 index 0000000..ab0c87c --- /dev/null +++ b/tests/test_logging.py @@ -0,0 +1,63 @@ +from __future__ import annotations + +import logging + +import pytest + +from app.core.logging_config import REDACTED, SecretMaskingFilter, masking_filter +from tests.conftest import ClientFactory + + +@pytest.fixture +def masking() -> SecretMaskingFilter: + masking = SecretMaskingFilter() + masking.set_secrets(["immich-secret", "tmdb-secret", "", "abc"]) + return masking + + +def _record(msg: str, args: object = None) -> logging.LogRecord: + return logging.LogRecord("test", logging.INFO, __file__, 1, msg, args, None) + + +def test_masks_secrets_in_message(masking: SecretMaskingFilter) -> None: + record = _record("Calling Immich with immich-secret and tmdb-secret") + masking.filter(record) + assert record.getMessage() == f"Calling Immich with {REDACTED} and {REDACTED}" + + +def test_masks_uvicorn_access_log_arguments(masking: SecretMaskingFilter) -> None: + record = _record( + '%s - "%s %s HTTP/%s" %d', + ("10.0.0.2:5000", "PUT", "/api/config?api_key=supersecret&x=1", "1.1", 200), + ) + masking.filter(record) + message = record.getMessage() + assert "supersecret" not in message + assert f"api_key={REDACTED}&x=1" in message + assert message.endswith(" 200") + + +def test_masks_dict_arguments(masking: SecretMaskingFilter) -> None: + record = _record("key=%(key)s", ({"key": "tmdb-secret"},)) + masking.filter(record) + assert record.getMessage() == f"key={REDACTED}" + + +def test_short_secrets_are_ignored(masking: SecretMaskingFilter) -> None: + assert masking.mask("abc") == "abc" + + +def test_secrets_can_be_replaced(masking: SecretMaskingFilter) -> None: + masking.set_secrets(["new-secret-value"]) + assert masking.mask("immich-secret new-secret-value") == f"immich-secret {REDACTED}" + + +def test_app_registers_env_and_saved_secrets(make_client: ClientFactory) -> None: + client = make_client(app_api_key="app-level-key") + response = client.put( + "/api/config", + json={"tmdb": {"api_key": "saved-tmdb-key"}}, + headers={"X-API-Key": "app-level-key"}, + ) + assert response.status_code == 200 + assert masking_filter.mask("app-level-key saved-tmdb-key") == f"{REDACTED} {REDACTED}" diff --git a/tests/test_root_path.py b/tests/test_root_path.py new file mode 100644 index 0000000..d6de1e4 --- /dev/null +++ b/tests/test_root_path.py @@ -0,0 +1,67 @@ +"""Reverse proxy sub-path support (``ROOT_PATH``).""" + +from __future__ import annotations + +from typing import Any + +import pytest + +from tests.conftest import ClientFactory + +KEY = "proxy-key" + + +def test_openapi_advertises_root_path(make_client: ClientFactory) -> None: + client = make_client(root_path="fraimic/") + spec = client.get("/openapi.json").json() + assert spec["servers"] == [{"url": "/fraimic"}] + + +def test_docs_reference_prefixed_openapi(make_client: ClientFactory) -> None: + client = make_client(root_path="/fraimic") + assert "/fraimic/openapi.json" in client.get("/docs").text + + +def test_routes_work_when_proxy_strips_prefix(make_client: ClientFactory) -> None: + client = make_client(root_path="/fraimic") + assert client.get("/api/health").status_code == 200 + + +def test_routes_work_when_proxy_keeps_prefix(make_client: ClientFactory) -> None: + client = make_client(root_path="/fraimic") + assert client.get("/fraimic/api/health").status_code == 200 + + +def test_auth_applies_under_prefixed_paths(make_client: ClientFactory) -> None: + client = make_client(root_path="/fraimic", app_api_key=KEY) + assert client.get("/fraimic/api/config").status_code == 401 + assert client.get("/fraimic/api/config", headers={"X-API-Key": KEY}).status_code == 200 + assert client.get("/fraimic/api/health").status_code == 200 + + +def test_index_redirect_honors_root_path(make_client: ClientFactory) -> None: + client = make_client(root_path="/fraimic") + response = client.get("/", follow_redirects=False) + assert response.headers["location"] == "/fraimic/docs" + + +def test_runner_trusts_forwarded_headers(monkeypatch: pytest.MonkeyPatch) -> None: + """``python -m app`` enables X-Forwarded-Proto/For handling for the configured proxies.""" + from app import __main__ as entry + from app.core import settings as settings_module + + captured: dict[str, Any] = {} + monkeypatch.setenv("FORWARDED_ALLOW_IPS", "172.16.0.0/12") + monkeypatch.setenv("PORT", "9000") + monkeypatch.setattr(entry.uvicorn, "run", lambda *args, **kwargs: captured.update(kwargs)) + settings_module.get_env_settings.cache_clear() + try: + entry.main() + finally: + settings_module.get_env_settings.cache_clear() + + assert captured["factory"] is True + assert captured["proxy_headers"] is True + assert captured["forwarded_allow_ips"] == "172.16.0.0/12" + assert captured["port"] == 9000 + assert captured["log_config"] is None diff --git a/tests/test_security.py b/tests/test_security.py new file mode 100644 index 0000000..9e4e4d3 --- /dev/null +++ b/tests/test_security.py @@ -0,0 +1,161 @@ +from __future__ import annotations + +import io +import socket +from collections.abc import AsyncIterator +from typing import Any + +import pytest +from PIL import Image + +from app.core.security import ( + InvalidImageError, + PayloadTooLargeError, + UnsafeURLError, + URLPolicy, + read_limited, + read_upload, + validate_external_url, + verify_image_bytes, +) + + +def fake_resolver(monkeypatch: pytest.MonkeyPatch, mapping: dict[str, list[str]]) -> None: + async def _getaddrinfo( + self: Any, host: str, port: int, **_: Any + ) -> list[tuple[Any, Any, Any, str, tuple[str, int]]]: + if host not in mapping: + raise socket.gaierror("not found") + return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", (ip, port)) for ip in mapping[host]] + + import asyncio + + monkeypatch.setattr(asyncio.BaseEventLoop, "getaddrinfo", _getaddrinfo) + + +OPEN = URLPolicy() +STRICT = URLPolicy.from_entries(True, []) + + +@pytest.mark.parametrize( + "url", + [ + "ftp://example.com/a.jpg", + "file:///etc/passwd", + "javascript:alert(1)", + "http://", + "http://user:pass@example.com/a.jpg", + "http://example.com:99999/", + ], +) +async def test_rejects_malformed_or_forbidden_urls(url: str) -> None: + with pytest.raises(UnsafeURLError): + await validate_external_url(url, OPEN) + + +async def test_private_addresses_allowed_by_default() -> None: + url = "http://192.168.1.10:8123/local/poster.jpg" + assert await validate_external_url(f" {url} ", OPEN) == url + + +@pytest.mark.parametrize( + "url", + [ + "http://127.0.0.1/", + "http://10.0.0.5/", + "http://169.254.169.254/latest/meta-data", + "http://[::1]/", + "http://[::ffff:192.168.0.1]/", + "http://0.0.0.0/", + "http://224.0.0.1/", + ], +) +async def test_strict_policy_blocks_non_public_ips(url: str) -> None: + with pytest.raises(UnsafeURLError): + await validate_external_url(url, STRICT) + + +async def test_strict_policy_checks_resolved_addresses(monkeypatch: pytest.MonkeyPatch) -> None: + fake_resolver( + monkeypatch, + {"public.example": ["93.184.216.34"], "sneaky.example": ["93.184.216.34", "10.1.2.3"]}, + ) + assert await validate_external_url("https://public.example/a.jpg", STRICT) + with pytest.raises(UnsafeURLError, match="blocked"): + await validate_external_url("https://sneaky.example/a.jpg", STRICT) + with pytest.raises(UnsafeURLError, match="resolve"): + await validate_external_url("https://missing.example/a.jpg", STRICT) + + +async def test_allowlist_networks_and_hostnames(monkeypatch: pytest.MonkeyPatch) -> None: + fake_resolver(monkeypatch, {"ha.lan": ["192.168.1.20"], "nas.lan": ["192.168.2.5"]}) + policy = URLPolicy.from_entries(True, ["192.168.1.0/24", "Immich.LAN", "", " "]) + assert policy.hostnames == frozenset({"immich.lan"}) + assert await validate_external_url("http://ha.lan:8123/x.jpg", policy) + assert await validate_external_url("http://immich.lan/x.jpg", policy) + with pytest.raises(UnsafeURLError): + await validate_external_url("http://nas.lan/x.jpg", policy) + + +async def _stream(*chunks: bytes) -> AsyncIterator[bytes]: + for chunk in chunks: + yield chunk + + +async def test_read_limited() -> None: + assert await read_limited(_stream(b"ab", b"cd"), 4) == b"abcd" + with pytest.raises(PayloadTooLargeError): + await read_limited(_stream(b"ab", b"cde"), 4) + with pytest.raises(PayloadTooLargeError): + await read_limited(_stream(), 4, declared_length=5) + + +class FakeUpload: + def __init__(self, data: bytes) -> None: + self._buffer = io.BytesIO(data) + + async def read(self, size: int = -1) -> bytes: + return self._buffer.read(size) + + +async def test_read_upload_enforces_limit() -> None: + payload = b"x" * (200 * 1024) + assert await read_upload(FakeUpload(payload), len(payload)) == payload + with pytest.raises(PayloadTooLargeError): + await read_upload(FakeUpload(payload), len(payload) - 1) + + +def _image_bytes(fmt: str, size: tuple[int, int] = (8, 6)) -> bytes: + buffer = io.BytesIO() + Image.new("RGB", size, (200, 30, 30)).save(buffer, format=fmt) + return buffer.getvalue() + + +@pytest.mark.parametrize("fmt", ["PNG", "JPEG", "WEBP", "GIF", "BMP"]) +def test_verify_image_accepts_supported_formats(fmt: str) -> None: + assert verify_image_bytes(_image_bytes(fmt)) == fmt + + +@pytest.mark.parametrize( + "data", + [b"", b"GIF89a-not-really", b"hello", b"%PDF-1.7\n", b"\x89PNG\r\n\x1a\n"], +) +def test_verify_image_rejects_non_images(data: bytes) -> None: + with pytest.raises(InvalidImageError): + verify_image_bytes(data) + + +def test_verify_image_rejects_truncated_png() -> None: + data = _image_bytes("PNG", (64, 64)) + with pytest.raises(InvalidImageError): + verify_image_bytes(data[: len(data) // 2]) + + +def test_verify_image_rejects_unsupported_format() -> None: + with pytest.raises(InvalidImageError, match="Unsupported"): + verify_image_bytes(_image_bytes("ICO", (16, 16))) + + +def test_verify_image_enforces_pixel_limit() -> None: + with pytest.raises(InvalidImageError, match="too large"): + verify_image_bytes(_image_bytes("PNG", (100, 100)), max_pixels=9_999) diff --git a/tests/test_settings.py b/tests/test_settings.py new file mode 100644 index 0000000..38a59f7 --- /dev/null +++ b/tests/test_settings.py @@ -0,0 +1,84 @@ +from __future__ import annotations + +from pathlib import Path + +import pytest +from pydantic import ValidationError + +from app.core.settings import EnvSettings +from tests.conftest import SettingsFactory + + +def test_defaults(make_settings: SettingsFactory, data_dir: Path) -> None: + settings = make_settings() + assert settings.data_dir == data_dir + assert settings.port == 8000 + assert settings.auth_enabled is False + assert settings.public_image_endpoints is True + assert settings.root_path == "" + assert settings.cors_origin_list == ["*"] + assert settings.max_upload_bytes == 20 * 1024 * 1024 + assert settings.config_path == data_dir / "config.json" + assert settings.history_path == data_dir / "history.json" + assert settings.cache_dir == data_dir / "cache" + assert settings.runtime_seed() == {} + assert settings.secret_values() == [] + + +@pytest.mark.parametrize( + ("raw", "expected"), + [("", ""), ("/", ""), ("fraimic", "/fraimic"), ("/fraimic/", "/fraimic"), (" /a/b ", "/a/b")], +) +def test_root_path_normalization(make_settings: SettingsFactory, raw: str, expected: str) -> None: + assert make_settings(root_path=raw).root_path == expected + + +def test_reads_environment(monkeypatch: pytest.MonkeyPatch, data_dir: Path) -> None: + monkeypatch.setenv("DATA_DIR", str(data_dir)) + monkeypatch.setenv("APP_API_KEY", " topsecret ") + monkeypatch.setenv("PUBLIC_IMAGE_ENDPOINTS", "false") + monkeypatch.setenv("CORS_ORIGINS", "https://a.example, https://b.example,") + monkeypatch.setenv("URL_ALLOWLIST", "10.0.0.0/8, immich.lan") + monkeypatch.setenv("LOG_LEVEL", "debug") + monkeypatch.setenv("IMMICH_URL", "http://immich.local:2283") + monkeypatch.setenv("IMMICH_API_KEY", "immich-key") + monkeypatch.setenv("TMDB_API_KEY", "") + monkeypatch.setenv("FRAIMIC_PANEL", "315") + monkeypatch.setenv("SCHEDULER_ENABLED", "true") + monkeypatch.setenv("REFRESH_INTERVAL_HOURS", "3") + monkeypatch.setenv("TZ", "Europe/Paris") + + settings = EnvSettings(_env_file=None) + + assert settings.api_key == "topsecret" + assert settings.auth_enabled is True + assert settings.public_image_endpoints is False + assert settings.cors_origin_list == ["https://a.example", "https://b.example"] + assert settings.url_allowlist_entries == ["10.0.0.0/8", "immich.lan"] + assert settings.log_level == "DEBUG" + assert settings.tmdb_api_key is None + assert settings.runtime_seed() == { + "immich": {"url": "http://immich.local:2283", "api_key": "immich-key"}, + "fraimic": {"panel": "315"}, + "scheduler": {"enabled": True, "interval_hours": 3.0, "timezone": "Europe/Paris"}, + } + assert sorted(settings.secret_values()) == ["immich-key", "topsecret"] + + +def test_reads_dotenv_file(tmp_path: Path) -> None: + env_file = tmp_path / ".env" + env_file.write_text("APP_API_KEY=from-file\nFRAIMIC_HOST=frame.lan\n", encoding="utf-8") + settings = EnvSettings(_env_file=env_file, data_dir=tmp_path) + assert settings.api_key == "from-file" + assert settings.runtime_seed() == {"fraimic": {"host": "frame.lan"}} + + +def test_invalid_port_rejected(make_settings: SettingsFactory) -> None: + with pytest.raises(ValidationError): + make_settings(port=70000) + + +def test_settings_are_frozen(make_settings: SettingsFactory) -> None: + settings = make_settings() + with pytest.raises(ValidationError): + settings.port = 1234 From 252a7123a48f01ba8f3c9f19fd6c26acf3a45e6a Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sat, 14 Nov 2026 17:16:18 +0100 Subject: [PATCH 08/86] chore(docker): add Dockerfile, docker-compose and .env.example python:3.11-slim image running as non-root uid 1000 with a /data volume, dependency layer caching and a /api/health HEALTHCHECK. Compose maps ./data, reads an optional .env and supports PUID/PGID and HOST_PORT. Co-Authored-By: Claude Opus 5.5 --- .dockerignore | 26 +++++++++++++++++ .env.example | 72 ++++++++++++++++++++++++++++++++++++++++++++++ Dockerfile | 42 +++++++++++++++++++++++++++ docker-compose.yml | 16 +++++++++++ 4 files changed, 156 insertions(+) create mode 100644 .dockerignore create mode 100644 .env.example create mode 100644 Dockerfile create mode 100644 docker-compose.yml diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..39a89d9 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,26 @@ +.git +.github +.gitignore +.gitattributes +.dockerignore +.env +.env.* +.venv +venv +data +fraimic-docs +tests +**/__pycache__ +**/*.py[cod] +*.egg-info +build +dist +.pytest_cache +.ruff_cache +.mypy_cache +.coverage +.idea +.vscode +docker-compose.yml +Dockerfile +CLAUDE.md diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..d417e9d --- /dev/null +++ b/.env.example @@ -0,0 +1,72 @@ +# ============================================================================= +# Smart Frame Engine - environment configuration +# Copy to `.env` and adjust. Never commit your real `.env`. +# +# Runtime settings (Immich, TMDB, Fraimic, display, eInk, scheduler) can also be +# edited from the web UI / `PUT /api/config`. Values saved there are stored in +# /data/config.json and take precedence over this file. Use +# `POST /api/config/reset` to fall back to the values below again. +# ============================================================================= + +# --- Docker Compose (host side) ---------------------------------------------- +# Host port published by docker-compose.yml. +HOST_PORT=8000 +# Host user/group owning ./data (run `id -u` / `id -g`). +PUID=1000 +PGID=1000 + +# --- Security ---------------------------------------------------------------- +# Leave empty for pure LAN usage (no authentication). +# When set, all POST/PUT/DELETE routes and /api/config require the +# `X-API-Key` header (or `?api_key=`). Generate one with: openssl rand -hex 32 +APP_API_KEY= +# Keep /api/current.jpg and /api/current.bin readable without a key +# (needed by Home Assistant Generic Camera). Set to false to require ?api_key=. +PUBLIC_IMAGE_ENDPOINTS=true +# Max size of uploaded/downloaded images, in MB. +MAX_UPLOAD_MB=20 +# Reject external image URLs resolving to private/loopback/link-local addresses. +BLOCK_PRIVATE_URLS=false +# Comma-separated hosts or CIDRs allowed even when BLOCK_PRIVATE_URLS=true, +# e.g. homeassistant.local,192.168.1.0/24 +URL_ALLOWLIST= + +# --- Reverse proxy ----------------------------------------------------------- +# Sub-path when served behind a proxy, e.g. /fraimic (empty = served at /). +ROOT_PATH= +# Comma-separated allowed CORS origins (* = any). +CORS_ORIGINS=* +# Proxy IPs trusted for X-Forwarded-Proto / X-Forwarded-For (* = any). +FORWARDED_ALLOW_IPS=* + +# --- Server ------------------------------------------------------------------ +LOG_LEVEL=INFO +# Container-internal port; change HOST_PORT instead when using Docker Compose. +# PORT=8000 +# DATA_DIR=/data + +# --- Immich (runtime default) ------------------------------------------------ +IMMICH_URL=http://immich.local:2283 +IMMICH_API_KEY= + +# --- TMDB movie & TV posters (runtime default) ------------------------------- +TMDB_API_KEY= +# Locale such as en-US or fr-FR. +TMDB_LANGUAGE=en-US + +# --- Fraimic frame (runtime default) ----------------------------------------- +# Hostname, IP or base URL of the frame. +FRAIMIC_HOST=fraimic.local +# continuous = mains powered, always reachable +# deepsleep = battery powered, uploads are queued until the frame wakes up +FRAIMIC_POWER_MODE=continuous +# 133 = 13.3" (1200x1600), 315 = 31.5" (1440x2560) +FRAIMIC_PANEL=133 +# portrait | landscape +ORIENTATION=portrait + +# --- Scheduler (runtime default) --------------------------------------------- +SCHEDULER_ENABLED=false +REFRESH_INTERVAL_HOURS=6 +# IANA timezone used for quiet hours, e.g. Europe/Paris +TZ=UTC diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..bfade39 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,42 @@ +# syntax=docker/dockerfile:1 +FROM python:3.11-slim + +LABEL org.opencontainers.image.title="Smart Frame Engine" \ + org.opencontainers.image.description="Immich / TMDB images optimized for color eInk and pushed to a Fraimic frame" \ + org.opencontainers.image.source="https://github.com/ant1fr/Smart-Frame-Engine" \ + org.opencontainers.image.licenses="MIT" + +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 \ + PIP_NO_CACHE_DIR=1 \ + PIP_DISABLE_PIP_VERSION_CHECK=1 \ + DATA_DIR=/data \ + PORT=8000 + +WORKDIR /app + +RUN groupadd --system --gid 1000 app \ + && useradd --system --uid 1000 --gid app --home-dir /app --no-create-home \ + --shell /usr/sbin/nologin app \ + && mkdir -p /data \ + && chown app:app /data + +# Install dependencies first so code changes do not invalidate this layer. +COPY pyproject.toml ./ +RUN python -c "import tomllib; print('\n'.join(tomllib.load(open('pyproject.toml', 'rb'))['project']['dependencies']))" \ + > /tmp/requirements.txt \ + && pip install -r /tmp/requirements.txt \ + && rm /tmp/requirements.txt + +COPY README.md LICENSE ./ +COPY app ./app +RUN pip install --no-deps . + +USER app +VOLUME ["/data"] +EXPOSE 8000 + +HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \ + CMD ["python", "-c", "import os, urllib.request; urllib.request.urlopen('http://127.0.0.1:%s/api/health' % os.environ.get('PORT', '8000'), timeout=4)"] + +CMD ["python", "-m", "app"] diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..b3cff14 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,16 @@ +services: + smart-frame-engine: + # Published multi-arch image; `build` is used as a fallback (or with `--build`). + image: ghcr.io/ant1fr/smart-frame-engine:latest + build: . + container_name: smart-frame-engine + restart: unless-stopped + # Run as the owner of ./data on the host (defaults to 1000:1000). + user: "${PUID:-1000}:${PGID:-1000}" + env_file: + - path: .env + required: false + ports: + - "${HOST_PORT:-8000}:8000" + volumes: + - ./data:/data From 4d5940dd9f35825f6ab673313d23193209d19681 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sat, 14 Nov 2026 17:16:18 +0100 Subject: [PATCH 09/86] chore(ci): add lint/test workflow and multi-arch release workflow CI runs ruff, mypy and pytest on Python 3.11/3.12 plus a Docker build and smoke test for pushes and PRs targeting develop and main. Tags v* build and push linux/amd64 and linux/arm64 images to GHCR. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 86 +++++++++++++++++++++++++++++++++++ .github/workflows/release.yml | 61 +++++++++++++++++++++++++ 2 files changed, 147 insertions(+) create mode 100644 .github/workflows/ci.yml create mode 100644 .github/workflows/release.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..3ba6911 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,86 @@ +name: CI + +on: + push: + branches: [develop, main] + pull_request: + branches: [develop, main] + +permissions: + contents: read + +concurrency: + group: ci-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + lint-test: + name: Lint & test (Python ${{ matrix.python-version }}) + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + python-version: ["3.11", "3.12"] + steps: + - name: Checkout + uses: actions/checkout@v7 + + - name: Set up Python + uses: actions/setup-python@v7 + with: + python-version: ${{ matrix.python-version }} + cache: pip + cache-dependency-path: pyproject.toml + + - name: Install + run: | + python -m pip install --upgrade pip + pip install -e ".[dev]" + + - name: Ruff (lint) + run: ruff check . + + - name: Ruff (format) + run: ruff format --check . + + - name: Mypy + run: mypy app + + - name: Pytest + run: pytest + + docker-build: + name: Docker build & smoke test + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v7 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v4 + + - name: Build image + uses: docker/build-push-action@v7 + with: + context: . + push: false + load: true + tags: smart-frame-engine:ci + cache-from: type=gha + cache-to: type=gha,mode=max + + - name: Smoke test + run: | + docker run -d --name sfe -p 8000:8000 -e APP_API_KEY=ci-key smart-frame-engine:ci + for i in $(seq 1 30); do + if curl -fsS http://127.0.0.1:8000/api/health; then break; fi + sleep 1 + done + echo + test "$(curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:8000/api/config)" = "401" + test "$(curl -s -o /dev/null -w '%{http_code}' -H 'X-API-Key: ci-key' http://127.0.0.1:8000/api/config)" = "200" + test "$(docker exec sfe id -u)" = "1000" + + - name: Container logs + if: always() + run: docker logs sfe || true diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..49e35ce --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,61 @@ +name: Release + +on: + push: + tags: ["v*"] + +permissions: + contents: read + packages: write + +concurrency: + group: release-${{ github.ref }} + cancel-in-progress: false + +jobs: + docker: + name: Build & push multi-arch image + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v7 + + - name: Compute image name (registry paths must be lowercase) + run: echo "IMAGE=ghcr.io/${GITHUB_REPOSITORY,,}" >> "$GITHUB_ENV" + + - name: Set up QEMU + uses: docker/setup-qemu-action@v4 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v4 + + - name: Log in to GHCR + uses: docker/login-action@v4 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Docker metadata + id: meta + uses: docker/metadata-action@v6 + with: + images: ${{ env.IMAGE }} + # vX.Y.Z -> X.Y.Z, X.Y, X (+ latest); vX / vX.Y tags are always pushed as-is. + tags: | + type=semver,pattern={{version}} + type=semver,pattern={{major}}.{{minor}} + type=semver,pattern={{major}} + type=ref,event=tag + + - name: Build & push + uses: docker/build-push-action@v7 + with: + context: . + platforms: linux/amd64,linux/arm64 + push: true + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + annotations: ${{ steps.meta.outputs.annotations }} + cache-from: type=gha + cache-to: type=gha,mode=max From 4ad92a7a3522723a16c05265e39718b7cae3383b Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sat, 14 Nov 2026 17:28:37 +0100 Subject: [PATCH 10/86] refactor: extract atomic file writes and add queue directory atomic_write_bytes (temp file + fsync + os.replace) now backs atomic_write_json and will persist the rendered images and the upload queue. Adds settings.queue_dir (/data/queue), pins numpy>=2.0 (NEP 50 promotion keeps the vectorized color metric identical to the official converter) and adds a 'slow' pytest marker run as a separate CI step. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 3 +++ app/core/atomic.py | 47 ++++++++++++++++++++++++++++++++ app/core/json_store.py | 31 +++++---------------- app/core/settings.py | 7 ++++- app/main.py | 2 +- pyproject.toml | 5 ++-- tests/test_api.py | 1 + tests/test_atomic.py | 58 ++++++++++++++++++++++++++++++++++++++++ 8 files changed, 125 insertions(+), 29 deletions(-) create mode 100644 app/core/atomic.py create mode 100644 tests/test_atomic.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3ba6911..45443cc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -49,6 +49,9 @@ jobs: - name: Pytest run: pytest + - name: Pytest (slow / performance) + run: pytest -m slow + docker-build: name: Docker build & smoke test runs-on: ubuntu-latest diff --git a/app/core/atomic.py b/app/core/atomic.py new file mode 100644 index 0000000..ed7d5ab --- /dev/null +++ b/app/core/atomic.py @@ -0,0 +1,47 @@ +"""Crash-safe file writes (temporary file + fsync + atomic rename).""" + +from __future__ import annotations + +import contextlib +import os +import tempfile +from pathlib import Path + + +def atomic_write_bytes(path: Path, data: bytes, *, file_mode: int | None = None) -> None: + """Write ``data`` to ``path`` atomically. + + The content is written to a temporary file in the same directory, flushed to disk + and then moved over ``path`` with :func:`os.replace`. Readers therefore observe + either the previous file or the complete new one, never a partial write, even if + the process crashes or the container stops mid-write. + + Args: + path: Destination file. Parent directories are created when missing. + data: Bytes to write. + file_mode: Optional POSIX permission bits (e.g. ``0o600``). Ignored where the + platform does not support ``chmod`` semantics. + """ + path.parent.mkdir(parents=True, exist_ok=True) + fd, tmp_name = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".tmp") + tmp_path = Path(tmp_name) + try: + with os.fdopen(fd, "wb") as handle: + handle.write(data) + handle.flush() + os.fsync(handle.fileno()) + if file_mode is not None: + with contextlib.suppress(OSError): + os.chmod(tmp_path, file_mode) + os.replace(tmp_path, path) + except BaseException: + with contextlib.suppress(OSError): + tmp_path.unlink() + raise + + +def remove_quietly(*paths: Path) -> None: + """Delete files, ignoring the ones that do not exist.""" + for path in paths: + with contextlib.suppress(FileNotFoundError): + path.unlink() diff --git a/app/core/json_store.py b/app/core/json_store.py index 1b7be68..7b62dde 100644 --- a/app/core/json_store.py +++ b/app/core/json_store.py @@ -2,16 +2,16 @@ from __future__ import annotations -import contextlib import json import logging import os -import tempfile from collections.abc import Callable from datetime import UTC, datetime from pathlib import Path from typing import Any +from app.core.atomic import atomic_write_bytes + logger = logging.getLogger(__name__) @@ -45,31 +45,12 @@ def read_json(path: Path, default_factory: Callable[[], Any]) -> Any: def atomic_write_json(path: Path, data: Any, *, file_mode: int | None = None) -> None: - """Write ``data`` as pretty JSON atomically (temp file + fsync + ``os.replace``). - - Readers never observe a partially written file, even if the process crashes or the - container is stopped mid-write. + """Write ``data`` as pretty UTF-8 JSON atomically (see :func:`atomic_write_bytes`). Args: path: Destination file. Parent directories are created when missing. data: JSON-serializable document. - file_mode: Optional POSIX permission bits (e.g. ``0o600``). Ignored where the - platform does not support ``chmod`` semantics. + file_mode: Optional POSIX permission bits (e.g. ``0o600``). """ - path.parent.mkdir(parents=True, exist_ok=True) - fd, tmp_name = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".tmp") - tmp_path = Path(tmp_name) - try: - with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as handle: - json.dump(data, handle, indent=2, ensure_ascii=False, sort_keys=False) - handle.write("\n") - handle.flush() - os.fsync(handle.fileno()) - if file_mode is not None: - with contextlib.suppress(OSError): - os.chmod(tmp_path, file_mode) - os.replace(tmp_path, path) - except BaseException: - with contextlib.suppress(OSError): - tmp_path.unlink() - raise + payload = json.dumps(data, indent=2, ensure_ascii=False) + "\n" + atomic_write_bytes(path, payload.encode("utf-8"), file_mode=file_mode) diff --git a/app/core/settings.py b/app/core/settings.py index 63e928f..a28fb1e 100644 --- a/app/core/settings.py +++ b/app/core/settings.py @@ -160,9 +160,14 @@ def history_path(self) -> Path: @property def cache_dir(self) -> Path: - """Directory holding ``current.jpg`` and ``current.bin``.""" + """Directory holding the current rendered image (``current.jpg``, ``current.bin``).""" return self.data_dir / "cache" + @property + def queue_dir(self) -> Path: + """Directory holding the upload waiting for the frame (``pending.bin``).""" + return self.data_dir / "queue" + def secret_values(self) -> list[str]: """All secret values provided through the environment (for log masking).""" values = [self.api_key] diff --git a/app/main.py b/app/main.py index 8c7472f..63da63a 100644 --- a/app/main.py +++ b/app/main.py @@ -41,7 +41,7 @@ def _prepare_data_dir(settings: EnvSettings) -> None: - for directory in (settings.data_dir, settings.cache_dir): + for directory in (settings.data_dir, settings.cache_dir, settings.queue_dir): try: directory.mkdir(parents=True, exist_ok=True) except OSError as exc: diff --git a/pyproject.toml b/pyproject.toml index a20ea33..a037a00 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -25,7 +25,7 @@ dependencies = [ "pydantic-settings>=2.4", "httpx>=0.27", "pillow>=10.4", - "numpy>=1.26", + "numpy>=2.0", "apscheduler>=3.10,<4", "jinja2>=3.1", "python-multipart>=0.0.9", @@ -75,7 +75,8 @@ known-first-party = ["app"] testpaths = ["tests"] asyncio_mode = "auto" asyncio_default_fixture_loop_scope = "function" -addopts = "-ra" +addopts = "-ra -m 'not slow'" +markers = ["slow: long-running performance tests (run with `pytest -m slow`)"] # --- Mypy ----------------------------------------------------------------------- [tool.mypy] diff --git a/tests/test_api.py b/tests/test_api.py index 585e197..ea02e06 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -36,6 +36,7 @@ def test_data_dir_is_created(make_client: ClientFactory, data_dir: Path) -> None make_client() assert data_dir.is_dir() assert (data_dir / "cache").is_dir() + assert (data_dir / "queue").is_dir() def test_config_read_update_reset_flow(make_client: ClientFactory, data_dir: Path) -> None: diff --git a/tests/test_atomic.py b/tests/test_atomic.py new file mode 100644 index 0000000..aa4a19c --- /dev/null +++ b/tests/test_atomic.py @@ -0,0 +1,58 @@ +from __future__ import annotations + +import json +import os +from pathlib import Path + +import pytest + +from app.core import atomic +from app.core.atomic import atomic_write_bytes, remove_quietly +from app.core.json_store import atomic_write_json, read_json + + +def test_atomic_write_bytes_creates_parents_and_replaces(tmp_path: Path) -> None: + target = tmp_path / "nested" / "file.bin" + atomic_write_bytes(target, b"first") + atomic_write_bytes(target, b"second") + assert target.read_bytes() == b"second" + assert [p.name for p in target.parent.iterdir()] == ["file.bin"] + + +def test_atomic_write_bytes_cleans_up_on_failure( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + target = tmp_path / "file.bin" + atomic_write_bytes(target, b"original") + + def failing_replace(src: object, dst: object) -> None: + raise OSError("disk full") + + monkeypatch.setattr(atomic.os, "replace", failing_replace) + with pytest.raises(OSError, match="disk full"): + atomic_write_bytes(target, b"new") + assert target.read_bytes() == b"original" + assert [p.name for p in tmp_path.iterdir()] == ["file.bin"] + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX permissions only") +def test_atomic_write_bytes_applies_mode(tmp_path: Path) -> None: + target = tmp_path / "secret.json" + atomic_write_bytes(target, b"{}", file_mode=0o600) + assert target.stat().st_mode & 0o777 == 0o600 + + +def test_atomic_write_json_round_trip(tmp_path: Path) -> None: + target = tmp_path / "doc.json" + atomic_write_json(target, {"name": "Élodie", "n": [1, 2]}) + raw = target.read_text(encoding="utf-8") + assert raw.endswith("\n") + assert json.loads(raw) == {"name": "Élodie", "n": [1, 2]} + assert read_json(target, dict) == {"name": "Élodie", "n": [1, 2]} + + +def test_remove_quietly(tmp_path: Path) -> None: + present = tmp_path / "a" + present.write_bytes(b"x") + remove_quietly(present, tmp_path / "missing") + assert not present.exists() From 85e2fdd23e838418b23c7f924b4381f174894e6c Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sat, 14 Nov 2026 17:29:55 +0100 Subject: [PATCH 11/86] feat: add Spectra 6 palette with official tuned color metric Palette order, 4-bit device codes (0x0-0x6, 0x4 skipped) and the RGB+luma distance metric from the official Fraimic converter. match_palette is a vectorized float64 version that selects the same entry as the official closest_palette_color, checked against a vendored copy of the official code (tests/reference, MIT) on 20k+ colors. Co-Authored-By: Claude Opus 5.5 --- app/processor/palette.py | 86 +++++++++ pyproject.toml | 4 +- tests/reference/__init__.py | 1 + tests/reference/fraimic_converter.py | 266 +++++++++++++++++++++++++++ tests/test_palette.py | 55 ++++++ 5 files changed, 410 insertions(+), 2 deletions(-) create mode 100644 app/processor/palette.py create mode 100644 tests/reference/__init__.py create mode 100644 tests/reference/fraimic_converter.py create mode 100644 tests/test_palette.py diff --git a/app/processor/palette.py b/app/processor/palette.py new file mode 100644 index 0000000..c741ca4 --- /dev/null +++ b/app/processor/palette.py @@ -0,0 +1,86 @@ +"""Spectra 6 palette, device codes and the official tuned color-distance metric. + +The palette order, 4-bit device codes and the RGB + luma distance metric are taken +from the official Fraimic converter (``convert_to_bin_spectra6.py``, +https://github.com/Fraimic/fraimic_bin_converter, MIT License, Copyright (c) 2026 +Fraimic), which itself builds on Toon-nooT's PhotoPainter Spectra 6 converter. + +:func:`match_palette` is a vectorized, numerically identical version of the official +``closest_palette_color``: it performs the same float64 operations in the same order, +so it selects the same palette entry for every input (verified by the test suite). +""" + +from __future__ import annotations + +from typing import Final + +import numpy as np +import numpy.typing as npt + +#: Palette colors in index order (index ``i`` is encoded as ``DEVICE_CODES[i]``). +PALETTE_RGB: Final[tuple[tuple[int, int, int], ...]] = ( + (0, 0, 0), # Black + (255, 255, 255), # White + (255, 255, 0), # Yellow + (255, 0, 0), # Red + (0, 0, 255), # Blue + (0, 255, 0), # Green +) +PALETTE_NAMES: Final[tuple[str, ...]] = ("black", "white", "yellow", "red", "blue", "green") + +#: 4-bit panel codes per palette index. ``0x4`` is intentionally skipped by the vendor. +DEVICE_CODES: Final[npt.NDArray[np.uint8]] = np.array([0x0, 0x1, 0x2, 0x3, 0x5, 0x6], np.uint8) +DEVICE_CODES.setflags(write=False) +ALLOWED_CODES: Final[frozenset[int]] = frozenset(int(code) for code in DEVICE_CODES) + +#: White device code, used for the EL315 off-panel padding nibbles (``0x11`` bytes). +WHITE_CODE: Final = 0x1 + +#: Palette as float32, the dtype the official converter diffuses errors with. +PALETTE_ARRAY: Final[npt.NDArray[np.float32]] = np.array(PALETTE_RGB, dtype=np.float32) +PALETTE_ARRAY.setflags(write=False) + +#: Perceptual luma per palette entry (weights 0.25 / 0.35 / 0.40, as officially tuned). +PALETTE_LUMA: Final[npt.NDArray[np.float32]] = np.array( + [r * 250 + g * 350 + b * 400 for (r, g, b) in PALETTE_RGB], dtype=np.float32 +) / (255.0 * 1000) +PALETTE_LUMA.setflags(write=False) + +_RED: Final = PALETTE_ARRAY[:, 0] +_GREEN: Final = PALETTE_ARRAY[:, 1] +_BLUE: Final = PALETTE_ARRAY[:, 2] + + +def match_palette(rgb: npt.NDArray[np.int64]) -> npt.NDArray[np.intp]: + """Return the closest palette index for each RGB triple. + + Args: + rgb: ``(N, 3)`` integer array with channel values in ``0..255`` (the official + converter clips and truncates the error-diffused value before matching). + + Returns: + ``(N,)`` array of palette indices in ``0..5``. + """ + red = rgb[:, 0:1] + green = rgb[:, 1:2] + blue = rgb[:, 2:3] + luma = (red * 250 + green * 350 + blue * 400) / (255.0 * 1000) + + diff_r = red - _RED + diff_g = green - _GREEN + diff_b = blue - _BLUE + # Blue boosted, green and red reduced: compensates eye sensitivity and panel response. + rgb_dist = ( + (diff_r * diff_r * 0.250 + diff_g * diff_g * 0.350 + diff_b * diff_b * 0.400) + * 0.75 + / (255.0 * 255.0) + ) + luma_diff = luma - PALETTE_LUMA + total = 1.5 * rgb_dist + 0.60 * (luma_diff * luma_diff) + return np.argmin(total, axis=1) + + +def indices_to_rgb(indices: npt.NDArray[np.uint8]) -> npt.NDArray[np.uint8]: + """Render palette indices as an RGB image array (used for dithered previews).""" + lut = np.array(PALETTE_RGB, dtype=np.uint8) + return lut[indices] diff --git a/pyproject.toml b/pyproject.toml index a037a00..2235eb8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -56,7 +56,7 @@ app = ["py.typed", "templates/*.html"] [tool.ruff] target-version = "py311" line-length = 100 -extend-exclude = ["fraimic-docs"] +extend-exclude = ["fraimic-docs", "tests/reference"] [tool.ruff.lint] select = ["E", "F", "W", "I", "UP", "B", "SIM", "S", "ANN", "RUF"] @@ -83,7 +83,7 @@ markers = ["slow: long-running performance tests (run with `pytest -m slow`)"] python_version = "3.11" strict = true plugins = ["pydantic.mypy"] -exclude = ["fraimic-docs/", "build/"] +exclude = ["fraimic-docs/", "build/", "tests/reference/"] [tool.pydantic-mypy] init_forbid_extra = true diff --git a/tests/reference/__init__.py b/tests/reference/__init__.py new file mode 100644 index 0000000..54ef9b4 --- /dev/null +++ b/tests/reference/__init__.py @@ -0,0 +1 @@ +"""Reference implementations used as test oracles (never imported by the application).""" diff --git a/tests/reference/fraimic_converter.py b/tests/reference/fraimic_converter.py new file mode 100644 index 0000000..b75d858 --- /dev/null +++ b/tests/reference/fraimic_converter.py @@ -0,0 +1,266 @@ +"""Verbatim excerpts of the official Fraimic Spectra 6 converter, used as a test oracle. + +Source: https://github.com/Fraimic/fraimic_bin_converter +File: convert_to_bin_spectra6.py (commit 1b794a3) + +MIT License + +Copyright (c) 2026 Fraimic + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +The code below is copied unchanged (only CLI, file I/O, panel plumbing and progress-bar +code was left out; ``enhance`` reproduces the enhancement lines of ``process_image``) so that the application's vectorized implementation can be checked against +the original behavior. Lint rules are relaxed for this file on purpose. +""" + +# ruff: noqa +# mypy: ignore-errors + +import numpy as np +from PIL import Image, ImageEnhance, ImageFilter + +# Define the 6-color palette (black, white, yellow, red, blue, green). +# Order matters: index i maps to COLOR_CODES[i]. +PALETTE_COLORS = [ + (0, 0, 0), # Black + (255, 255, 255), # White + (255, 255, 0), # Yellow + (255, 0, 0), # Red + (0, 0, 255), # Blue + (0, 255, 0) # Green +] + +# 4-bit device codes for the EL133UF1 panel. Note 0x4 is intentionally skipped. +# Black White Yellow Red Blue Green +COLOR_CODES = np.array([0x0, 0x1, 0x2, 0x3, 0x5, 0x6], dtype=np.uint8) + +# White. Used for the off-panel dummy pixels in the EL315 padded ICs, which are +# always 0x11 regardless of the image's own border color. +WHITE_CODE = 0x1 + +# Letterbox border colors, selectable with --letterbox. +LETTERBOX_COLORS = {'black': (0, 0, 0), 'white': (255, 255, 255)} + +# Precompute palette as NumPy arrays for faster access +PALETTE_ARRAY = np.array(PALETTE_COLORS, dtype=np.float32) + +# blue and green prints darker, lower its luma value so the distance metric favors it over white, also at luma1 +PALETTE_LUMA_ARRAY = np.array([r*250 + g*350 + b*400 for (r, g, b) in PALETTE_COLORS], dtype=np.float32) / (255.0 * 1000) + + +# Find the closest palette color using floating-point arithmetic (exact RGBL method) +def closest_palette_color(rgb): + r1, g1, b1 = rgb + # Calculate luma for the input pixel + luma1 = (r1 * 250 + g1 * 350 + b1 * 400) / (255.0 * 1000) + + # Calculate differences using precomputed arrays + diffR = r1 - PALETTE_ARRAY[:, 0] + diffG = g1 - PALETTE_ARRAY[:, 1] + diffB = b1 - PALETTE_ARRAY[:, 2] + + # Calculate RGB component of distance + # boost blue, reduce green a bit and red a little more to compensate for human eye sensitivity and e-ink display characteristics (trial and error) + rgb_dist = (diffR*diffR*0.250 + diffG*diffG*0.350 + diffB*diffB*0.400) * 0.75 / (255.0*255.0) + + # Calculate luma differences + luma_diff = luma1 - PALETTE_LUMA_ARRAY + luma_dist = luma_diff * luma_diff + + # Total distance + total_dist = 1.5*rgb_dist + 0.60*luma_dist # hue errors are more important, increased the rgb_dist factor. + + # Find minimum distance index + return np.argmin(total_dist) + + +# Atkinson dithering returning a per-pixel palette-index array (not RGB). +# Uses the tuned closest_palette_color metric for each decision. +def quantize_atkinson_indexed(image): + img_array = np.array(image.convert('RGB')) + height, width, _ = img_array.shape + # Use float array for error diffusion to avoid integer truncation issues + working_img = img_array.astype(np.float32) + indices = np.zeros((height, width), dtype=np.uint8) + + for y in range(height): + for x in range(width): + old_pixel = working_img[y, x].copy() + # Use exact color comparison instead of lookup table for better accuracy + idx = closest_palette_color(tuple(np.clip(old_pixel, 0, 255).astype(int))) + new_pixel = np.array(PALETTE_COLORS[idx], dtype=np.float32) + working_img[y, x] = new_pixel + indices[y, x] = idx + + # Calculate error + error = old_pixel - new_pixel + + # Atkinson error distribution - only to not-yet-processed pixels (right and down) + # Weights: Right: 1/8, Bottom-left: 1/8, Bottom: 1/4, Bottom-right: 1/8 + # Total distributed: 5/8, which is standard for Atkinson + if x + 1 < width: + working_img[y, x + 1] += error * (1/8) + if y + 1 < height: + if x - 1 >= 0: + working_img[y + 1, x - 1] += error * (1/8) + working_img[y + 1, x] += error * (1/4) + if x + 1 < width: + working_img[y + 1, x + 1] += error * (1/8) + + return indices + + +# Scale an (already EXIF-corrected, RGB) image to its final on-panel pixel size. +# Under 'crop' this returns exactly the panel frame; under letterbox/rotate it +# returns the picture alone, which pad_to_frame later centers on the frame. +# Kept separate from padding so enhancement runs on the picture only — see +# process_image. +def scale_to_frame(image, fit, panel): + img = image + width, height = img.size + target_width, target_height = panel.width, panel.height + + # 'rotate': turn landscape images upright so they better fill the portrait + # frame, then letterbox as usual. + if fit == 'rotate' and width > height: + img = img.rotate(90, expand=True) + width, height = img.size + + if fit == 'crop': + # Scale to fill, then center-crop the overflow (no borders, edges lost). + scale_ratio = max(target_width / width, target_height / height) + resized_width = max(1, int(round(width * scale_ratio))) + resized_height = max(1, int(round(height * scale_ratio))) + resized = img.resize((resized_width, resized_height), Image.LANCZOS) + left = (resized_width - target_width) // 2 + top = (resized_height - target_height) // 2 + return resized.crop((left, top, left + target_width, top + target_height)) + + # 'letterbox' (and 'rotate' after reorientation): scale to fit entirely inside + # the frame, no cropping. Any leftover space becomes bars in pad_to_frame. + scale_ratio = min(target_width / width, target_height / height) + resized_width = max(1, int(round(width * scale_ratio))) + resized_height = max(1, int(round(height * scale_ratio))) + return img.resize((resized_width, resized_height), Image.LANCZOS) + + +# Center the scaled picture on the panel frame, padding any remainder with +# letterbox_rgb. A no-op when the picture already fills the frame (e.g. --fit crop). +def pad_to_frame(image, panel, letterbox_rgb): + if image.size == (panel.width, panel.height): + return image + + framed = Image.new('RGB', (panel.width, panel.height), letterbox_rgb) + framed.paste(image, ((panel.width - image.width) // 2, + (panel.height - image.height) // 2)) + return framed + + +# Pack device codes into the EL133UF1 (13.3") .bin layout. +def pack_el133uf1(color_code_array): + """ + - 1200x1600 pixels, portrait + - Two pixels per byte (high nibble = even col, low nibble = odd col) + - Split into left half (cols 0-599) then right half (cols 600-1199): + all left-half bytes for the whole image come first, then all right-half bytes + - Total size: 960,000 bytes + """ + left_half = color_code_array[:, 0:600] + left_packed = (left_half[:, 0::2] << 4) | left_half[:, 1::2] + + right_half = color_code_array[:, 600:1200] + right_packed = (right_half[:, 0::2] << 4) | right_half[:, 1::2] + + return np.concatenate([left_packed.ravel(), right_packed.ravel()]).astype(np.uint8) + + +# EL315 block geometry: 8 IC blocks, each 720 block rows x 800 block pixels. +EL315_BLOCK_ROWS = 720 + + +EL315_BLOCK_PIXELS = 800 + + +EL315_PADDED_PIXELS = 160 # real pixels per row in the padded ICs (IC4, IC8) + + +EL315_ROW_PIXELS = 2560 # block pixels per block row, across an IC group + + +EL315_HALF_ROWS = 1280 # image rows covered by one IC group + + +# Pack device codes into the EL315 (31.5") .bin layout. +def pack_el315(color_code_array): + """ + - 1440x2560 pixels, portrait + - 8 IC blocks of 288,000 bytes written sequentially IC1 -> IC8; each block is + 720 block rows x 400 bytes, two pixels per byte (high nibble first) + - The ICs come in two groups of four, each group covering half the image: + IC1-IC4 the BOTTOM half (rows 1280-2559), IC5-IC8 the TOP half (rows 0-1279). + - Within a group, one block row is a 2-pixel-wide VERTICAL STRIP of the image, + 1280 rows tall, read bottom->top; the two pixels of each image row are stored + left then right. So block row b covers image columns 2b and 2b+1, and block + pixel p sits at image row offset p // 2 up from the bottom of the half. + - The four ICs in a group split that 1280-row strip as 400/400/400/80 rows, + counting up from the bottom of the half, so IC4 and IC8 hold only 160 real + pixels per row; the remaining 320 bytes of their rows are 0x11 padding. + - Total size: 2,304,000 bytes + """ + # Flipping vertically puts the bottom half of the image first, matching the + # IC1-IC4 group, and makes each half read bottom->top. + flipped = np.flipud(color_code_array) # 2560 x 1440 + + blocks = [] + for half in range(2): # IC1-IC4 (bottom half), then IC5-IC8 (top half) + strip = flipped[half * EL315_HALF_ROWS:(half + 1) * EL315_HALF_ROWS] + # Regroup 1280 rows x 1440 cols into 720 block rows of 2560 pixels, so that + # each block row walks one 2-px-wide column pair down the strip. + band = (strip.reshape(EL315_HALF_ROWS, EL315_BLOCK_ROWS, 2) + .transpose(1, 0, 2) + .reshape(EL315_BLOCK_ROWS, EL315_ROW_PIXELS)) + for ic in range(4): + real_pixels = EL315_PADDED_PIXELS if ic == 3 else EL315_BLOCK_PIXELS + start = ic * EL315_BLOCK_PIXELS + # Prefill with white so the padded ICs' dummy bytes come out as 0x11. + nibbles = np.full((EL315_BLOCK_ROWS, EL315_BLOCK_PIXELS), WHITE_CODE, dtype=np.uint8) + nibbles[:, :real_pixels] = band[:, start:start + real_pixels] + blocks.append((nibbles[:, 0::2] << 4) | nibbles[:, 1::2]) + + return np.concatenate([block.ravel() for block in blocks]).astype(np.uint8) + + +class Panel: + """Minimal stand-in for the official Panel class (only width/height are used here).""" + + def __init__(self, width, height): + self.width = width + self.height = height + + +def enhance(scaled_image, brightness=1.1, contrast=1.2, saturation=1.2): + """The enhancement steps of the official process_image(), same calls in the same order.""" + enhanced_image = ImageEnhance.Brightness(scaled_image).enhance(brightness) + enhanced_image = ImageEnhance.Contrast(enhanced_image).enhance(contrast) + enhanced_image = ImageEnhance.Color(enhanced_image).enhance(saturation) + enhanced_image = enhanced_image.filter(ImageFilter.EDGE_ENHANCE) + enhanced_image = enhanced_image.filter(ImageFilter.SMOOTH) + enhanced_image = enhanced_image.filter(ImageFilter.SHARPEN) + return enhanced_image diff --git a/tests/test_palette.py b/tests/test_palette.py new file mode 100644 index 0000000..ef5e337 --- /dev/null +++ b/tests/test_palette.py @@ -0,0 +1,55 @@ +from __future__ import annotations + +import numpy as np + +from app.processor.palette import ( + ALLOWED_CODES, + DEVICE_CODES, + PALETTE_ARRAY, + PALETTE_LUMA, + PALETTE_RGB, + indices_to_rgb, + match_palette, +) +from tests.reference import fraimic_converter as ref + + +def test_device_codes_skip_0x4() -> None: + assert DEVICE_CODES.tolist() == [0x0, 0x1, 0x2, 0x3, 0x5, 0x6] + assert sorted(ALLOWED_CODES) == [0, 1, 2, 3, 5, 6] + assert 0x4 not in ALLOWED_CODES + + +def test_palette_matches_official_constants() -> None: + assert list(PALETTE_RGB) == ref.PALETTE_COLORS + assert np.array_equal(PALETTE_ARRAY, ref.PALETTE_ARRAY) + assert np.array_equal(PALETTE_LUMA, ref.PALETTE_LUMA_ARRAY) + assert np.array_equal(DEVICE_CODES, ref.COLOR_CODES) + + +def test_pure_palette_colors_map_to_themselves() -> None: + colors = np.array(PALETTE_RGB, dtype=np.int64) + assert match_palette(colors).tolist() == list(range(6)) + + +def test_match_palette_equals_official_metric() -> None: + rng = np.random.default_rng(2026) + colors = rng.integers(0, 256, size=(20_000, 3), dtype=np.int64) + # Include the grey axis and channel extremes, where ties are most likely. + grey = np.repeat(np.arange(256, dtype=np.int64)[:, None], 3, axis=1) + corners = np.array( + [[r, g, b] for r in (0, 1, 254, 255) for g in (0, 1, 254, 255) for b in (0, 1, 254, 255)], + dtype=np.int64, + ) + samples = np.concatenate([colors, grey, corners]) + + expected = [int(ref.closest_palette_color(tuple(color))) for color in samples] + assert match_palette(samples).tolist() == expected + + +def test_indices_to_rgb() -> None: + indices = np.array([[0, 1], [4, 5]], dtype=np.uint8) + rgb = indices_to_rgb(indices) + assert rgb.shape == (2, 2, 3) + assert rgb[1, 0].tolist() == [0, 0, 255] + assert rgb[1, 1].tolist() == [0, 255, 0] From 6afe7934dc7124f58748ca0e08783b8a0b67cbe0 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sat, 14 Nov 2026 17:31:19 +0100 Subject: [PATCH 12/86] feat: add vectorized wavefront Atkinson and Floyd-Steinberg dithering Both kernels only diffuse error right and into the next row, so pixels on the same x + 2y anti-diagonal are independent and are quantized as one NumPy batch (W + 2H steps instead of W * H). Applying the down-left tap before the right tap keeps the float32 summation order of the sequential loop, making Atkinson bit-identical to the official converter while running in ~0.7 s (13.3") / ~1.1 s (31.5") instead of ~40 s. Floyd-Steinberg uses the same engine with the tuned palette metric. Co-Authored-By: Claude Opus 5.5 --- app/processor/dither.py | 140 ++++++++++++++++++++++++++++++++++++++++ tests/test_dither.py | 134 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 274 insertions(+) create mode 100644 app/processor/dither.py create mode 100644 tests/test_dither.py diff --git a/app/processor/dither.py b/app/processor/dither.py new file mode 100644 index 0000000..f414978 --- /dev/null +++ b/app/processor/dither.py @@ -0,0 +1,140 @@ +"""Exact, NumPy-vectorized error-diffusion dithering onto the Spectra 6 palette. + +Error diffusion is sequential by nature: every pixel depends on the quantization +error of the pixels processed before it. Both supported kernels, however, only push +error to the right neighbour ``(y, x+1)`` and to the three pixels below +``(y+1, x-1..x+1)``. A pixel therefore only depends on pixels with a strictly smaller +wavefront key ``t = x + 2y``, so all pixels sharing the same ``t`` (an anti-diagonal) +can be quantized together in one vectorized step. This turns ``W * H`` Python +iterations into ``W + 2H`` NumPy steps (about 0.7 s for 1200x1600 instead of ~40 s). + +Within a step the down-left contribution is applied before the right contribution, +which reproduces the floating-point summation order of the sequential row-by-row +loop. The result is bit-identical to the official Fraimic converter's Atkinson +implementation (``quantize_atkinson_indexed``), as verified by the test suite. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Final + +import numpy as np +import numpy.typing as npt +from PIL import Image + +from app.core.config_models import DitherAlgorithm +from app.processor.palette import PALETTE_ARRAY, match_palette + + +@dataclass(frozen=True, slots=True) +class DitherTap: + """One error-diffusion target relative to the current pixel.""" + + dy: int + dx: int + weight: float + + +@dataclass(frozen=True, slots=True) +class DitherKernel: + """An error-diffusion kernel compatible with the ``t = x + 2y`` wavefront. + + ``taps`` are listed in the order they must be applied within a wavefront step. + """ + + name: str + taps: tuple[DitherTap, ...] + + def __post_init__(self) -> None: + for tap in self.taps: + forward_in_row = tap.dy == 0 and tap.dx >= 1 + next_row = tap.dy == 1 and tap.dx >= -1 + if not (forward_in_row or next_row): + raise ValueError( + f"Tap ({tap.dy}, {tap.dx}) is incompatible with the x + 2y wavefront" + ) + + +#: The official Fraimic/PhotoPainter Atkinson variant: 4 neighbours, 5/8 of the error. +ATKINSON: Final = DitherKernel( + "atkinson", + ( + DitherTap(1, -1, 1 / 8), # down-left (must precede "right": same target step) + DitherTap(0, 1, 1 / 8), # right + DitherTap(1, 0, 1 / 4), # down + DitherTap(1, 1, 1 / 8), # down-right + ), +) + +#: Classic Floyd-Steinberg (7/16, 3/16, 5/16, 1/16) with the tuned palette metric. +FLOYD_STEINBERG: Final = DitherKernel( + "floyd_steinberg", + ( + DitherTap(1, -1, 3 / 16), + DitherTap(0, 1, 7 / 16), + DitherTap(1, 0, 5 / 16), + DitherTap(1, 1, 1 / 16), + ), +) + +KERNELS: Final[dict[DitherAlgorithm, DitherKernel]] = { + "atkinson": ATKINSON, + "floyd_steinberg": FLOYD_STEINBERG, +} + + +def dither( + rgb: npt.NDArray[np.uint8], algorithm: DitherAlgorithm = "atkinson" +) -> npt.NDArray[np.uint8]: + """Quantize an RGB image to Spectra 6 palette indices with error diffusion. + + Args: + rgb: ``(H, W, 3)`` ``uint8`` image. + algorithm: ``"atkinson"`` (official default) or ``"floyd_steinberg"``. + + Returns: + ``(H, W)`` ``uint8`` array of palette indices in ``0..5``. + """ + if rgb.ndim != 3 or rgb.shape[2] != 3 or rgb.shape[0] < 1 or rgb.shape[1] < 1: + raise ValueError(f"Expected an (H, W, 3) RGB array, got shape {rgb.shape}") + kernel = KERNELS[algorithm] + height, width = int(rgb.shape[0]), int(rgb.shape[1]) + + # Float32 working buffer, exactly like the official converter. + work = rgb.reshape(-1, 3).astype(np.float32) + out = np.empty(height * width, dtype=np.uint8) + taps = [(tap.dy, tap.dx, tap.dy * width + tap.dx, tap.weight) for tap in kernel.taps] + + for step in range(width + 2 * (height - 1)): + # Pixels with x + 2y == step: y in [y_min, y_max], x = step - 2y in [0, width). + y_min = max(0, (step - width + 2) // 2) + y_max = min(height - 1, step // 2) + if y_min > y_max: + continue + ys = np.arange(y_min, y_max + 1) + xs = step - 2 * ys + flat = ys * width + xs + + old = work[flat] + chosen = match_palette(np.clip(old, 0, 255).astype(np.int64)) + new = PALETTE_ARRAY[chosen] + out[flat] = chosen + work[flat] = new + error = old - new + + for dy, dx, offset, weight in taps: + valid = (ys + dy < height) & (xs + dx >= 0) & (xs + dx < width) + if valid.all(): + work[flat + offset] += error * weight + elif valid.any(): + work[flat[valid] + offset] += error[valid] * weight + + return out.reshape(height, width) + + +def dither_image( + image: Image.Image, algorithm: DitherAlgorithm = "atkinson" +) -> npt.NDArray[np.uint8]: + """Convenience wrapper around :func:`dither` for Pillow images.""" + return dither(np.asarray(image.convert("RGB"), dtype=np.uint8), algorithm) diff --git a/tests/test_dither.py b/tests/test_dither.py new file mode 100644 index 0000000..c260d92 --- /dev/null +++ b/tests/test_dither.py @@ -0,0 +1,134 @@ +from __future__ import annotations + +import time + +import numpy as np +import numpy.typing as npt +import pytest +from PIL import Image + +from app.processor.dither import ( + ATKINSON, + FLOYD_STEINBERG, + DitherKernel, + DitherTap, + dither, + dither_image, +) +from app.processor.palette import PALETTE_ARRAY, PALETTE_RGB +from tests.reference import fraimic_converter as ref + + +def sequential_reference(rgb: npt.NDArray[np.uint8], kernel: DitherKernel) -> npt.NDArray[np.uint8]: + """Plain row-by-row error diffusion with the official per-pixel metric.""" + work = rgb.astype(np.float32) + height, width, _ = work.shape + out = np.zeros((height, width), dtype=np.uint8) + # Classic application order: right first, then the row below left-to-right. + ordered = sorted(kernel.taps, key=lambda tap: (tap.dy, tap.dx)) + for y in range(height): + for x in range(width): + old = work[y, x].copy() + idx = ref.closest_palette_color(tuple(np.clip(old, 0, 255).astype(int))) + new = PALETTE_ARRAY[idx] + work[y, x] = new + out[y, x] = idx + error = old - new + for tap in ordered: + ny, nx = y + tap.dy, x + tap.dx + if 0 <= ny < height and 0 <= nx < width: + work[ny, nx] += error * tap.weight + return out + + +def random_image(height: int, width: int, seed: int) -> npt.NDArray[np.uint8]: + return np.random.default_rng(seed).integers(0, 256, (height, width, 3), dtype=np.uint8) + + +def gradient_image(height: int, width: int) -> npt.NDArray[np.uint8]: + gx, gy = np.meshgrid(np.linspace(0, 255, width), np.linspace(0, 255, height)) + return np.dstack([gx, gy, np.full_like(gx, 128)]).astype(np.uint8) + + +CASES = [ + pytest.param(random_image(23, 37, 1), id="random-37x23"), + pytest.param(random_image(48, 64, 2), id="random-64x48"), + pytest.param(random_image(61, 17, 3), id="random-17x61"), + pytest.param(random_image(1, 50, 4), id="single-row"), + pytest.param(random_image(50, 1, 5), id="single-column"), + pytest.param(random_image(1, 1, 6), id="single-pixel"), + pytest.param(random_image(2, 2, 7), id="2x2"), + pytest.param(gradient_image(90, 120), id="gradient"), +] + + +@pytest.mark.parametrize("rgb", CASES) +def test_atkinson_is_bit_identical_to_official(rgb: npt.NDArray[np.uint8]) -> None: + expected = ref.quantize_atkinson_indexed(Image.fromarray(rgb)) + assert np.array_equal(dither(rgb, "atkinson"), expected) + + +@pytest.mark.parametrize("rgb", CASES) +def test_floyd_steinberg_matches_sequential_loop(rgb: npt.NDArray[np.uint8]) -> None: + expected = sequential_reference(rgb, FLOYD_STEINBERG) + assert np.array_equal(dither(rgb, "floyd_steinberg"), expected) + + +def test_sequential_reference_agrees_with_official_atkinson() -> None: + rgb = random_image(20, 30, 9) + expected = ref.quantize_atkinson_indexed(Image.fromarray(rgb)) + assert np.array_equal(sequential_reference(rgb, ATKINSON), expected) + + +@pytest.mark.parametrize("algorithm", ["atkinson", "floyd_steinberg"]) +def test_output_range_and_dtype(algorithm: str) -> None: + result = dither(random_image(40, 30, 11), algorithm) # type: ignore[arg-type] + assert result.dtype == np.uint8 + assert result.shape == (40, 30) + assert set(np.unique(result).tolist()) <= set(range(6)) + + +@pytest.mark.parametrize("algorithm", ["atkinson", "floyd_steinberg"]) +@pytest.mark.parametrize("index", range(6)) +def test_flat_palette_colors_stay_flat(algorithm: str, index: int) -> None: + rgb = np.full((16, 24, 3), PALETTE_RGB[index], dtype=np.uint8) + assert np.all(dither(rgb, algorithm) == index) # type: ignore[arg-type] + + +@pytest.mark.parametrize("algorithm", ["atkinson", "floyd_steinberg"]) +@pytest.mark.parametrize("level", [64, 128, 192]) +def test_flat_grey_preserves_average_color(algorithm: str, level: int) -> None: + """Greys are rendered as color mixes (e.g. yellow + blue) whose average stays grey.""" + rgb = np.full((64, 64, 3), level, dtype=np.uint8) + rendered = np.array(PALETTE_RGB, dtype=np.float64)[dither(rgb, algorithm)] # type: ignore[arg-type] + mean = rendered.reshape(-1, 3).mean(axis=0) + assert np.all(np.abs(mean - level) < 25), mean.round(1).tolist() + + +def test_dither_image_accepts_pillow_images() -> None: + image = Image.fromarray(random_image(10, 12, 3)).convert("RGBA") + assert dither_image(image).shape == (10, 12) + + +@pytest.mark.parametrize("shape", [(10, 10), (10, 10, 4), (0, 5, 3)]) +def test_rejects_bad_shapes(shape: tuple[int, ...]) -> None: + with pytest.raises(ValueError): + dither(np.zeros(shape, dtype=np.uint8)) + + +def test_kernel_validation() -> None: + with pytest.raises(ValueError, match="wavefront"): + DitherKernel("bad", (DitherTap(1, -2, 0.5),)) + with pytest.raises(ValueError, match="wavefront"): + DitherKernel("bad", (DitherTap(2, 0, 0.5),)) + + +@pytest.mark.slow +@pytest.mark.parametrize(("width", "height", "budget_s"), [(1200, 1600, 5.0), (1440, 2560, 8.0)]) +def test_full_panel_performance(width: int, height: int, budget_s: float) -> None: + rgb = random_image(height, width, 42) + started = time.perf_counter() + result = dither(rgb, "atkinson") + elapsed = time.perf_counter() - started + assert result.shape == (height, width) + assert elapsed < budget_s, f"{width}x{height} took {elapsed:.2f}s" From b102e37a63f41a3be4128b3bf62cad585ae546e7 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sat, 14 Nov 2026 17:32:25 +0100 Subject: [PATCH 13/86] feat: add EL133UF1 and EL315 bin packing encode_bin maps palette indices to the 4-bit device codes and packs them in the panel layout: left/right half split for the 13.3" EL133UF1 (960,000 B) and the 8 IC blocks of bottom-to-top column-pair strips with 0x11 padding in IC4/IC8 for the 31.5" EL315 (2,304,000 B). decode_bin is the exact inverse and rejects invalid nibbles. Tests check byte parity with the official packers, the spec walkthroughs and the EL315 mapping formula. Co-Authored-By: Claude Opus 5.5 --- app/processor/packing.py | 165 +++++++++++++++++++++++++++++++++++++++ tests/test_packing.py | 137 ++++++++++++++++++++++++++++++++ 2 files changed, 302 insertions(+) create mode 100644 app/processor/packing.py create mode 100644 tests/test_packing.py diff --git a/app/processor/packing.py b/app/processor/packing.py new file mode 100644 index 0000000..26d8d62 --- /dev/null +++ b/app/processor/packing.py @@ -0,0 +1,165 @@ +"""Fraimic / Spectra 6 ``.bin`` frame-buffer encoding and decoding. + +Both panels store 4-bit device codes, two pixels per byte (high nibble first), with no +header, footer or compression. Only the memory layout differs: + +* **EL133UF1 (13.3", 1200x1600, 960,000 bytes):** each row is split into a left half + (columns 0-599) and a right half (columns 600-1199). All left-half bytes for the + whole image come first, then all right-half bytes. +* **EL315 (31.5", 1440x2560, 2,304,000 bytes):** 8 IC blocks of 720 block rows x 400 + bytes. IC1-IC4 cover the bottom half of the image and IC5-IC8 the top half. A block + row is a 2-pixel-wide vertical strip read bottom->top; IC4 and IC8 only carry 160 + real pixels per row, the remaining 320 bytes are ``0x11`` padding. + +The packers are ports of the official Fraimic converter (MIT License, +Copyright (c) 2026 Fraimic) and are checked byte-for-byte against it in the tests. +""" + +from __future__ import annotations + +from collections.abc import Callable +from typing import Final + +import numpy as np +import numpy.typing as npt + +from app.core.config_models import PANEL_SPECS, PanelModel, PanelSpec +from app.processor.palette import DEVICE_CODES, WHITE_CODE + +UInt8Array = npt.NDArray[np.uint8] + +EL133_HALF_COLUMNS: Final = 600 + +EL315_BLOCK_ROWS: Final = 720 +EL315_BLOCK_PIXELS: Final = 800 +EL315_PADDED_PIXELS: Final = 160 +EL315_ROW_PIXELS: Final = 2560 +EL315_HALF_ROWS: Final = 1280 +EL315_BLOCK_BYTES: Final = EL315_BLOCK_ROWS * EL315_BLOCK_PIXELS // 2 + +#: Device code -> palette index (``255`` marks codes the panel does not accept). +_CODE_TO_INDEX: Final = np.full(16, 255, dtype=np.uint8) +_CODE_TO_INDEX[DEVICE_CODES] = np.arange(len(DEVICE_CODES), dtype=np.uint8) + + +class BinFormatError(ValueError): + """Input does not satisfy the panel's ``.bin`` specification.""" + + +def _pack_nibbles(codes: UInt8Array) -> UInt8Array: + """Pack pairs of 4-bit codes along the last axis (high nibble first).""" + return np.asarray((codes[..., 0::2] << 4) | codes[..., 1::2], dtype=np.uint8) + + +def _unpack_nibbles(packed: UInt8Array) -> UInt8Array: + """Inverse of :func:`_pack_nibbles`.""" + out = np.empty((*packed.shape[:-1], packed.shape[-1] * 2), dtype=np.uint8) + out[..., 0::2] = packed >> 4 + out[..., 1::2] = packed & 0x0F + return out + + +def pack_el133uf1(codes: UInt8Array) -> UInt8Array: + """Pack a ``(1600, 1200)`` device-code array into the EL133UF1 layout.""" + left = _pack_nibbles(codes[:, :EL133_HALF_COLUMNS]) + right = _pack_nibbles(codes[:, EL133_HALF_COLUMNS:]) + return np.concatenate([left.ravel(), right.ravel()]) + + +def unpack_el133uf1(data: UInt8Array) -> UInt8Array: + """Inverse of :func:`pack_el133uf1`, returning ``(1600, 1200)`` device codes.""" + spec = PANEL_SPECS["133"] + half = data.size // 2 + rows = spec.height + left = _unpack_nibbles(data[:half].reshape(rows, EL133_HALF_COLUMNS // 2)) + right = _unpack_nibbles(data[half:].reshape(rows, EL133_HALF_COLUMNS // 2)) + return np.concatenate([left, right], axis=1) + + +def pack_el315(codes: UInt8Array) -> UInt8Array: + """Pack a ``(2560, 1440)`` device-code array into the EL315 IC-block layout.""" + flipped = np.flipud(codes) # bottom half first, each half read bottom -> top + blocks: list[UInt8Array] = [] + for half in range(2): # IC1-IC4 (bottom half), then IC5-IC8 (top half) + strip = flipped[half * EL315_HALF_ROWS : (half + 1) * EL315_HALF_ROWS] + band = ( + strip.reshape(EL315_HALF_ROWS, EL315_BLOCK_ROWS, 2) + .transpose(1, 0, 2) + .reshape(EL315_BLOCK_ROWS, EL315_ROW_PIXELS) + ) + for ic in range(4): + real_pixels = EL315_PADDED_PIXELS if ic == 3 else EL315_BLOCK_PIXELS + start = ic * EL315_BLOCK_PIXELS + nibbles = np.full((EL315_BLOCK_ROWS, EL315_BLOCK_PIXELS), WHITE_CODE, dtype=np.uint8) + nibbles[:, :real_pixels] = band[:, start : start + real_pixels] + blocks.append(_pack_nibbles(nibbles)) + return np.concatenate([block.ravel() for block in blocks]) + + +def unpack_el315(data: UInt8Array) -> UInt8Array: + """Inverse of :func:`pack_el315`, returning ``(2560, 1440)`` device codes.""" + blocks = _unpack_nibbles(data.reshape(8, EL315_BLOCK_ROWS, EL315_BLOCK_PIXELS // 2)) + halves: list[UInt8Array] = [] + for half in range(2): + group = blocks[half * 4 : half * 4 + 4] + band = np.concatenate( + [group[0], group[1], group[2], group[3][:, :EL315_PADDED_PIXELS]], axis=1 + ) + strip = ( + band.reshape(EL315_BLOCK_ROWS, EL315_HALF_ROWS, 2) + .transpose(1, 0, 2) + .reshape(EL315_HALF_ROWS, EL315_BLOCK_ROWS * 2) + ) + halves.append(strip) + return np.flipud(np.concatenate(halves, axis=0)) + + +PACKERS: Final[dict[PanelModel, Callable[[UInt8Array], UInt8Array]]] = { + "133": pack_el133uf1, + "315": pack_el315, +} +UNPACKERS: Final[dict[PanelModel, Callable[[UInt8Array], UInt8Array]]] = { + "133": unpack_el133uf1, + "315": unpack_el315, +} + + +def encode_bin(indices: UInt8Array, spec: PanelSpec) -> bytes: + """Encode portrait palette indices into the panel's ``.bin`` frame buffer. + + Args: + indices: ``(height, width)`` palette indices (``0..5``) in the panel's native + portrait orientation. + spec: Target panel. + + Raises: + BinFormatError: On a size mismatch or out-of-range palette index. + """ + if indices.shape != (spec.height, spec.width): + raise BinFormatError( + f"{spec.label} needs {spec.width}x{spec.height} portrait indices, " + f"got {indices.shape[1] if indices.ndim > 1 else '?'}x{indices.shape[0]}" + ) + if bool(np.any(indices >= len(DEVICE_CODES))): + raise BinFormatError("Palette indices must be in 0..5") + codes = DEVICE_CODES[indices.astype(np.intp, copy=False)] + packed = PACKERS[spec.key](codes) + if packed.size != spec.bin_size: + raise BinFormatError(f"Encoded {packed.size} bytes, expected exactly {spec.bin_size}") + return packed.tobytes() + + +def decode_bin(data: bytes, spec: PanelSpec) -> UInt8Array: + """Decode a ``.bin`` back to ``(height, width)`` portrait palette indices. + + Raises: + BinFormatError: On a wrong length or a nibble that is not a valid device code. + """ + if len(data) != spec.bin_size: + raise BinFormatError(f"{spec.label} .bin must be {spec.bin_size} bytes, got {len(data)}") + raw = np.frombuffer(data, dtype=np.uint8) + nibbles = _unpack_nibbles(raw) + if not np.all(np.isin(nibbles, DEVICE_CODES)): + raise BinFormatError("The .bin contains nibbles outside {0x0,0x1,0x2,0x3,0x5,0x6}") + codes = UNPACKERS[spec.key](raw) + return _CODE_TO_INDEX[codes] diff --git a/tests/test_packing.py b/tests/test_packing.py new file mode 100644 index 0000000..f40d989 --- /dev/null +++ b/tests/test_packing.py @@ -0,0 +1,137 @@ +from __future__ import annotations + +import numpy as np +import numpy.typing as npt +import pytest + +from app.core.config_models import PANEL_SPECS +from app.processor.packing import BinFormatError, decode_bin, encode_bin +from app.processor.palette import DEVICE_CODES +from tests.reference import fraimic_converter as ref + +SPEC_133 = PANEL_SPECS["133"] +SPEC_315 = PANEL_SPECS["315"] +BLACK, WHITE, YELLOW, RED, BLUE, GREEN = range(6) + + +def random_indices(height: int, width: int, seed: int = 0) -> npt.NDArray[np.uint8]: + return np.random.default_rng(seed).integers(0, 6, (height, width), dtype=np.uint8) + + +@pytest.mark.parametrize(("key", "size"), [("133", 960_000), ("315", 2_304_000)]) +def test_exact_byte_length(key: str, size: int) -> None: + spec = PANEL_SPECS[key] # type: ignore[index] + data = encode_bin(random_indices(spec.height, spec.width), spec) + assert len(data) == size == spec.bin_size + + +@pytest.mark.parametrize("key", ["133", "315"]) +def test_every_nibble_is_a_valid_device_code(key: str) -> None: + spec = PANEL_SPECS[key] # type: ignore[index] + raw = np.frombuffer(encode_bin(random_indices(spec.height, spec.width, 1), spec), np.uint8) + nibbles = set(np.unique(raw >> 4).tolist()) | set(np.unique(raw & 0x0F).tolist()) + assert nibbles == {0x0, 0x1, 0x2, 0x3, 0x5, 0x6} + assert 0x4 not in nibbles + + +@pytest.mark.parametrize("key", ["133", "315"]) +def test_byte_parity_with_official_packers(key: str) -> None: + spec = PANEL_SPECS[key] # type: ignore[index] + indices = random_indices(spec.height, spec.width, 2) + official = ref.pack_el133uf1 if key == "133" else ref.pack_el315 + expected = official(ref.COLOR_CODES[indices]).tobytes() + assert encode_bin(indices, spec) == expected + + +@pytest.mark.parametrize("key", ["133", "315"]) +def test_decode_round_trip(key: str) -> None: + spec = PANEL_SPECS[key] # type: ignore[index] + indices = random_indices(spec.height, spec.width, 3) + assert np.array_equal(decode_bin(encode_bin(indices, spec), spec), indices) + + +def test_el133_spec_walkthrough() -> None: + """Row 0 starts with [Black, White, Yellow, Red] -> bytes 0x01 0x23.""" + indices = np.full((1600, 1200), WHITE, dtype=np.uint8) + indices[0, :4] = [BLACK, WHITE, YELLOW, RED] + indices[0, 600:602] = [RED, BLUE] # first pixels of the right half + data = encode_bin(indices, SPEC_133) + assert data[0:2] == bytes([0x01, 0x23]) + assert data[480_000] == 0x35 # right half starts at byte 480,000 + assert data[2] == 0x11 + + +def test_el133_left_half_precedes_right_half() -> None: + indices = np.zeros((1600, 1200), dtype=np.uint8) + indices[:, 600:] = GREEN + data = encode_bin(indices, SPEC_133) + assert set(data[:480_000]) == {0x00} + assert set(data[480_000:]) == {0x66} + + +def test_el315_spec_walkthrough() -> None: + """Bottom-left 2x2 [[Yellow, Red], [Black, White]] -> first bytes 0x01 0x23.""" + indices = np.full((2560, 1440), WHITE, dtype=np.uint8) + indices[2559, 0:2] = [BLACK, WHITE] + indices[2558, 0:2] = [YELLOW, RED] + data = encode_bin(indices, SPEC_315) + assert data[0:2] == bytes([0x01, 0x23]) + + +def test_el315_padding_in_ic4_and_ic8() -> None: + indices = np.zeros((2560, 1440), dtype=np.uint8) # all black -> real bytes are 0x00 + raw = np.frombuffer(encode_bin(indices, SPEC_315), np.uint8).reshape(8, 720, 400) + for ic in (3, 7): # IC4 and IC8 + assert np.all(raw[ic, :, :80] == 0x00) + assert np.all(raw[ic, :, 80:] == 0x11) + for ic in (0, 1, 2, 4, 5, 6): + assert np.all(raw[ic] == 0x00) + + +def test_el315_matches_spec_frame_mapping() -> None: + """Check sampled nibbles against the spec formula on an asymmetric pattern.""" + rng = np.random.default_rng(7) + indices = random_indices(2560, 1440, 4) + raw = np.frombuffer(encode_bin(indices, SPEC_315), np.uint8) + codes = DEVICE_CODES[indices] + for _ in range(5_000): + k = int(rng.integers(1, 9)) # IC1..IC8 + g, j = (k - 1) // 4, (k - 1) % 4 + real = 160 if j == 3 else 800 + b = int(rng.integers(0, 720)) + p = int(rng.integers(0, real)) + q = j * 800 + p + x = 2 * b + (q % 2) + y = 2559 - (g * 1280 + q // 2) + byte = raw[(k - 1) * 288_000 + b * 400 + p // 2] + nibble = byte >> 4 if p % 2 == 0 else byte & 0x0F + assert nibble == codes[y, x], (k, b, p) + + +def test_el315_is_not_a_plain_transpose() -> None: + """The spec warns that a transposed layout 'looks plausible'; use an asymmetric marker.""" + indices = np.full((2560, 1440), WHITE, dtype=np.uint8) + indices[0:80, 1438:1440] = RED # top-right 80x2 strip -> IC8, last block row + raw = np.frombuffer(encode_bin(indices, SPEC_315), np.uint8).reshape(8, 720, 400) + assert np.all(raw[7, 719, :80] == 0x33) + assert np.count_nonzero(raw == 0x33) == 80 + + +@pytest.mark.parametrize("shape", [(1200, 1600), (1600, 1201), (10, 10)]) +def test_encode_rejects_wrong_shape(shape: tuple[int, int]) -> None: + with pytest.raises(BinFormatError): + encode_bin(np.zeros(shape, dtype=np.uint8), SPEC_133) + + +def test_encode_rejects_out_of_range_index() -> None: + indices = np.zeros((1600, 1200), dtype=np.uint8) + indices[5, 5] = 6 + with pytest.raises(BinFormatError, match=r"0..5"): + encode_bin(indices, SPEC_133) + + +def test_decode_rejects_bad_data() -> None: + with pytest.raises(BinFormatError, match="960000"): + decode_bin(b"\x00" * 10, SPEC_133) + with pytest.raises(BinFormatError, match="nibbles"): + decode_bin(bytes([0x44]) * 960_000, SPEC_133) From c81e6adc9fde0fffa86a2eb190235eacb6ad864b Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sat, 14 Nov 2026 17:35:09 +0100 Subject: [PATCH 14/86] feat: add fit modes, eInk enhancement and render pipeline - smart_crop: official cover-scale + crop, with the window shifted to keep focus regions (faces) in frame; identical to the official crop fit when no regions are given. - contain: official fit + centered paste on a black, white or blurred, darkened background; identical to the official letterbox for flat fills. - enhance: brightness -> contrast -> saturation -> [sharpness] -> EDGE_ENHANCE -> SMOOTH -> SHARPEN on the picture only (official order). - render: decode (magic bytes, EXIF orientation, alpha flattened on white), compose and dither in viewing orientation, rotate indices losslessly by landscape_rotation into the native portrait buffer, then encode the .bin. Produces the clean JPEG preview and an exact 6-color dithered PNG. Co-Authored-By: Claude Opus 5.5 --- app/processor/__init__.py | 22 ++++- app/processor/enhance.py | 35 ++++++++ app/processor/fit.py | 139 +++++++++++++++++++++++++++++++ app/processor/pipeline.py | 166 ++++++++++++++++++++++++++++++++++++++ tests/test_enhance.py | 46 +++++++++++ tests/test_fit.py | 150 ++++++++++++++++++++++++++++++++++ tests/test_pipeline.py | 163 +++++++++++++++++++++++++++++++++++++ 7 files changed, 717 insertions(+), 4 deletions(-) create mode 100644 app/processor/enhance.py create mode 100644 app/processor/fit.py create mode 100644 app/processor/pipeline.py create mode 100644 tests/test_enhance.py create mode 100644 tests/test_fit.py create mode 100644 tests/test_pipeline.py diff --git a/app/processor/__init__.py b/app/processor/__init__.py index 9303ead..87b01b7 100644 --- a/app/processor/__init__.py +++ b/app/processor/__init__.py @@ -1,6 +1,20 @@ -"""Image processing pipeline. +"""Image processing pipeline for Spectra 6 color eInk panels. -Fit modes (``smart_crop``, ``contain``), eInk enhancement, Spectra 6 dithering -and Fraimic ``.bin`` packing live here. They are added in the -``feat/eink-fraimic`` milestone. +* :mod:`~app.processor.fit` - ``smart_crop`` (face-aware) and ``contain`` fit modes. +* :mod:`~app.processor.enhance` - official brightness/contrast/saturation/filter chain. +* :mod:`~app.processor.dither` - exact vectorized Atkinson / Floyd-Steinberg dithering. +* :mod:`~app.processor.packing` - EL133UF1 / EL315 ``.bin`` encoding. +* :mod:`~app.processor.pipeline` - end-to-end :func:`render`. """ + +from app.processor.fit import FocusRegion +from app.processor.pipeline import RenderOptions, RenderResult, decode_image, render, render_bytes + +__all__ = [ + "FocusRegion", + "RenderOptions", + "RenderResult", + "decode_image", + "render", + "render_bytes", +] diff --git a/app/processor/enhance.py b/app/processor/enhance.py new file mode 100644 index 0000000..0a6a040 --- /dev/null +++ b/app/processor/enhance.py @@ -0,0 +1,35 @@ +"""eInk enhancement pipeline (official Fraimic order and defaults). + +Order: Brightness -> Contrast -> Color (saturation) -> [Sharpness] -> EDGE_ENHANCE -> +SMOOTH -> SHARPEN. With ``sharpness == 1.0`` (default) the extra Sharpness step is +skipped, making the output identical to the official converter's ``process_image``. +Enhancement must run on the picture only (before letterbox padding) so flat bars do +not skew the contrast pivot and filters do not bleed across the picture/bar seam. +""" + +from __future__ import annotations + +from PIL import Image, ImageEnhance, ImageFilter + +from app.core.config_models import EinkConfig + + +def enhance(image: Image.Image, eink: EinkConfig, *, edge_filters: bool = True) -> Image.Image: + """Apply the eInk color and detail adjustments. + + Args: + image: RGB picture (already scaled to its on-panel size). + eink: Enhancement settings. + edge_filters: Set to ``False`` to skip the edge-enhance/smooth/sharpen chain + regardless of ``eink.edge_filters`` (used for blurred backgrounds). + """ + result = ImageEnhance.Brightness(image).enhance(eink.brightness) + result = ImageEnhance.Contrast(result).enhance(eink.contrast) + result = ImageEnhance.Color(result).enhance(eink.saturation) + if eink.sharpness != 1.0: + result = ImageEnhance.Sharpness(result).enhance(eink.sharpness) + if edge_filters and eink.edge_filters: + result = result.filter(ImageFilter.EDGE_ENHANCE) + result = result.filter(ImageFilter.SMOOTH) + result = result.filter(ImageFilter.SHARPEN) + return result diff --git a/app/processor/fit.py b/app/processor/fit.py new file mode 100644 index 0000000..4d07251 --- /dev/null +++ b/app/processor/fit.py @@ -0,0 +1,139 @@ +"""Fit modes: face-aware ``smart_crop`` and ``contain`` with a padded background. + +Scaling follows the official Fraimic converter (Lanczos resampling, ``int(round())`` +sizes, centered placement), so that ``smart_crop`` without focus regions equals the +official ``--fit crop`` and ``contain`` with a black/white background equals the +official ``--fit letterbox``. +""" + +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import dataclass +from typing import Final, Literal + +from PIL import Image, ImageEnhance, ImageFilter + +BackgroundStyle = Literal["blur", "black", "white"] +Size = tuple[int, int] + +FLAT_BACKGROUNDS: Final[dict[str, tuple[int, int, int]]] = { + "black": (0, 0, 0), + "white": (255, 255, 255), +} +#: Vertical position of the faces' centre in a portrait-ish crop (leaves headroom). +VERTICAL_FOCUS_ANCHOR: Final = 0.4 +#: The blurred background is computed at 1/BLUR_DOWNSCALE resolution for speed. +BLUR_DOWNSCALE: Final = 8 +BLUR_RADIUS: Final = 5 +BLUR_DARKEN: Final = 0.8 + + +@dataclass(frozen=True, slots=True) +class FocusRegion: + """A region of interest (e.g. a detected face) in normalized coordinates. + + Coordinates are fractions (``0..1``) of the EXIF-corrected image, with ``(x, y)`` + the top-left corner. + """ + + x: float + y: float + width: float + height: float + + def __post_init__(self) -> None: + if not (0.0 <= self.x <= 1.0 and 0.0 <= self.y <= 1.0): + raise ValueError("FocusRegion origin must be within 0..1") + if self.width <= 0 or self.height <= 0: + raise ValueError("FocusRegion size must be positive") + if self.x + self.width > 1.0 + 1e-6 or self.y + self.height > 1.0 + 1e-6: + raise ValueError("FocusRegion must lie inside the image") + + @classmethod + def from_pixels( + cls, x1: float, y1: float, x2: float, y2: float, image_width: int, image_height: int + ) -> FocusRegion: + """Build a region from pixel corners measured on an image of the given size.""" + if image_width <= 0 or image_height <= 0: + raise ValueError("Image size must be positive") + left = min(max(min(x1, x2) / image_width, 0.0), 1.0) + top = min(max(min(y1, y2) / image_height, 0.0), 1.0) + right = min(max(max(x1, x2) / image_width, 0.0), 1.0) + bottom = min(max(max(y1, y2) / image_height, 0.0), 1.0) + return cls(left, top, max(right - left, 1e-6), max(bottom - top, 1e-6)) + + +def _scaled_size(size: Size, ratio: float) -> Size: + return max(1, round(size[0] * ratio)), max(1, round(size[1] * ratio)) + + +def _place_window(lo: float, hi: float, window: int, total: int, anchor: float) -> int: + """Start offset of a ``window`` along an axis of length ``total``. + + The window is positioned so the focus span ``[lo, hi]`` sits at ``anchor`` (fraction + of the window). When the span fits, it is kept entirely inside the window. + """ + start = (lo + hi) / 2 - anchor * window + if hi - lo <= window: + start = min(max(start, hi - window), lo) + return round(min(max(start, 0.0), float(total - window))) + + +def smart_crop(image: Image.Image, size: Size, regions: Sequence[FocusRegion] = ()) -> Image.Image: + """Scale to fill ``size`` and crop the overflow, keeping focus regions in frame. + + Without regions this is a centered crop identical to the official ``crop`` fit. + With regions, the crop window is moved along the overflowing axis so the union of + the regions is centered horizontally, or placed at 40% of the height vertically. + """ + target_w, target_h = size + ratio = max(target_w / image.width, target_h / image.height) + resized_w, resized_h = _scaled_size(image.size, ratio) + resized = image.resize((resized_w, resized_h), Image.Resampling.LANCZOS) + + left = (resized_w - target_w) // 2 + top = (resized_h - target_h) // 2 + if regions: + x1 = min(r.x for r in regions) * resized_w + x2 = max(r.x + r.width for r in regions) * resized_w + y1 = min(r.y for r in regions) * resized_h + y2 = max(r.y + r.height for r in regions) * resized_h + if resized_w > target_w: + left = _place_window(x1, x2, target_w, resized_w, 0.5) + if resized_h > target_h: + top = _place_window(y1, y2, target_h, resized_h, VERTICAL_FOCUS_ANCHOR) + return resized.crop((left, top, left + target_w, top + target_h)) + + +def fit_inside(image: Image.Image, size: Size) -> Image.Image: + """Scale ``image`` to fit entirely inside ``size`` (no cropping).""" + ratio = min(size[0] / image.width, size[1] / image.height) + return image.resize(_scaled_size(image.size, ratio), Image.Resampling.LANCZOS) + + +def blurred_background(image: Image.Image, size: Size) -> Image.Image: + """A soft, darkened, frame-filling version of ``image`` used behind ``contain``.""" + small = (max(1, size[0] // BLUR_DOWNSCALE), max(1, size[1] // BLUR_DOWNSCALE)) + cover = smart_crop(image, small).filter(ImageFilter.GaussianBlur(BLUR_RADIUS)) + upscaled = cover.resize(size, Image.Resampling.BICUBIC) + return ImageEnhance.Brightness(upscaled).enhance(BLUR_DARKEN) + + +def make_background(image: Image.Image, size: Size, style: BackgroundStyle) -> Image.Image: + """Frame-sized background for the ``contain`` fit mode.""" + if style == "blur": + return blurred_background(image, size) + return Image.new("RGB", size, FLAT_BACKGROUNDS[style]) + + +def paste_centered(background: Image.Image, picture: Image.Image) -> Image.Image: + """Center ``picture`` on a copy of ``background`` (official ``pad_to_frame`` offsets).""" + if picture.size == background.size: + return picture + framed = background.copy() + framed.paste( + picture, + ((background.width - picture.width) // 2, (background.height - picture.height) // 2), + ) + return framed diff --git a/app/processor/pipeline.py b/app/processor/pipeline.py new file mode 100644 index 0000000..ea2ed50 --- /dev/null +++ b/app/processor/pipeline.py @@ -0,0 +1,166 @@ +"""End-to-end rendering: image bytes -> composed preview -> dithered indices -> ``.bin``. + +Steps: + +1. Decode, validate, apply the EXIF orientation and flatten transparency onto white. +2. Compose in *viewing* orientation (``frame_size`` honours portrait/landscape): + ``smart_crop`` (fill, face-aware) or ``contain`` (fit + blur/black/white background), + with the eInk enhancement applied to the picture only. +3. Dither in viewing orientation (Atkinson or Floyd-Steinberg, tuned metric). +4. Rotate the palette indices losslessly into the panel's native portrait buffer + (``landscape_rotation`` degrees counter-clockwise) and pack the ``.bin``. + +Rendering is CPU-bound and synchronous; call it through ``asyncio.to_thread``. +""" + +from __future__ import annotations + +import hashlib +import io +from collections.abc import Sequence +from dataclasses import dataclass, field +from functools import cached_property +from typing import Literal + +import numpy as np +import numpy.typing as npt +from PIL import Image, ImageOps + +from app.core.config_models import EinkConfig, FitMode, PanelSpec, RuntimeConfig +from app.core.security import verify_image_bytes +from app.processor.dither import dither +from app.processor.enhance import enhance +from app.processor.fit import ( + BackgroundStyle, + FocusRegion, + fit_inside, + make_background, + paste_centered, + smart_crop, +) +from app.processor.packing import encode_bin +from app.processor.palette import indices_to_rgb + +Rotation = Literal[0, 90, 270] +PREVIEW_JPEG_QUALITY = 90 + + +def decode_image(data: bytes) -> Image.Image: + """Decode untrusted image bytes into an upright RGB image. + + Raises: + InvalidImageError: If the data is not a supported, valid image. + """ + verify_image_bytes(data) + with Image.open(io.BytesIO(data)) as opened: + opened.load() + upright = ImageOps.exif_transpose(opened) + has_alpha = upright.mode in {"RGBA", "LA", "PA"} or ( + upright.mode == "P" and "transparency" in upright.info + ) + if has_alpha: + rgba = upright.convert("RGBA") + flattened = Image.new("RGB", rgba.size, (255, 255, 255)) + flattened.paste(rgba, mask=rgba.getchannel("A")) + return flattened + return upright.convert("RGB") + + +@dataclass(frozen=True, slots=True) +class RenderOptions: + """Everything the renderer needs, resolved from the runtime configuration.""" + + panel: PanelSpec + frame_size: tuple[int, int] + rotation: Rotation + fit: FitMode + background: BackgroundStyle + eink: EinkConfig + + def __post_init__(self) -> None: + native = (self.panel.width, self.panel.height) + expected = native if self.rotation == 0 else (native[1], native[0]) + if self.frame_size != expected: + raise ValueError( + f"frame_size {self.frame_size} does not match panel {native} " + f"with rotation {self.rotation}" + ) + + @classmethod + def from_config(cls, config: RuntimeConfig, *, fit: FitMode | None = None) -> RenderOptions: + """Build options from the effective config, optionally overriding the fit mode.""" + rotation: Rotation = ( + 0 if config.display.orientation == "portrait" else config.display.landscape_rotation + ) + return cls( + panel=config.fraimic.spec, + frame_size=config.frame_size, + rotation=rotation, + fit=fit or config.display.default_fit, + background=config.display.contain_background, + eink=config.eink, + ) + + +@dataclass(frozen=True) +class RenderResult: + """Output of :func:`render`.""" + + options: RenderOptions + composed: Image.Image = field(repr=False) + indices: npt.NDArray[np.uint8] = field(repr=False) + bin: bytes = field(repr=False) + + @cached_property + def sha256(self) -> str: + """SHA-256 of the ``.bin`` payload (hex).""" + return hashlib.sha256(self.bin).hexdigest() + + def preview_jpeg(self, quality: int = PREVIEW_JPEG_QUALITY) -> bytes: + """The enhanced composition (before dithering) as JPEG, in viewing orientation.""" + buffer = io.BytesIO() + self.composed.save(buffer, format="JPEG", quality=quality, optimize=True) + return buffer.getvalue() + + def dithered_png(self) -> bytes: + """Exact 6-color simulation of the panel output, in viewing orientation.""" + buffer = io.BytesIO() + Image.fromarray(indices_to_rgb(self.indices)).save(buffer, format="PNG", optimize=True) + return buffer.getvalue() + + +def compose( + image: Image.Image, options: RenderOptions, regions: Sequence[FocusRegion] = () +) -> Image.Image: + """Fit and enhance ``image`` into the frame, in viewing orientation.""" + if options.fit == "smart_crop": + return enhance(smart_crop(image, options.frame_size, regions), options.eink) + picture = enhance(fit_inside(image, options.frame_size), options.eink) + if picture.size == options.frame_size: + return picture + background = make_background(image, options.frame_size, options.background) + if options.background == "blur": + background = enhance(background, options.eink, edge_filters=False) + return paste_centered(background, picture) + + +def render( + image: Image.Image, options: RenderOptions, regions: Sequence[FocusRegion] = () +) -> RenderResult: + """Compose, dither and encode ``image`` for the configured panel.""" + composed = compose(image.convert("RGB"), options, regions) + indices = dither(np.asarray(composed, dtype=np.uint8), options.eink.dither) + portrait = np.ascontiguousarray(np.rot90(indices, k=options.rotation // 90)) + return RenderResult( + options=options, + composed=composed, + indices=indices, + bin=encode_bin(portrait, options.panel), + ) + + +def render_bytes( + data: bytes, options: RenderOptions, regions: Sequence[FocusRegion] = () +) -> RenderResult: + """Decode untrusted bytes and :func:`render` them.""" + return render(decode_image(data), options, regions) diff --git a/tests/test_enhance.py b/tests/test_enhance.py new file mode 100644 index 0000000..d43afd2 --- /dev/null +++ b/tests/test_enhance.py @@ -0,0 +1,46 @@ +from __future__ import annotations + +import numpy as np +from PIL import Image + +from app.core.config_models import EinkConfig +from app.processor.enhance import enhance +from tests.reference import fraimic_converter as ref + + +def sample() -> Image.Image: + rng = np.random.default_rng(5) + return Image.fromarray(rng.integers(0, 256, (120, 90, 3), dtype=np.uint8)) + + +def test_defaults_match_official_chain() -> None: + image = sample() + expected = ref.enhance(image) + assert np.array_equal(np.asarray(enhance(image, EinkConfig())), np.asarray(expected)) + + +def test_custom_factors_match_official_chain() -> None: + image = sample() + config = EinkConfig(brightness=0.9, contrast=1.4, saturation=1.6) + expected = ref.enhance(image, brightness=0.9, contrast=1.4, saturation=1.6) + assert np.array_equal(np.asarray(enhance(image, config)), np.asarray(expected)) + + +def test_neutral_settings_leave_image_unchanged() -> None: + image = sample() + config = EinkConfig(brightness=1.0, contrast=1.0, saturation=1.0, edge_filters=False) + assert np.array_equal(np.asarray(enhance(image, config)), np.asarray(image)) + + +def test_edge_filters_can_be_suppressed_per_call() -> None: + image = sample() + config = EinkConfig(brightness=1.0, contrast=1.0, saturation=1.0, edge_filters=True) + assert np.array_equal(np.asarray(enhance(image, config, edge_filters=False)), np.asarray(image)) + assert not np.array_equal(np.asarray(enhance(image, config)), np.asarray(image)) + + +def test_sharpness_is_applied_when_not_neutral() -> None: + image = sample() + base = EinkConfig(edge_filters=False) + sharp = EinkConfig(edge_filters=False, sharpness=2.0) + assert not np.array_equal(np.asarray(enhance(image, base)), np.asarray(enhance(image, sharp))) diff --git a/tests/test_fit.py b/tests/test_fit.py new file mode 100644 index 0000000..3dde2ed --- /dev/null +++ b/tests/test_fit.py @@ -0,0 +1,150 @@ +from __future__ import annotations + +import io + +import numpy as np +import pytest +from PIL import Image + +from app.processor.fit import ( + FocusRegion, + fit_inside, + make_background, + paste_centered, + smart_crop, +) +from app.processor.pipeline import decode_image +from tests.reference import fraimic_converter as ref + + +def noise(width: int, height: int, seed: int = 0) -> Image.Image: + rng = np.random.default_rng(seed) + return Image.fromarray(rng.integers(0, 256, (height, width, 3), dtype=np.uint8)) + + +def with_marker(width: int, height: int, box: tuple[int, int, int, int]) -> Image.Image: + image = Image.new("RGB", (width, height), (255, 255, 255)) + image.paste((255, 0, 0), box) + return image + + +def red_fraction(image: Image.Image) -> float: + arr = np.asarray(image).astype(int) + red = (arr[..., 0] > 200) & (arr[..., 1] < 60) & (arr[..., 2] < 60) + return float(red.mean()) + + +# --- FocusRegion ----------------------------------------------------------------- +def test_focus_region_from_pixels_normalizes_and_clamps() -> None: + region = FocusRegion.from_pixels(300, 50, 100, 150, 400, 200) + assert (region.x, region.y) == (0.25, 0.25) + assert (region.width, region.height) == (0.5, 0.5) + clamped = FocusRegion.from_pixels(-10, -10, 500, 300, 400, 200) + assert (clamped.x, clamped.y, clamped.width, clamped.height) == (0, 0, 1, 1) + + +@pytest.mark.parametrize( + "args", [(-0.1, 0, 0.5, 0.5), (0, 0, 0, 0.5), (0.8, 0, 0.5, 0.5), (0, 1.1, 0.1, 0.1)] +) +def test_focus_region_validation(args: tuple[float, float, float, float]) -> None: + with pytest.raises(ValueError): + FocusRegion(*args) + + +# --- smart_crop ------------------------------------------------------------------ +@pytest.mark.parametrize("source", [(4000, 3000), (3000, 4000), (1200, 1600), (300, 200)]) +@pytest.mark.parametrize("target", [(1200, 1600), (1600, 1200)]) +def test_smart_crop_without_regions_equals_official_crop( + source: tuple[int, int], target: tuple[int, int] +) -> None: + image = noise(*source) + expected = ref.scale_to_frame(image, "crop", ref.Panel(*target)) + result = smart_crop(image, target) + assert result.size == target + assert np.array_equal(np.asarray(result), np.asarray(expected)) + + +def test_smart_crop_keeps_face_near_horizontal_edge() -> None: + # Landscape photo, portrait frame: only a centered vertical slice survives a plain crop. + image = with_marker(4000, 3000, (3600, 1200, 3900, 1500)) + region = FocusRegion.from_pixels(3600, 1200, 3900, 1500, 4000, 3000) + assert red_fraction(smart_crop(image, (1200, 1600))) == 0.0 + cropped = smart_crop(image, (1200, 1600), [region]) + assert red_fraction(cropped) > 0.01 + + +def test_smart_crop_keeps_face_near_top_with_headroom() -> None: + # Portrait photo, landscape frame: the face at the very top would be cut by a centre crop. + image = with_marker(3000, 4000, (1300, 100, 1700, 500)) + region = FocusRegion.from_pixels(1300, 100, 1700, 500, 3000, 4000) + assert red_fraction(smart_crop(image, (1600, 1200))) == 0.0 + cropped = smart_crop(image, (1600, 1200), [region]) + rows = np.where(np.asarray(cropped)[..., 1].min(axis=1) < 60)[0] + assert rows.size > 0 + assert rows.min() >= 0 and rows.max() < 1200 + + +def test_smart_crop_union_of_regions_stays_inside() -> None: + image = with_marker(4000, 3000, (1000, 1000, 1100, 1100)) + image.paste((255, 0, 0), (2300, 1000, 2400, 1100)) + regions = [ + FocusRegion.from_pixels(1000, 1000, 1100, 1100, 4000, 3000), + FocusRegion.from_pixels(2300, 1000, 2400, 1100, 4000, 3000), + ] + cropped = np.asarray(smart_crop(image, (1200, 1600), regions)) + cols = np.where(cropped[..., 1].min(axis=0) < 60)[0] + assert cols.min() > 0 and cols.max() < 1199 + assert cols.max() - cols.min() > 400 # both faces are in frame + + +# --- contain ---------------------------------------------------------------------- +@pytest.mark.parametrize("source", [(4000, 3000), (3000, 4000), (500, 500)]) +@pytest.mark.parametrize("style", ["black", "white"]) +def test_contain_with_flat_background_equals_official_letterbox( + source: tuple[int, int], style: str +) -> None: + image = noise(*source, seed=3) + panel = ref.Panel(1200, 1600) + expected = ref.pad_to_frame( + ref.scale_to_frame(image, "letterbox", panel), panel, ref.LETTERBOX_COLORS[style] + ) + background = make_background(image, (1200, 1600), style) # type: ignore[arg-type] + result = paste_centered(background, fit_inside(image, (1200, 1600))) + assert np.array_equal(np.asarray(result), np.asarray(expected)) + + +def test_contain_keeps_aspect_ratio_and_corners() -> None: + picture = fit_inside(noise(4000, 2000), (1200, 1600)) + assert picture.size == (1200, 600) + framed = paste_centered(make_background(picture, (1200, 1600), "white"), picture) + assert framed.getpixel((0, 0)) == (255, 255, 255) + assert framed.getpixel((1199, 1599)) == (255, 255, 255) + + +def test_blur_background_fills_frame() -> None: + image = Image.new("RGB", (400, 300), (200, 40, 40)) + background = make_background(image, (1200, 1600), "blur") + assert background.size == (1200, 1600) + corner = background.getpixel((0, 0)) + assert isinstance(corner, tuple) + assert corner[0] > corner[1] # derived from the image, not a flat fill + assert corner[0] < 200 # darkened + + +# --- decoding ----------------------------------------------------------------------- +def test_decode_applies_exif_orientation() -> None: + image = Image.new("RGB", (40, 20), (10, 200, 10)) + exif = Image.Exif() + exif[0x0112] = 6 # rotate 90 CW on display + buffer = io.BytesIO() + image.save(buffer, format="JPEG", exif=exif) + assert decode_image(buffer.getvalue()).size == (20, 40) + + +def test_decode_flattens_transparency_on_white() -> None: + image = Image.new("RGBA", (10, 10), (255, 0, 0, 0)) + buffer = io.BytesIO() + image.save(buffer, format="PNG") + decoded = decode_image(buffer.getvalue()) + assert decoded.mode == "RGB" + assert decoded.getpixel((5, 5)) == (255, 255, 255) diff --git a/tests/test_pipeline.py b/tests/test_pipeline.py new file mode 100644 index 0000000..446fa4a --- /dev/null +++ b/tests/test_pipeline.py @@ -0,0 +1,163 @@ +from __future__ import annotations + +import io +from typing import Any + +import numpy as np +import pytest +from PIL import Image + +from app.core.config_models import RuntimeConfig +from app.processor.packing import decode_bin +from app.processor.pipeline import RenderOptions, compose, render, render_bytes +from tests.reference import fraimic_converter as ref + +RED, WHITE = 3, 1 + + +def config(**sections: Any) -> RuntimeConfig: + return RuntimeConfig.model_validate(sections) + + +def neutral_eink() -> dict[str, Any]: + """No enhancement so flat test colors survive untouched.""" + return { + "brightness": 1.0, + "contrast": 1.0, + "saturation": 1.0, + "edge_filters": False, + "dither": "floyd_steinberg", + } + + +def png_bytes(image: Image.Image) -> bytes: + buffer = io.BytesIO() + image.save(buffer, format="PNG") + return buffer.getvalue() + + +@pytest.mark.parametrize( + ("panel", "orientation", "frame", "size"), + [ + ("133", "portrait", (1200, 1600), 960_000), + ("133", "landscape", (1600, 1200), 960_000), + ("315", "portrait", (1440, 2560), 2_304_000), + ("315", "landscape", (2560, 1440), 2_304_000), + ], +) +def test_render_produces_exact_bin_for_every_panel_and_orientation( + panel: str, orientation: str, frame: tuple[int, int], size: int +) -> None: + options = RenderOptions.from_config( + config(fraimic={"panel": panel}, display={"orientation": orientation}) + ) + assert options.frame_size == frame + image = Image.new("RGB", (640, 480), (30, 120, 200)) + result = render(image, options) + assert len(result.bin) == size + assert result.composed.size == frame + assert result.indices.shape == (frame[1], frame[0]) + assert len(result.sha256) == 64 + + +@pytest.mark.parametrize( + ("rotation", "corner"), + [(90, "bottom-left"), (270, "top-right")], +) +def test_landscape_rotation_places_top_left_marker(rotation: int, corner: str) -> None: + options = RenderOptions.from_config( + config( + display={ + "orientation": "landscape", + "landscape_rotation": rotation, + "default_fit": "contain", + }, + eink=neutral_eink(), + ) + ) + image = Image.new("RGB", (1600, 1200), (255, 255, 255)) + image.paste((255, 0, 0), (0, 0, 100, 100)) # top-left marker in viewing orientation + result = render(image, options) + assert result.indices[50, 50] == RED + + portrait = decode_bin(result.bin, options.panel) # native 1200x1600 portrait buffer + assert portrait.shape == (1600, 1200) + marker = { + "bottom-left": portrait[1600 - 100 :, :100], + "top-right": portrait[:100, 1200 - 100 :], + }[corner] + assert np.all(marker == RED) + assert np.count_nonzero(portrait == RED) == 100 * 100 + assert np.count_nonzero(portrait == WHITE) == 1200 * 1600 - 100 * 100 + + +def test_portrait_render_is_not_rotated() -> None: + options = RenderOptions.from_config( + config(display={"default_fit": "contain"}, eink=neutral_eink()) + ) + image = Image.new("RGB", (1200, 1600), (255, 255, 255)) + image.paste((255, 0, 0), (0, 0, 100, 100)) + portrait = decode_bin(render(image, options).bin, options.panel) + assert np.all(portrait[:100, :100] == RED) + + +def test_contain_compose_equals_official_letterbox_pipeline() -> None: + rng = np.random.default_rng(8) + image = Image.fromarray(rng.integers(0, 256, (900, 1600, 3), dtype=np.uint8)) + options = RenderOptions.from_config( + config(display={"default_fit": "contain", "contain_background": "black"}) + ) + panel = ref.Panel(1200, 1600) + expected = ref.pad_to_frame( + ref.enhance(ref.scale_to_frame(image, "letterbox", panel)), panel, (0, 0, 0) + ) + assert np.array_equal(np.asarray(compose(image, options)), np.asarray(expected)) + + +def test_smart_crop_compose_equals_official_crop_pipeline() -> None: + rng = np.random.default_rng(9) + image = Image.fromarray(rng.integers(0, 256, (900, 1600, 3), dtype=np.uint8)) + options = RenderOptions.from_config(config(display={"default_fit": "smart_crop"})) + expected = ref.enhance(ref.scale_to_frame(image, "crop", ref.Panel(1200, 1600))) + assert np.array_equal(np.asarray(compose(image, options)), np.asarray(expected)) + + +def test_blur_background_is_not_edge_filtered_but_picture_is() -> None: + options = RenderOptions.from_config( + config(display={"default_fit": "contain", "contain_background": "blur"}) + ) + composed = compose(Image.new("RGB", (1600, 400), (200, 60, 60)), options) + assert composed.size == (1200, 1600) + corner = composed.getpixel((0, 0)) + assert isinstance(corner, tuple) and corner != (0, 0, 0) + + +def test_previews_are_in_viewing_orientation() -> None: + options = RenderOptions.from_config(config(display={"orientation": "landscape"})) + result = render(Image.new("RGB", (800, 600), (90, 90, 200)), options) + jpeg = Image.open(io.BytesIO(result.preview_jpeg())) + dithered = Image.open(io.BytesIO(result.dithered_png())) + assert jpeg.format == "JPEG" and jpeg.size == (1600, 1200) + assert dithered.format == "PNG" and dithered.size == (1600, 1200) + colors = {tuple(c) for c in np.asarray(dithered.convert("RGB")).reshape(-1, 3)[::97]} + allowed = {(0, 0, 0), (255, 255, 255), (255, 255, 0), (255, 0, 0), (0, 0, 255), (0, 255, 0)} + assert colors <= allowed + + +def test_render_bytes_decodes_and_validates() -> None: + options = RenderOptions.from_config(config()) + image = Image.new("RGBA", (300, 400), (0, 0, 255, 255)) + assert len(render_bytes(png_bytes(image), options).bin) == 960_000 + + +def test_render_options_reject_inconsistent_frame() -> None: + base = RenderOptions.from_config(config()) + with pytest.raises(ValueError, match="frame_size"): + RenderOptions( + panel=base.panel, + frame_size=(1600, 1200), + rotation=0, + fit=base.fit, + background=base.background, + eink=base.eink, + ) From c8971660b3dd3eee4b061882c3c3e5b59eb58845 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sat, 14 Nov 2026 17:35:46 +0100 Subject: [PATCH 15/86] feat: add current image cache store CurrentImageStore atomically writes current.bin, current.jpg (clean enhanced composition), current_dithered.png (exact 6-color simulation) and current.json last as the commit marker. The stored SHA-256 detects sets interrupted mid-write, which are then ignored instead of being served or pushed to the frame. Co-Authored-By: Claude Opus 5.5 --- app/services/__init__.py | 1 + app/services/current_image.py | 169 ++++++++++++++++++++++++++++++++++ tests/test_current_image.py | 56 +++++++++++ 3 files changed, 226 insertions(+) create mode 100644 app/services/__init__.py create mode 100644 app/services/current_image.py create mode 100644 tests/test_current_image.py diff --git a/app/services/__init__.py b/app/services/__init__.py new file mode 100644 index 0000000..294269e --- /dev/null +++ b/app/services/__init__.py @@ -0,0 +1 @@ +"""Application services orchestrating processing, storage and frame delivery.""" diff --git a/app/services/current_image.py b/app/services/current_image.py new file mode 100644 index 0000000..c1b1220 --- /dev/null +++ b/app/services/current_image.py @@ -0,0 +1,169 @@ +"""Persistence of the most recently rendered image in ``/data/cache``. + +Files: + +* ``current.bin`` - the panel frame buffer pushed to the Fraimic frame. +* ``current.jpg`` - the enhanced composition before dithering (Home Assistant, UI). +* ``current_dithered.png`` - exact 6-color simulation of what the panel shows. +* ``current.json`` - metadata, written **last** as the commit marker. It records the + SHA-256 of ``current.bin``, so a set interrupted mid-write is detected and ignored. +""" + +from __future__ import annotations + +import hashlib +import logging +import threading +from datetime import UTC, datetime +from pathlib import Path +from typing import Final + +from pydantic import AwareDatetime, BaseModel, ConfigDict, Field, JsonValue, ValidationError + +from app.core.atomic import atomic_write_bytes +from app.core.config_models import DitherAlgorithm, FitMode, PanelModel +from app.core.json_store import atomic_write_json, read_json +from app.processor.pipeline import RenderResult + +logger = logging.getLogger(__name__) + +BIN_NAME: Final = "current.bin" +JPEG_NAME: Final = "current.jpg" +DITHERED_NAME: Final = "current_dithered.png" +META_NAME: Final = "current.json" + + +class CurrentImageMeta(BaseModel): + """Metadata of the current image (served by ``GET /api/status``).""" + + model_config = ConfigDict(frozen=True) + + source: str = Field(description="Where the image came from, e.g. 'upload' or 'immich'") + title: str | None = Field(default=None, description="Human-readable title or file name") + details: dict[str, JsonValue] = Field( + default_factory=dict, description="Provider metadata (date, location, people...)" + ) + panel: PanelModel + orientation: str + rotation: int + fit: FitMode + dither: DitherAlgorithm + frame_size: tuple[int, int] = Field(description="Composition size (width, height)") + processed_at: AwareDatetime + sha256: str = Field(description="SHA-256 of current.bin") + bin_size: int + + +class CurrentImageStore: + """Reads and atomically writes the current image set.""" + + def __init__(self, cache_dir: Path) -> None: + self._dir = cache_dir + self._lock = threading.Lock() + self._meta: CurrentImageMeta | None = None + + @property + def bin_path(self) -> Path: + """Location of ``current.bin``.""" + return self._dir / BIN_NAME + + @property + def jpeg_path(self) -> Path: + """Location of ``current.jpg``.""" + return self._dir / JPEG_NAME + + @property + def dithered_path(self) -> Path: + """Location of ``current_dithered.png``.""" + return self._dir / DITHERED_NAME + + @property + def meta_path(self) -> Path: + """Location of ``current.json``.""" + return self._dir / META_NAME + + @property + def meta(self) -> CurrentImageMeta | None: + """Metadata of the current image, or ``None`` when nothing was rendered yet.""" + return self._meta + + def load(self) -> CurrentImageMeta | None: + """Load and verify the stored set (call once at startup).""" + with self._lock: + self._meta = self._load_verified() + return self._meta + + def save( + self, + result: RenderResult, + *, + source: str, + title: str | None = None, + details: dict[str, JsonValue] | None = None, + ) -> CurrentImageMeta: + """Persist a render result as the current image (blocking; use a thread).""" + options = result.options + meta = CurrentImageMeta( + source=source, + title=title, + details=details or {}, + panel=options.panel.key, + orientation="portrait" if options.rotation == 0 else "landscape", + rotation=options.rotation, + fit=options.fit, + dither=options.eink.dither, + frame_size=options.frame_size, + processed_at=datetime.now(UTC), + sha256=result.sha256, + bin_size=len(result.bin), + ) + jpeg = result.preview_jpeg() + dithered = result.dithered_png() + with self._lock: + atomic_write_bytes(self.bin_path, result.bin) + atomic_write_bytes(self.jpeg_path, jpeg) + atomic_write_bytes(self.dithered_path, dithered) + atomic_write_json(self.meta_path, meta.model_dump(mode="json")) + self._meta = meta + logger.info( + "Saved current image from %s (%s, %d bytes, sha256 %s)", + source, + title or "untitled", + meta.bin_size, + meta.sha256[:12], + ) + return meta + + def read_bin(self) -> tuple[bytes, CurrentImageMeta] | None: + """Return ``current.bin`` and its metadata if both are present and consistent.""" + with self._lock: + meta = self._meta + if meta is None: + return None + try: + data = self.bin_path.read_bytes() + except FileNotFoundError: + return None + if hashlib.sha256(data).hexdigest() != meta.sha256: + logger.warning("current.bin does not match current.json; ignoring it") + return None + return data, meta + + def _load_verified(self) -> CurrentImageMeta | None: + raw = read_json(self.meta_path, lambda: None) + if raw is None: + return None + try: + meta = CurrentImageMeta.model_validate(raw) + except ValidationError: + logger.warning("Ignoring invalid %s", self.meta_path) + return None + try: + data = self.bin_path.read_bytes() + except FileNotFoundError: + logger.warning("%s is missing; no current image", self.bin_path) + return None + if len(data) != meta.bin_size or hashlib.sha256(data).hexdigest() != meta.sha256: + logger.warning("current.bin does not match current.json; no current image") + return None + return meta diff --git a/tests/test_current_image.py b/tests/test_current_image.py new file mode 100644 index 0000000..6f28ed5 --- /dev/null +++ b/tests/test_current_image.py @@ -0,0 +1,56 @@ +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from PIL import Image + +from app.core.config_models import RuntimeConfig +from app.processor.pipeline import RenderOptions, RenderResult, render +from app.services.current_image import CurrentImageStore + + +@pytest.fixture(scope="module") +def result() -> RenderResult: + options = RenderOptions.from_config(RuntimeConfig()) + return render(Image.new("RGB", (300, 400), (40, 90, 160)), options) + + +def test_save_writes_all_files_and_reloads(tmp_path: Path, result: RenderResult) -> None: + store = CurrentImageStore(tmp_path) + assert store.load() is None + + meta = store.save(result, source="upload", title="beach.jpg", details={"size": 123}) + assert meta.sha256 == result.sha256 + assert meta.bin_size == 960_000 + assert meta.frame_size == (1200, 1600) + assert store.bin_path.read_bytes() == result.bin + assert store.jpeg_path.read_bytes()[:2] == b"\xff\xd8" + assert store.dithered_path.read_bytes()[:8] == b"\x89PNG\r\n\x1a\n" + assert json.loads(store.meta_path.read_text(encoding="utf-8"))["title"] == "beach.jpg" + + reloaded = CurrentImageStore(tmp_path) + assert reloaded.load() == meta + loaded = reloaded.read_bin() + assert loaded is not None + assert loaded[0] == result.bin + assert loaded[1].source == "upload" + + +def test_mismatched_bin_is_ignored(tmp_path: Path, result: RenderResult) -> None: + store = CurrentImageStore(tmp_path) + store.save(result, source="upload") + store.bin_path.write_bytes(b"\x11" * 960_000) # e.g. interrupted overwrite + assert store.read_bin() is None + assert CurrentImageStore(tmp_path).load() is None + + +def test_missing_or_invalid_meta(tmp_path: Path, result: RenderResult) -> None: + store = CurrentImageStore(tmp_path) + store.save(result, source="upload") + store.bin_path.unlink() + assert CurrentImageStore(tmp_path).load() is None + + store.meta_path.write_text('{"source": 1}', encoding="utf-8") + assert CurrentImageStore(tmp_path).load() is None From 20d04ceec81396dfd0db92544bf25ce1ad24b341 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sat, 14 Nov 2026 17:36:43 +0100 Subject: [PATCH 16/86] feat: add async Fraimic LAN client FraimicClient wraps httpx for GET /api/info (battery, charging, Wi-Fi RSSI and IP, firmware; parsed leniently) and POST /api/image (raw .bin as application/octet-stream, refused before sending when the size does not match the panel). Keep-alive is disabled because the frame drops Wi-Fi in deep sleep. Transport failures map to FraimicUnreachableError (with an mDNS hint for .local hosts in Docker) and non-2xx answers to FraimicResponseError. Paths and timeouts come from the fraimic config. Co-Authored-By: Claude Opus 5.5 --- app/clients/fraimic.py | 269 +++++++++++++++++++++++++++++++++++ tests/test_fraimic_client.py | 130 +++++++++++++++++ 2 files changed, 399 insertions(+) create mode 100644 app/clients/fraimic.py create mode 100644 tests/test_fraimic_client.py diff --git a/app/clients/fraimic.py b/app/clients/fraimic.py new file mode 100644 index 0000000..d20f720 --- /dev/null +++ b/app/clients/fraimic.py @@ -0,0 +1,269 @@ +"""Async client for the Fraimic frame's local REST API. + +Endpoints (official Fraimic REST guide, no authentication, LAN only): + +* ``GET /api/info`` - status JSON: ``battery.percent``, ``battery.charging``, + ``wifi.rssi``, ``wifi.ip``, ``firmware_version``. Used as the availability ping. +* ``POST /api/image`` - raw ``.bin`` frame buffer, ``Content-Type: + application/octet-stream``. The frame displays it. + +Both paths are configurable (``fraimic.status_path`` / ``fraimic.upload_path``). The +frame is unreachable while in deep sleep; callers decide whether and when to retry. +""" + +from __future__ import annotations + +import logging +import time +from dataclasses import dataclass +from types import TracebackType +from typing import Any, Final, Self + +import httpx +from pydantic import BaseModel, Field, JsonValue + +from app.core.config_models import FraimicConfig + +logger = logging.getLogger(__name__) + +CONNECT_TIMEOUT_S: Final = 5.0 +INFO_TIMEOUT_S: Final = 8.0 +_ERROR_BODY_PREVIEW: Final = 200 +_MDNS_HINT: Final = ( + " (.local names rely on mDNS, which usually does not resolve inside Docker " + "bridge networks; configure the frame's IP address instead)" +) + + +class FraimicError(Exception): + """Base class for frame communication errors (messages are safe to show users).""" + + +class FraimicNotConfiguredError(FraimicError): + """No frame host is configured.""" + + +class FraimicUnreachableError(FraimicError): + """The frame could not be reached (asleep, offline, DNS failure, timeout).""" + + +class FraimicResponseError(FraimicError): + """The frame answered with an error status or an unexpected payload.""" + + def __init__(self, message: str, status_code: int | None = None) -> None: + super().__init__(message) + self.status_code = status_code + + +class FraimicPayloadError(FraimicError): + """The ``.bin`` payload does not have the size the panel expects.""" + + +class FrameInfo(BaseModel): + """Frame telemetry parsed leniently from ``GET /api/info``.""" + + battery_percent: float | None = Field(default=None, description="Battery level (%)") + charging: bool | None = Field(default=None, description="Whether the battery is charging") + rssi: int | None = Field(default=None, description="Wi-Fi signal strength (dBm)") + ip: str | None = Field(default=None, description="Frame IP address") + firmware_version: str | None = Field(default=None, description="Firmware version") + raw: dict[str, JsonValue] = Field(default_factory=dict, description="Full JSON response") + + @classmethod + def from_payload(cls, payload: Any) -> FrameInfo: + """Extract known fields, tolerating missing keys and unexpected types.""" + if not isinstance(payload, dict): + raise FraimicResponseError("Frame info is not a JSON object") + battery = payload.get("battery") + wifi = payload.get("wifi") + battery = battery if isinstance(battery, dict) else {} + wifi = wifi if isinstance(wifi, dict) else {} + return cls( + battery_percent=_as_float(battery.get("percent")), + charging=battery.get("charging") if isinstance(battery.get("charging"), bool) else None, + rssi=_as_int(wifi.get("rssi")), + ip=wifi.get("ip") if isinstance(wifi.get("ip"), str) else None, + firmware_version=_as_str(payload.get("firmware_version")), + raw=payload, + ) + + +def _as_float(value: Any) -> float | None: + if isinstance(value, bool) or not isinstance(value, int | float | str): + return None + try: + return float(value) + except ValueError: + return None + + +def _as_int(value: Any) -> int | None: + number = _as_float(value) + return None if number is None else int(number) + + +def _as_str(value: Any) -> str | None: + if isinstance(value, str): + return value + if isinstance(value, int | float) and not isinstance(value, bool): + return str(value) + return None + + +@dataclass(frozen=True, slots=True) +class UploadResult: + """Outcome of a successful ``.bin`` upload.""" + + status_code: int + bytes_sent: int + duration_s: float + + +class FraimicClient: + """Thin async wrapper around the frame's HTTP API.""" + + def __init__( + self, + *, + base_url: str, + upload_path: str = "/api/image", + status_path: str = "/api/info", + timeout_s: float = 60.0, + transport: httpx.AsyncBaseTransport | None = None, + ) -> None: + """Create a client. + + Args: + base_url: Frame base URL (e.g. ``http://192.168.1.50``); empty = unconfigured. + upload_path: Endpoint receiving the raw ``.bin``. + status_path: Endpoint returning the frame status JSON. + timeout_s: Read/write timeout for uploads. + transport: Optional custom transport (tests). + """ + self.base_url = base_url.rstrip("/") + self.upload_path = upload_path + self.status_path = status_path + self.timeout_s = timeout_s + # No keep-alive: the frame drops Wi-Fi in deep sleep, so pooled sockets go stale. + self._http = httpx.AsyncClient( + transport=transport, + limits=httpx.Limits(max_keepalive_connections=0), + follow_redirects=False, + headers={"User-Agent": "smart-frame-engine"}, + ) + + @classmethod + def from_config( + cls, config: FraimicConfig, *, transport: httpx.AsyncBaseTransport | None = None + ) -> FraimicClient: + """Build a client from the ``fraimic`` configuration section.""" + return cls( + base_url=config.base_url, + upload_path=config.upload_path, + status_path=config.status_path, + timeout_s=config.request_timeout_s, + transport=transport, + ) + + @property + def configured(self) -> bool: + """Whether a frame host is configured.""" + return bool(self.base_url) + + async def aclose(self) -> None: + """Close the underlying HTTP client.""" + await self._http.aclose() + + async def __aenter__(self) -> Self: + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: + await self.aclose() + + async def get_info(self) -> FrameInfo: + """Fetch frame telemetry; doubles as the availability ping. + + Raises: + FraimicNotConfiguredError, FraimicUnreachableError, FraimicResponseError + """ + response = await self._request( + "GET", + self.status_path, + timeout=httpx.Timeout(INFO_TIMEOUT_S, connect=CONNECT_TIMEOUT_S), + ) + try: + payload = response.json() + except ValueError as exc: + raise FraimicResponseError( + "Frame info is not valid JSON", response.status_code + ) from exc + return FrameInfo.from_payload(payload) + + async def upload_bin(self, data: bytes, *, expected_size: int) -> UploadResult: + """Send a ``.bin`` frame buffer to the frame. + + Args: + data: Encoded frame buffer. + expected_size: Exact size required by the configured panel. + + Raises: + FraimicPayloadError: If ``data`` has the wrong size (nothing is sent). + FraimicNotConfiguredError, FraimicUnreachableError, FraimicResponseError + """ + if len(data) != expected_size: + raise FraimicPayloadError( + f"Refusing to upload {len(data)} bytes; the panel expects {expected_size}" + ) + started = time.monotonic() + response = await self._request( + "POST", + self.upload_path, + content=data, + headers={"Content-Type": "application/octet-stream"}, + timeout=httpx.Timeout(self.timeout_s, connect=CONNECT_TIMEOUT_S), + ) + duration = time.monotonic() - started + logger.info( + "Uploaded %d bytes to the frame in %.1fs (HTTP %d)", + len(data), + duration, + response.status_code, + ) + return UploadResult(response.status_code, len(data), duration) + + async def _request(self, method: str, path: str, **kwargs: Any) -> httpx.Response: + if not self.base_url: + raise FraimicNotConfiguredError("No Fraimic frame host is configured") + url = f"{self.base_url}{path}" + try: + response = await self._http.request(method, url, **kwargs) + except httpx.TimeoutException as exc: + raise FraimicUnreachableError( + f"Frame did not respond in time ({type(exc).__name__})" + ) from exc + except httpx.ConnectError as exc: + raise FraimicUnreachableError(self._connect_message(exc)) from exc + except httpx.HTTPError as exc: + raise FraimicUnreachableError( + f"Frame connection failed ({type(exc).__name__})" + ) from exc + if not response.is_success: + snippet = response.text[:_ERROR_BODY_PREVIEW].strip() + raise FraimicResponseError( + f"Frame returned HTTP {response.status_code}" + (f": {snippet}" if snippet else ""), + response.status_code, + ) + return response + + def _connect_message(self, exc: httpx.ConnectError) -> str: + host = httpx.URL(self.base_url).host + message = f"Cannot connect to the frame at {host}" + if host.endswith(".local"): + message += _MDNS_HINT + detail = str(exc).strip() + return f"{message}: {detail}" if detail else message diff --git a/tests/test_fraimic_client.py b/tests/test_fraimic_client.py new file mode 100644 index 0000000..69ed1f4 --- /dev/null +++ b/tests/test_fraimic_client.py @@ -0,0 +1,130 @@ +from __future__ import annotations + +from collections.abc import AsyncIterator + +import httpx +import pytest +import respx + +from app.clients.fraimic import ( + FraimicClient, + FraimicNotConfiguredError, + FraimicPayloadError, + FraimicResponseError, + FraimicUnreachableError, + FrameInfo, +) +from app.core.config_models import FraimicConfig + +BASE = "http://frame.test" +INFO = { + "battery": {"percent": 87, "charging": False}, + "wifi": {"rssi": -61, "ip": "192.0.2.10"}, + "firmware_version": "1.4.2", + "display": {"busy": False}, +} + + +@pytest.fixture +async def client() -> AsyncIterator[FraimicClient]: + async with FraimicClient(base_url=BASE, timeout_s=10) as frame: + yield frame + + +@respx.mock +async def test_get_info_parses_telemetry(client: FraimicClient) -> None: + respx.get(f"{BASE}/api/info").respond(json=INFO) + info = await client.get_info() + assert info.battery_percent == 87.0 + assert info.charging is False + assert info.rssi == -61 + assert info.ip == "192.0.2.10" + assert info.firmware_version == "1.4.2" + assert info.raw["display"] == {"busy": False} + + +def test_frame_info_is_lenient() -> None: + info = FrameInfo.from_payload( + {"battery": "n/a", "wifi": {"rssi": "-70.4"}, "firmware_version": 3} + ) + assert info.battery_percent is None + assert info.rssi == -70 + assert info.firmware_version == "3" + with pytest.raises(FraimicResponseError): + FrameInfo.from_payload(["not", "an", "object"]) + + +@respx.mock +async def test_get_info_rejects_invalid_json(client: FraimicClient) -> None: + respx.get(f"{BASE}/api/info").respond(text="") + with pytest.raises(FraimicResponseError, match="JSON"): + await client.get_info() + + +@respx.mock +async def test_upload_sends_raw_octet_stream(client: FraimicClient) -> None: + route = respx.post(f"{BASE}/api/image").respond(200, text="OK") + payload = bytes(range(256)) * 3750 # 960,000 bytes + result = await client.upload_bin(payload, expected_size=960_000) + assert result.status_code == 200 + assert result.bytes_sent == 960_000 + request = route.calls.last.request + assert request.headers["content-type"] == "application/octet-stream" + assert request.headers["content-length"] == "960000" + assert request.content == payload + + +@respx.mock +async def test_upload_rejects_wrong_size_without_request(client: FraimicClient) -> None: + route = respx.post(f"{BASE}/api/image") + with pytest.raises(FraimicPayloadError, match="960000"): + await client.upload_bin(b"\x11" * 10, expected_size=960_000) + assert not route.called + + +@respx.mock +async def test_http_error_status(client: FraimicClient) -> None: + respx.post(f"{BASE}/api/image").respond(500, text="decoder busy") + with pytest.raises(FraimicResponseError, match="HTTP 500: decoder busy") as info: + await client.upload_bin(b"\x11" * 960_000, expected_size=960_000) + assert info.value.status_code == 500 + + +@respx.mock +@pytest.mark.parametrize( + "error", + [ + httpx.ConnectTimeout("timed out"), + httpx.ReadTimeout("timed out"), + httpx.ConnectError("refused"), + httpx.RemoteProtocolError("disconnected"), + ], +) +async def test_transport_errors_are_unreachable(client: FraimicClient, error: Exception) -> None: + respx.get(f"{BASE}/api/info").mock(side_effect=error) + with pytest.raises(FraimicUnreachableError): + await client.get_info() + + +@respx.mock +async def test_mdns_hint_for_local_hosts() -> None: + respx.get("http://fraimic.local/api/info").mock(side_effect=httpx.ConnectError("no such host")) + async with FraimicClient.from_config(FraimicConfig(host="fraimic.local")) as frame: + with pytest.raises(FraimicUnreachableError, match="IP address"): + await frame.get_info() + + +@respx.mock +async def test_custom_paths_from_config() -> None: + route = respx.get("http://192.0.2.5:8080/status").respond(json={}) + config = FraimicConfig(host="192.0.2.5:8080", status_path="/status") + async with FraimicClient.from_config(config) as frame: + await frame.get_info() + assert route.called + + +async def test_unconfigured_client() -> None: + async with FraimicClient(base_url="") as frame: + assert not frame.configured + with pytest.raises(FraimicNotConfiguredError): + await frame.get_info() From 3ca9df231416882aba656c04a59915b3d5dd3d62 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sat, 14 Nov 2026 17:39:53 +0100 Subject: [PATCH 17/86] feat: add delivery service with deepsleep queue and wakeup worker DeliveryService persists the newest image as /data/queue/pending.bin + pending.json (atomic, SHA-256 checked, restored on restart) and delivers it through a background worker: - continuous: immediate push; failures stay queued and retry with exponential backoff (30 s to 15 min); telemetry refresh every 5 min. - deepsleep: queue only; probe GET /api/info every poll_interval_s and upload as soon as the frame answers; wakeup() flushes immediately. Uploads are serialized (no double push on wakeup/worker races), an image submitted mid-upload stays pending, a status endpoint error does not block the upload, and a panel change discards a pending image built for the old panel. Frame telemetry (online, last seen, battery, RSSI, firmware) is tracked without extra network calls. Co-Authored-By: Claude Opus 5.5 --- app/services/delivery.py | 507 +++++++++++++++++++++++++++++++++++++++ tests/test_delivery.py | 357 +++++++++++++++++++++++++++ 2 files changed, 864 insertions(+) create mode 100644 app/services/delivery.py create mode 100644 tests/test_delivery.py diff --git a/app/services/delivery.py b/app/services/delivery.py new file mode 100644 index 0000000..a2cecd7 --- /dev/null +++ b/app/services/delivery.py @@ -0,0 +1,507 @@ +"""Delivery of ``.bin`` frame buffers to the Fraimic frame, for both power modes. + +* **continuous** (mains powered): a new image is pushed immediately. If the push fails, + the image stays queued and is retried with exponential backoff (30 s .. 15 min). +* **deepsleep** (battery): the frame is unreachable most of the time. A new image is + queued (``/data/queue/pending.bin`` + ``pending.json``, written atomically) and the + background worker probes ``GET /api/info`` every ``poll_interval_s`` seconds. As soon + as the frame answers, the image is uploaded. ``POST /api/fraimic/wakeup`` (e.g. from + a Home Assistant automation) triggers an immediate attempt. + +Only the newest image is kept: submitting a new image replaces any pending one. The +queue survives restarts. Uploads are serialized, so a wakeup racing with the worker +never pushes the same image twice. +""" + +from __future__ import annotations + +import asyncio +import contextlib +import hashlib +import logging +from collections.abc import Callable, Coroutine +from datetime import UTC, datetime, timedelta +from pathlib import Path +from typing import Any, Final, Literal + +from pydantic import AwareDatetime, BaseModel, Field, ValidationError + +from app.clients.fraimic import ( + FraimicClient, + FraimicError, + FraimicResponseError, + FraimicUnreachableError, + FrameInfo, +) +from app.core.atomic import atomic_write_bytes, remove_quietly +from app.core.config_models import PANEL_SPECS, FraimicConfig, PanelModel, PowerMode, RuntimeConfig +from app.core.config_store import ConfigStore +from app.core.json_store import atomic_write_json, read_json + +logger = logging.getLogger(__name__) + +PENDING_BIN: Final = "pending.bin" +PENDING_META: Final = "pending.json" +RETRY_BASE_S: Final = 30.0 +RETRY_MAX_S: Final = 900.0 +TELEMETRY_INTERVAL_S: Final = 300.0 +WORKER_ERROR_PAUSE_S: Final = 5.0 + +DeliveryReason = Literal["submit", "force", "wakeup", "worker"] +Clock = Callable[[], datetime] +ClientFactory = Callable[[FraimicConfig], FraimicClient] + + +def _utcnow() -> datetime: + return datetime.now(UTC) + + +def _online_after(exc: FraimicError) -> bool | None: + """Frame reachability implied by an error (``None`` when it says nothing).""" + if isinstance(exc, FraimicUnreachableError): + return False + if isinstance(exc, FraimicResponseError): + return True # it answered, just not successfully + return None + + +class PendingUpload(BaseModel): + """Metadata of the image waiting for the frame (persisted as ``pending.json``).""" + + sha256: str + size: int + panel: PanelModel + created_at: AwareDatetime + source: str | None = None + title: str | None = None + attempts: int = Field(default=0, description="Failed delivery attempts so far") + last_attempt_at: AwareDatetime | None = None + last_error: str | None = None + next_attempt_at: AwareDatetime | None = None + + +class LastDelivery(BaseModel): + """The most recent successful upload.""" + + sha256: str + delivered_at: AwareDatetime + duration_s: float + bytes: int + reason: DeliveryReason + + +class FrameTelemetry(BaseModel): + """Last known frame state (updated whenever the frame is contacted).""" + + online: bool | None = Field(default=None, description="None = never contacted") + last_seen: AwareDatetime | None = None + last_checked: AwareDatetime | None = None + last_error: str | None = None + info: FrameInfo | None = None + + +class DeliveryOutcome(BaseModel): + """Result of a submit, push or flush.""" + + status: Literal["delivered", "queued", "nothing_pending"] + reason: DeliveryReason + sha256: str | None = None + error: str | None = None + duration_s: float | None = None + + +class DeliverySnapshot(BaseModel): + """Delivery state exposed through ``GET /api/status``.""" + + power_mode: PowerMode + pending: PendingUpload | None + last_delivery: LastDelivery | None + telemetry: FrameTelemetry + + +class DeliveryService: + """Owns the pending upload, the frame client and the background worker.""" + + def __init__( + self, + queue_dir: Path, + config_store: ConfigStore, + *, + client_factory: ClientFactory = FraimicClient.from_config, + clock: Clock = _utcnow, + ) -> None: + self._bin_path = queue_dir / PENDING_BIN + self._meta_path = queue_dir / PENDING_META + self._config_store = config_store + self._client_factory = client_factory + self._clock = clock + + self._state_lock = asyncio.Lock() # pending files + in-memory pending state + self._upload_lock = asyncio.Lock() # one upload at a time + self._wake = asyncio.Event() + self._task: asyncio.Task[None] | None = None + self._background: set[asyncio.Task[DeliveryOutcome]] = set() + + self._client: FraimicClient | None = None + self._client_config: FraimicConfig | None = None + self._pending: PendingUpload | None = None + self._last_delivery: LastDelivery | None = None + self._telemetry = FrameTelemetry() + + # --- Lifecycle ---------------------------------------------------------------------- + def load(self) -> PendingUpload | None: + """Restore a pending upload from disk, discarding inconsistent leftovers.""" + raw = read_json(self._meta_path, lambda: None) + pending: PendingUpload | None = None + if raw is not None: + try: + pending = PendingUpload.model_validate(raw) + except ValidationError: + logger.warning("Discarding invalid %s", self._meta_path) + if pending is not None and not self._pending_file_valid(pending): + pending = None + if pending is None: + remove_quietly(self._bin_path, self._meta_path) + else: + logger.info("Restored pending upload %s from %s", pending.sha256[:12], pending.source) + self._pending = pending + return pending + + async def start(self) -> None: + """Start the background worker and follow configuration changes.""" + self._config_store.add_listener(self._on_config_change) + if self._task is None: + self._task = asyncio.create_task(self._run(), name="fraimic-delivery-worker") + + async def stop(self) -> None: + """Stop the worker and close the frame client.""" + tasks = [t for t in (self._task, *self._background) if t is not None] + for task in tasks: + task.cancel() + for task in tasks: + with contextlib.suppress(asyncio.CancelledError): + await task + self._task = None + self._background.clear() + if self._client is not None: + await self._client.aclose() + self._client = None + + # --- Read access ------------------------------------------------------------------- + @property + def pending(self) -> PendingUpload | None: + """The image waiting for the frame, if any.""" + return self._pending + + @property + def telemetry(self) -> FrameTelemetry: + """Last known frame telemetry.""" + return self._telemetry + + def snapshot(self) -> DeliverySnapshot: + """Current delivery state (no network access).""" + return DeliverySnapshot( + power_mode=self._config.fraimic.power_mode, + pending=self._pending, + last_delivery=self._last_delivery, + telemetry=self._telemetry, + ) + + # --- Operations ------------------------------------------------------------------------ + async def submit( + self, + data: bytes, + *, + source: str | None = None, + title: str | None = None, + immediate: bool | None = None, + ) -> DeliveryOutcome: + """Queue ``data`` for the frame, replacing any pending image. + + Args: + data: Encoded ``.bin`` for the configured panel. + source: Short description of where the image came from. + title: Optional human-readable title. + immediate: Attempt the upload now. ``None`` follows the power mode + (``continuous`` = now, ``deepsleep`` = queue for the worker). + + Raises: + ValueError: If ``data`` does not match the configured panel's size. + """ + config = self._config + spec = config.fraimic.spec + if len(data) != spec.bin_size: + raise ValueError(f"{spec.label} needs a {spec.bin_size}-byte .bin, got {len(data)}") + pending = PendingUpload( + sha256=hashlib.sha256(data).hexdigest(), + size=len(data), + panel=spec.key, + created_at=self._clock(), + source=source, + title=title, + ) + async with self._state_lock: + await asyncio.to_thread(self._write_pending, data, pending) + self._pending = pending + logger.info("Queued image %s for the frame (%s)", pending.sha256[:12], source or "unknown") + + attempt_now = config.fraimic.power_mode == "continuous" if immediate is None else immediate + if attempt_now: + return await self.flush("force" if immediate else "submit") + self._wake.set() + return DeliveryOutcome(status="queued", reason="submit", sha256=pending.sha256) + + async def flush(self, reason: DeliveryReason = "wakeup") -> DeliveryOutcome: + """Try to deliver the pending image now (no-op when nothing is pending).""" + async with self._upload_lock: + async with self._state_lock: + pending = self._pending + data = await asyncio.to_thread(self._read_pending, pending) if pending else None + if pending is not None and data is None: + await asyncio.to_thread(remove_quietly, self._bin_path, self._meta_path) + self._pending = None + if pending is None or data is None: + return DeliveryOutcome(status="nothing_pending", reason=reason) + + client = await self._get_client() + try: + await self._probe(client) + result = await client.upload_bin(data, expected_size=pending.size) + except FraimicError as exc: + await self._record_failure(pending, exc, reason) + return DeliveryOutcome( + status="queued", reason=reason, sha256=pending.sha256, error=str(exc) + ) + + now = self._clock() + self._telemetry = self._telemetry.model_copy( + update={"online": True, "last_seen": now, "last_checked": now, "last_error": None} + ) + self._last_delivery = LastDelivery( + sha256=pending.sha256, + delivered_at=now, + duration_s=round(result.duration_s, 3), + bytes=result.bytes_sent, + reason=reason, + ) + async with self._state_lock: + if self._pending is not None and self._pending.sha256 == pending.sha256: + await asyncio.to_thread(remove_quietly, self._bin_path, self._meta_path) + self._pending = None + else: + self._wake.set() # a newer image arrived during the upload + logger.info("Delivered image %s to the frame (%s)", pending.sha256[:12], reason) + return DeliveryOutcome( + status="delivered", + reason=reason, + sha256=pending.sha256, + duration_s=round(result.duration_s, 3), + ) + + async def wakeup(self, *, wait: bool) -> DeliveryOutcome | None: + """Handle a "frame is awake" signal. + + Args: + wait: Await the delivery and return its outcome; otherwise start it in the + background and return ``None``. + """ + if self._pending is None: + self._spawn(self._refresh_quietly()) + return DeliveryOutcome(status="nothing_pending", reason="wakeup") if wait else None + if wait: + return await self.flush("wakeup") + self._spawn(self.flush("wakeup")) + return None + + async def refresh_info(self) -> FrameInfo: + """Query the frame's telemetry now. + + Raises: + FraimicError: If the frame cannot be reached or answers with an error. + """ + client = await self._get_client() + now = self._clock() + try: + info = await client.get_info() + except FraimicError as exc: + self._telemetry = self._telemetry.model_copy( + update={"online": _online_after(exc), "last_checked": now, "last_error": str(exc)} + ) + raise + self._telemetry = FrameTelemetry( + online=True, last_seen=now, last_checked=now, last_error=None, info=info + ) + return info + + def wake(self) -> None: + """Wake the worker so it re-evaluates immediately.""" + self._wake.set() + + # --- Worker --------------------------------------------------------------------------- + def next_wait(self) -> float | None: + """Seconds the worker sleeps before its next check (``None`` = until woken).""" + config = self._config.fraimic + pending = self._pending + if pending is not None: + if config.power_mode == "deepsleep": + return float(config.poll_interval_s) + if pending.next_attempt_at is None: + return 0.0 + return max(0.0, (pending.next_attempt_at - self._clock()).total_seconds()) + if config.power_mode == "continuous" and config.base_url: + return TELEMETRY_INTERVAL_S + return None + + async def _run(self) -> None: + while True: + woken = False + try: + timeout = self.next_wait() + if timeout is None: + await self._wake.wait() + woken = True + else: + await asyncio.wait_for(self._wake.wait(), timeout) + woken = True + except TimeoutError: + pass + self._wake.clear() + try: + await self._tick(woken) + except asyncio.CancelledError: + raise + except Exception: + logger.exception("Delivery worker iteration failed") + await asyncio.sleep(WORKER_ERROR_PAUSE_S) + + async def _tick(self, woken: bool) -> None: + config = self._config.fraimic + pending = self._pending + if pending is not None: + due = pending.next_attempt_at is None or pending.next_attempt_at <= self._clock() + if woken or config.power_mode == "deepsleep" or due: + await self.flush("worker") + elif config.power_mode == "continuous" and config.base_url: + await self._refresh_quietly() + + # --- Internals -------------------------------------------------------------------------- + @property + def _config(self) -> RuntimeConfig: + return self._config_store.config + + async def _get_client(self) -> FraimicClient: + config = self._config.fraimic + if self._client is None or self._client_config != config: + if self._client is not None: + await self._client.aclose() + self._client = self._client_factory(config) + self._client_config = config + return self._client + + async def _probe(self, client: FraimicClient) -> None: + """Ping the frame before uploading; only an unreachable frame aborts the upload.""" + now = self._clock() + try: + info = await client.get_info() + except FraimicResponseError as exc: + # The frame is up but its status endpoint misbehaves: still try the upload. + logger.debug("Frame status endpoint error ignored: %s", exc) + self._telemetry = self._telemetry.model_copy( + update={"online": True, "last_seen": now, "last_checked": now} + ) + return + except FraimicUnreachableError as exc: + self._telemetry = self._telemetry.model_copy( + update={"online": _online_after(exc), "last_checked": now, "last_error": str(exc)} + ) + raise + self._telemetry = FrameTelemetry( + online=True, last_seen=now, last_checked=now, last_error=None, info=info + ) + + async def _record_failure( + self, pending: PendingUpload, exc: FraimicError, reason: DeliveryReason + ) -> None: + now = self._clock() + attempts = pending.attempts + 1 + if self._config.fraimic.power_mode == "deepsleep": + delay = float(self._config.fraimic.poll_interval_s) + else: + delay = min(RETRY_BASE_S * 2 ** (attempts - 1), RETRY_MAX_S) + updated = pending.model_copy( + update={ + "attempts": attempts, + "last_attempt_at": now, + "last_error": str(exc), + "next_attempt_at": now + timedelta(seconds=delay), + } + ) + async with self._state_lock: + if self._pending is not None and self._pending.sha256 == pending.sha256: + self._pending = updated + await asyncio.to_thread( + atomic_write_json, self._meta_path, updated.model_dump(mode="json") + ) + if not isinstance(exc, FraimicUnreachableError): + level = logging.WARNING + elif reason == "worker" and attempts > 1: + level = logging.DEBUG # a sleeping frame is expected; avoid log spam + else: + level = logging.INFO + logger.log(level, "Frame delivery failed (%s, attempt %d): %s", reason, attempts, exc) + + async def _refresh_quietly(self) -> DeliveryOutcome: + with contextlib.suppress(FraimicError): + await self.refresh_info() + return DeliveryOutcome(status="nothing_pending", reason="wakeup") + + def _spawn(self, coro: Coroutine[Any, Any, DeliveryOutcome]) -> None: + task = asyncio.create_task(coro) + self._background.add(task) + task.add_done_callback(self._background.discard) + + async def _on_config_change(self, config: RuntimeConfig) -> None: + pending = self._pending + if pending is not None and pending.panel != config.fraimic.panel: + async with self._state_lock: + logger.warning( + "Panel changed to %s; discarding pending image built for %s", + config.fraimic.panel, + pending.panel, + ) + await asyncio.to_thread(remove_quietly, self._bin_path, self._meta_path) + self._pending = None + self._wake.set() + + def _write_pending(self, data: bytes, pending: PendingUpload) -> None: + atomic_write_bytes(self._bin_path, data) + atomic_write_json(self._meta_path, pending.model_dump(mode="json")) + + def _read_pending(self, pending: PendingUpload) -> bytes | None: + """Read ``pending.bin``; ``None`` when it is missing or does not match ``pending``.""" + try: + data = self._bin_path.read_bytes() + except FileNotFoundError: + logger.warning("pending.bin vanished; dropping the queued upload") + return None + if hashlib.sha256(data).hexdigest() != pending.sha256: + logger.warning("pending.bin does not match pending.json; dropping it") + return None + return data + + def _pending_file_valid(self, pending: PendingUpload) -> bool: + try: + data = self._bin_path.read_bytes() + except FileNotFoundError: + logger.warning("pending.json without pending.bin; discarding the queued upload") + return False + if len(data) != PANEL_SPECS[pending.panel].bin_size or len(data) != pending.size: + logger.warning("pending.bin has the wrong size; discarding it") + return False + if hashlib.sha256(data).hexdigest() != pending.sha256: + logger.warning("pending.bin does not match pending.json; discarding it") + return False + if pending.panel != self._config.fraimic.panel: + logger.warning("pending.bin was built for panel %s; discarding it", pending.panel) + return False + return True diff --git a/tests/test_delivery.py b/tests/test_delivery.py new file mode 100644 index 0000000..88b0db5 --- /dev/null +++ b/tests/test_delivery.py @@ -0,0 +1,357 @@ +from __future__ import annotations + +import asyncio +import hashlib +from collections.abc import AsyncIterator, Callable +from datetime import UTC, datetime, timedelta +from pathlib import Path +from typing import Any + +import httpx +import pytest +import respx + +from app.clients.fraimic import FraimicClient, FrameInfo, UploadResult +from app.core.config_models import FraimicConfig +from app.core.config_store import ConfigStore +from app.services.delivery import DeliveryService + +BASE = "http://frame.test" +INFO_URL = f"{BASE}/api/info" +IMAGE_URL = f"{BASE}/api/image" +BIN_A = bytes([0x11]) * 960_000 +BIN_B = bytes([0x00]) * 960_000 +INFO = {"battery": {"percent": 55, "charging": True}, "wifi": {"rssi": -48}} + + +class FakeClock: + def __init__(self) -> None: + self.now = datetime(2026, 11, 14, 12, 0, tzinfo=UTC) + + def __call__(self) -> datetime: + return self.now + + def advance(self, seconds: float) -> None: + self.now += timedelta(seconds=seconds) + + +def make_config_store( + tmp_path: Path, power_mode: str = "continuous", **fraimic: Any +) -> ConfigStore: + seed = {"fraimic": {"host": "frame.test", "power_mode": power_mode, **fraimic}} + store = ConfigStore(tmp_path / "config.json", seed) + store.load() + return store + + +ServiceFactory = Callable[..., DeliveryService] + + +@pytest.fixture +async def make_service(tmp_path: Path) -> AsyncIterator[ServiceFactory]: + services: list[DeliveryService] = [] + + def _make( + power_mode: str = "continuous", + clock: FakeClock | None = None, + client_factory: Callable[[FraimicConfig], Any] | None = None, + **fraimic: Any, + ) -> DeliveryService: + kwargs: dict[str, Any] = {} + if clock is not None: + kwargs["clock"] = clock + if client_factory is not None: + kwargs["client_factory"] = client_factory + service = DeliveryService( + tmp_path / "queue", make_config_store(tmp_path, power_mode, **fraimic), **kwargs + ) + service.load() + services.append(service) + return service + + yield _make + for service in services: + await service.stop() + + +async def eventually(condition: Callable[[], bool], timeout: float = 3.0) -> None: + deadline = asyncio.get_running_loop().time() + timeout + while not condition(): + if asyncio.get_running_loop().time() > deadline: + raise AssertionError("condition not met in time") + await asyncio.sleep(0.01) + + +def queue_files(tmp_path: Path) -> set[str]: + queue = tmp_path / "queue" + return {p.name for p in queue.iterdir()} if queue.exists() else set() + + +# --- continuous ------------------------------------------------------------------------ +@respx.mock +async def test_continuous_submit_delivers_immediately( + make_service: ServiceFactory, tmp_path: Path +) -> None: + respx.get(INFO_URL).respond(json=INFO) + upload = respx.post(IMAGE_URL).respond(200) + service = make_service("continuous") + + outcome = await service.submit(BIN_A, source="upload", title="a.jpg") + + assert outcome.status == "delivered" + assert outcome.sha256 == hashlib.sha256(BIN_A).hexdigest() + assert upload.call_count == 1 + assert upload.calls.last.request.content == BIN_A + assert service.pending is None + assert queue_files(tmp_path) == set() + snapshot = service.snapshot() + assert snapshot.last_delivery is not None and snapshot.last_delivery.reason == "submit" + assert snapshot.telemetry.online is True + assert snapshot.telemetry.info is not None + assert snapshot.telemetry.info.battery_percent == 55 + + +@respx.mock +async def test_continuous_failure_queues_with_backoff( + make_service: ServiceFactory, tmp_path: Path +) -> None: + clock = FakeClock() + respx.get(INFO_URL).respond(json=INFO) + upload = respx.post(IMAGE_URL).mock(side_effect=httpx.ConnectError("refused")) + service = make_service("continuous", clock=clock) + + outcome = await service.submit(BIN_A, source="upload") + assert outcome.status == "queued" + assert outcome.error and "Cannot connect" in outcome.error + assert queue_files(tmp_path) == {"pending.bin", "pending.json"} + assert service.pending is not None and service.pending.attempts == 1 + assert service.next_wait() == pytest.approx(30.0) + + clock.advance(30) + assert (await service.flush("worker")).status == "queued" + assert service.pending is not None and service.pending.attempts == 2 + assert service.next_wait() == pytest.approx(60.0) + + upload.mock(return_value=httpx.Response(200)) + clock.advance(60) + assert (await service.flush("worker")).status == "delivered" + assert queue_files(tmp_path) == set() + + +async def test_backoff_is_capped(make_service: ServiceFactory) -> None: + clock = FakeClock() + with respx.mock: + respx.get(INFO_URL).mock(side_effect=httpx.ConnectTimeout("t")) + service = make_service("continuous", clock=clock) + await service.submit(BIN_A) + for _ in range(8): + await service.flush("worker") + assert service.next_wait() == pytest.approx(900.0) + + +@respx.mock +async def test_status_endpoint_errors_do_not_block_upload(make_service: ServiceFactory) -> None: + respx.get(INFO_URL).respond(404) + upload = respx.post(IMAGE_URL).respond(200) + service = make_service("continuous") + assert (await service.submit(BIN_A)).status == "delivered" + assert upload.called + + +@respx.mock +async def test_unconfigured_host_keeps_image_queued(make_service: ServiceFactory) -> None: + service = make_service("continuous", host="") + outcome = await service.submit(BIN_A) + assert outcome.status == "queued" + assert outcome.error == "No Fraimic frame host is configured" + assert service.snapshot().telemetry.online is None + + +async def test_submit_rejects_wrong_size(make_service: ServiceFactory) -> None: + with pytest.raises(ValueError, match="960000"): + await make_service().submit(b"\x11" * 10) + + +# --- deepsleep --------------------------------------------------------------------------- +@respx.mock +async def test_deepsleep_submit_only_queues(make_service: ServiceFactory, tmp_path: Path) -> None: + info = respx.get(INFO_URL).respond(json=INFO) + upload = respx.post(IMAGE_URL).respond(200) + service = make_service("deepsleep", poll_interval_s=20) + + outcome = await service.submit(BIN_A, source="upload") + + assert outcome.status == "queued" + assert not info.called and not upload.called + assert queue_files(tmp_path) == {"pending.bin", "pending.json"} + assert (tmp_path / "queue" / "pending.bin").read_bytes() == BIN_A + assert service.next_wait() == 20.0 + + +@respx.mock +async def test_deepsleep_worker_delivers_once_frame_answers(make_service: ServiceFactory) -> None: + info = respx.get(INFO_URL).mock(side_effect=httpx.ConnectTimeout("asleep")) + upload = respx.post(IMAGE_URL).respond(200) + service = make_service("deepsleep") + await service.start() + + await service.submit(BIN_A) + await eventually(lambda: service.pending is not None and service.pending.attempts >= 1) + assert not upload.called + assert service.snapshot().telemetry.online is False + + info.mock(return_value=httpx.Response(200, json=INFO)) + service.wake() # e.g. the next poll tick + await eventually(lambda: service.pending is None) + assert upload.call_count == 1 + assert service.snapshot().telemetry.online is True + + +@respx.mock +async def test_wakeup_wait_delivers(make_service: ServiceFactory) -> None: + respx.get(INFO_URL).respond(json=INFO) + upload = respx.post(IMAGE_URL).respond(200) + service = make_service("deepsleep") + await service.submit(BIN_A) + + outcome = await service.wakeup(wait=True) + assert outcome is not None and outcome.status == "delivered" + assert outcome.reason == "wakeup" + assert upload.call_count == 1 + + +@respx.mock +async def test_wakeup_background_delivers(make_service: ServiceFactory) -> None: + respx.get(INFO_URL).respond(json=INFO) + upload = respx.post(IMAGE_URL).respond(200) + service = make_service("deepsleep") + await service.submit(BIN_A) + + assert await service.wakeup(wait=False) is None + await eventually(lambda: service.pending is None) + assert upload.call_count == 1 + + +@respx.mock +async def test_wakeup_without_pending_refreshes_telemetry(make_service: ServiceFactory) -> None: + respx.get(INFO_URL).respond(json=INFO) + service = make_service("deepsleep") + outcome = await service.wakeup(wait=True) + assert outcome is not None and outcome.status == "nothing_pending" + await eventually(lambda: service.telemetry.online is True) + + +@respx.mock +async def test_concurrent_flushes_upload_once(make_service: ServiceFactory) -> None: + respx.get(INFO_URL).respond(json=INFO) + upload = respx.post(IMAGE_URL).respond(200) + service = make_service("deepsleep") + await service.submit(BIN_A) + + results = await asyncio.gather(service.flush("wakeup"), service.flush("worker")) + + assert sorted(r.status for r in results) == ["delivered", "nothing_pending"] + assert upload.call_count == 1 + + +# --- queue semantics ---------------------------------------------------------------------- +@respx.mock +async def test_newer_submit_replaces_pending(make_service: ServiceFactory, tmp_path: Path) -> None: + service = make_service("deepsleep") + await service.submit(BIN_A, source="first") + await service.submit(BIN_B, source="second") + assert service.pending is not None + assert service.pending.sha256 == hashlib.sha256(BIN_B).hexdigest() + assert (tmp_path / "queue" / "pending.bin").read_bytes() == BIN_B + + +class GatedClient(FraimicClient): + """Fake client whose upload blocks until released.""" + + def __init__(self) -> None: + super().__init__(base_url=BASE) + self.release = asyncio.Event() + self.started = asyncio.Event() + self.uploads: list[bytes] = [] + + async def get_info(self) -> FrameInfo: + return FrameInfo() + + async def upload_bin(self, data: bytes, *, expected_size: int) -> UploadResult: + self.started.set() + await self.release.wait() + self.uploads.append(data) + return UploadResult(200, len(data), 0.1) + + +async def test_image_submitted_during_upload_stays_pending(make_service: ServiceFactory) -> None: + client = GatedClient() + service = make_service("deepsleep", client_factory=lambda _: client) + await service.submit(BIN_A) + + flush = asyncio.create_task(service.flush("wakeup")) + await client.started.wait() + await service.submit(BIN_B) # arrives while BIN_A is being uploaded + client.release.set() + outcome = await flush + + assert outcome.status == "delivered" + assert outcome.sha256 == hashlib.sha256(BIN_A).hexdigest() + assert service.pending is not None + assert service.pending.sha256 == hashlib.sha256(BIN_B).hexdigest() + + assert (await service.flush("worker")).status == "delivered" + assert client.uploads == [BIN_A, BIN_B] + assert service.pending is None + + +async def test_pending_survives_restart_and_tampering_is_detected(tmp_path: Path) -> None: + store = make_config_store(tmp_path, "deepsleep") + first = DeliveryService(tmp_path / "queue", store) + first.load() + await first.submit(BIN_A, source="upload", title="a.jpg") + + restarted = DeliveryService(tmp_path / "queue", store) + restored = restarted.load() + assert restored is not None + assert restored.title == "a.jpg" + assert restored.sha256 == hashlib.sha256(BIN_A).hexdigest() + + (tmp_path / "queue" / "pending.bin").write_bytes(BIN_B) + tampered = DeliveryService(tmp_path / "queue", store) + assert tampered.load() is None + assert queue_files(tmp_path) == set() + + +async def test_panel_change_discards_pending(make_service: ServiceFactory) -> None: + service = make_service("deepsleep") + await service.start() + await service.submit(BIN_A) + await service._config_store.update({"fraimic": {"panel": "315"}}) + assert service.pending is None + + +# --- telemetry ------------------------------------------------------------------------------ +@respx.mock +async def test_refresh_info_updates_telemetry(make_service: ServiceFactory) -> None: + clock = FakeClock() + route = respx.get(INFO_URL).respond(json=INFO) + service = make_service("continuous", clock=clock) + + info = await service.refresh_info() + assert info.rssi == -48 + assert service.telemetry.online is True + assert service.telemetry.last_seen == clock.now + + route.mock(side_effect=httpx.ConnectError("gone")) + clock.advance(10) + with pytest.raises(Exception, match="Cannot connect"): + await service.refresh_info() + assert service.telemetry.online is False + assert service.telemetry.last_checked == clock.now + assert service.telemetry.info is not None # last known values are kept + + +def test_next_wait_when_idle(make_service: ServiceFactory) -> None: + assert make_service("continuous").next_wait() == 300.0 + assert make_service("deepsleep").next_wait() is None From 65e7eaa90adbd7accf77aebdcdfca4921562dc68 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sat, 14 Nov 2026 17:49:21 +0100 Subject: [PATCH 18/86] fix: encode dithered preview as an indexed PNG Saving the 6-color preview as an RGB PNG with optimize=True took ~1.4 s per render. A palette PNG is pixel-identical, smaller and encodes in ~30 ms. Co-Authored-By: Claude Opus 5.5 --- app/processor/pipeline.py | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/app/processor/pipeline.py b/app/processor/pipeline.py index ea2ed50..cedcfb0 100644 --- a/app/processor/pipeline.py +++ b/app/processor/pipeline.py @@ -39,7 +39,7 @@ smart_crop, ) from app.processor.packing import encode_bin -from app.processor.palette import indices_to_rgb +from app.processor.palette import PALETTE_RGB Rotation = Literal[0, 90, 270] PREVIEW_JPEG_QUALITY = 90 @@ -123,9 +123,16 @@ def preview_jpeg(self, quality: int = PREVIEW_JPEG_QUALITY) -> bytes: return buffer.getvalue() def dithered_png(self) -> bytes: - """Exact 6-color simulation of the panel output, in viewing orientation.""" + """Exact 6-color simulation of the panel output, in viewing orientation. + + Written as a palette (indexed) PNG: pixel-identical to the RGB rendering, but an + order of magnitude faster to encode and smaller than an RGB PNG. + """ + height, width = self.indices.shape + image = Image.frombytes("P", (width, height), np.ascontiguousarray(self.indices).tobytes()) + image.putpalette([channel for color in PALETTE_RGB for channel in color]) buffer = io.BytesIO() - Image.fromarray(indices_to_rgb(self.indices)).save(buffer, format="PNG", optimize=True) + image.save(buffer, format="PNG") return buffer.getvalue() From bce259da101d8b0c130a9502a11b308b9b45922d Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sat, 14 Nov 2026 17:49:21 +0100 Subject: [PATCH 19/86] fix: refresh frame telemetry only on the periodic timer Waking the worker (e.g. after a configuration change) no longer triggers a telemetry request when nothing is pending; continuous mode still refreshes telemetry every 5 minutes. Co-Authored-By: Claude Opus 5.5 --- app/services/delivery.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/services/delivery.py b/app/services/delivery.py index a2cecd7..376d4ee 100644 --- a/app/services/delivery.py +++ b/app/services/delivery.py @@ -381,7 +381,8 @@ async def _tick(self, woken: bool) -> None: due = pending.next_attempt_at is None or pending.next_attempt_at <= self._clock() if woken or config.power_mode == "deepsleep" or due: await self.flush("worker") - elif config.power_mode == "continuous" and config.base_url: + elif not woken and config.power_mode == "continuous" and config.base_url: + # Periodic telemetry only; wake signals (e.g. config edits) do not hit the network. await self._refresh_quietly() # --- Internals -------------------------------------------------------------------------- From d305f5f7027b432adf6bb0e5dcc4c376b881d0b4 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sat, 14 Nov 2026 17:49:21 +0100 Subject: [PATCH 20/86] feat: add display upload, current image, fraimic and status endpoints - POST /api/display/upload: multipart image (MAX_UPLOAD_MB, magic-byte check, 413/415), optional fit override and push_to_fraimic. - GET|HEAD /api/current.jpg, /api/current_dithered.png, /api/current.bin with ETag (bin hash), If-None-Match 304 and Cache-Control: no-cache; the dithered preview follows PUBLIC_IMAGE_ENDPOINTS like the others. - POST /api/fraimic/push: force push current.bin (200 delivered, 202 queued, 409 when there is no image for the configured panel). - POST /api/fraimic/wakeup: background flush returning 202 by default, ?wait=true returns the delivery outcome. - GET /api/fraimic/info: cached telemetry, ?refresh=true queries the frame (504 unreachable, 502 frame error, 409 no host). - GET /api/status now reports frame telemetry, the upload queue, the last delivery and the current image metadata without any network access. - BodySizeLimitMiddleware rejects oversized bodies before FastAPI spools multipart uploads to disk. - Tests block external DNS so they can never reach the network. Co-Authored-By: Claude Opus 5.5 --- app/api/deps.py | 21 +++ app/api/routes/display.py | 76 +++++++++ app/api/routes/fraimic.py | 119 +++++++++++++++ app/api/routes/images.py | 92 +++++++++++ app/api/routes/system.py | 40 ++++- app/core/auth.py | 7 +- app/core/limits.py | 78 ++++++++++ app/main.py | 42 ++++- app/services/display.py | 95 ++++++++++++ tests/conftest.py | 17 +++ tests/test_api_phase2.py | 313 ++++++++++++++++++++++++++++++++++++++ tests/test_auth.py | 4 + tests/test_limits.py | 76 +++++++++ 13 files changed, 970 insertions(+), 10 deletions(-) create mode 100644 app/api/routes/display.py create mode 100644 app/api/routes/fraimic.py create mode 100644 app/api/routes/images.py create mode 100644 app/core/limits.py create mode 100644 app/services/display.py create mode 100644 tests/test_api_phase2.py create mode 100644 tests/test_limits.py diff --git a/app/api/deps.py b/app/api/deps.py index db9da7d..9eb4eba 100644 --- a/app/api/deps.py +++ b/app/api/deps.py @@ -9,6 +9,9 @@ from app.core.config_store import ConfigStore from app.core.history_store import HistoryStore from app.core.settings import EnvSettings +from app.services.current_image import CurrentImageStore +from app.services.delivery import DeliveryService +from app.services.display import DisplayService def get_settings(request: Request) -> EnvSettings: @@ -26,6 +29,24 @@ def get_history_store(request: Request) -> HistoryStore: return cast(HistoryStore, request.app.state.history_store) +def get_current_image_store(request: Request) -> CurrentImageStore: + """Store of the current rendered image.""" + return cast(CurrentImageStore, request.app.state.current_image_store) + + +def get_delivery_service(request: Request) -> DeliveryService: + """Frame delivery service (queue, worker, telemetry).""" + return cast(DeliveryService, request.app.state.delivery_service) + + +def get_display_service(request: Request) -> DisplayService: + """Render-and-display orchestration service.""" + return cast(DisplayService, request.app.state.display_service) + + SettingsDep = Annotated[EnvSettings, Depends(get_settings)] ConfigStoreDep = Annotated[ConfigStore, Depends(get_config_store)] HistoryStoreDep = Annotated[HistoryStore, Depends(get_history_store)] +CurrentImageStoreDep = Annotated[CurrentImageStore, Depends(get_current_image_store)] +DeliveryServiceDep = Annotated[DeliveryService, Depends(get_delivery_service)] +DisplayServiceDep = Annotated[DisplayService, Depends(get_display_service)] diff --git a/app/api/routes/display.py b/app/api/routes/display.py new file mode 100644 index 0000000..d893c75 --- /dev/null +++ b/app/api/routes/display.py @@ -0,0 +1,76 @@ +"""Display endpoints (manual sources). Provider-based sources arrive in later milestones.""" + +from __future__ import annotations + +import re +from pathlib import PurePath +from typing import Annotated, Any + +from fastapi import APIRouter, File, Form, HTTPException, Security, UploadFile + +from app.api.deps import DisplayServiceDep, SettingsDep +from app.core.auth import api_key_scheme +from app.core.config_models import FitMode +from app.core.security import InvalidImageError, PayloadTooLargeError, read_upload +from app.services.display import DisplayResult + +router = APIRouter(prefix="/api/display", tags=["display"], dependencies=[Security(api_key_scheme)]) + +_UNSAFE_CHARS = re.compile(r"[\x00-\x1f\x7f]") +_MAX_TITLE_LENGTH = 120 + + +def _clean_filename(name: str | None) -> str | None: + """Base name of an uploaded file, stripped of control characters and truncated.""" + if not name: + return None + base = PurePath(name.replace("\\", "/")).name + cleaned = _UNSAFE_CHARS.sub("", base).strip() + return cleaned[:_MAX_TITLE_LENGTH] or None + + +_UPLOAD_RESPONSES: dict[int | str, dict[str, Any]] = { + 413: {"description": "File larger than MAX_UPLOAD_MB"}, + 415: {"description": "Not a supported image (JPEG, PNG, WebP, GIF, TIFF, BMP)"}, +} + + +@router.post( + "/upload", + response_model=DisplayResult, + responses=_UPLOAD_RESPONSES, + summary="Display an uploaded image", +) +async def display_upload( + settings: SettingsDep, + display: DisplayServiceDep, + file: Annotated[UploadFile, File(description="Image file (max MAX_UPLOAD_MB)")], + fit: Annotated[FitMode | None, Form(description="Override the default fit mode")] = None, + push_to_fraimic: Annotated[ + bool, Form(description="Send the result to the frame (or queue it in deepsleep mode)") + ] = True, +) -> DisplayResult: + """Render an uploaded image for the frame and make it the current image. + + In ``continuous`` mode the response includes the delivery outcome; in ``deepsleep`` + mode the image is queued until the frame wakes up. + """ + try: + data = await read_upload(file, settings.max_upload_bytes) + except PayloadTooLargeError as exc: + raise HTTPException(status_code=413, detail=str(exc)) from exc + finally: + await file.close() + + title = _clean_filename(file.filename) + try: + return await display.display_bytes( + data, + source="upload", + title=title, + details={"filename": title, "bytes": len(data)}, + fit=fit, + push=push_to_fraimic, + ) + except InvalidImageError as exc: + raise HTTPException(status_code=415, detail=str(exc)) from exc diff --git a/app/api/routes/fraimic.py b/app/api/routes/fraimic.py new file mode 100644 index 0000000..daa651b --- /dev/null +++ b/app/api/routes/fraimic.py @@ -0,0 +1,119 @@ +"""Frame control endpoints: force push, wake-up webhook and telemetry.""" + +from __future__ import annotations + +from typing import Annotated, Any + +from fastapi import APIRouter, HTTPException, Query, Security +from fastapi.responses import JSONResponse +from pydantic import BaseModel, Field + +from app.api.deps import DeliveryServiceDep, DisplayServiceDep +from app.clients.fraimic import ( + FraimicError, + FraimicNotConfiguredError, + FraimicUnreachableError, +) +from app.core.auth import api_key_scheme +from app.services.delivery import DeliveryOutcome, FrameTelemetry +from app.services.display import NoCurrentImageError + +router = APIRouter(prefix="/api/fraimic", tags=["fraimic"]) +protected = [Security(api_key_scheme)] + + +class WakeupAccepted(BaseModel): + """Response of a non-blocking wake-up.""" + + accepted: bool = True + pending: bool = Field(description="Whether an image was waiting for the frame") + + +def _outcome_response(outcome: DeliveryOutcome) -> JSONResponse: + status_code = 200 if outcome.status in {"delivered", "nothing_pending"} else 202 + return JSONResponse(outcome.model_dump(mode="json"), status_code=status_code) + + +_OUTCOME_RESPONSES: dict[int | str, dict[str, Any]] = { + 200: {"model": DeliveryOutcome, "description": "Delivered (or nothing was pending)"}, + 202: {"model": DeliveryOutcome, "description": "Frame unreachable; the image stays queued"}, +} + + +@router.post( + "/push", + dependencies=protected, + responses={**_OUTCOME_RESPONSES, 409: {"description": "No current image to push"}}, + summary="Force push the current image to the frame", +) +async def force_push(display: DisplayServiceDep) -> JSONResponse: + """Send ``current.bin`` now, whatever the power mode. + + Returns ``200`` when delivered and ``202`` when the frame could not be reached; the + image then stays queued and is retried automatically. + """ + try: + outcome = await display.push_current() + except NoCurrentImageError as exc: + raise HTTPException(status_code=409, detail=str(exc)) from exc + return _outcome_response(outcome) + + +@router.post( + "/wakeup", + dependencies=protected, + responses={ + **_OUTCOME_RESPONSES, + 202: { + "model": WakeupAccepted | DeliveryOutcome, + "description": "Accepted (wait=false), or frame unreachable (wait=true)", + }, + }, + summary="Signal that the frame is awake (Home Assistant webhook)", +) +async def wakeup( + delivery: DeliveryServiceDep, + wait: Annotated[ + bool, Query(description="Wait for the upload to finish and return its outcome") + ] = False, +) -> JSONResponse: + """Flush the queued image now that the frame is reachable. + + By default the upload runs in the background and the call returns ``202`` + immediately (Home Assistant ``rest_command`` timeouts are short). With + ``?wait=true`` the delivery outcome is returned. + """ + pending = delivery.pending is not None + outcome = await delivery.wakeup(wait=wait) + if outcome is None: + return JSONResponse(WakeupAccepted(pending=pending).model_dump(), status_code=202) + return _outcome_response(outcome) + + +@router.get( + "/info", + response_model=FrameTelemetry, + responses={ + 409: {"description": "No frame host configured"}, + 502: {"description": "The frame answered with an error"}, + 504: {"description": "The frame is unreachable (asleep or offline)"}, + }, + summary="Frame telemetry (battery, Wi-Fi, firmware)", +) +async def frame_info( + delivery: DeliveryServiceDep, + refresh: Annotated[ + bool, Query(description="Query the frame now instead of returning cached values") + ] = False, +) -> FrameTelemetry: + """Return the last known telemetry, or query the frame with ``?refresh=true``.""" + if refresh: + try: + await delivery.refresh_info() + except FraimicNotConfiguredError as exc: + raise HTTPException(status_code=409, detail=str(exc)) from exc + except FraimicUnreachableError as exc: + raise HTTPException(status_code=504, detail=str(exc)) from exc + except FraimicError as exc: + raise HTTPException(status_code=502, detail=str(exc)) from exc + return delivery.telemetry diff --git a/app/api/routes/images.py b/app/api/routes/images.py new file mode 100644 index 0000000..c99e618 --- /dev/null +++ b/app/api/routes/images.py @@ -0,0 +1,92 @@ +"""Current image files (Home Assistant Generic Camera, UI preview, Fraimic pull). + +Readable without an API key unless ``PUBLIC_IMAGE_ENDPOINTS=false`` (enforced by the +auth middleware). Responses carry an ``ETag`` derived from the ``.bin`` hash and +``Cache-Control: no-cache`` so clients revalidate cheaply and never show stale images. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +from fastapi import APIRouter, HTTPException, Request +from fastapi.responses import FileResponse, Response + +from app.api.deps import CurrentImageStoreDep + +router = APIRouter(prefix="/api", tags=["images"]) + + +def _responses(media_type: str) -> dict[int | str, dict[str, Any]]: + return { + 200: {"content": {media_type: {}}}, + 404: {"description": "No image has been rendered yet"}, + } + + +def _serve( + request: Request, + path: Path, + etag_base: str | None, + suffix: str, + media_type: str, + filename: str | None = None, +) -> Response: + if etag_base is None or not path.is_file(): + raise HTTPException(status_code=404, detail="No image has been rendered yet") + etag = f'"{etag_base[:32]}-{suffix}"' + headers = {"ETag": etag, "Cache-Control": "no-cache"} + if request.headers.get("if-none-match") == etag: + return Response(status_code=304, headers=headers) + return FileResponse( + path, + media_type=media_type, + headers=headers, + filename=filename, + content_disposition_type="inline" if filename is None else "attachment", + ) + + +@router.head("/current.jpg", include_in_schema=False) +@router.get( + "/current.jpg", + responses=_responses("image/jpeg"), + summary="Current image (enhanced, before dithering)", +) +async def current_jpeg(request: Request, store: CurrentImageStoreDep) -> Response: + """The current composition as JPEG, in viewing orientation.""" + meta = store.meta + return _serve(request, store.jpeg_path, meta.sha256 if meta else None, "jpg", "image/jpeg") + + +@router.head("/current_dithered.png", include_in_schema=False) +@router.get( + "/current_dithered.png", + responses=_responses("image/png"), + summary="Current image as rendered by the panel (6-color simulation)", +) +async def current_dithered(request: Request, store: CurrentImageStoreDep) -> Response: + """Exact 6-color dithered preview, in viewing orientation.""" + meta = store.meta + return _serve(request, store.dithered_path, meta.sha256 if meta else None, "png", "image/png") + + +@router.head("/current.bin", include_in_schema=False) +@router.get( + "/current.bin", + responses=_responses("application/octet-stream"), + summary="Current Fraimic frame buffer (.bin)", +) +async def current_bin(request: Request, store: CurrentImageStoreDep) -> Response: + """The raw ``.bin`` sent to the frame (960,000 or 2,304,000 bytes).""" + meta = store.meta + filename = f"current_{meta.panel}.bin" if meta else None + return _serve( + request, + store.bin_path, + meta.sha256 if meta else None, + "bin", + "application/octet-stream", + filename=filename, + ) diff --git a/app/api/routes/system.py b/app/api/routes/system.py index 7c552fa..dccdf42 100644 --- a/app/api/routes/system.py +++ b/app/api/routes/system.py @@ -9,7 +9,14 @@ from pydantic import BaseModel, Field from app import __version__ -from app.api.deps import ConfigStoreDep, SettingsDep +from app.api.deps import ( + ConfigStoreDep, + CurrentImageStoreDep, + DeliveryServiceDep, + SettingsDep, +) +from app.services.current_image import CurrentImageMeta +from app.services.delivery import FrameTelemetry, LastDelivery, PendingUpload router = APIRouter(prefix="/api", tags=["system"]) @@ -30,6 +37,15 @@ class FrameStatus(BaseModel): orientation: str frame_size: tuple[int, int] = Field(description="Composition size (width, height)") configured: bool = Field(description="Whether a frame host is configured") + telemetry: FrameTelemetry = Field(description="Last known frame state (no live query)") + + +class DeliveryStatus(BaseModel): + """Upload queue state.""" + + pending: bool = Field(description="Whether an image is waiting for the frame") + pending_upload: PendingUpload | None = None + last_delivery: LastDelivery | None = None class SchedulerStatus(BaseModel): @@ -55,6 +71,10 @@ class StatusResponse(BaseModel): auth_enabled: bool public_image_endpoints: bool frame: FrameStatus + delivery: DeliveryStatus + current_image: CurrentImageMeta | None = Field( + default=None, description="Metadata of the current image (null before the first one)" + ) scheduler: SchedulerStatus services: ServiceConfigured @@ -66,9 +86,16 @@ async def health() -> HealthResponse: @router.get("/status", response_model=StatusResponse, summary="System status") -async def status(request: Request, settings: SettingsDep, store: ConfigStoreDep) -> StatusResponse: - """Overall system status and configuration summary (no secrets).""" +async def status( + request: Request, + settings: SettingsDep, + store: ConfigStoreDep, + current: CurrentImageStoreDep, + delivery: DeliveryServiceDep, +) -> StatusResponse: + """Overall system status, queue state and current image (no secrets, no network).""" config = store.config + snapshot = delivery.snapshot() started_at: float = request.app.state.started_at return StatusResponse( version=__version__, @@ -82,7 +109,14 @@ async def status(request: Request, settings: SettingsDep, store: ConfigStoreDep) orientation=config.display.orientation, frame_size=config.frame_size, configured=bool(config.fraimic.base_url), + telemetry=snapshot.telemetry, + ), + delivery=DeliveryStatus( + pending=snapshot.pending is not None, + pending_upload=snapshot.pending, + last_delivery=snapshot.last_delivery, ), + current_image=current.meta, scheduler=SchedulerStatus( enabled=config.scheduler.enabled, interval_hours=config.scheduler.interval_hours, diff --git a/app/core/auth.py b/app/core/auth.py index d9033c4..865ea7b 100644 --- a/app/core/auth.py +++ b/app/core/auth.py @@ -4,7 +4,8 @@ * ``POST``/``PUT``/``PATCH``/``DELETE`` on any route require the key. * ``/api/config`` and everything below it require the key for every method. -* ``/api/current.jpg`` and ``/api/current.bin`` require the key only when +* ``/api/current.jpg``, ``/api/current.bin`` and ``/api/current_dithered.png`` require + the key only when ``PUBLIC_IMAGE_ENDPOINTS=false``. * Everything else (UI, ``/docs``, ``/openapi.json``, ``/api/health``, ``GET /api/status``) stays public so the UI can load and prompt for the key. @@ -28,7 +29,9 @@ MUTATING_METHODS: Final = frozenset({"POST", "PUT", "PATCH", "DELETE"}) PROTECTED_PREFIXES: Final = ("/api/config",) -IMAGE_ENDPOINTS: Final = frozenset({"/api/current.jpg", "/api/current.bin"}) +IMAGE_ENDPOINTS: Final = frozenset( + {"/api/current.jpg", "/api/current.bin", "/api/current_dithered.png"} +) #: OpenAPI-only security scheme so ``/docs`` offers an "Authorize" button. Enforcement #: is done by :class:`APIKeyMiddleware`, never by this dependency. diff --git a/app/core/limits.py b/app/core/limits.py new file mode 100644 index 0000000..b05501c --- /dev/null +++ b/app/core/limits.py @@ -0,0 +1,78 @@ +"""Request body size limit (pure ASGI middleware). + +FastAPI parses (and spools to disk) multipart bodies *before* the endpoint runs, so a +per-route size check alone cannot stop a client from streaming gigabytes. This +middleware rejects requests whose ``Content-Length`` exceeds the limit and aborts +chunked bodies as soon as they grow past it. +""" + +from __future__ import annotations + +from typing import Final + +from starlette.responses import JSONResponse +from starlette.types import ASGIApp, Message, Receive, Scope, Send + +#: Allowance for multipart boundaries and form fields on top of the file itself. +MULTIPART_OVERHEAD_BYTES: Final = 1024 * 1024 + + +class BodyTooLargeError(Exception): + """Raised inside ``receive`` when a streamed body exceeds the limit.""" + + +class BodySizeLimitMiddleware: + """Reject HTTP request bodies larger than ``max_body_bytes`` with ``413``.""" + + 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 + + for name, value in scope.get("headers", []): + if name.lower() == b"content-length": + try: + declared = int(value) + except ValueError: + declared = -1 + if declared < 0 or declared > self.max_body_bytes: + await self._reject(scope, receive, send) + return + break + + received = 0 + response_started = False + + 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 BodyTooLargeError + return message + + async def tracking_send(message: Message) -> None: + nonlocal response_started + if message["type"] == "http.response.start": + response_started = True + await send(message) + + try: + await self.app(scope, limited_receive, tracking_send) + except BodyTooLargeError: + if not response_started: + await self._reject(scope, receive, send) + + async def _reject(self, scope: Scope, receive: Receive, send: Send) -> None: + limit_mb = self.max_body_bytes // (1024 * 1024) + response = JSONResponse( + {"detail": f"Request body exceeds the {limit_mb} MB limit"}, + status_code=413, + headers={"Connection": "close"}, + ) + await response(scope, receive, send) diff --git a/app/main.py b/app/main.py index 63da63a..e3b7860 100644 --- a/app/main.py +++ b/app/main.py @@ -20,14 +20,21 @@ from app import __version__ from app.api.routes import config as config_routes +from app.api.routes import display as display_routes +from app.api.routes import fraimic as fraimic_routes +from app.api.routes import images as image_routes from app.api.routes import system as system_routes from app.core.auth import APIKeyMiddleware from app.core.config_models import RuntimeConfig from app.core.config_store import ConfigStore from app.core.history_store import HistoryStore +from app.core.limits import MULTIPART_OVERHEAD_BYTES, BodySizeLimitMiddleware from app.core.logging_config import masking_filter, setup_logging from app.core.proxy import RootPathMiddleware from app.core.settings import EnvSettings, get_env_settings +from app.services.current_image import CurrentImageStore +from app.services.delivery import DeliveryService +from app.services.display import DisplayService logger = logging.getLogger(__name__) @@ -78,19 +85,36 @@ async def _on_config_change(_: RuntimeConfig) -> None: _refresh_masked_secrets() config_store.add_listener(_on_config_change) + current_store = CurrentImageStore(settings.cache_dir) + current_store.load() + delivery = DeliveryService(settings.queue_dir, config_store) + delivery.load() + display = DisplayService(config_store, current_store, delivery) + app.state.config_store = config_store app.state.history_store = history_store + app.state.current_image_store = current_store + app.state.delivery_service = delivery + app.state.display_service = display + await delivery.start() + config = config_store.config logger.info( - "Smart Frame Engine %s started (data_dir=%s, auth=%s, root_path=%r, panel=%s)", + "Smart Frame Engine %s started (data_dir=%s, auth=%s, root_path=%r, panel=%s, " + "power_mode=%s, pending=%s)", __version__, settings.data_dir, "enabled" if settings.auth_enabled else "disabled", settings.root_path, - config_store.config.fraimic.panel, + config.fraimic.panel, + config.fraimic.power_mode, + delivery.pending is not None, ) - yield - logger.info("Smart Frame Engine stopped") + try: + yield + finally: + await delivery.stop() + logger.info("Smart Frame Engine stopped") app = FastAPI( title="Smart Frame Engine", @@ -101,7 +125,8 @@ async def _on_config_change(_: RuntimeConfig) -> None: app.state.settings = settings app.state.started_at = time.monotonic() - # Middleware added last runs first. Order (outermost first): RootPath -> CORS -> auth. + # Middleware added last runs first. Order (outermost first): + # RootPath -> BodySizeLimit -> CORS -> auth. # CORS wraps auth so 401 responses keep CORS headers; RootPath must run before auth # so protected paths are recognized under a sub-path. app.add_middleware( @@ -117,6 +142,10 @@ async def _on_config_change(_: RuntimeConfig) -> None: allow_methods=["*"], allow_headers=["*"], ) + app.add_middleware( + BodySizeLimitMiddleware, + max_body_bytes=settings.max_upload_bytes + MULTIPART_OVERHEAD_BYTES, + ) app.add_middleware(RootPathMiddleware, root_path=settings.root_path) @app.exception_handler(RequestValidationError) @@ -130,6 +159,9 @@ async def _validation_handler(_: Request, exc: RequestValidationError) -> JSONRe app.include_router(system_routes.router) app.include_router(config_routes.router) + app.include_router(image_routes.router) + app.include_router(display_routes.router) + app.include_router(fraimic_routes.router) @app.get("/", include_in_schema=False) async def index(request: Request) -> RedirectResponse: diff --git a/app/services/display.py b/app/services/display.py new file mode 100644 index 0000000..832919b --- /dev/null +++ b/app/services/display.py @@ -0,0 +1,95 @@ +"""Display orchestration: render an image, store it as current, deliver it to the frame. + +Every image source (uploads now; Immich, TMDB and URLs in later milestones) goes +through :meth:`DisplayService.display_bytes`, which serializes rendering so that only +one image is processed at a time (bounded memory, consistent ``current.*`` files). +""" + +from __future__ import annotations + +import asyncio +from collections.abc import Sequence + +from pydantic import BaseModel, Field, JsonValue + +from app.core.config_models import FitMode +from app.core.config_store import ConfigStore +from app.processor.fit import FocusRegion +from app.processor.pipeline import RenderOptions, render_bytes +from app.services.current_image import CurrentImageMeta, CurrentImageStore +from app.services.delivery import DeliveryOutcome, DeliveryService + + +class NoCurrentImageError(LookupError): + """There is no usable current image to push.""" + + +class DisplayResult(BaseModel): + """Result of displaying an image.""" + + image: CurrentImageMeta + delivery: DeliveryOutcome | None = Field( + default=None, description="Frame delivery outcome (null when push was disabled)" + ) + + +class DisplayService: + """Renders images and hands them to the delivery service.""" + + def __init__( + self, + config_store: ConfigStore, + current_store: CurrentImageStore, + delivery: DeliveryService, + ) -> None: + self._config_store = config_store + self._current = current_store + self._delivery = delivery + self._render_lock = asyncio.Lock() + + async def display_bytes( + self, + data: bytes, + *, + source: str, + title: str | None = None, + details: dict[str, JsonValue] | None = None, + fit: FitMode | None = None, + regions: Sequence[FocusRegion] = (), + push: bool = True, + ) -> DisplayResult: + """Render ``data``, make it the current image and optionally push it. + + Raises: + InvalidImageError: If ``data`` is not a supported image. + """ + async with self._render_lock: + options = RenderOptions.from_config(self._config_store.config, fit=fit) + result = await asyncio.to_thread(render_bytes, data, options, tuple(regions)) + meta = await asyncio.to_thread( + self._current.save, result, source=source, title=title, details=details + ) + delivery = ( + await self._delivery.submit(result.bin, source=source, title=title) if push else None + ) + return DisplayResult(image=meta, delivery=delivery) + + async def push_current(self) -> DeliveryOutcome: + """Send the current image to the frame now, whatever the power mode. + + Raises: + NoCurrentImageError: If nothing was rendered yet, or the current image was + rendered for a different panel than the one configured now. + """ + loaded = await asyncio.to_thread(self._current.read_bin) + if loaded is None: + raise NoCurrentImageError("No image has been rendered yet") + data, meta = loaded + if meta.panel != self._config_store.config.fraimic.panel: + raise NoCurrentImageError( + f"The current image was rendered for panel {meta.panel}; display a new image " + f"for panel {self._config_store.config.fraimic.panel} first" + ) + return await self._delivery.submit( + data, source=meta.source, title=meta.title, immediate=True + ) diff --git a/tests/conftest.py b/tests/conftest.py index 443707a..873606a 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -2,6 +2,7 @@ from __future__ import annotations +import socket from collections.abc import Callable, Iterator from pathlib import Path from typing import Any @@ -23,6 +24,22 @@ def _isolate_env(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.delenv(name.upper(), raising=False) +_LOCAL_HOSTS = {None, "localhost", "127.0.0.1", "::1", "testserver"} + + +@pytest.fixture(autouse=True) +def _no_external_dns(monkeypatch: pytest.MonkeyPatch) -> None: + """Fail fast instead of resolving real hostnames (tests must never hit the network).""" + real_getaddrinfo = socket.getaddrinfo + + def guarded(host: Any, *args: Any, **kwargs: Any) -> Any: + if host not in _LOCAL_HOSTS: + raise socket.gaierror(f"External DNS lookups are disabled in tests ({host!r})") + return real_getaddrinfo(host, *args, **kwargs) + + monkeypatch.setattr(socket, "getaddrinfo", guarded) + + @pytest.fixture def data_dir(tmp_path: Path) -> Path: return tmp_path / "data" diff --git a/tests/test_api_phase2.py b/tests/test_api_phase2.py new file mode 100644 index 0000000..a294566 --- /dev/null +++ b/tests/test_api_phase2.py @@ -0,0 +1,313 @@ +"""API tests for display upload, current image files, frame control and status.""" + +from __future__ import annotations + +import io +import time +from collections.abc import Callable + +import httpx +import numpy as np +import pytest +import respx +from fastapi.testclient import TestClient +from PIL import Image + +from app.api.routes.display import _clean_filename +from tests.conftest import ClientFactory + +BASE = "http://frame.test" +INFO_URL = f"{BASE}/api/info" +IMAGE_URL = f"{BASE}/api/image" +INFO = { + "battery": {"percent": 76, "charging": False}, + "wifi": {"rssi": -55}, + "firmware_version": "2.0", +} +KEY = "phase2-key" + + +def jpeg_bytes(size: tuple[int, int] = (640, 480)) -> bytes: + rng = np.random.default_rng(1) + buffer = io.BytesIO() + Image.fromarray(rng.integers(0, 256, (size[1], size[0], 3), dtype=np.uint8)).save( + buffer, format="JPEG" + ) + return buffer.getvalue() + + +def upload( + client: TestClient, push: bool = True, data: bytes | None = None, **headers: str +) -> httpx.Response: + return client.post( + "/api/display/upload", + files={"file": ("../../etc/holiday.jpg", data or jpeg_bytes(), "image/jpeg")}, + data={"push_to_fraimic": "true" if push else "false"}, + headers=headers, + ) + + +def wait_for(condition: Callable[[], bool], timeout: float = 3.0) -> None: + deadline = time.monotonic() + timeout + while not condition(): + if time.monotonic() > deadline: + raise AssertionError("condition not met in time") + time.sleep(0.02) + + +@pytest.fixture +def frame_client(make_client: ClientFactory) -> Callable[..., TestClient]: + def _make(**overrides: object) -> TestClient: + overrides.setdefault("fraimic_host", "frame.test") + return make_client(**overrides) + + return _make + + +# --- upload + current files ------------------------------------------------------------ +@respx.mock +def test_upload_renders_delivers_and_serves_files(frame_client: Callable[..., TestClient]) -> None: + respx.get(INFO_URL).respond(json=INFO) + frame_upload = respx.post(IMAGE_URL).respond(200) + client = frame_client() + + response = upload(client) + + assert response.status_code == 200, response.text + body = response.json() + assert body["image"]["source"] == "upload" + assert body["image"]["title"] == "holiday.jpg" + assert body["image"]["bin_size"] == 960_000 + assert body["image"]["frame_size"] == [1200, 1600] + assert body["delivery"]["status"] == "delivered" + + bin_response = client.get("/api/current.bin") + assert bin_response.status_code == 200 + assert bin_response.headers["content-type"] == "application/octet-stream" + assert len(bin_response.content) == 960_000 + assert frame_upload.calls.last.request.content == bin_response.content + + jpeg = client.get("/api/current.jpg") + assert jpeg.headers["content-type"] == "image/jpeg" + assert Image.open(io.BytesIO(jpeg.content)).size == (1200, 1600) + assert jpeg.headers["cache-control"] == "no-cache" + etag = jpeg.headers["etag"] + assert client.get("/api/current.jpg", headers={"If-None-Match": etag}).status_code == 304 + assert client.head("/api/current.jpg").status_code == 200 + + dithered = client.get("/api/current_dithered.png") + assert dithered.headers["content-type"] == "image/png" + assert Image.open(io.BytesIO(dithered.content)).size == (1200, 1600) + + +def test_current_files_404_before_first_render(make_client: ClientFactory) -> None: + client = make_client() + for path in ("/api/current.jpg", "/api/current.bin", "/api/current_dithered.png"): + assert client.get(path).status_code == 404 + + +@respx.mock +def test_upload_without_push_does_not_contact_frame( + frame_client: Callable[..., TestClient], +) -> None: + frame = respx.route(host="frame.test") + client = frame_client() + response = upload(client, push=False) + assert response.status_code == 200 + assert response.json()["delivery"] is None + assert not frame.called + + +@respx.mock +def test_upload_landscape_uses_rotated_frame(frame_client: Callable[..., TestClient]) -> None: + client = frame_client(orientation="landscape") + body = upload(client, push=False).json() + assert body["image"]["frame_size"] == [1600, 1200] + assert body["image"]["rotation"] == 90 + jpeg = Image.open(io.BytesIO(client.get("/api/current.jpg").content)) + assert jpeg.size == (1600, 1200) + + +def test_upload_rejects_non_images(make_client: ClientFactory) -> None: + response = upload(make_client(), push=False, data=b"definitely not an image") + assert response.status_code == 415 + + +def test_upload_rejects_large_files(make_client: ClientFactory) -> None: + client = make_client(max_upload_mb=1) + payload = b"\xff\xd8" + b"\x00" * (1024 * 1024 + 10) + response = upload(client, push=False, data=payload) + assert response.status_code == 413 + assert "1 MB" in response.json()["detail"] + + +def test_body_limit_middleware_rejects_oversized_requests(make_client: ClientFactory) -> None: + client = make_client(max_upload_mb=1) + response = client.post( + "/api/display/upload", + content=b"x" * (3 * 1024 * 1024), + headers={"Content-Type": "application/octet-stream"}, + ) + assert response.status_code == 413 + + +# --- deepsleep queue + wakeup ----------------------------------------------------------- +@respx.mock +def test_deepsleep_queue_then_wakeup(frame_client: Callable[..., TestClient]) -> None: + info = respx.get(INFO_URL).mock(side_effect=httpx.ConnectTimeout("asleep")) + frame_upload = respx.post(IMAGE_URL).respond(200) + client = frame_client(fraimic_power_mode="deepsleep") + + body = upload(client).json() + assert body["delivery"]["status"] == "queued" + status = client.get("/api/status").json() + assert status["delivery"]["pending"] is True + assert status["delivery"]["pending_upload"]["source"] == "upload" + assert status["current_image"]["title"] == "holiday.jpg" + + # The worker probes the sleeping frame once right after the submit; wait for that + # failed probe so the wake-up below is what delivers the image. + def probed() -> bool: + pending = client.get("/api/status").json()["delivery"]["pending_upload"] + return pending is not None and pending["attempts"] >= 1 + + wait_for(probed) + info.mock(return_value=httpx.Response(200, json=INFO)) + woke = client.post("/api/fraimic/wakeup", params={"wait": "true"}) + assert woke.status_code == 200 + assert woke.json()["status"] == "delivered" + assert frame_upload.call_count == 1 + + status = client.get("/api/status").json() + assert status["delivery"]["pending"] is False + assert status["delivery"]["last_delivery"]["reason"] == "wakeup" + assert status["frame"]["telemetry"]["online"] is True + assert status["frame"]["telemetry"]["info"]["battery_percent"] == 76 + + +@respx.mock +def test_wakeup_default_is_non_blocking(frame_client: Callable[..., TestClient]) -> None: + info = respx.get(INFO_URL).mock(side_effect=httpx.ConnectTimeout("asleep")) + frame_upload = respx.post(IMAGE_URL).respond(200) + client = frame_client(fraimic_power_mode="deepsleep") + upload(client) + wait_for(lambda: info.called) # the worker's first probe found the frame asleep + wait_for(lambda: client.get("/api/status").json()["delivery"]["pending_upload"]["attempts"]) + info.mock(return_value=httpx.Response(200, json=INFO)) + + response = client.post("/api/fraimic/wakeup") + assert response.status_code == 202 + assert response.json() == {"accepted": True, "pending": True} + wait_for(lambda: not client.get("/api/status").json()["delivery"]["pending"]) + assert frame_upload.call_count == 1 + + +@respx.mock +def test_wakeup_wait_with_unreachable_frame_returns_202( + frame_client: Callable[..., TestClient], +) -> None: + respx.get(INFO_URL).mock(side_effect=httpx.ConnectError("down")) + client = frame_client(fraimic_power_mode="deepsleep") + upload(client) + response = client.post("/api/fraimic/wakeup", params={"wait": "true"}) + assert response.status_code == 202 + assert response.json()["status"] == "queued" + + +# --- force push ------------------------------------------------------------------------- +@respx.mock +def test_force_push(frame_client: Callable[..., TestClient]) -> None: + respx.get(INFO_URL).respond(json=INFO) + frame_upload = respx.post(IMAGE_URL).respond(200) + client = frame_client(fraimic_power_mode="deepsleep") + + assert client.post("/api/fraimic/push").status_code == 409 + upload(client, push=False) + response = client.post("/api/fraimic/push") + assert response.status_code == 200 + assert response.json()["status"] == "delivered" + assert response.json()["reason"] == "force" + assert frame_upload.call_count == 1 + + +@respx.mock +def test_force_push_with_unreachable_frame_queues(frame_client: Callable[..., TestClient]) -> None: + respx.get(INFO_URL).mock(side_effect=httpx.ConnectError("down")) + client = frame_client() + upload(client, push=False) + response = client.post("/api/fraimic/push") + assert response.status_code == 202 + assert response.json()["status"] == "queued" + assert client.get("/api/status").json()["delivery"]["pending"] is True + + +@respx.mock +def test_force_push_refuses_image_for_other_panel(frame_client: Callable[..., TestClient]) -> None: + client = frame_client() + upload(client, push=False) + assert client.put("/api/config", json={"fraimic": {"panel": "315"}}).status_code == 200 + response = client.post("/api/fraimic/push") + assert response.status_code == 409 + assert "panel 133" in response.json()["detail"] + + +# --- telemetry ---------------------------------------------------------------------------- +@respx.mock +def test_frame_info_cached_and_refresh(frame_client: Callable[..., TestClient]) -> None: + route = respx.get(INFO_URL).respond(json=INFO) + client = frame_client() + + cached = client.get("/api/fraimic/info").json() + assert cached["online"] is None + + fresh = client.get("/api/fraimic/info", params={"refresh": "true"}) + assert fresh.status_code == 200 + assert fresh.json()["info"]["rssi"] == -55 + assert fresh.json()["info"]["firmware_version"] == "2.0" + + route.mock(side_effect=httpx.ConnectTimeout("asleep")) + assert client.get("/api/fraimic/info", params={"refresh": "true"}).status_code == 504 + route.mock(return_value=httpx.Response(500)) + assert client.get("/api/fraimic/info", params={"refresh": "true"}).status_code == 502 + assert client.get("/api/fraimic/info").json()["online"] is True + + +def test_frame_info_refresh_without_host(make_client: ClientFactory) -> None: + client = make_client() + assert client.put("/api/config", json={"fraimic": {"host": ""}}).status_code == 200 + assert client.get("/api/fraimic/info", params={"refresh": "true"}).status_code == 409 + + +# --- auth --------------------------------------------------------------------------------- +def test_new_mutating_routes_require_api_key(make_client: ClientFactory) -> None: + client = make_client(app_api_key=KEY, public_image_endpoints=False) + assert upload(client, push=False).status_code == 401 + assert client.post("/api/fraimic/push").status_code == 401 + assert client.post("/api/fraimic/wakeup").status_code == 401 + assert client.get("/api/current_dithered.png").status_code == 401 + assert client.get("/api/fraimic/info").status_code == 200 + assert upload(client, push=False, **{"X-API-Key": KEY}).status_code == 200 + assert client.get("/api/current.bin", params={"api_key": KEY}).status_code == 200 + + +def test_status_before_any_image(make_client: ClientFactory) -> None: + body = make_client().get("/api/status").json() + assert body["current_image"] is None + assert body["delivery"] == {"pending": False, "pending_upload": None, "last_delivery": None} + assert body["frame"]["telemetry"]["online"] is None + + +@pytest.mark.parametrize( + ("raw", "expected"), + [ + ("holiday.jpg", "holiday.jpg"), + ("../../etc/passwd", "passwd"), + ("C:/Users/me/IMG_01.HEIC", "IMG_01.HEIC"), + ("bad" + chr(7) + chr(27) + "name.png", "badname.png"), + ("", None), + (None, None), + ("x" * 300 + ".jpg", "x" * 120), + ], +) +def test_clean_filename(raw: str | None, expected: str | None) -> None: + assert _clean_filename(raw) == expected diff --git a/tests/test_auth.py b/tests/test_auth.py index b0108c6..6898db6 100644 --- a/tests/test_auth.py +++ b/tests/test_auth.py @@ -30,6 +30,10 @@ ("HEAD", "/api/current.jpg", True, False), ("GET", "/api/current.jpg", False, True), ("GET", "/api/current.bin", False, True), + ("GET", "/api/current_dithered.png", True, False), + ("GET", "/api/current_dithered.png", False, True), + ("GET", "/api/fraimic/info", True, False), + ("POST", "/api/fraimic/wakeup", True, True), ], ) def test_requires_api_key_rules( diff --git a/tests/test_limits.py b/tests/test_limits.py new file mode 100644 index 0000000..96cf415 --- /dev/null +++ b/tests/test_limits.py @@ -0,0 +1,76 @@ +from __future__ import annotations + +from typing import Any + +from starlette.types import Message, Receive, Scope, Send + +from app.core.limits import BodySizeLimitMiddleware + + +async def echo_app(scope: Scope, receive: Receive, send: Send) -> None: + """Reads the whole body, then answers 200 with its length.""" + size = 0 + while True: + message = await receive() + size += len(message.get("body", b"")) + if not message.get("more_body", False): + break + await send({"type": "http.response.start", "status": 200, "headers": []}) + await send({"type": "http.response.body", "body": str(size).encode()}) + + +async def call( + app: Any, chunks: list[bytes], headers: list[tuple[bytes, bytes]] | None = None +) -> list[Message]: + scope = {"type": "http", "method": "POST", "path": "/", "headers": headers or []} + pending = [ + {"type": "http.request", "body": chunk, "more_body": i < len(chunks) - 1} + for i, chunk in enumerate(chunks) + ] + sent: list[Message] = [] + + async def receive() -> Message: + return pending.pop(0) if pending else {"type": "http.disconnect"} + + async def send(message: Message) -> None: + sent.append(message) + + await app(scope, receive, send) + return sent + + +async def test_small_bodies_pass_through() -> None: + app = BodySizeLimitMiddleware(echo_app, max_body_bytes=10) + sent = await call(app, [b"12345", b"678"], [(b"content-length", b"8")]) + assert sent[0]["status"] == 200 + assert sent[1]["body"] == b"8" + + +async def test_declared_length_over_limit_is_rejected_before_reading() -> None: + app = BodySizeLimitMiddleware(echo_app, max_body_bytes=10) + sent = await call(app, [b"x"], [(b"content-length", b"11")]) + assert sent[0]["status"] == 413 + + +async def test_invalid_content_length_is_rejected() -> None: + app = BodySizeLimitMiddleware(echo_app, max_body_bytes=10) + sent = await call(app, [b"x"], [(b"content-length", b"nope")]) + assert sent[0]["status"] == 413 + + +async def test_chunked_body_over_limit_is_aborted() -> None: + app = BodySizeLimitMiddleware(echo_app, max_body_bytes=10) + sent = await call(app, [b"123456", b"789012", b"345"]) # no Content-Length + assert sent[0]["status"] == 413 + assert len([m for m in sent if m["type"] == "http.response.start"]) == 1 + + +async def test_non_http_scopes_are_ignored() -> None: + seen: list[str] = [] + + async def lifespan_app(scope: Scope, receive: Receive, send: Send) -> None: + seen.append(scope["type"]) + + app = BodySizeLimitMiddleware(lifespan_app, max_body_bytes=1) + await app({"type": "lifespan"}, None, None) # type: ignore[arg-type] + assert seen == ["lifespan"] From f39d4adfd6f635578f447950299ac20344ef130d Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sat, 14 Nov 2026 17:52:00 +0100 Subject: [PATCH 21/86] docs: document Fraimic endpoints, queue layout and Docker mDNS caveat README gains eInk pipeline and frame delivery sections (files, endpoints, power modes, performance) and credits the upstream converters. .env.example warns that .local names do not resolve inside Docker bridge networks. CLAUDE.md now matches the official frame API (POST /api/image, GET /api/info), the Atkinson default and the /data/cache + /data/queue layout. Co-Authored-By: Claude Opus 5.5 --- .env.example | 4 +++- CLAUDE.md | 8 ++++---- README.md | 47 ++++++++++++++++++++++++++++++++++++++++++----- 3 files changed, 49 insertions(+), 10 deletions(-) diff --git a/.env.example b/.env.example index d417e9d..e0ae194 100644 --- a/.env.example +++ b/.env.example @@ -55,7 +55,9 @@ TMDB_API_KEY= TMDB_LANGUAGE=en-US # --- Fraimic frame (runtime default) ----------------------------------------- -# Hostname, IP or base URL of the frame. +# Hostname, IP or base URL of the frame (see fraimic.local/info for its IP). +# Inside Docker, .local (mDNS) names usually do NOT resolve on the default bridge +# network: use the frame's IP address and give it a DHCP reservation. FRAIMIC_HOST=fraimic.local # continuous = mains powered, always reachable # deepsleep = battery powered, uploads are queued until the frame wakes up diff --git a/CLAUDE.md b/CLAUDE.md index 3b98d9b..0f0f3e1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -33,17 +33,17 @@ Implement two providers initially: - `smart_crop`: Intelligent crop centered on face bounding boxes detected by Immich, fitted to target frame dimensions (`FRAME_WIDTH`, `FRAME_HEIGHT`, `ORIENTATION=landscape|portrait`). - `contain`: Full image display with adaptive padding or blurred background (ideal for movie/TV posters). - **eInk Optimization:** Configurable contrast, saturation, and sharpness adjustments. -- **Fraimic Binary Encoding:** Implement the exact `.bin` binary format and Floyd-Steinberg dithering on the official Fraimic color palette, strictly following the reference documentation and official converter code located in `/fraimic-docs` (specifically `/fraimic-docs/fraimic_bin_converter`). -- **Cache:** Save the latest processed image in `/data/cache/` in two formats: `current.jpg` (for the web UI and Home Assistant) and `current.bin` (for Fraimic). +- **Fraimic Binary Encoding:** Implement the exact `.bin` binary format and error-diffusion dithering (Atkinson by default, as in the official converter, or Floyd-Steinberg) with the official tuned color metric on the official Fraimic color palette, strictly following the reference documentation and official converter code located in `/fraimic-docs` (specifically `/fraimic-docs/fraimic_bin_converter`). +- **Cache:** Save the latest processed image in `/data/cache/`: `current.jpg` (clean composition for the web UI and Home Assistant), `current_dithered.png` (exact 6-color preview), `current.bin` (for Fraimic) and `current.json` (metadata, written last). The deep-sleep upload queue lives in `/data/queue/` (`pending.bin` + `pending.json`). ### 3. Fraimic Communication & Power Management (`clients/fraimic.py`) Support two configurable power modes via the UI and `.env` (`FRAIMIC_POWER_MODE`): - **`continuous` mode (Mains-powered / Always-On):** - - Frame is always reachable. Every newly generated image is pushed immediately (`POST /api/upload`). + - Frame is always reachable. Every newly generated image is pushed immediately (`POST /api/image` on the frame, raw `.bin` as `application/octet-stream`). - **`deepsleep` mode (Battery-powered / Power-saving):** - Frame turns off Wi-Fi during deep sleep and wakes up periodically or on button press. - When a new image is ready, queue it (`pending_upload = True`) without blocking the API. - - Run a lightweight background worker (and expose a wake-up webhook `POST /api/fraimic/wakeup` for Home Assistant) that checks frame availability (lightweight HTTP ping to `/api/status` or `/api/battery` every X seconds while an upload is pending) and automatically pushes `current.bin` as soon as the frame responds. + - Run a lightweight background worker (and expose a wake-up webhook `POST /api/fraimic/wakeup` for Home Assistant) that checks frame availability (lightweight HTTP ping to the frame's `GET /api/info` every X seconds while an upload is pending) and automatically pushes `current.bin` as soon as the frame responds. - **Autonomous Scheduler:** Configurable periodic auto-refresh (every X hours, with a quiet-hours night window) controllable from the UI. ### 4. Built-in Web UI (`GET /`) diff --git a/README.md b/README.md index 6ab20de..cb1816d 100644 --- a/README.md +++ b/README.md @@ -5,9 +5,9 @@ TMDB movie/TV posters, direct URLs), optimizes them for a color eInk panel (Spec and pushes them to a [Fraimic](https://fraimic.com) picture frame. Home Assistant friendly, runs standalone in Docker. -> **Status:** early development (`v0.x`). The core service, configuration, security and -> container packaging are in place; image providers, the eInk pipeline and the web UI -> are being added milestone by milestone. +> **Status:** early development (`v0.x`). The core service, the eInk pipeline and frame +> delivery (continuous and deep-sleep) are in place; image providers and the web UI are +> being added milestone by milestone. ## Quickstart @@ -24,6 +24,41 @@ Runtime settings are stored in `./data/config.json` and can be edited with `GET`/`PUT /api/config`. Values saved there take precedence over `.env`, which in turn takes precedence over built-in defaults. `POST /api/config/reset` removes saved values. +## eInk pipeline + +Images are fitted to the panel (`smart_crop` around faces, or `contain` on a blurred / +black / white background), enhanced (brightness 1.1, contrast 1.2, saturation 1.2, +edge-enhance, smooth, sharpen) and dithered onto the 6-color Spectra 6 palette with +the official tuned color metric. Dithering is vectorized along anti-diagonals: the +Atkinson output is byte-identical to the official Fraimic converter while running in +about 0.7 s (13.3") / 1.1 s (31.5") instead of ~40 s. + +Generated files (`./data/cache/`): + +| File | Endpoint | Content | +| --- | --- | --- | +| `current.jpg` | `GET /api/current.jpg` | Enhanced composition, before dithering (HA Generic Camera) | +| `current_dithered.png` | `GET /api/current_dithered.png` | Exact 6-color preview of the panel | +| `current.bin` | `GET /api/current.bin` | Frame buffer sent to the frame (960,000 / 2,304,000 bytes) | + +## Frame delivery + +The frame is driven through its local REST API (`GET /api/info`, `POST /api/image`). + +- **`continuous`** (mains powered): every new image is pushed immediately; failures are + retried with exponential backoff. +- **`deepsleep`** (battery): the image is queued in `./data/queue/` and pushed as soon as + the frame answers (probed every `poll_interval_s`), or immediately when Home Assistant + calls `POST /api/fraimic/wakeup`. + +| Endpoint | Purpose | +| --- | --- | +| `POST /api/display/upload` | Upload an image (multipart `file`, optional `fit`, `push_to_fraimic`) | +| `POST /api/fraimic/push` | Force push the current image now (200 delivered, 202 queued) | +| `POST /api/fraimic/wakeup` | Frame is awake: flush the queue (202, or `?wait=true` for the outcome) | +| `GET /api/fraimic/info` | Last known battery / Wi-Fi / firmware (`?refresh=true` queries the frame) | +| `GET /api/status` | Frame telemetry, queue state and current image metadata | + ## Development ```bash @@ -36,8 +71,10 @@ DATA_DIR=./data python -m app # serve on http://localhost:8000 ## Credits -The `.bin` encoding follows the official -[Fraimic Bin Converter](https://github.com/Fraimic/fraimic_bin_converter) (MIT). +The palette, color metric, Atkinson kernel and `.bin` layouts follow the official +[Fraimic Bin Converter](https://github.com/Fraimic/fraimic_bin_converter) (MIT), which +builds on Toon-nooT's +[PhotoPainter Spectra 6 converter](https://github.com/Toon-nooT/PhotoPainter-E-Ink-Spectra-6-image-converter). ## License From cd6614b1581b06d44753e1c498e711fdba17f729 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sat, 14 Nov 2026 17:55:13 +0100 Subject: [PATCH 22/86] fix: keep match_palette typed under NumPy 2.4 stubs np.argmin(axis=1) is typed as Any by the NumPy 2.4 stubs used on Python 3.11 in CI; wrapping it in np.asarray(..., dtype=np.intp) keeps mypy strict happy on every supported NumPy version. Co-Authored-By: Claude Opus 5.5 --- app/processor/palette.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/processor/palette.py b/app/processor/palette.py index c741ca4..44781fb 100644 --- a/app/processor/palette.py +++ b/app/processor/palette.py @@ -77,7 +77,7 @@ def match_palette(rgb: npt.NDArray[np.int64]) -> npt.NDArray[np.intp]: ) luma_diff = luma - PALETTE_LUMA total = 1.5 * rgb_dist + 0.60 * (luma_diff * luma_diff) - return np.argmin(total, axis=1) + return np.asarray(np.argmin(total, axis=1), dtype=np.intp) def indices_to_rgb(indices: npt.NDArray[np.uint8]) -> npt.NDArray[np.uint8]: From 34cc63a5dbffd9825d00c3b692f15345339121c2 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sat, 14 Nov 2026 19:53:48 +0100 Subject: [PATCH 23/86] fix: rotate before dithering so landscape matches the official converter Landscape mode now rotates the composition into the panel's native portrait buffer before error diffusion, like the official --fit rotate flow, so the .bin is byte-identical to the reference (previously ~8.6% of dither dots differed, colour-neutral). Portrait output is unchanged. Co-Authored-By: Claude Sonnet 5.5 --- app/processor/pipeline.py | 17 ++++++++++++----- tests/test_pipeline.py | 40 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 5 deletions(-) diff --git a/app/processor/pipeline.py b/app/processor/pipeline.py index cedcfb0..4b085a9 100644 --- a/app/processor/pipeline.py +++ b/app/processor/pipeline.py @@ -6,9 +6,9 @@ 2. Compose in *viewing* orientation (``frame_size`` honours portrait/landscape): ``smart_crop`` (fill, face-aware) or ``contain`` (fit + blur/black/white background), with the eInk enhancement applied to the picture only. -3. Dither in viewing orientation (Atkinson or Floyd-Steinberg, tuned metric). -4. Rotate the palette indices losslessly into the panel's native portrait buffer - (``landscape_rotation`` degrees counter-clockwise) and pack the ``.bin``. +3. Rotate the composition into the panel's native portrait buffer (``landscape_rotation`` + degrees counter-clockwise), then dither it (Atkinson or Floyd-Steinberg, tuned metric). +4. Pack the ``.bin``; the preview indices are rotated back to viewing orientation. Rendering is CPU-bound and synchronous; call it through ``asyncio.to_thread``. """ @@ -156,8 +156,15 @@ def render( ) -> RenderResult: """Compose, dither and encode ``image`` for the configured panel.""" composed = compose(image.convert("RGB"), options, regions) - indices = dither(np.asarray(composed, dtype=np.uint8), options.eink.dither) - portrait = np.ascontiguousarray(np.rot90(indices, k=options.rotation // 90)) + quarter_turns = options.rotation // 90 + # Rotate *before* dithering, like the official converter's ``--fit rotate``: error + # diffusion scans the panel's native portrait buffer, so the ``.bin`` is byte-identical. + native_rgb = np.ascontiguousarray( + np.rot90(np.asarray(composed, dtype=np.uint8), k=quarter_turns) + ) + portrait = dither(native_rgb, options.eink.dither) + # The preview indices stay in viewing orientation (a lossless inverse rotation). + indices = np.ascontiguousarray(np.rot90(portrait, k=-quarter_turns)) return RenderResult( options=options, composed=composed, diff --git a/tests/test_pipeline.py b/tests/test_pipeline.py index 446fa4a..8bb7eb5 100644 --- a/tests/test_pipeline.py +++ b/tests/test_pipeline.py @@ -161,3 +161,43 @@ def test_render_options_reject_inconsistent_frame() -> None: background=base.background, eink=base.eink, ) + + +def _official_rotate_image(image: Image.Image, background: tuple[int, int, int]) -> Image.Image: + panel = ref.Panel(1200, 1600) + return ref.pad_to_frame( + ref.enhance(ref.scale_to_frame(image, "rotate", panel)), panel, background + ) + + +def _landscape_options(**eink: Any) -> RenderOptions: + return RenderOptions.from_config( + config( + display={ + "orientation": "landscape", + "landscape_rotation": 90, + "default_fit": "contain", + "contain_background": "white", + }, + eink=eink, + ) + ) + + +def test_landscape_composition_equals_official_rotate_fit() -> None: + rng = np.random.default_rng(21) + image = Image.fromarray(rng.integers(0, 256, (900, 1600, 3), dtype=np.uint8)) + composed = compose(image, _landscape_options()) + expected = _official_rotate_image(image, (255, 255, 255)) + assert np.array_equal(np.rot90(np.asarray(composed)), np.asarray(expected)) + + +@pytest.mark.slow +def test_landscape_bin_is_byte_identical_to_official_rotate_fit() -> None: + rng = np.random.default_rng(22) + base = rng.integers(0, 256, (36, 64, 3), dtype=np.uint8) + image = Image.fromarray(base).resize((1600, 900), Image.Resampling.BICUBIC) + options = _landscape_options(dither="atkinson") + official_indices = ref.quantize_atkinson_indexed(_official_rotate_image(image, (255, 255, 255))) + expected = ref.pack_el133uf1(ref.COLOR_CODES[official_indices]).tobytes() + assert render(image, options).bin == expected From 06619aa15e8ed9a064c06f7681e9fe4eb598cd8b Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sat, 14 Nov 2026 19:55:00 +0100 Subject: [PATCH 24/86] feat: add display.safe_margin_px inset for frame mats The composition area is inset by safe_margin_px on every side (default 0, unchanged output); the margin is filled with the contain background style. Co-Authored-By: Claude Sonnet 5.5 --- app/core/config_models.py | 7 ++++ app/processor/pipeline.py | 17 +++++++-- tests/test_pipeline.py | 77 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 98 insertions(+), 3 deletions(-) diff --git a/app/core/config_models.py b/app/core/config_models.py index 7950f66..d06151a 100644 --- a/app/core/config_models.py +++ b/app/core/config_models.py @@ -200,6 +200,13 @@ class DisplayConfig(_Section): contain_background: Literal["blur", "black", "white"] = Field( default="blur", description="Padding style used by the contain fit mode" ) + safe_margin_px: int = Field( + default=0, + ge=0, + le=250, + description="Inset (pixels) kept clear on every side so subjects stay out of the " + "frame's mat/bezel; the margin is filled with the contain background style", + ) class EinkConfig(_Section): diff --git a/app/processor/pipeline.py b/app/processor/pipeline.py index 4b085a9..572684e 100644 --- a/app/processor/pipeline.py +++ b/app/processor/pipeline.py @@ -76,6 +76,7 @@ class RenderOptions: fit: FitMode background: BackgroundStyle eink: EinkConfig + safe_margin_px: int = 0 def __post_init__(self) -> None: native = (self.panel.width, self.panel.height) @@ -85,6 +86,8 @@ def __post_init__(self) -> None: f"frame_size {self.frame_size} does not match panel {native} " f"with rotation {self.rotation}" ) + if not 0 <= self.safe_margin_px < min(self.frame_size) // 4: + raise ValueError("safe_margin_px must be between 0 and a quarter of the short side") @classmethod def from_config(cls, config: RuntimeConfig, *, fit: FitMode | None = None) -> RenderOptions: @@ -99,6 +102,7 @@ def from_config(cls, config: RuntimeConfig, *, fit: FitMode | None = None) -> Re fit=fit or config.display.default_fit, background=config.display.contain_background, eink=config.eink, + safe_margin_px=config.display.safe_margin_px, ) @@ -139,10 +143,17 @@ def dithered_png(self) -> bytes: def compose( image: Image.Image, options: RenderOptions, regions: Sequence[FocusRegion] = () ) -> Image.Image: - """Fit and enhance ``image`` into the frame, in viewing orientation.""" + """Fit and enhance ``image`` into the frame, in viewing orientation. + + The picture fills the frame minus ``safe_margin_px`` on every side; whatever is left + over (the margin, or the bars of the ``contain`` fit) is the background. + """ + margin = options.safe_margin_px + area = (options.frame_size[0] - 2 * margin, options.frame_size[1] - 2 * margin) if options.fit == "smart_crop": - return enhance(smart_crop(image, options.frame_size, regions), options.eink) - picture = enhance(fit_inside(image, options.frame_size), options.eink) + picture = enhance(smart_crop(image, area, regions), options.eink) + else: + picture = enhance(fit_inside(image, area), options.eink) if picture.size == options.frame_size: return picture background = make_background(image, options.frame_size, options.background) diff --git a/tests/test_pipeline.py b/tests/test_pipeline.py index 8bb7eb5..1b92fe6 100644 --- a/tests/test_pipeline.py +++ b/tests/test_pipeline.py @@ -201,3 +201,80 @@ def test_landscape_bin_is_byte_identical_to_official_rotate_fit() -> None: official_indices = ref.quantize_atkinson_indexed(_official_rotate_image(image, (255, 255, 255))) expected = ref.pack_el133uf1(ref.COLOR_CODES[official_indices]).tobytes() assert render(image, options).bin == expected + + +# --- safe margin --------------------------------------------------------------------------- +def _margin_options(margin: int, fit: str, background: str = "white") -> RenderOptions: + return RenderOptions.from_config( + config( + display={ + "default_fit": fit, + "contain_background": background, + "safe_margin_px": margin, + }, + eink=neutral_eink(), + ) + ) + + +@pytest.mark.parametrize("fit", ["smart_crop", "contain"]) +def test_safe_margin_zero_is_the_unchanged_composition(fit: str) -> None: + rng = np.random.default_rng(31) + image = Image.fromarray(rng.integers(0, 256, (900, 1600, 3), dtype=np.uint8)) + default = RenderOptions.from_config(config(display={"default_fit": fit})) + explicit = RenderOptions.from_config(config(display={"default_fit": fit, "safe_margin_px": 0})) + assert np.array_equal(np.asarray(compose(image, default)), np.asarray(compose(image, explicit))) + + +@pytest.mark.parametrize( + ("fit", "background", "fill"), + [ + ("smart_crop", "white", (255, 255, 255)), + ("smart_crop", "black", (0, 0, 0)), + ("contain", "black", (0, 0, 0)), + ], +) +def test_safe_margin_insets_the_picture_and_fills_the_rim( + fit: str, background: str, fill: tuple[int, int, int] +) -> None: + margin = 40 + image = Image.new("RGB", (1200, 1600), (200, 30, 30)) + composed = np.asarray(compose(image, _margin_options(margin, fit, background))) + assert composed.shape == (1600, 1200, 3) + assert np.all(composed[:margin] == fill) and np.all(composed[-margin:] == fill) + assert np.all(composed[:, :margin] == fill) and np.all(composed[:, -margin:] == fill) + assert np.all(composed[margin + 20 : -margin - 20, margin + 20 : -margin - 20] != fill) + + +def test_safe_margin_blur_background_fills_the_rim_with_the_photo() -> None: + rng = np.random.default_rng(32) + image = Image.fromarray(rng.integers(0, 256, (900, 1600, 3), dtype=np.uint8)) + composed = np.asarray(compose(image, _margin_options(60, "smart_crop", "blur"))) + assert composed.shape == (1600, 1200, 3) + assert composed[:60].std() > 1 # a blurred copy of the photo, not a flat fill + + +def test_safe_margin_is_applied_in_viewing_orientation_and_survives_rotation() -> None: + options = RenderOptions.from_config( + config( + display={ + "orientation": "landscape", + "safe_margin_px": 50, + "contain_background": "white", + }, + eink=neutral_eink(), + ) + ) + result = render(Image.new("RGB", (1600, 1200), (255, 0, 0)), options) + assert result.composed.size == (1600, 1200) + assert np.all(result.indices[:50] == WHITE) and np.all(result.indices[:, :50] == WHITE) + assert result.indices[600, 800] == RED + portrait = decode_bin(result.bin, options.panel) + assert np.all(portrait[:50] == WHITE) and portrait[800, 600] == RED + + +def test_safe_margin_validation() -> None: + with pytest.raises(ValueError): + config(display={"safe_margin_px": -1}) + with pytest.raises(ValueError): + config(display={"safe_margin_px": 251}) From ef43b1624ebb89e6a11c19c85bccd2b168d2c8bd Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sat, 14 Nov 2026 19:55:48 +0100 Subject: [PATCH 25/86] feat: add spread guard and padding for focus regions in smart_crop smart_crop now keeps the largest-first subset of focus regions that fits the crop window instead of slicing faces on opposite edges in half. FocusRegion gains padded() so providers can leave room for hair and shoulders. Co-Authored-By: Claude Sonnet 5.5 --- app/processor/fit.py | 49 +++++++++++++++++++++++++++++++++++++++-- tests/test_fit.py | 52 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 99 insertions(+), 2 deletions(-) diff --git a/app/processor/fit.py b/app/processor/fit.py index 4d07251..3f030d4 100644 --- a/app/processor/fit.py +++ b/app/processor/fit.py @@ -63,6 +63,23 @@ def from_pixels( bottom = min(max(max(y1, y2) / image_height, 0.0), 1.0) return cls(left, top, max(right - left, 1e-6), max(bottom - top, 1e-6)) + @property + def area(self) -> float: + """Normalized area (fraction of the image).""" + return self.width * self.height + + def padded(self, fraction: float) -> FocusRegion: + """Grow every side by ``fraction`` of the region's own size, clamped to the image. + + Used for faces so hair, chin and shoulders are not cut at the crop edge. + """ + if fraction < 0: + raise ValueError("Padding fraction must not be negative") + dx, dy = self.width * fraction, self.height * fraction + left, top = max(self.x - dx, 0.0), max(self.y - dy, 0.0) + right, bottom = min(self.x + self.width + dx, 1.0), min(self.y + self.height + dy, 1.0) + return FocusRegion(left, top, right - left, bottom - top) + def _scaled_size(size: Size, ratio: float) -> Size: return max(1, round(size[0] * ratio)), max(1, round(size[1] * ratio)) @@ -80,12 +97,39 @@ def _place_window(lo: float, hi: float, window: int, total: int, anchor: float) return round(min(max(start, 0.0), float(total - window))) +def regions_that_fit( + regions: Sequence[FocusRegion], max_width: float, max_height: float +) -> list[FocusRegion]: + """The largest-first subset of ``regions`` whose union fits a crop window. + + ``max_width``/``max_height`` are the window size as fractions of the image (values + ``>= 1`` mean that axis is never cropped, so it never limits the selection). The + biggest region is always kept - even when it alone exceeds the window - and every + other region is added only if the union still fits. Two people on opposite edges of + a wide photo therefore yield one whole face instead of two sliced ones. + """ + if not regions: + return [] + ordered = sorted(regions, key=lambda region: region.area, reverse=True) + kept = [ordered[0]] + x1, y1 = ordered[0].x, ordered[0].y + x2, y2 = x1 + ordered[0].width, y1 + ordered[0].height + for region in ordered[1:]: + nx1, ny1 = min(x1, region.x), min(y1, region.y) + nx2, ny2 = max(x2, region.x + region.width), max(y2, region.y + region.height) + if nx2 - nx1 <= max_width + 1e-9 and ny2 - ny1 <= max_height + 1e-9: + kept.append(region) + x1, y1, x2, y2 = nx1, ny1, nx2, ny2 + return kept + + def smart_crop(image: Image.Image, size: Size, regions: Sequence[FocusRegion] = ()) -> Image.Image: """Scale to fill ``size`` and crop the overflow, keeping focus regions in frame. Without regions this is a centered crop identical to the official ``crop`` fit. - With regions, the crop window is moved along the overflowing axis so the union of - the regions is centered horizontally, or placed at 40% of the height vertically. + With regions, the ones that fit the crop window together (see + :func:`regions_that_fit`) decide where it goes: it is moved along the overflowing + axis so their union is centered horizontally, or placed at 40% of the height. """ target_w, target_h = size ratio = max(target_w / image.width, target_h / image.height) @@ -94,6 +138,7 @@ def smart_crop(image: Image.Image, size: Size, regions: Sequence[FocusRegion] = left = (resized_w - target_w) // 2 top = (resized_h - target_h) // 2 + regions = regions_that_fit(regions, target_w / resized_w, target_h / resized_h) if regions: x1 = min(r.x for r in regions) * resized_w x2 = max(r.x + r.width for r in regions) * resized_w diff --git a/tests/test_fit.py b/tests/test_fit.py index 3dde2ed..dec71ca 100644 --- a/tests/test_fit.py +++ b/tests/test_fit.py @@ -11,6 +11,7 @@ fit_inside, make_background, paste_centered, + regions_that_fit, smart_crop, ) from app.processor.pipeline import decode_image @@ -148,3 +149,54 @@ def test_decode_flattens_transparency_on_white() -> None: decoded = decode_image(buffer.getvalue()) assert decoded.mode == "RGB" assert decoded.getpixel((5, 5)) == (255, 255, 255) + + +# --- padding + spread guard ---------------------------------------------------------- +def test_focus_region_padded_grows_each_side_and_clamps() -> None: + padded = FocusRegion(0.4, 0.4, 0.2, 0.1).padded(0.25) + assert (padded.x, padded.y) == pytest.approx((0.35, 0.375)) + assert (padded.width, padded.height) == pytest.approx((0.3, 0.15)) + edge = FocusRegion(0.0, 0.9, 0.2, 0.1).padded(0.5) + assert edge.x == 0.0 and edge.y + edge.height == pytest.approx(1.0) + with pytest.raises(ValueError): + FocusRegion(0.1, 0.1, 0.1, 0.1).padded(-0.1) + + +def test_regions_that_fit_keeps_all_when_union_fits() -> None: + a, b = FocusRegion(0.1, 0.4, 0.1, 0.1), FocusRegion(0.3, 0.4, 0.1, 0.1) + assert regions_that_fit([a, b], 0.5, 1.0) == [a, b] + + +def test_regions_that_fit_drops_regions_that_do_not_fit_largest_first() -> None: + small_left = FocusRegion(0.02, 0.4, 0.06, 0.1) + big_right = FocusRegion(0.85, 0.3, 0.1, 0.25) + mid_center = FocusRegion(0.7, 0.4, 0.08, 0.1) + kept = regions_that_fit([small_left, big_right, mid_center], 0.3, 1.0) + assert kept == [big_right, mid_center] + + +def test_regions_that_fit_keeps_oversized_single_region_and_ignores_free_axes() -> None: + huge = FocusRegion(0.1, 0.1, 0.8, 0.8) + assert regions_that_fit([huge, FocusRegion(0.0, 0.0, 0.05, 0.05)], 0.3, 0.3) == [huge] + # The vertical axis is never cropped (window >= 1): only horizontal spread matters. + a, b = FocusRegion(0.1, 0.0, 0.1, 0.1), FocusRegion(0.15, 0.9, 0.1, 0.1) + assert regions_that_fit([a, b], 0.2, 1.0) == [a, b] + assert regions_that_fit([], 0.5, 0.5) == [] + + +def test_smart_crop_keeps_the_larger_face_whole_when_faces_are_too_far_apart() -> None: + # 4000x3000 photo into a portrait frame: the window covers 1200/2133 = 56% of the width. + image = Image.new("RGB", (4000, 3000), (255, 255, 255)) + image.paste((255, 0, 0), (150, 1200, 450, 1500)) # small face, far left + image.paste((0, 0, 255), (3300, 1000, 3800, 1500)) # larger face, far right + regions = [ + FocusRegion.from_pixels(150, 1200, 450, 1500, 4000, 3000), + FocusRegion.from_pixels(3300, 1000, 3800, 1500, 4000, 3000), + ] + cropped = np.asarray(smart_crop(image, (1200, 1600), regions)) + blue = (cropped[..., 2] > 200) & (cropped[..., 0] < 60) & (cropped[..., 1] < 60) + red = (cropped[..., 0] > 200) & (cropped[..., 1] < 60) & (cropped[..., 2] < 60) + ys, xs = np.where(blue) + assert ys.size > 0 and xs.min() > 0 and xs.max() < 1199 # the big face is complete + assert xs.max() - xs.min() >= 0.9 * (500 * 1600 / 3000) + assert not red.any() # the small face is dropped, not sliced in half From 6bcf40850f725b376f5031083b119639b658f49e Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sat, 14 Nov 2026 19:58:46 +0100 Subject: [PATCH 26/86] feat: add Immich accounts config with masked secrets immich.accounts holds multiple named accounts (url + api_key) plus always_include, person_aliases, cache TTL and candidate count. Account keys are masked in GET /api/config, restored from the stored value when a masked or omitted key is sent back, and registered for log masking. IMMICH_URL and IMMICH_API_KEY seed an account named 'default'; saved legacy immich.url and immich.api_key values are migrated on load. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- app/api/routes/config.py | 12 +++- app/api/routes/system.py | 2 +- app/core/config_models.py | 109 +++++++++++++++++++++++++++++++---- app/core/config_store.py | 42 +++++++++++++- app/core/settings.py | 13 +++-- tests/test_api.py | 23 ++++++++ tests/test_config_models.py | 50 ++++++++++++---- tests/test_config_store.py | 110 +++++++++++++++++++++++++++++++++--- tests/test_settings.py | 4 +- 9 files changed, 325 insertions(+), 40 deletions(-) diff --git a/app/api/routes/config.py b/app/api/routes/config.py index aafeada..42c1030 100644 --- a/app/api/routes/config.py +++ b/app/api/routes/config.py @@ -37,8 +37,8 @@ class ResetRequest(BaseModel): paths: list[str] | None = Field( default=None, - description="Entries like 'immich' (whole section) or 'immich.url' (single field)", - examples=[["immich.url", "eink"]], + description="Entries like 'immich' (whole section) or 'immich.accounts' (single field)", + examples=[["immich.accounts", "eink"]], ) @@ -56,7 +56,13 @@ class ConfigErrorResponse(BaseModel): }, "immich": { "summary": "Immich defaults", - "value": {"immich": {"persons": ["Alice", "Bob"], "match_mode": "any"}}, + "value": { + "immich": { + "accounts": {"default": {"url": "http://immich.local:2283", "api_key": "..."}}, + "persons": ["Alice", "Bob"], + "match_mode": "any", + } + }, }, } diff --git a/app/api/routes/system.py b/app/api/routes/system.py index dccdf42..565eb84 100644 --- a/app/api/routes/system.py +++ b/app/api/routes/system.py @@ -123,7 +123,7 @@ async def status( timezone=config.scheduler.timezone, ), services=ServiceConfigured( - immich=bool(config.immich.url and config.immich.api_key.get_secret_value()), + immich=bool(config.immich.accounts), tmdb=bool(config.tmdb.api_key.get_secret_value()), ), ) diff --git a/app/core/config_models.py b/app/core/config_models.py index d06151a..a1ffd4c 100644 --- a/app/core/config_models.py +++ b/app/core/config_models.py @@ -77,35 +77,106 @@ class _Section(BaseModel): model_config = ConfigDict(extra="forbid", validate_assignment=True) +ACCOUNT_NAME_RE: Final = re.compile(r"^[A-Za-z0-9_-]{1,32}$") + + +def _clean_names(value: list[str]) -> list[str]: + cleaned: list[str] = [] + for name in value: + stripped = name.strip() + if stripped and stripped not in cleaned: + cleaned.append(stripped) + return cleaned + + +class ImmichAccountConfig(_Section): + """One Immich server/account (a family member or a shared library).""" + + url: str = Field(description="Immich base URL, e.g. http://immich.local:2283") + api_key: SecretStr = Field(description="Immich API key of this account") + + @field_validator("url") + @classmethod + def _validate_url(cls, value: str) -> str: + normalized = _normalize_http_base_url(value) + if not normalized: + raise ValueError("must not be empty") + return normalized + + @field_validator("api_key") + @classmethod + def _validate_key(cls, value: SecretStr) -> SecretStr: + raw = value.get_secret_value().strip() + if not raw: + raise ValueError("must not be empty") + return SecretStr(raw) + + class ImmichConfig(_Section): - """Connection and default selection filters for the Immich provider.""" + """Immich accounts and the default selection filters of the Immich provider.""" - url: str = Field(default="", description="Immich base URL, e.g. http://immich.local:2283") - api_key: SecretStr = Field(default=SecretStr(""), description="Immich API key") + accounts: dict[str, ImmichAccountConfig] = Field( + default_factory=dict, + description="Immich accounts by name (IMMICH_URL/IMMICH_API_KEY seed one named 'default')", + ) persons: list[str] = Field(default_factory=list, description="Default person names filter") + always_include: list[str] = Field( + default_factory=list, + description="Person names merged into every selection (e.g. children without a " + "Home Assistant presence), unless a request overrides them", + ) match_mode: Literal["any", "all"] = Field( default="any", description="Match photos containing any or all of the persons" ) + person_aliases: dict[str, dict[str, list[str]]] = Field( + default_factory=dict, + description="Canonical person name -> account name -> person IDs or names in that " + "account (disambiguates duplicate or differently named people)", + ) album: str = Field(default="", description="Default album name filter (empty = all)") favorites_only: bool = Field(default=False, description="Only pick favorite assets") exclude_archived: bool = Field(default=True, description="Skip archived assets") anti_repeat_days: int = Field( default=30, ge=0, le=3650, description="Do not show the same photo again within N days" ) + people_cache_ttl_s: int = Field( + default=3600, ge=0, le=604_800, description="How long the people list is cached (0 = off)" + ) + search_candidates: int = Field( + default=40, ge=5, le=200, description="Candidates fetched per search before picking one" + ) - @field_validator("url") + @field_validator("accounts") @classmethod - def _validate_url(cls, value: str) -> str: - return _normalize_http_base_url(value) + def _validate_account_names( + cls, value: dict[str, ImmichAccountConfig] + ) -> dict[str, ImmichAccountConfig]: + for name in value: + if not ACCOUNT_NAME_RE.match(name): + raise ValueError(f"invalid account name {name!r}: use 1-32 letters, digits, - or _") + return value - @field_validator("persons") + @field_validator("persons", "always_include") @classmethod def _clean_persons(cls, value: list[str]) -> list[str]: - cleaned: list[str] = [] - for name in value: - stripped = name.strip() - if stripped and stripped not in cleaned: - cleaned.append(stripped) + return _clean_names(value) + + @field_validator("person_aliases") + @classmethod + def _clean_aliases( + cls, value: dict[str, dict[str, list[str]]] + ) -> dict[str, dict[str, list[str]]]: + cleaned: dict[str, dict[str, list[str]]] = {} + for canonical, per_account in value.items(): + name = canonical.strip() + if not name: + raise ValueError("alias names must not be empty") + targets: dict[str, list[str]] = {} + for account, entries in per_account.items(): + if not ACCOUNT_NAME_RE.match(account): + raise ValueError(f"invalid account name {account!r} in alias {name!r}") + targets[account] = _clean_names(entries) + cleaned[name] = targets return cleaned @@ -342,9 +413,23 @@ def dump_config(config: RuntimeConfig, *, reveal_secrets: bool) -> dict[str, dic secret: SecretStr = getattr(getattr(config, section), name) raw = secret.get_secret_value() data[section][name] = raw if reveal_secrets else mask_secret(raw) + for account_name, account in config.immich.accounts.items(): + raw = account.api_key.get_secret_value() + data["immich"]["accounts"][account_name]["api_key"] = ( + raw if reveal_secrets else mask_secret(raw) + ) return data +def nested_secret_values(config: RuntimeConfig) -> list[str]: + """Secrets stored inside nested structures (the Immich account API keys).""" + return [ + raw + for account in config.immich.accounts.values() + if (raw := account.api_key.get_secret_value()) + ] + + MASK_PREFIX: Final = "•" * 8 diff --git a/app/core/config_store.py b/app/core/config_store.py index 2b2aff1..597ac1f 100644 --- a/app/core/config_store.py +++ b/app/core/config_store.py @@ -26,6 +26,7 @@ RuntimeConfig, dump_config, is_masked, + nested_secret_values, secret_field_paths, section_fields, ) @@ -156,6 +157,7 @@ def secret_values(self) -> list[str]: raw = getattr(getattr(self._config, section), name).get_secret_value() if raw: values.append(raw) + values.extend(nested_secret_values(self._config)) return values def add_listener(self, listener: ConfigListener) -> None: @@ -169,7 +171,7 @@ def load(self) -> RuntimeConfig: Invalid entries (e.g. left over from an older version) are logged and ignored in memory; the file is rewritten without them on the next successful save. """ - raw = read_json(self._path, dict) + raw = self._migrate_legacy(read_json(self._path, dict)) overrides = self._sanitize_shape(raw) overrides = self._prune_invalid(overrides) self._overrides = overrides @@ -197,6 +199,7 @@ async def update(self, patch: Mapping[str, Any]) -> RuntimeConfig: """ normalized = self._normalize_patch(patch) async with self._lock: + self._restore_masked_account_keys(normalized) candidate = _merge(self._overrides, normalized) config = self._build(candidate) canonical = dump_config(config, reveal_secrets=True) @@ -262,6 +265,43 @@ async def _notify(self, config: RuntimeConfig) -> None: except Exception: logger.exception("Configuration listener %r failed", listener) + def _restore_masked_account_keys(self, normalized: Overrides) -> None: + """Let a masked or omitted account ``api_key`` keep the stored key of that account. + + ``immich.accounts`` is replaced as a whole, so a client that sends the masked view + back (or omits the key) must not wipe the secrets. A new account without a real + key is left without one and fails validation. + """ + accounts = normalized.get("immich", {}).get("accounts") + if not isinstance(accounts, dict): + return + for name, account in accounts.items(): + if not isinstance(account, dict): + continue + key = account.get("api_key") + if key is not None and not is_masked(key): + continue + account.pop("api_key", None) + existing = self._config.immich.accounts.get(name) + if existing is not None: + account["api_key"] = existing.api_key.get_secret_value() + + @staticmethod + def _migrate_legacy(raw: Any) -> Any: + """Move the pre-accounts ``immich.url``/``api_key`` pair into ``accounts.default``.""" + if not isinstance(raw, dict) or not isinstance(raw.get("immich"), dict): + return raw + section = dict(raw["immich"]) + url, key = section.pop("url", None), section.pop("api_key", None) + if url is None and key is None: + return raw + if url and key and "accounts" not in section: + section["accounts"] = {"default": {"url": url, "api_key": key}} + logger.info("Migrated saved immich.url/api_key to immich.accounts.default") + else: + logger.warning("Ignoring incomplete legacy immich.url/api_key settings") + return {**raw, "immich": section} + @staticmethod def _normalize_patch(patch: Mapping[str, Any]) -> Overrides: if not isinstance(patch, Mapping): diff --git a/app/core/settings.py b/app/core/settings.py index a28fb1e..1541219 100644 --- a/app/core/settings.py +++ b/app/core/settings.py @@ -183,10 +183,6 @@ def runtime_seed(self) -> dict[str, dict[str, Any]]: to the built-in defaults. """ candidates: dict[tuple[str, str], Any] = { - ("immich", "url"): self.immich_url, - ("immich", "api_key"): ( - self.immich_api_key.get_secret_value() if self.immich_api_key else None - ), ("tmdb", "api_key"): ( self.tmdb_api_key.get_secret_value() if self.tmdb_api_key else None ), @@ -203,6 +199,15 @@ def runtime_seed(self) -> dict[str, dict[str, Any]]: for (section, name), value in candidates.items(): if value is not None: seed.setdefault(section, {})[name] = value + if self.immich_url and self.immich_api_key: + seed["immich"] = { + "accounts": { + "default": { + "url": self.immich_url, + "api_key": self.immich_api_key.get_secret_value(), + } + } + } return seed diff --git a/tests/test_api.py b/tests/test_api.py index ea02e06..71f2dfb 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -113,3 +113,26 @@ def test_index_redirects_to_docs(make_client: ClientFactory) -> None: response = make_client().get("/", follow_redirects=False) assert response.status_code == 307 assert response.headers["location"] == "/docs" + + +def test_config_api_masks_immich_account_keys(make_client: ClientFactory) -> None: + client = make_client() + accounts = {"home": {"url": "http://immich.local:2283", "api_key": "home-secret-key-1111"}} + response = client.put("/api/config", json={"immich": {"accounts": accounts}}) + assert response.status_code == 200 + assert "home-secret-key-1111" not in response.text + shown = response.json()["config"]["immich"]["accounts"]["home"] + assert shown["api_key"].endswith("1111") and shown["api_key"].startswith("•") + + # Sending the masked view back must not overwrite the stored key. + again = client.put("/api/config", json={"immich": response.json()["config"]["immich"]}) + assert again.status_code == 200 + status = client.get("/api/status").json() + assert status["services"]["immich"] is True + assert "home-secret-key-1111" not in client.get("/api/status").text + + rejected = client.put( + "/api/config", json={"immich": {"accounts": {"new": {"url": "http://immich.lan"}}}} + ) + assert rejected.status_code == 422 + assert "home-secret-key-1111" not in rejected.text diff --git a/tests/test_config_models.py b/tests/test_config_models.py index e229990..c511ab0 100644 --- a/tests/test_config_models.py +++ b/tests/test_config_models.py @@ -9,6 +9,7 @@ MASK_PREFIX, PANEL_SPECS, FraimicConfig, + ImmichAccountConfig, ImmichConfig, RuntimeConfig, SchedulerConfig, @@ -16,6 +17,7 @@ dump_config, is_masked, mask_secret, + nested_secret_values, secret_field_paths, ) @@ -82,16 +84,36 @@ def test_fraimic_paths_must_be_absolute(path: str) -> None: FraimicConfig(status_path=path) -def test_immich_url_and_persons_are_cleaned() -> None: - config = ImmichConfig(url=" http://immich.local:2283/ ", persons=[" Alice", "Bob", "Alice", ""]) - assert config.url == "http://immich.local:2283" +def test_immich_persons_and_account_are_cleaned() -> None: + config = ImmichConfig( + persons=[" Alice", "Bob", "Alice", ""], + always_include=[" Kid ", "Kid"], + accounts={"home": {"url": " http://immich.local:2283/ ", "api_key": " key-1 "}}, # type: ignore[dict-item] + person_aliases={" Marie ": {"home": [" Marie ", "", "7f0c"]}}, + ) assert config.persons == ["Alice", "Bob"] + assert config.always_include == ["Kid"] + assert config.accounts["home"].url == "http://immich.local:2283" + assert config.accounts["home"].api_key.get_secret_value() == "key-1" + assert config.person_aliases == {"Marie": {"home": ["Marie", "7f0c"]}} + + +@pytest.mark.parametrize("url", ["", "immich.local", "file:///etc/passwd", "http://u:p@immich"]) +def test_immich_account_url_rejects_bad_values(url: str) -> None: + with pytest.raises(ValidationError): + ImmichAccountConfig(url=url, api_key=SecretStr("k")) -@pytest.mark.parametrize("url", ["immich.local", "file:///etc/passwd", "http://u:p@immich"]) -def test_immich_url_rejects_bad_values(url: str) -> None: +def test_immich_account_requires_a_key_and_valid_names() -> None: + with pytest.raises(ValidationError): + ImmichAccountConfig(url="http://immich", api_key=SecretStr(" ")) + account = {"url": "http://immich", "api_key": "k"} + with pytest.raises(ValidationError): + ImmichConfig.model_validate({"accounts": {"bad name!": account}}) + with pytest.raises(ValidationError): + ImmichConfig.model_validate({"person_aliases": {"Marie": {"bad name": ["x"]}}}) with pytest.raises(ValidationError): - ImmichConfig(url=url) + ImmichConfig.model_validate({"person_aliases": {" ": {}}}) @pytest.mark.parametrize("language", ["fr-FR", "en-US", "de-DE"]) @@ -142,13 +164,21 @@ def test_secret_masking() -> None: def test_dump_config_reveals_or_masks_secrets() -> None: config = RuntimeConfig( - immich=ImmichConfig(api_key=SecretStr("immich-secret-key-1234")), + immich=ImmichConfig( + accounts={ + "home": ImmichAccountConfig( + url="http://immich", api_key=SecretStr("immich-secret-key-1234") + ) + } + ), tmdb=TmdbConfig(api_key=SecretStr("tmdb")), ) - assert set(secret_field_paths()) == {("immich", "api_key"), ("tmdb", "api_key")} + assert set(secret_field_paths()) == {("tmdb", "api_key")} + assert nested_secret_values(config) == ["immich-secret-key-1234"] revealed = dump_config(config, reveal_secrets=True) masked = dump_config(config, reveal_secrets=False) - assert revealed["immich"]["api_key"] == "immich-secret-key-1234" - assert masked["immich"]["api_key"] == MASK_PREFIX + "1234" + assert revealed["immich"]["accounts"]["home"]["api_key"] == "immich-secret-key-1234" + assert masked["immich"]["accounts"]["home"]["api_key"] == MASK_PREFIX + "1234" + assert "immich-secret-key-1234" not in str(masked) assert masked["tmdb"]["api_key"] == MASK_PREFIX assert RuntimeConfig.model_validate(revealed) == config diff --git a/tests/test_config_store.py b/tests/test_config_store.py index 36bcc97..aa4368c 100644 --- a/tests/test_config_store.py +++ b/tests/test_config_store.py @@ -47,8 +47,8 @@ async def test_precedence_default_env_config_and_reset(config_path: Path) -> Non async def test_overrides_are_sparse_and_canonical(config_path: Path) -> None: store = make_store(config_path) - await store.update({"immich": {"url": "http://immich.local:2283/", "persons": ["A", " A "]}}) - assert saved(config_path) == {"immich": {"url": "http://immich.local:2283", "persons": ["A"]}} + await store.update({"immich": {"album": " Family ", "persons": ["A", " A "]}}) + assert saved(config_path) == {"immich": {"album": " Family ", "persons": ["A"]}} async def test_unchanged_values_do_not_freeze_env_fallback(config_path: Path) -> None: @@ -61,17 +61,17 @@ async def test_unchanged_values_do_not_freeze_env_fallback(config_path: Path) -> async def test_masked_secret_round_trip_keeps_value(config_path: Path) -> None: - store = make_store(config_path, {"immich": {"api_key": "env-immich-secret-0001"}}) + store = make_store(config_path, {"tmdb": {"api_key": "env-tmdb-secret-0001"}}) view = store.public_view() - assert view["config"]["immich"]["api_key"] == MASK_PREFIX + "0001" + assert view["config"]["tmdb"]["api_key"] == MASK_PREFIX + "0001" await store.update(view["config"]) - assert store.config.immich.api_key.get_secret_value() == "env-immich-secret-0001" + assert store.config.tmdb.api_key.get_secret_value() == "env-tmdb-secret-0001" assert not config_path.exists() or saved(config_path) == {} - await store.update({"immich": {"api_key": "new-key"}}) - assert store.config.immich.api_key.get_secret_value() == "new-key" - assert saved(config_path) == {"immich": {"api_key": "new-key"}} + await store.update({"tmdb": {"api_key": "new-key"}}) + assert store.config.tmdb.api_key.get_secret_value() == "new-key" + assert saved(config_path) == {"tmdb": {"api_key": "new-key"}} assert "new-key" in store.secret_values() @@ -164,3 +164,97 @@ async def broken(_: RuntimeConfig) -> None: await store.update({"eink": {"contrast": 1.7}}) await store.reset() assert seen == [1.7, 1.2] + + +# --- Immich accounts: nested secrets ------------------------------------------------------- +ACCOUNTS = { + "home": {"url": "http://immich.local:2283", "api_key": "home-secret-key-1111"}, + "partner": {"url": "https://photos.example.org", "api_key": "partner-secret-key-2222"}, +} + + +async def test_account_keys_are_masked_but_stored_and_logged_as_secrets(config_path: Path) -> None: + store = make_store(config_path) + await store.update({"immich": {"accounts": ACCOUNTS}}) + + view = store.public_view()["config"]["immich"]["accounts"] + assert view["home"]["api_key"] == MASK_PREFIX + "1111" + assert view["partner"]["url"] == "https://photos.example.org" + assert "secret-key" not in str(store.public_view()) + assert saved(config_path)["immich"]["accounts"]["home"]["api_key"] == "home-secret-key-1111" + assert {"home-secret-key-1111", "partner-secret-key-2222"} <= set(store.secret_values()) + + +async def test_masked_account_keys_round_trip_and_survive_removals(config_path: Path) -> None: + store = make_store(config_path) + await store.update({"immich": {"accounts": ACCOUNTS}}) + + form = store.public_view()["config"]["immich"] + await store.update({"immich": form}) # the UI sends the masked view back + assert store.config.immich.accounts["home"].api_key.get_secret_value() == "home-secret-key-1111" + + form["accounts"].pop("partner") # omitting an account deletes it + form["accounts"]["home"]["url"] = "http://immich.lan:2283" + await store.update({"immich": form}) + assert set(store.config.immich.accounts) == {"home"} + home = store.config.immich.accounts["home"] + assert home.url == "http://immich.lan:2283" + assert home.api_key.get_secret_value() == "home-secret-key-1111" + + await store.update({"immich": {"accounts": {"home": {"url": "http://immich.lan:2283"}}}}) + assert store.config.immich.accounts["home"].api_key.get_secret_value() == "home-secret-key-1111" + + +async def test_new_account_without_a_real_key_is_rejected(config_path: Path) -> None: + store = make_store(config_path) + for bad in ( + {"url": "http://immich"}, + {"url": "http://immich", "api_key": MASK_PREFIX + "1111"}, + ): + with pytest.raises(ConfigValidationError): + await store.update({"immich": {"accounts": {"new": bad}}}) + assert not config_path.exists() + + +async def test_env_seed_account_and_config_json_precedence(config_path: Path) -> None: + seed = {"immich": {"accounts": {"default": ACCOUNTS["home"]}}} + store = make_store(config_path, seed) + assert set(store.config.immich.accounts) == {"default"} + assert store.sources()["immich.accounts"] == "env" + + await store.update({"immich": {"accounts": {"partner": ACCOUNTS["partner"]}}}) + assert set(store.config.immich.accounts) == {"partner"} # config.json always wins + assert store.sources()["immich.accounts"] == "config" + + +def test_legacy_single_account_settings_are_migrated(config_path: Path) -> None: + config_path.write_text( + json.dumps( + { + "immich": { + "url": "http://immich.local:2283", + "api_key": "legacy-secret-key-9999", + "album": "Family", + } + } + ), + encoding="utf-8", + ) + store = make_store(config_path) + store.load() + account = store.config.immich.accounts["default"] + assert account.url == "http://immich.local:2283" + assert account.api_key.get_secret_value() == "legacy-secret-key-9999" + assert store.config.immich.album == "Family" + assert "legacy-secret-key-9999" in store.secret_values() + + +def test_incomplete_legacy_settings_are_dropped(config_path: Path) -> None: + config_path.write_text( + json.dumps({"immich": {"url": "http://immich.local:2283", "album": "Family"}}), + encoding="utf-8", + ) + store = make_store(config_path) + store.load() + assert store.config.immich.accounts == {} + assert store.config.immich.album == "Family" diff --git a/tests/test_settings.py b/tests/test_settings.py index 38a59f7..84c21e0 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -58,7 +58,9 @@ def test_reads_environment(monkeypatch: pytest.MonkeyPatch, data_dir: Path) -> N assert settings.log_level == "DEBUG" assert settings.tmdb_api_key is None assert settings.runtime_seed() == { - "immich": {"url": "http://immich.local:2283", "api_key": "immich-key"}, + "immich": { + "accounts": {"default": {"url": "http://immich.local:2283", "api_key": "immich-key"}} + }, "fraimic": {"panel": "315"}, "scheduler": {"enabled": True, "interval_hours": 3.0, "timezone": "Europe/Paris"}, } From 580e53a6ede13d62f1e856280fbcd6753e73fc02 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sat, 14 Nov 2026 20:00:00 +0100 Subject: [PATCH 27/86] feat: decode HEIC/HEIF images via pillow-heif iPhone HEIC originals now decode at full resolution everywhere images are validated or rendered, including POST /api/display/upload. AVIF stays disallowed and the magic-byte, pixel-count and truncation checks still apply. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- app/api/routes/display.py | 2 +- app/core/security.py | 8 +++++++- pyproject.toml | 1 + tests/test_api_phase2.py | 10 ++++++++++ tests/test_security.py | 26 ++++++++++++++++++++++++++ 5 files changed, 45 insertions(+), 2 deletions(-) diff --git a/app/api/routes/display.py b/app/api/routes/display.py index d893c75..3159aa3 100644 --- a/app/api/routes/display.py +++ b/app/api/routes/display.py @@ -31,7 +31,7 @@ def _clean_filename(name: str | None) -> str | None: _UPLOAD_RESPONSES: dict[int | str, dict[str, Any]] = { 413: {"description": "File larger than MAX_UPLOAD_MB"}, - 415: {"description": "Not a supported image (JPEG, PNG, WebP, GIF, TIFF, BMP)"}, + 415: {"description": "Not a supported image (JPEG, PNG, WebP, GIF, TIFF, BMP, HEIC)"}, } diff --git a/app/core/security.py b/app/core/security.py index 4654ae0..98ddbc2 100644 --- a/app/core/security.py +++ b/app/core/security.py @@ -12,11 +12,17 @@ from urllib.parse import urlsplit from PIL import Image, UnidentifiedImageError +from pillow_heif import register_heif_opener IPAddress = ipaddress.IPv4Address | ipaddress.IPv6Address IPNetwork = ipaddress.IPv4Network | ipaddress.IPv6Network -ALLOWED_IMAGE_FORMATS: Final = frozenset({"JPEG", "MPO", "PNG", "WEBP", "GIF", "TIFF", "BMP"}) +# HEIC/HEIF (iPhone originals) decode through pillow-heif; AVIF is intentionally not allowed. +register_heif_opener() + +ALLOWED_IMAGE_FORMATS: Final = frozenset( + {"JPEG", "MPO", "PNG", "WEBP", "GIF", "TIFF", "BMP", "HEIF"} +) MAX_IMAGE_PIXELS: Final = 120_000_000 UPLOAD_CHUNK_SIZE: Final = 64 * 1024 diff --git a/pyproject.toml b/pyproject.toml index 2235eb8..d175422 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -25,6 +25,7 @@ dependencies = [ "pydantic-settings>=2.4", "httpx>=0.27", "pillow>=10.4", + "pillow-heif>=0.20", "numpy>=2.0", "apscheduler>=3.10,<4", "jinja2>=3.1", diff --git a/tests/test_api_phase2.py b/tests/test_api_phase2.py index a294566..3de885c 100644 --- a/tests/test_api_phase2.py +++ b/tests/test_api_phase2.py @@ -311,3 +311,13 @@ def test_status_before_any_image(make_client: ClientFactory) -> None: ) def test_clean_filename(raw: str | None, expected: str | None) -> None: assert _clean_filename(raw) == expected + + +@respx.mock +def test_upload_accepts_heic(frame_client: Callable[..., TestClient]) -> None: + buffer = io.BytesIO() + Image.new("RGB", (320, 240), (30, 90, 200)).save(buffer, format="HEIF", quality=85) + client = frame_client() + response = upload(client, push=False, data=buffer.getvalue()) + assert response.status_code == 200, response.text + assert response.json()["image"]["bin_size"] == 960_000 diff --git a/tests/test_security.py b/tests/test_security.py index 9e4e4d3..658ac79 100644 --- a/tests/test_security.py +++ b/tests/test_security.py @@ -159,3 +159,29 @@ def test_verify_image_rejects_unsupported_format() -> None: def test_verify_image_enforces_pixel_limit() -> None: with pytest.raises(InvalidImageError, match="too large"): verify_image_bytes(_image_bytes("PNG", (100, 100)), max_pixels=9_999) + + +# --- HEIC / HEIF --------------------------------------------------------------------------- +def _heic_bytes( + size: tuple[int, int] = (96, 64), color: tuple[int, int, int] = (200, 40, 40) +) -> bytes: + buffer = io.BytesIO() + Image.new("RGB", size, color).save(buffer, format="HEIF", quality=85) + return buffer.getvalue() + + +def test_heic_images_are_accepted_and_decoded() -> None: + from app.processor.pipeline import decode_image + + data = _heic_bytes() + assert verify_image_bytes(data) == "HEIF" + decoded = decode_image(data) + assert decoded.mode == "RGB" and decoded.size == (96, 64) + red, green, blue = decoded.getpixel((10, 10)) + assert red > 150 and green < 90 and blue < 90 + + +def test_corrupt_heic_is_rejected() -> None: + data = _heic_bytes() + with pytest.raises(InvalidImageError): + verify_image_bytes(data[: len(data) // 2]) From ee9312f2d546c25d41180568f11a57a9162c7359 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sat, 14 Nov 2026 20:12:42 +0100 Subject: [PATCH 28/86] feat: add Immich provider with multi-account selection and face regions - BaseImageProvider/ImageAsset abstraction with typed provider errors - ImmichClient + gateway (x-api-key header, no redirects, SSRF policy, size caps), contracts pinned against Immich 3.3.5 - PeopleDirectory: per-account TTL cache, aliases (IDs or names), ambiguity errors - Face boxes -> padded FocusRegions, target people first, orientation guard - ImmichProvider: random/album/favorites/search through one query path, any/all person matching, always_include merge, checksum dedupe across accounts, anti-repeat history, original -> fullsize -> preview downloads - Reusable fake Immich server for tests Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- app/providers/__init__.py | 3 +- app/providers/base.py | 92 ++++++ app/providers/immich/__init__.py | 8 + app/providers/immich/client.py | 318 ++++++++++++++++++ app/providers/immich/faces.py | 98 ++++++ app/providers/immich/models.py | 153 +++++++++ app/providers/immich/people.py | 176 ++++++++++ app/providers/immich/provider.py | 412 +++++++++++++++++++++++ tests/immich_fake.py | 222 +++++++++++++ tests/test_immich_client.py | 198 +++++++++++ tests/test_immich_faces.py | 125 +++++++ tests/test_immich_people.py | 171 ++++++++++ tests/test_immich_provider.py | 552 +++++++++++++++++++++++++++++++ 13 files changed, 2526 insertions(+), 2 deletions(-) create mode 100644 app/providers/base.py create mode 100644 app/providers/immich/__init__.py create mode 100644 app/providers/immich/client.py create mode 100644 app/providers/immich/faces.py create mode 100644 app/providers/immich/models.py create mode 100644 app/providers/immich/people.py create mode 100644 app/providers/immich/provider.py create mode 100644 tests/immich_fake.py create mode 100644 tests/test_immich_client.py create mode 100644 tests/test_immich_faces.py create mode 100644 tests/test_immich_people.py create mode 100644 tests/test_immich_provider.py diff --git a/app/providers/__init__.py b/app/providers/__init__.py index 7c95856..d7d9d66 100644 --- a/app/providers/__init__.py +++ b/app/providers/__init__.py @@ -2,6 +2,5 @@ Every provider subclasses ``BaseImageProvider`` and returns a standardized ``ImageAsset`` (raw bytes, metadata, recommended fit mode, regions of interest). -Providers (Immich, TMDB media posters, direct URLs) are added in the -``feat/providers-api`` milestone. +Implemented: ``immich`` (multi-account, face-aware). TMDB posters and direct URLs follow. """ diff --git a/app/providers/base.py b/app/providers/base.py new file mode 100644 index 0000000..b55081e --- /dev/null +++ b/app/providers/base.py @@ -0,0 +1,92 @@ +"""Provider abstractions shared by every image source. + +A provider turns a *request* (what the user asked for) into an :class:`ImageAsset` +(raw bytes plus everything the renderer and the UI need). Providers never render, +store or deliver anything: :class:`app.services.display.DisplayService` does that. + +Adding a source = subclass :class:`BaseImageProvider`, return :class:`ImageAsset` +objects and raise the :class:`ProviderError` subclasses below so the API layer can map +them to HTTP status codes without knowing the provider. +""" + +from __future__ import annotations + +from abc import ABC, abstractmethod +from dataclasses import dataclass, field +from typing import Generic, TypeVar + +from pydantic import JsonValue + +from app.core.config_models import FitMode +from app.processor.fit import FocusRegion + + +class ProviderError(Exception): + """Base class of every error a provider raises on purpose (messages are client-safe).""" + + +class ProviderNotConfiguredError(ProviderError): + """The provider has no usable credentials or endpoint yet (HTTP 409).""" + + +class InvalidSelectionError(ProviderError): + """The request names something that does not exist or is ambiguous (HTTP 422).""" + + +class NoCandidateError(ProviderError): + """Nothing eligible matched the request (HTTP 404).""" + + +class ProviderUnavailableError(ProviderError): + """The upstream service failed or could not be reached (HTTP 502, or 504 on timeout).""" + + def __init__(self, message: str, *, timeout: bool = False) -> None: + super().__init__(message) + self.timeout = timeout + + +@dataclass(frozen=True, slots=True) +class ImageAsset: + """A fetched image and its metadata, ready for rendering. + + Attributes: + data: Raw image bytes (any format Pillow can decode). + source: Provider name (``"immich"``, ``"media"``...); also the history namespace. + history_key: Stable identifier used by the anti-repeat history. Providers that can + see the same picture through several routes (e.g. two Immich accounts) should + derive it from the content so the cooldown applies across routes. + title: Short human-readable title (people, place, movie name...). + details: Provider metadata shown in the UI; never put secrets or URLs with keys here. + recommended_fit: Fit mode this source prefers (e.g. posters: ``contain``); ``None`` + means "use the configured default". + regions: Regions of interest (faces) in normalized coordinates, most relevant first. + """ + + data: bytes = field(repr=False) + source: str + history_key: str + title: str | None = None + details: dict[str, JsonValue] = field(default_factory=dict) + recommended_fit: FitMode | None = None + regions: tuple[FocusRegion, ...] = () + + +RequestT = TypeVar("RequestT", contravariant=True) + + +class BaseImageProvider(ABC, Generic[RequestT]): + """An image source.""" + + #: Short, stable provider name (also the :attr:`ImageAsset.source` value). + name: str + + @abstractmethod + async def fetch(self, request: RequestT) -> ImageAsset: + """Select an image for ``request`` and download it. + + Raises: + ProviderNotConfiguredError: The provider is not set up. + InvalidSelectionError: The request references unknown or ambiguous items. + NoCandidateError: Nothing eligible matched. + ProviderUnavailableError: The upstream service failed. + """ diff --git a/app/providers/immich/__init__.py b/app/providers/immich/__init__.py new file mode 100644 index 0000000..bf9b4d6 --- /dev/null +++ b/app/providers/immich/__init__.py @@ -0,0 +1,8 @@ +"""Immich image provider: multi-account client, people resolution and face-aware selection.""" + +from app.providers.immich.client import ImmichGateway +from app.providers.immich.models import ImmichDisplayRequest +from app.providers.immich.people import PeopleDirectory +from app.providers.immich.provider import ImmichProvider + +__all__ = ["ImmichDisplayRequest", "ImmichGateway", "ImmichProvider", "PeopleDirectory"] diff --git a/app/providers/immich/client.py b/app/providers/immich/client.py new file mode 100644 index 0000000..fea4ce9 --- /dev/null +++ b/app/providers/immich/client.py @@ -0,0 +1,318 @@ +"""Async Immich REST client and the gateway that opens clients for configured accounts. + +Only the endpoints the engine needs are implemented. Contracts were pinned against the +OpenAPI document of Immich 3.3.5 (``/api/spec.json``); every payload is parsed leniently +(unknown fields ignored) so minor server upgrades do not break the provider. + +Security: API keys travel in the ``x-api-key`` header only, redirects are never followed, +URLs go through the SSRF policy and error messages never include response bodies. +""" + +from __future__ import annotations + +import logging +import ssl +from collections.abc import AsyncIterator, Mapping, Sequence +from contextlib import asynccontextmanager +from functools import lru_cache +from types import TracebackType +from typing import Any, Final, Self, TypeVar + +import httpx +from pydantic import TypeAdapter, ValidationError + +from app.core.config_models import ImmichAccountConfig +from app.core.config_store import ConfigStore +from app.core.security import ( + PayloadTooLargeError, + UnsafeURLError, + URLPolicy, + read_limited, + validate_external_url, +) +from app.providers.base import ( + InvalidSelectionError, + ProviderNotConfiguredError, + ProviderUnavailableError, +) +from app.providers.immich.models import ( + AlbumDto, + AssetDto, + FaceDto, + PersonDto, + SearchFilters, +) + +logger = logging.getLogger(__name__) + +T = TypeVar("T") + +CONNECT_TIMEOUT_S: Final = 10.0 +READ_TIMEOUT_S: Final = 30.0 +PEOPLE_PAGE_SIZE: Final = 500 +MAX_PEOPLE_PAGES: Final = 50 + +_ASSETS: Final = TypeAdapter(list[AssetDto]) +_ALBUMS: Final = TypeAdapter(list[AlbumDto]) +_FACES: Final = TypeAdapter(list[FaceDto]) +_PEOPLE: Final = TypeAdapter(list[PersonDto]) + + +@lru_cache(maxsize=1) +def _ssl_context() -> ssl.SSLContext: + """One TLS context for every short-lived client (building it is the slowest part).""" + return httpx.create_ssl_context() + + +class ImmichError(ProviderUnavailableError): + """Base class of Immich communication failures (messages never contain secrets).""" + + +class ImmichUnreachableError(ImmichError): + """The server did not answer (DNS, connection refused, timeout...).""" + + +class ImmichAuthError(ImmichError): + """The server rejected the API key.""" + + +class ImmichResponseError(ImmichError): + """The server answered with an error status or an unexpected payload.""" + + def __init__(self, message: str, status_code: int | None = None) -> None: + super().__init__(message) + self.status_code = status_code + + +class ImmichClient: + """One Immich account. Use as ``async with`` (closes the HTTP connection pool).""" + + def __init__( + self, + name: str, + account: ImmichAccountConfig, + *, + transport: httpx.AsyncBaseTransport | None = None, + ) -> None: + self.name = name + self._http = httpx.AsyncClient( + base_url=account.url, + headers={"x-api-key": account.api_key.get_secret_value(), "Accept": "application/json"}, + timeout=httpx.Timeout(READ_TIMEOUT_S, connect=CONNECT_TIMEOUT_S), + follow_redirects=False, + verify=_ssl_context(), + transport=transport, + ) + + async def __aenter__(self) -> Self: + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: + await self._http.aclose() + + # --- plumbing ----------------------------------------------------------------------- + def _fail(self, exc: Exception) -> ImmichError: + if isinstance(exc, httpx.TimeoutException): + return ImmichUnreachableError( + f"Immich account {self.name!r} did not respond in time", timeout=True + ) + return ImmichUnreachableError( + f"Cannot connect to Immich account {self.name!r} ({type(exc).__name__})" + ) + + def _check(self, response: httpx.Response) -> None: + status = response.status_code + if status in {401, 403}: + raise ImmichAuthError(f"Immich account {self.name!r} rejected the API key") + if status >= 400 or 300 <= status < 400: + raise ImmichResponseError( + f"Immich account {self.name!r} answered HTTP {status}", status + ) + + async def _json( + self, + method: str, + path: str, + *, + json: Mapping[str, object] | None = None, + params: Mapping[str, str | int | bool] | None = None, + ) -> Any: + try: + response = await self._http.request(method, path, json=json, params=params) + except httpx.HTTPError as exc: + raise self._fail(exc) from None + self._check(response) + try: + return response.json() + except ValueError: + raise ImmichResponseError( + f"Immich account {self.name!r} returned invalid JSON", response.status_code + ) from None + + def _parse(self, adapter: TypeAdapter[T], payload: Any) -> T: + try: + return adapter.validate_python(payload) + except ValidationError: + raise ImmichResponseError( + f"Immich account {self.name!r} returned an unexpected payload" + ) from None + + # --- endpoints ---------------------------------------------------------------------- + async def version(self) -> str: + """``GET /api/server/version`` (no authentication needed) as ``major.minor.patch``.""" + data = await self._json("GET", "/api/server/version") + try: + return f"{data['major']}.{data['minor']}.{data['patch']}" + except (KeyError, TypeError): + raise ImmichResponseError( + f"Immich account {self.name!r} returned an unexpected version payload" + ) from None + + async def people(self) -> list[PersonDto]: + """Every visible person (``GET /api/people``, all pages).""" + people: list[PersonDto] = [] + for page in range(1, MAX_PEOPLE_PAGES + 1): + data = await self._json( + "GET", + "/api/people", + params={"withHidden": False, "page": page, "size": PEOPLE_PAGE_SIZE}, + ) + if not isinstance(data, dict): + raise ImmichResponseError( + f"Immich account {self.name!r} returned a bad people list" + ) + page_people: list[PersonDto] = self._parse(_PEOPLE, data.get("people", [])) + people.extend(page_people) + if not data.get("hasNextPage"): + break + return people + + async def albums(self) -> list[AlbumDto]: + """Albums the key can see (owned and shared).""" + return self._parse(_ALBUMS, await self._json("GET", "/api/albums")) + + async def search_random(self, filters: SearchFilters, size: int) -> list[AssetDto]: + """``POST /api/search/random``.""" + data = await self._json("POST", "/api/search/random", json=filters.body(size)) + return self._parse(_ASSETS, data) + + async def search_smart(self, query: str, filters: SearchFilters, size: int) -> list[AssetDto]: + """``POST /api/search/smart`` (CLIP): the top ``size`` matches of ``query``.""" + body = {**filters.body(size), "query": query} + data = await self._json("POST", "/api/search/smart", json=body) + items = data.get("assets", {}).get("items", []) if isinstance(data, dict) else None + if items is None: + raise ImmichResponseError(f"Immich account {self.name!r} returned a bad search result") + return self._parse(_ASSETS, items) + + async def asset(self, asset_id: str) -> AssetDto: + """Full metadata of one asset.""" + data = await self._json("GET", f"/api/assets/{asset_id}") + return self._parse(TypeAdapter(AssetDto), data) + + async def faces(self, asset_id: str) -> list[FaceDto]: + """Detected faces of an asset (``GET /api/faces?id=``), with their person.""" + return self._parse(_FACES, await self._json("GET", "/api/faces", params={"id": asset_id})) + + async def download( + self, + asset_id: str, + *, + variant: str, + max_bytes: int, + edited: bool = False, + ) -> bytes: + """Download an asset image. + + Args: + asset_id: Immich asset ID. + variant: ``original`` (the file as uploaded) or a thumbnail size + (``fullsize`` or ``preview``). + max_bytes: Abort once the body exceeds this size. + edited: Ask for the edited version of an edited asset. + + Raises: + ImmichResponseError: Error status (``status_code`` set) or oversized body. + """ + params: dict[str, str | bool] = {} + if edited: + params["edited"] = True + if variant == "original": + path = f"/api/assets/{asset_id}/original" + else: + path = f"/api/assets/{asset_id}/thumbnail" + params["size"] = variant + try: + async with self._http.stream( + "GET", path, params=params, headers={"Accept": "*/*"} + ) as response: + self._check(response) + declared = response.headers.get("content-length") + return await read_limited( + response.aiter_bytes(), + max_bytes, + declared_length=int(declared) if declared and declared.isdigit() else None, + ) + except PayloadTooLargeError: + raise ImmichResponseError( + f"Immich asset exceeds the {max_bytes // (1024 * 1024)} MB limit", 413 + ) from None + except httpx.HTTPError as exc: + raise self._fail(exc) from None + + +class ImmichGateway: + """Resolves configured accounts and opens validated clients for them.""" + + def __init__( + self, + config_store: ConfigStore, + url_policy: URLPolicy, + *, + transport: httpx.AsyncBaseTransport | None = None, + ) -> None: + self._config_store = config_store + self._url_policy = url_policy + self._transport = transport + + def accounts(self, names: Sequence[str] | None = None) -> dict[str, ImmichAccountConfig]: + """Configured accounts (optionally only ``names``), in configuration order. + + Raises: + ProviderNotConfiguredError: No account is configured. + InvalidSelectionError: ``names`` references an unknown account. + """ + configured = self._config_store.config.immich.accounts + if not configured: + raise ProviderNotConfiguredError( + "No Immich account is configured (set IMMICH_URL and IMMICH_API_KEY, " + "or add immich.accounts in the settings)" + ) + if names is None: + return dict(configured) + unknown = [name for name in names if name not in configured] + if unknown: + raise InvalidSelectionError( + f"Unknown Immich account(s): {', '.join(sorted(set(unknown)))}. " + f"Configured: {', '.join(configured)}" + ) + return {name: configured[name] for name in configured if name in names} + + @asynccontextmanager + async def client(self, name: str) -> AsyncIterator[ImmichClient]: + """Open a client for account ``name`` after checking its URL against the SSRF policy.""" + account = self.accounts([name])[name] + try: + await validate_external_url(account.url, self._url_policy) + except UnsafeURLError as exc: + raise ImmichResponseError( + f"Immich account {name!r} URL is blocked by the URL policy: {exc} " + "(add its host to URL_ALLOWLIST)" + ) from None + async with ImmichClient(name, account, transport=self._transport) as client: + yield client diff --git a/app/providers/immich/faces.py b/app/providers/immich/faces.py new file mode 100644 index 0000000..ecac92a --- /dev/null +++ b/app/providers/immich/faces.py @@ -0,0 +1,98 @@ +"""Turn Immich face boxes into :class:`~app.processor.fit.FocusRegion` objects. + +Verified against Immich 3.3.5: ``GET /api/faces?id=`` boxes are pixels of the +face's own ``imageWidth`` x ``imageHeight`` frame, which is the EXIF-*corrected* +orientation (same as the asset ``width``/``height``) - exactly the frame our decoder +produces after ``exif_transpose``. An orientation guard still covers servers that report +boxes in raw sensor space: for EXIF orientations 5-8 the frame's portrait/landscape +shape then disagrees with the corrected image and the boxes are rotated into place. +""" + +from __future__ import annotations + +from collections.abc import Collection, Sequence +from typing import Final + +from app.processor.fit import FocusRegion +from app.providers.immich.models import FaceDto + +#: Room added on every side of a face so hair, chin and shoulders survive the crop. +FACE_PADDING: Final = 0.25 + +Box = tuple[float, float, float, float] + + +def _orient(box: Box, orientation: int) -> Box: + """Map a normalized raw-sensor box into the displayed frame (EXIF orientation 5-8).""" + x1, y1, x2, y2 = box + corners = [(x1, y1), (x2, y1), (x1, y2), (x2, y2)] + if orientation == 6: # rotate 90 clockwise to display + mapped = [(1 - v, u) for u, v in corners] + elif orientation == 8: # rotate 90 counter-clockwise + mapped = [(v, 1 - u) for u, v in corners] + elif orientation == 5: # transpose + mapped = [(v, u) for u, v in corners] + else: # 7: transverse + mapped = [(1 - v, 1 - u) for u, v in corners] + xs, ys = [p[0] for p in mapped], [p[1] for p in mapped] + return min(xs), min(ys), max(xs), max(ys) + + +def _parse_orientation(value: str | int | None) -> int | None: + try: + number = int(value) if value is not None else None + except ValueError: + return None + return number if number in range(1, 9) else None + + +def face_regions( + faces: Sequence[FaceDto], + *, + image_size: tuple[int, int], + target_person_ids: Collection[str] = (), + exif_orientation: str | int | None = None, + padding: float = FACE_PADDING, +) -> list[FocusRegion]: + """Focus regions for smart cropping, most relevant first. + + Args: + faces: Detected faces of the asset. + image_size: ``(width, height)`` of the EXIF-corrected image. + target_person_ids: People the user asked for. Their faces are used exclusively + (strangers and unassigned faces are ignored); all faces are the fallback when + none of them was detected. + exif_orientation: EXIF orientation of the original (used by the orientation guard). + padding: Fraction of each box added on every side. + """ + targets = set(target_person_ids) + chosen = [face for face in faces if face.person is not None and face.person.id in targets] + pool = chosen or list(faces) + orientation = _parse_orientation(exif_orientation) + image_is_landscape = image_size[0] > image_size[1] + + regions: list[FocusRegion] = [] + for face in pool: + if face.imageWidth <= 0 or face.imageHeight <= 0: + continue + box: Box = ( + min(face.boundingBoxX1, face.boundingBoxX2) / face.imageWidth, + min(face.boundingBoxY1, face.boundingBoxY2) / face.imageHeight, + max(face.boundingBoxX1, face.boundingBoxX2) / face.imageWidth, + max(face.boundingBoxY1, face.boundingBoxY2) / face.imageHeight, + ) + box_frame_is_landscape = face.imageWidth > face.imageHeight + non_square = image_size[0] != image_size[1] and face.imageWidth != face.imageHeight + if ( + orientation in {5, 6, 7, 8} + and non_square + and box_frame_is_landscape != image_is_landscape + ): + box = _orient(box, orientation or 0) + left, top = min(max(box[0], 0.0), 1.0), min(max(box[1], 0.0), 1.0) + right, bottom = min(max(box[2], 0.0), 1.0), min(max(box[3], 0.0), 1.0) + if right - left <= 0 or bottom - top <= 0: + continue + regions.append(FocusRegion(left, top, right - left, bottom - top).padded(padding)) + regions.sort(key=lambda region: region.area, reverse=True) + return regions diff --git a/app/providers/immich/models.py b/app/providers/immich/models.py new file mode 100644 index 0000000..ffe4ffe --- /dev/null +++ b/app/providers/immich/models.py @@ -0,0 +1,153 @@ +"""Immich API data (lenient DTOs) and the request model of ``POST /api/display/immich``.""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Literal + +from pydantic import BaseModel, ConfigDict, Field, model_validator + +from app.core.config_models import FitMode + +ImmichMode = Literal["random", "album", "favorites", "search"] +MatchMode = Literal["any", "all"] + + +class _Dto(BaseModel): + """Immich payloads change between versions: ignore unknown fields, default the rest.""" + + model_config = ConfigDict(extra="ignore") + + +class PersonDto(_Dto): + id: str + name: str = "" + isHidden: bool = False + + +class AlbumDto(_Dto): + id: str + albumName: str = "" + assetCount: int = 0 + shared: bool = False + + +class ExifDto(_Dto): + city: str | None = None + state: str | None = None + country: str | None = None + orientation: str | None = None + dateTimeOriginal: str | None = None + fileSizeInByte: int | None = None + + +class AssetDto(_Dto): + id: str + type: str = "IMAGE" + originalFileName: str = "" + originalMimeType: str = "" + checksum: str | None = None + isFavorite: bool = False + isArchived: bool = False + isTrashed: bool = False + isEdited: bool = False + localDateTime: str | None = None + fileCreatedAt: str | None = None + width: int | None = None + height: int | None = None + exifInfo: ExifDto | None = None + people: list[PersonDto] = Field(default_factory=list) + + +class FaceDto(_Dto): + """A detected face; the box is in pixels of an ``imageWidth`` x ``imageHeight`` frame.""" + + imageWidth: int + imageHeight: int + boundingBoxX1: float + boundingBoxY1: float + boundingBoxX2: float + boundingBoxY2: float + person: PersonDto | None = None + + +@dataclass(frozen=True, slots=True) +class SearchFilters: + """Filters shared by the random and smart search endpoints.""" + + person_ids: tuple[str, ...] = () + album_ids: tuple[str, ...] = () + favorites_only: bool = False + exclude_archived: bool = True + + def body(self, size: int) -> dict[str, object]: + """JSON body for ``/search/random`` and ``/search/smart``.""" + body: dict[str, object] = {"type": "IMAGE", "size": size, "withExif": True} + if self.person_ids: + body["personIds"] = list(self.person_ids) + if self.album_ids: + body["albumIds"] = list(self.album_ids) + if self.favorites_only: + body["isFavorite"] = True + if self.exclude_archived: + body["visibility"] = "timeline" + return body + + +class AlbumInfo(BaseModel): + """An album of one account (``GET /api/immich/albums``).""" + + account: str + id: str + name: str + asset_count: int + shared: bool + + +class ImmichDisplayRequest(BaseModel): + """Which Immich photo to show (``POST /api/display/immich``). + + Every field except ``mode`` is optional: unset filters fall back to the ``immich`` + section of the runtime configuration. People are plain names; the provider resolves + them to Immich person IDs per account (see ``immich.person_aliases``). + """ + + model_config = ConfigDict(extra="forbid") + + mode: ImmichMode = Field( + default="random", + description="random = any matching photo; album = from an album; " + "favorites = favorites only; search = CLIP text search", + ) + persons: list[str] | None = Field( + default=None, description="Person names (default: immich.persons)" + ) + always_include: list[str] | None = Field( + default=None, + description="Names merged into persons (default: immich.always_include; [] disables)", + ) + match_mode: MatchMode | None = Field( + default=None, description="any or all of the persons (default: immich.match_mode)" + ) + album_name: str | None = Field(default=None, description="Album name (case-insensitive)") + album_id: str | None = Field(default=None, description="Album ID (alternative to the name)") + clip_queries: list[str] = Field( + default_factory=list, description="CLIP search phrases (mode=search)", max_length=10 + ) + accounts: list[str] | None = Field( + default=None, description="Limit the selection to these account names" + ) + fit: FitMode | None = Field(default=None, description="Override the default fit mode") + push_to_fraimic: bool = Field( + default=True, description="Send the result to the frame (or queue it in deepsleep mode)" + ) + ignore_history: bool = Field( + default=False, description="Allow photos that were shown within anti_repeat_days" + ) + + @model_validator(mode="after") + def _check_mode(self) -> ImmichDisplayRequest: + self.clip_queries = [query.strip() for query in self.clip_queries if query.strip()] + if self.mode == "search" and not self.clip_queries: + raise ValueError("mode 'search' needs at least one clip_queries entry") + return self diff --git a/app/providers/immich/people.py b/app/providers/immich/people.py new file mode 100644 index 0000000..ad6d01c --- /dev/null +++ b/app/providers/immich/people.py @@ -0,0 +1,176 @@ +"""People discovery and name resolution across Immich accounts. + +The engine only ever deals in plain person *names* (never Home Assistant entity IDs). +This module turns a name into the Immich person IDs of one account: + +1. ``immich.person_aliases`` wins: ``{"Marie": {"partner": ["Maman", ""]}}`` + maps the canonical name to IDs or names that only exist in that account. +2. Otherwise the name is looked up (case-insensitively) in the account's people list. + +Two people sharing a name in one account is an error unless an alias pins an ID. +""" + +from __future__ import annotations + +import difflib +import re +import time +from collections.abc import Callable, Iterable, Mapping +from dataclasses import dataclass, field +from datetime import UTC, datetime +from typing import Final + +from app.core.config_store import ConfigStore +from app.providers.base import InvalidSelectionError, ProviderError +from app.providers.immich.client import ImmichGateway +from app.providers.immich.models import PersonDto + +_UUID_RE: Final = re.compile( + r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", re.IGNORECASE +) + + +class AmbiguousPersonError(InvalidSelectionError): + """Several people of one account carry the requested name.""" + + +@dataclass(frozen=True, slots=True) +class AccountPeople: + """The named people of one account.""" + + by_id: dict[str, str] + by_name: dict[str, list[str]] + fetched_at: datetime + fingerprint: tuple[str, str] + + @classmethod + def build( + cls, people: Iterable[PersonDto], fingerprint: tuple[str, str], fetched_at: datetime + ) -> AccountPeople: + by_id: dict[str, str] = {} + by_name: dict[str, list[str]] = {} + for person in people: + name = person.name.strip() + if not name or person.isHidden: + continue + by_id[person.id] = name + by_name.setdefault(name.casefold(), []).append(person.id) + return cls(by_id, by_name, fetched_at, fingerprint) + + def names(self) -> list[str]: + """Distinct display names, sorted.""" + return sorted(set(self.by_id.values()), key=str.casefold) + + +@dataclass(slots=True) +class PeopleSnapshot: + """What ``GET /api/immich/people`` reports for one account.""" + + account: str + people: AccountPeople | None = None + error: str | None = None + ambiguous: list[str] = field(default_factory=list) + + +def resolve_person( + name: str, + account: str, + people: AccountPeople, + aliases: Mapping[str, Mapping[str, list[str]]], +) -> list[str]: + """Immich person IDs of ``name`` in ``account`` (empty when the account has no such person). + + Raises: + AmbiguousPersonError: Several people match and no alias pins one. + """ + folded = name.casefold() + alias_entries: list[str] = [] + for canonical, per_account in aliases.items(): + if canonical.casefold() == folded and account in per_account: + alias_entries = per_account[account] + candidates = alias_entries or [name] + + ids: list[str] = [] + for entry in candidates: + if entry in people.by_id or _UUID_RE.match(entry): + matched = [entry] + else: + matched = people.by_name.get(entry.casefold(), []) + if len(matched) > 1 and not alias_entries: + raise AmbiguousPersonError( + f"Several people are named {entry!r} in Immich account {account!r}; " + f"pin one ID in immich.person_aliases[{name!r}][{account!r}]" + ) + for person_id in matched: + if person_id not in ids: + ids.append(person_id) + return ids + + +def suggest_names(name: str, available: Iterable[str]) -> list[str]: + """Close matches of ``name`` among ``available`` person names (for error messages).""" + return difflib.get_close_matches(name, sorted(set(available)), n=3, cutoff=0.6) + + +class PeopleDirectory: + """Per-account cache of the people list with TTL and manual refresh.""" + + def __init__( + self, + config_store: ConfigStore, + gateway: ImmichGateway, + *, + clock: Callable[[], float] = time.monotonic, + now: Callable[[], datetime] = lambda: datetime.now(UTC), + ) -> None: + self._config_store = config_store + self._gateway = gateway + self._clock = clock + self._now = now + self._cache: dict[str, tuple[float, AccountPeople]] = {} + + def _fingerprint(self, account: str) -> tuple[str, str]: + config = self._gateway.accounts([account])[account] + return config.url, config.api_key.get_secret_value() + + async def get(self, account: str, *, refresh: bool = False) -> AccountPeople: + """The people of ``account``, from cache unless expired, changed or ``refresh``.""" + fingerprint = self._fingerprint(account) + ttl = self._config_store.config.immich.people_cache_ttl_s + cached = self._cache.get(account) + if ( + not refresh + and cached is not None + and cached[1].fingerprint == fingerprint + and self._clock() - cached[0] < ttl + ): + return cached[1] + async with self._gateway.client(account) as client: + people = AccountPeople.build(await client.people(), fingerprint, self._now()) + self._cache[account] = (self._clock(), people) + return people + + async def snapshot(self, accounts: Iterable[str], *, refresh: bool) -> list[PeopleSnapshot]: + """People of several accounts; a failing account is reported, not raised.""" + result: list[PeopleSnapshot] = [] + for account in accounts: + entry = PeopleSnapshot(account) + try: + entry.people = await self.get(account, refresh=refresh) + except ProviderError as exc: + entry.error = str(exc) + else: + entry.ambiguous = sorted( + { + entry.people.by_id[ids[0]] + for ids in entry.people.by_name.values() + if len(ids) > 1 + }, + key=str.casefold, + ) + result.append(entry) + return result + + def forget(self) -> None: + """Drop every cached list.""" + self._cache.clear() diff --git a/app/providers/immich/provider.py b/app/providers/immich/provider.py new file mode 100644 index 0000000..8dc7ddd --- /dev/null +++ b/app/providers/immich/provider.py @@ -0,0 +1,412 @@ +"""The Immich image provider: select a photo, fetch it with its face regions. + +One query path serves every mode. For each selected account the provider resolves the +requested people/album, runs random (``random``/``album``/``favorites``) or CLIP smart +(``search``) queries, merges the accounts, removes duplicates by content checksum and +photos still on the anti-repeat cooldown, then picks one at random. +""" + +from __future__ import annotations + +import itertools +import logging +import random +from collections.abc import Sequence +from dataclasses import dataclass, field +from datetime import datetime +from pathlib import PurePath +from typing import Final + +from pydantic import JsonValue + +from app.core.config_models import ImmichConfig +from app.core.config_store import ConfigStore +from app.core.history_store import HistoryStore +from app.core.security import InvalidImageError, verify_image_bytes +from app.processor.fit import FocusRegion +from app.providers.base import ( + BaseImageProvider, + ImageAsset, + InvalidSelectionError, + NoCandidateError, + ProviderUnavailableError, +) +from app.providers.immich.client import ImmichClient, ImmichGateway, ImmichResponseError +from app.providers.immich.faces import face_regions +from app.providers.immich.models import ( + AlbumInfo, + AssetDto, + ImmichDisplayRequest, + SearchFilters, +) +from app.providers.immich.people import PeopleDirectory, resolve_person, suggest_names + +logger = logging.getLogger(__name__) + +SOURCE: Final = "immich" +MAX_QUERIES_PER_ACCOUNT: Final = 10 +MAX_PERSON_COMBINATIONS: Final = 8 +MAX_TITLE_PEOPLE: Final = 4 + +RAW_EXTENSIONS: Final = frozenset( + { + ".dng", ".cr2", ".cr3", ".crw", ".nef", ".nrw", ".arw", ".srf", ".sr2", ".raf", ".orf", + ".rw2", ".pef", ".raw", ".3fr", ".erf", ".kdc", ".mrw", ".x3f", ".srw", ".rwl", ".iiq", + } +) # fmt: skip + + +@dataclass(frozen=True, slots=True) +class _Plan: + names: tuple[str, ...] + match_mode: str + album_name: str + album_id: str + favorites: bool + exclude_archived: bool + queries: tuple[str, ...] + size: int + + +@dataclass(slots=True) +class _AccountResult: + assets: list[AssetDto] = field(default_factory=list) + resolved: set[str] = field(default_factory=set) + known_names: list[str] = field(default_factory=list) + target_ids: set[str] = field(default_factory=set) + album_found: bool = False + + +@dataclass(frozen=True, slots=True) +class _Candidate: + account: str + asset: AssetDto + key: str + + +def history_key(account: str, asset: AssetDto) -> str: + """Content-based key (SHA-1 checksum) so one photo in two accounts is one photo.""" + return f"sha1:{asset.checksum}" if asset.checksum else f"{account}:{asset.id}" + + +def is_raw(asset: AssetDto) -> bool: + """RAW camera files cannot be decoded by Pillow; use Immich's converted JPEG instead.""" + suffix = PurePath(asset.originalFileName).suffix.lower() + mime = asset.originalMimeType.lower() + return suffix in RAW_EXTENSIONS or (mime.startswith("image/x-") and "bmp" not in mime) + + +def _merge_names(first: Sequence[str], second: Sequence[str]) -> tuple[str, ...]: + merged: dict[str, str] = {} + for name in (*first, *second): + stripped = name.strip() + if stripped: + merged.setdefault(stripped.casefold(), stripped) + return tuple(merged.values()) + + +def _parse_date(asset: AssetDto) -> datetime | None: + for raw in (asset.localDateTime, asset.exifInfo.dateTimeOriginal if asset.exifInfo else None): + if raw: + try: + return datetime.fromisoformat(raw) + except ValueError: + continue + return None + + +def build_title_and_details( + account: str, asset: AssetDto, quality: str, faces_used: int +) -> tuple[str, dict[str, JsonValue]]: + """Human-readable title (people - date - place) and metadata for the UI.""" + people = [person.name.strip() for person in asset.people if person.name.strip()] + taken = _parse_date(asset) + exif = asset.exifInfo + place = ", ".join(part for part in (exif.city, exif.country) if part) if exif else "" + parts = [ + ", ".join(people[:MAX_TITLE_PEOPLE]), + f"{taken.day} {taken:%b %Y}" if taken else "", + place, + ] + title = " · ".join(part for part in parts if part) or asset.originalFileName or "Immich photo" + details: dict[str, JsonValue] = { + "account": account, + "asset_id": asset.id, + "filename": asset.originalFileName or None, + "taken_at": taken.isoformat() if taken else None, + "location": place or None, + "people": list(people), + "quality": quality, + "faces_used": faces_used, + } + return title, details + + +class ImmichProvider(BaseImageProvider[ImmichDisplayRequest]): + """Selects and downloads photos from one or several Immich accounts.""" + + name = SOURCE + + def __init__( + self, + config_store: ConfigStore, + gateway: ImmichGateway, + people: PeopleDirectory, + history: HistoryStore, + *, + max_bytes: int, + rng: random.Random | None = None, + ) -> None: + self._config_store = config_store + self._gateway = gateway + self._people = people + self._history = history + self._max_bytes = max_bytes + self._rng = rng or random.Random() # noqa: S311 - not security relevant + + # --- public API ---------------------------------------------------------------------- + async def fetch(self, request: ImmichDisplayRequest) -> ImageAsset: + config = self._config_store.config.immich + accounts = list(self._gateway.accounts(request.accounts)) + plan = self._plan(request, config) + + results: dict[str, _AccountResult] = {} + errors: dict[str, ProviderUnavailableError] = {} + for account in accounts: + try: + results[account] = await self._gather(account, plan, config) + except ProviderUnavailableError as exc: + errors[account] = exc + if not results: + raise next(iter(errors.values())) + for account, failure in errors.items(): + logger.warning("Immich account %r skipped: %s", account, failure) + + self._check_resolution(plan, results) + candidates = self._merge(results) + chosen = self._choose(candidates, config, request.ignore_history) + + account_result = results[chosen.account] + async with self._gateway.client(chosen.account) as client: + asset = await client.asset(chosen.asset.id) + data, quality = await self._download(client, asset) + regions = await self._regions(client, asset, account_result.target_ids) + title, details = build_title_and_details(chosen.account, asset, quality, len(regions)) + return ImageAsset( + data=data, + source=SOURCE, + history_key=chosen.key, + title=title, + details=details, + regions=tuple(regions), + ) + + async def albums( + self, accounts: Sequence[str] | None = None + ) -> tuple[list[AlbumInfo], dict[str, str]]: + """Albums of the selected accounts plus per-account error messages.""" + found: list[AlbumInfo] = [] + errors: dict[str, str] = {} + for account in self._gateway.accounts(accounts): + try: + async with self._gateway.client(account) as client: + for album in await client.albums(): + found.append( + AlbumInfo( + account=account, + id=album.id, + name=album.albumName, + asset_count=album.assetCount, + shared=album.shared, + ) + ) + except ProviderUnavailableError as exc: + errors[account] = str(exc) + found.sort(key=lambda album: (album.name.casefold(), album.account)) + return found, errors + + # --- planning ------------------------------------------------------------------------ + @staticmethod + def _plan(request: ImmichDisplayRequest, config: ImmichConfig) -> _Plan: + persons = config.persons if request.persons is None else request.persons + always = config.always_include if request.always_include is None else request.always_include + album_id = (request.album_id or "").strip() + album_name = (request.album_name or "").strip() + if not album_id and not album_name: + album_name = config.album.strip() + if request.mode == "album" and not album_id and not album_name: + raise InvalidSelectionError("mode 'album' needs album_name or album_id") + return _Plan( + names=_merge_names(persons, always), + match_mode=request.match_mode or config.match_mode, + album_name=album_name, + album_id=album_id, + favorites=request.mode == "favorites" or config.favorites_only, + exclude_archived=config.exclude_archived, + queries=tuple(request.clip_queries) if request.mode == "search" else (), + size=config.search_candidates, + ) + + # --- candidate gathering --------------------------------------------------------------- + async def _gather(self, account: str, plan: _Plan, config: ImmichConfig) -> _AccountResult: + result = _AccountResult() + slots: list[list[str]] = [] + if plan.names: + people = await self._people.get(account) + result.known_names = people.names() + for name in plan.names: + ids = resolve_person(name, account, people, config.person_aliases) + if ids: + result.resolved.add(name.casefold()) + slots.append(ids) + result.target_ids = {person_id for ids in slots for person_id in ids} + + async with self._gateway.client(account) as client: + album_ids: tuple[str, ...] = () + if plan.album_id or plan.album_name: + album_ids = await self._album_ids(client, plan) + result.album_found = bool(album_ids) + if not album_ids: + return result + + combos = self._person_combinations(slots, plan.match_mode) + if combos is None: + return result + seen: set[str] = set() + queries = plan.queries or ("",) + for query, combo in itertools.product(queries, combos): + filters = SearchFilters(combo, album_ids, plan.favorites, plan.exclude_archived) + found = ( + await client.search_smart(query, filters, plan.size) + if query + else await client.search_random(filters, plan.size) + ) + for asset in found: + if asset.id not in seen: + seen.add(asset.id) + result.assets.append(asset) + return result + + @staticmethod + def _person_combinations( + slots: list[list[str]], match_mode: str + ) -> list[tuple[str, ...]] | None: + """Person-ID tuples to query, or ``None`` when this account cannot satisfy the request.""" + if not slots: + return [()] + if match_mode == "all": + if any(not ids for ids in slots): + return None + return list(itertools.islice(itertools.product(*slots), MAX_PERSON_COMBINATIONS)) + flat = [person_id for ids in slots for person_id in ids] + if not flat: + return None + singles: list[tuple[str, ...]] = [(person_id,) for person_id in dict.fromkeys(flat)] + return singles[:MAX_QUERIES_PER_ACCOUNT] + + @staticmethod + async def _album_ids(client: ImmichClient, plan: _Plan) -> tuple[str, ...]: + albums = await client.albums() + if plan.album_id: + return tuple(album.id for album in albums if album.id == plan.album_id) + wanted = plan.album_name.casefold() + return tuple(album.id for album in albums if album.albumName.casefold() == wanted) + + @staticmethod + def _check_resolution(plan: _Plan, results: dict[str, _AccountResult]) -> None: + known = [name for result in results.values() for name in result.known_names] + for name in plan.names: + if not any(name.casefold() in result.resolved for result in results.values()): + hint = suggest_names(name, known) + suffix = f" Did you mean: {', '.join(hint)}?" if hint else "" + raise InvalidSelectionError( + f"Unknown person {name!r} in the selected accounts.{suffix}" + ) + if (plan.album_id or plan.album_name) and not any(r.album_found for r in results.values()): + label = plan.album_name or plan.album_id + raise InvalidSelectionError(f"Album {label!r} was not found in the selected accounts") + + # --- selection --------------------------------------------------------------------------- + @staticmethod + def _merge(results: dict[str, _AccountResult]) -> list[_Candidate]: + merged: list[_Candidate] = [] + seen: set[str] = set() + for account, result in results.items(): + for asset in result.assets: + if asset.isTrashed or asset.type.upper() != "IMAGE": + continue + key = history_key(account, asset) + if key not in seen: + seen.add(key) + merged.append(_Candidate(account, asset, key)) + return merged + + def _choose( + self, candidates: list[_Candidate], config: ImmichConfig, ignore_history: bool + ) -> _Candidate: + if config.exclude_archived: + candidates = [c for c in candidates if not c.asset.isArchived] + if not candidates: + raise NoCandidateError("No photo matched the request") + recent = ( + set() if ignore_history else self._history.recent_ids(SOURCE, config.anti_repeat_days) + ) + eligible = [c for c in candidates if c.key not in recent] + if not eligible: + raise NoCandidateError( + f"All {len(candidates)} matching photo(s) were shown within the last " + f"{config.anti_repeat_days} day(s); retry with ignore_history or widen the filters" + ) + return self._rng.choice(eligible) + + # --- download -------------------------------------------------------------------------------- + async def _download(self, client: ImmichClient, asset: AssetDto) -> tuple[bytes, str]: + """Original at full resolution; Immich's converted JPEG for RAW, oversized or odd files.""" + size = asset.exifInfo.fileSizeInByte if asset.exifInfo else None + variants: list[str] = [] + if not is_raw(asset) and (size is None or size <= self._max_bytes): + variants.append("original") + variants += ["fullsize", "preview"] + last: Exception | None = None + for variant in variants: + try: + data = await client.download( + asset.id, + variant=variant, + max_bytes=self._max_bytes, + edited=asset.isEdited, + ) + verify_image_bytes(data) + except (ImmichResponseError, InvalidImageError) as exc: + logger.info("Immich %s download of an asset failed (%s); trying next", variant, exc) + last = exc + continue + return data, variant + raise ProviderUnavailableError( + f"Could not download a usable image from Immich account {client.name!r}" + ) from last + + async def _regions( + self, client: ImmichClient, asset: AssetDto, target_ids: set[str] + ) -> list[FocusRegion]: + """Face regions for smart cropping (none for edited assets: boxes refer to the original).""" + if asset.isEdited: + return [] + try: + faces = await client.faces(asset.id) + except ProviderUnavailableError as exc: + logger.warning("Could not load faces from Immich: %s", exc) + return [] + if not faces: + return [] + image_size = ( + (asset.width, asset.height) + if asset.width and asset.height + else (faces[0].imageWidth, faces[0].imageHeight) + ) + return face_regions( + faces, + image_size=image_size, + target_person_ids=target_ids, + exif_orientation=asset.exifInfo.orientation if asset.exifInfo else None, + ) diff --git a/tests/immich_fake.py b/tests/immich_fake.py new file mode 100644 index 0000000..fd1d093 --- /dev/null +++ b/tests/immich_fake.py @@ -0,0 +1,222 @@ +"""A small in-memory Immich server (respx) shaped like the 3.3.5 API the provider uses.""" + +from __future__ import annotations + +import io +import json +from collections.abc import Callable +from typing import Any + +import httpx +import respx +from PIL import Image + + +def jpeg(size: tuple[int, int] = (640, 480), color: tuple[int, int, int] = (90, 140, 200)) -> bytes: + buffer = io.BytesIO() + Image.new("RGB", size, color).save(buffer, format="JPEG") + return buffer.getvalue() + + +def heic(size: tuple[int, int] = (320, 240)) -> bytes: + buffer = io.BytesIO() + Image.new("RGB", size, (200, 60, 60)).save(buffer, format="HEIF", quality=85) + return buffer.getvalue() + + +def asset(asset_id: str, **overrides: Any) -> dict[str, Any]: + """An asset as returned by search and ``GET /assets/{id}``.""" + data: dict[str, Any] = { + "id": asset_id, + "type": "IMAGE", + "originalFileName": f"{asset_id}.jpg", + "originalMimeType": "image/jpeg", + "checksum": f"sum-{asset_id}", + "isFavorite": False, + "isArchived": False, + "isTrashed": False, + "isEdited": False, + "visibility": "timeline", + "localDateTime": "2024-07-14T10:22:11.000Z", + "width": 640, + "height": 480, + "exifInfo": { + "city": "Lyon", + "country": "France", + "orientation": "1", + "fileSizeInByte": 50_000, + }, + "people": [], + } + data.update(overrides) + return data + + +def face( + person_id: str | None, + box: tuple[int, int, int, int], + frame: tuple[int, int] = (640, 480), + name: str = "", +) -> dict[str, Any]: + return { + "id": f"face-{person_id}-{box[0]}", + "imageWidth": frame[0], + "imageHeight": frame[1], + "boundingBoxX1": box[0], + "boundingBoxY1": box[1], + "boundingBoxX2": box[2], + "boundingBoxY2": box[3], + "person": {"id": person_id, "name": name} if person_id else None, + } + + +class FakeImmich: + """State plus request handlers. ``calls`` records ``(method, path, query/body)``.""" + + def __init__(self, base: str = "http://immich.test", key: str = "good-key") -> None: + self.base = base + self.key = key + self.people: list[dict[str, Any]] = [] + self.albums: list[dict[str, Any]] = [] # each: {"id", "albumName", "assetIds": [...]} + self.assets: dict[str, dict[str, Any]] = {} + self.faces: dict[str, list[dict[str, Any]]] = {} + self.files: dict[tuple[str, str], bytes | int] = {} # (asset id, variant) -> body|status + self.smart_results: dict[str, list[str]] = {} + self.people_page_size = 500 + self.calls: list[tuple[str, str, Any]] = [] + self.search_error: int | None = None + self.faces_error: int | None = None + + # --- fixtures ---------------------------------------------------------------------- + def add_person(self, person_id: str, name: str, hidden: bool = False) -> None: + self.people.append({"id": person_id, "name": name, "isHidden": hidden}) + + def add_asset( + self, + asset_id: str, + *, + people: list[tuple[str, str]] = (), # type: ignore[assignment] + faces: list[dict[str, Any]] | None = None, + original: bytes | int | None = None, + **overrides: Any, + ) -> dict[str, Any]: + overrides.setdefault("people", [{"id": pid, "name": name} for pid, name in people]) + data = asset(asset_id, **overrides) + self.assets[asset_id] = data + self.faces[asset_id] = faces or [] + self.files[(asset_id, "original")] = jpeg() if original is None else original + self.files[(asset_id, "fullsize")] = jpeg((1440, 1080)) + self.files[(asset_id, "preview")] = jpeg((1440, 1080)) + return data + + def add_album(self, album_id: str, name: str, asset_ids: list[str]) -> None: + self.albums.append({"id": album_id, "albumName": name, "assetIds": asset_ids}) + + # --- request log helpers --------------------------------------------------------------- + def bodies(self, path: str) -> list[dict[str, Any]]: + return [body for _, p, body in self.calls if p == path] + + def downloads(self) -> list[tuple[str, dict[str, str]]]: + return [ + (p, q) + for m, p, q in self.calls + if m == "GET" and "/assets/" in p and (p.endswith(("/original", "/thumbnail"))) + ] + + # --- wiring ---------------------------------------------------------------------------------- + def mount(self, router: respx.MockRouter) -> None: + router.route(host=httpx.URL(self.base).host).mock(side_effect=self._handle) + + def _handle(self, request: httpx.Request) -> httpx.Response: + path = request.url.path + query = dict(request.url.params) + body = json.loads(request.content) if request.content else None + self.calls.append((request.method, path, body if body is not None else query)) + if path == "/api/server/version": + return httpx.Response(200, json={"major": 3, "minor": 3, "patch": 5}) + if request.headers.get("x-api-key") != self.key: + return httpx.Response(401, json={"message": "Invalid API key"}) + if path == "/api/people": + return self._people(query) + if path == "/api/albums": + return httpx.Response( + 200, + json=[ + { + "id": a["id"], + "albumName": a["albumName"], + "assetCount": len(a["assetIds"]), + "shared": False, + } + for a in self.albums + ], + ) + if path in {"/api/search/random", "/api/search/smart"}: + return self._search(path, body) + if path == "/api/faces": + if self.faces_error is not None: + return httpx.Response(self.faces_error) + return httpx.Response(200, json=self.faces.get(query["id"], [])) + if path.startswith("/api/assets/"): + return self._asset(path, query) + return httpx.Response(404) + + def _people(self, query: dict[str, str]) -> httpx.Response: + page = int(query.get("page", "1")) + size = self.people_page_size + chunk = self.people[(page - 1) * size : page * size] + return httpx.Response( + 200, + json={ + "people": chunk, + "hasNextPage": page * size < len(self.people), + "total": len(self.people), + "hidden": 0, + }, + ) + + def _matches(self, data: dict[str, Any], body: dict[str, Any]) -> bool: + if body.get("isFavorite") and not data["isFavorite"]: + return False + if body.get("visibility") == "timeline" and data["isArchived"]: + return False + person_ids = body.get("personIds") or [] + present = {p["id"] for p in data["people"]} + if person_ids and not set(person_ids) <= present: + return False + album_ids = body.get("albumIds") or [] + if album_ids: + members = {aid for a in self.albums if a["id"] in album_ids for aid in a["assetIds"]} + if data["id"] not in members: + return False + return not data["isTrashed"] + + def _search(self, path: str, body: dict[str, Any]) -> httpx.Response: + if self.search_error is not None: + return httpx.Response(self.search_error) + pool = [a for a in self.assets.values() if self._matches(a, body)] + if path == "/api/search/smart": + ranked = self.smart_results.get(body["query"]) + if ranked is not None: + pool = [self.assets[i] for i in ranked if i in {a["id"] for a in pool}] + items = pool[: body["size"]] + return httpx.Response( + 200, json={"albums": {}, "assets": {"items": items, "count": len(items)}} + ) + return httpx.Response(200, json=pool[: body["size"]]) + + def _asset(self, path: str, query: dict[str, str]) -> httpx.Response: + parts = path.split("/") # ['', 'api', 'assets', id, (original|thumbnail)?] + asset_id = parts[3] + if asset_id not in self.assets: + return httpx.Response(404) + if len(parts) == 4: + return httpx.Response(200, json=self.assets[asset_id]) + variant = "original" if parts[4] == "original" else query.get("size", "preview") + content = self.files.get((asset_id, variant), 404) + if isinstance(content, int): + return httpx.Response(content) + return httpx.Response(200, content=content, headers={"content-type": "image/jpeg"}) + + +Mounter = Callable[[FakeImmich], FakeImmich] diff --git a/tests/test_immich_client.py b/tests/test_immich_client.py new file mode 100644 index 0000000..65e195a --- /dev/null +++ b/tests/test_immich_client.py @@ -0,0 +1,198 @@ +from __future__ import annotations + +from collections.abc import Iterator +from contextlib import contextmanager +from pathlib import Path + +import httpx +import pytest +import respx + +from app.core.config_models import ImmichAccountConfig +from app.core.config_store import ConfigStore +from app.core.security import URLPolicy +from app.providers.base import InvalidSelectionError, ProviderNotConfiguredError +from app.providers.immich.client import ( + ImmichAuthError, + ImmichClient, + ImmichGateway, + ImmichResponseError, + ImmichUnreachableError, +) +from app.providers.immich.models import SearchFilters +from tests.immich_fake import FakeImmich, jpeg + + +@contextmanager +def mocked(*fakes: FakeImmich) -> Iterator[respx.MockRouter]: + with respx.mock(assert_all_called=False) as router: + for fake in fakes: + fake.mount(router) + yield router + + +def account(fake: FakeImmich, key: str | None = None) -> ImmichAccountConfig: + return ImmichAccountConfig.model_validate({"url": fake.base, "api_key": key or fake.key}) + + +def make_gateway(tmp_path: Path, fakes: dict[str, FakeImmich], **policy: object) -> ImmichGateway: + accounts = {n: {"url": f.base, "api_key": f.key} for n, f in fakes.items()} + store = ConfigStore(tmp_path / "config.json", {"immich": {"accounts": accounts}}) + return ImmichGateway(store, URLPolicy(**policy)) # type: ignore[arg-type] + + +async def test_requests_send_the_api_key_header_only_and_parse_payloads() -> None: + fake = FakeImmich() + fake.add_person("p1", "Alice") + fake.add_asset("a1", people=[("p1", "Alice")]) + fake.add_album("al1", "Family", ["a1"]) + with mocked(fake) as router: + async with ImmichClient("home", account(fake)) as client: + assert await client.version() == "3.3.5" + assert [p.name for p in await client.people()] == ["Alice"] + assert [a.albumName for a in await client.albums()] == ["Family"] + assets = await client.search_random(SearchFilters(), 5) + assert [a.id for a in assets] == ["a1"] and assets[0].people[0].name == "Alice" + assert (await client.asset("a1")).exifInfo is not None + sent = [c.request for c in router.calls if c.request.url.path != "/api/server/version"] + assert sent and all(r.headers["x-api-key"] == "good-key" for r in sent) + assert all("good-key" not in str(r.url) for r in sent) + + +async def test_people_are_paged() -> None: + fake = FakeImmich() + fake.people_page_size = 2 + for index in range(5): + fake.add_person(f"p{index}", f"Person {index}") + with mocked(fake): + async with ImmichClient("home", account(fake)) as client: + assert len(await client.people()) == 5 + assert [q["page"] for _, p, q in fake.calls if p == "/api/people"] == ["1", "2", "3"] + + +async def test_search_bodies_carry_the_filters() -> None: + fake = FakeImmich() + fake.add_asset("a1") + filters = SearchFilters(("p1", "p2"), ("al1",), favorites_only=True, exclude_archived=True) + with mocked(fake): + async with ImmichClient("home", account(fake)) as client: + await client.search_random(filters, 7) + await client.search_smart("beach", filters, 7) + random_body, smart_body = ( + fake.bodies("/api/search/random")[0], + fake.bodies("/api/search/smart")[0], + ) + assert random_body == { + "type": "IMAGE", + "size": 7, + "withExif": True, + "personIds": ["p1", "p2"], + "albumIds": ["al1"], + "isFavorite": True, + "visibility": "timeline", + } + assert smart_body == {**random_body, "query": "beach"} + assert "visibility" not in SearchFilters(exclude_archived=False).body(1) + + +async def test_error_statuses_map_to_typed_errors() -> None: + fake = FakeImmich() + with mocked(fake): + async with ImmichClient("home", account(fake, key="wrong")) as client: + with pytest.raises(ImmichAuthError, match="rejected the API key"): + await client.albums() + fake.search_error = 500 + async with ImmichClient("home", account(fake)) as client: + with pytest.raises(ImmichResponseError) as info: + await client.search_random(SearchFilters(), 5) + assert info.value.status_code == 500 + with pytest.raises(ImmichResponseError) as missing: + await client.asset("nope") + assert missing.value.status_code == 404 + + +async def test_unreachable_and_timeout_errors_do_not_leak_urls_or_keys() -> None: + fake = FakeImmich() + with mocked(fake) as router: + route = router.route(host="immich.test") + route.mock(side_effect=httpx.ConnectError("boom good-key http://immich.test")) + async with ImmichClient("home", account(fake)) as client: + with pytest.raises(ImmichUnreachableError) as info: + await client.albums() + assert not info.value.timeout + assert "good-key" not in str(info.value) and "immich.test" not in str(info.value) + + route.mock(side_effect=httpx.ReadTimeout("slow")) + async with ImmichClient("home", account(fake)) as client: + with pytest.raises(ImmichUnreachableError) as slow: + await client.albums() + assert slow.value.timeout + + +async def test_redirects_are_never_followed() -> None: + fake = FakeImmich() + with mocked(fake) as router: + router.route(host="immich.test").respond(302, headers={"location": "http://evil.test/"}) + async with ImmichClient("home", account(fake)) as client: + with pytest.raises(ImmichResponseError) as info: + await client.albums() + assert info.value.status_code == 302 + + +async def test_download_variants_params_and_size_limit() -> None: + fake = FakeImmich() + fake.add_asset("a1", original=jpeg((200, 100))) + fake.add_asset("big", original=b"x" * 5000) + with mocked(fake): + async with ImmichClient("home", account(fake)) as client: + assert len(await client.download("a1", variant="original", max_bytes=10**6)) > 100 + await client.download("a1", variant="preview", max_bytes=10**6) + await client.download("a1", variant="original", max_bytes=10**6, edited=True) + with pytest.raises(ImmichResponseError) as info: + await client.download("big", variant="original", max_bytes=1000) + assert info.value.status_code == 413 + downloads = fake.downloads() + assert downloads[0] == ("/api/assets/a1/original", {}) + assert downloads[1] == ("/api/assets/a1/thumbnail", {"size": "preview"}) + assert downloads[2] == ("/api/assets/a1/original", {"edited": "true"}) + + +async def test_faces_endpoint_is_parsed() -> None: + from tests.immich_fake import face + + fake = FakeImmich() + fake.add_asset( + "a1", faces=[face("p1", (10, 20, 110, 140), name="Alice"), face(None, (1, 2, 3, 4))] + ) + with mocked(fake): + async with ImmichClient("home", account(fake)) as client: + faces = await client.faces("a1") + assert faces[0].person is not None and faces[0].person.id == "p1" + assert faces[1].person is None and faces[0].boundingBoxX2 == 110 + + +# --- gateway --------------------------------------------------------------------------------- +async def test_gateway_account_selection_errors(tmp_path: Path) -> None: + fake = FakeImmich() + gateway = make_gateway(tmp_path, {"home": fake}) + assert list(gateway.accounts()) == ["home"] + with pytest.raises(InvalidSelectionError, match="Unknown Immich account"): + gateway.accounts(["nope"]) + empty = ImmichGateway(ConfigStore(tmp_path / "other.json", {}), URLPolicy()) + with pytest.raises(ProviderNotConfiguredError): + empty.accounts() + + +async def test_gateway_blocks_private_urls_when_policy_says_so(tmp_path: Path) -> None: + fake = FakeImmich(base="http://192.168.1.50:2283") + gateway = make_gateway(tmp_path, {"home": fake}, block_private=True) + with pytest.raises(ImmichResponseError, match="URL_ALLOWLIST"): + async with gateway.client("home"): + pass + + allowed = make_gateway( + tmp_path, {"home": fake}, block_private=True, hostnames=frozenset({"192.168.1.50"}) + ) + with mocked(fake): + async with allowed.client("home") as client: + assert await client.version() == "3.3.5" diff --git a/tests/test_immich_faces.py b/tests/test_immich_faces.py new file mode 100644 index 0000000..5e0f67c --- /dev/null +++ b/tests/test_immich_faces.py @@ -0,0 +1,125 @@ +from __future__ import annotations + +import pytest + +from app.processor.fit import FocusRegion +from app.providers.immich.faces import FACE_PADDING, face_regions +from app.providers.immich.models import FaceDto, PersonDto + + +def face( + person: str | None, + box: tuple[float, float, float, float], + frame: tuple[int, int] = (1000, 500), +) -> FaceDto: + return FaceDto( + imageWidth=frame[0], + imageHeight=frame[1], + boundingBoxX1=box[0], + boundingBoxY1=box[1], + boundingBoxX2=box[2], + boundingBoxY2=box[3], + person=PersonDto(id=person) if person else None, + ) + + +def test_boxes_are_normalized_by_their_own_frame_and_padded() -> None: + [region] = face_regions([face("a", (400, 100, 600, 300))], image_size=(1000, 500), padding=0.0) + assert (region.x, region.y, region.width, region.height) == pytest.approx((0.4, 0.2, 0.2, 0.4)) + + [padded] = face_regions([face("a", (400, 100, 600, 300))], image_size=(1000, 500)) + assert padded.width == pytest.approx(0.2 * (1 + 2 * FACE_PADDING)) + assert padded.height == pytest.approx(0.4 * (1 + 2 * FACE_PADDING)) + + +def test_box_frame_may_differ_from_the_image_size() -> None: + # Immich scales boxes to a ~1440px preview frame; the original has other pixels. + [region] = face_regions( + [face("a", (720, 480, 1080, 960), frame=(1440, 1920))], + image_size=(3024, 4032), + padding=0.0, + ) + assert (region.x, region.y) == pytest.approx((0.5, 0.25)) + assert (region.width, region.height) == pytest.approx((0.25, 0.25)) + + +def test_target_people_win_and_strangers_are_ignored() -> None: + faces = [ + face("stranger", (0, 0, 300, 300)), # biggest face, but not requested + face("alice", (500, 100, 600, 200)), + face(None, (700, 100, 800, 200)), + ] + regions = face_regions(faces, image_size=(1000, 500), target_person_ids={"alice"}, padding=0) + assert len(regions) == 1 and regions[0].x == pytest.approx(0.5) + + +def test_all_faces_are_the_fallback_when_no_target_matches_and_sorted_by_size() -> None: + faces = [ + face("a", (0, 0, 50, 50)), + face(None, (200, 0, 400, 200)), + face("b", (600, 0, 650, 50)), + ] + regions = face_regions(faces, image_size=(1000, 500), target_person_ids={"zzz"}, padding=0) + areas = [r.area for r in regions] + assert areas == sorted(areas, reverse=True) and len(regions) == 3 + assert face_regions(faces, image_size=(1000, 500), padding=0)[0].x == pytest.approx(0.2) + + +def test_degenerate_and_out_of_range_boxes() -> None: + faces = [ + face("a", (10, 10, 10, 50)), # zero width + FaceDto( # unusable frame + imageWidth=0, + imageHeight=0, + boundingBoxX1=0, + boundingBoxY1=0, + boundingBoxX2=1, + boundingBoxY2=1, + ), + face("b", (-50, -50, 100, 100)), # sticks out of the frame: clamped + face("c", (300, 300, 100, 100)), # reversed corners + ] + regions = face_regions(faces, image_size=(1000, 500), padding=0) + assert len(regions) == 2 + assert all(isinstance(r, FocusRegion) for r in regions) + assert min(r.x for r in regions) == 0.0 + + +@pytest.mark.parametrize( + ("orientation", "expected"), + [ + # Raw sensor frame 4000x3000 (landscape), displayed 3000x4000 (portrait). The raw box + # x 3000-3400, y 600-1000 is u 0.75-0.85, v 0.2-0.333 in normalized coordinates. + ("6", (1 - 1 / 3, 0.75, 1 / 3 - 0.2, 0.1)), # (u, v) -> (1 - v, u): clockwise + ("8", (0.2, 0.15, 1 / 3 - 0.2, 0.1)), # (u, v) -> (v, 1 - u): counter-clockwise + ], +) +def test_orientation_guard_rotates_raw_space_boxes( + orientation: str, expected: tuple[float, float, float, float] +) -> None: + raw = face("a", (3000, 600, 3400, 1000), frame=(4000, 3000)) + [region] = face_regions([raw], image_size=(3000, 4000), exif_orientation=orientation, padding=0) + assert (region.x, region.y, region.width, region.height) == pytest.approx(expected, abs=1e-6) + + +def test_orientation_guard_stays_off_for_already_corrected_boxes() -> None: + # Verified live (Immich 3.3.5): orientation 6 asset, boxes already in the portrait frame. + box = face("a", (731, 460, 853, 596), frame=(1440, 1920)) + plain = face_regions([box], image_size=(3024, 4032), exif_orientation=None, padding=0) + guarded = face_regions([box], image_size=(3024, 4032), exif_orientation="6", padding=0) + assert plain == guarded + # Orientations 1-4 never change dimensions, so the guard cannot (and does not) act. + for orientation in ("1", "3", "0", "bogus", None, 9): + assert ( + face_regions([box], image_size=(3024, 4032), exif_orientation=orientation, padding=0) + == plain + ) + + +def test_orientation_five_and_seven_transform_corners_exactly() -> None: + raw = face("a", (0, 0, 1000, 500), frame=(4000, 3000)) # top-left quarter-ish box + five = face_regions([raw], image_size=(3000, 4000), exif_orientation=5, padding=0)[0] + seven = face_regions([raw], image_size=(3000, 4000), exif_orientation="7", padding=0)[0] + assert (five.x, five.y) == pytest.approx((0.0, 0.0)) + assert (five.width, five.height) == pytest.approx((500 / 3000, 1000 / 4000)) + assert (seven.x + seven.width, seven.y + seven.height) == pytest.approx((1.0, 1.0)) diff --git a/tests/test_immich_people.py b/tests/test_immich_people.py new file mode 100644 index 0000000..442e363 --- /dev/null +++ b/tests/test_immich_people.py @@ -0,0 +1,171 @@ +from __future__ import annotations + +from datetime import UTC, datetime +from pathlib import Path + +import pytest + +from app.core.config_store import ConfigStore +from app.core.security import URLPolicy +from app.providers.immich.client import ImmichGateway +from app.providers.immich.models import PersonDto +from app.providers.immich.people import ( + AccountPeople, + AmbiguousPersonError, + PeopleDirectory, + resolve_person, + suggest_names, +) +from tests.immich_fake import FakeImmich +from tests.test_immich_client import mocked + +NOW = datetime(2026, 1, 1, tzinfo=UTC) +UUID_A = "11111111-2222-3333-4444-555555555555" + + +def build(*people: tuple[str, str]) -> AccountPeople: + dtos = [PersonDto(id=pid, name=name) for pid, name in people] + return AccountPeople.build(dtos, ("http://x", "k"), NOW) + + +def test_names_are_case_insensitive_and_hidden_or_unnamed_are_skipped() -> None: + people = AccountPeople.build( + [ + PersonDto(id="1", name="Alice"), + PersonDto(id="2", name=""), + PersonDto(id="3", name="Hidden", isHidden=True), + ], + ("u", "k"), + NOW, + ) + assert resolve_person(" alice".strip(), "home", people, {}) == ["1"] + assert resolve_person("ALICE", "home", people, {}) == ["1"] + assert resolve_person("Hidden", "home", people, {}) == [] + assert people.names() == ["Alice"] + + +def test_unknown_name_resolves_to_nothing_for_this_account() -> None: + assert resolve_person("Zed", "home", build(("1", "Alice")), {}) == [] + + +def test_duplicate_names_are_ambiguous_until_an_alias_pins_an_id() -> None: + people = build(("1", "Marie"), ("2", "Marie"), ("3", "Bob")) + with pytest.raises(AmbiguousPersonError, match="person_aliases"): + resolve_person("Marie", "home", people, {}) + assert resolve_person("Marie", "home", people, {"Marie": {"home": ["2"]}}) == ["2"] + # An alias is per account: another account without one is still ambiguous. + with pytest.raises(AmbiguousPersonError): + resolve_person("Marie", "home", people, {"Marie": {"partner": ["2"]}}) + + +def test_aliases_map_a_canonical_name_to_ids_or_other_names_per_account() -> None: + partner = build(("p1", "Maman"), ("p2", "Maman Sylvie")) + aliases = {"Marie": {"partner": ["Maman", UUID_A]}} + assert resolve_person("marie", "partner", partner, aliases) == ["p1", UUID_A] + # Without an alias entry for the account, the canonical name is looked up directly. + assert resolve_person("Marie", "home", build(("h1", "Marie")), aliases) == ["h1"] + assert resolve_person("Marie", "partner", build(("x", "Other")), {"Marie": {}}) == [] + + +def test_alias_listing_a_known_id_keeps_it() -> None: + people = build(("not-a-uuid-id", "Bob")) + assert resolve_person("Robert", "home", people, {"Robert": {"home": ["not-a-uuid-id"]}}) == [ + "not-a-uuid-id" + ] + + +def test_suggestions_are_close_matches() -> None: + suggestions = suggest_names("Alise", ["Alice", "Bob", "Alicia"]) + assert suggestions[0] == "Alice" and "Bob" not in suggestions + assert suggest_names("Zzz", ["Alice"]) == [] + + +# --- directory (cache, TTL, refresh, errors) ------------------------------------------------- +class Clock: + def __init__(self) -> None: + self.now = 1000.0 + + def __call__(self) -> float: + return self.now + + +def make_directory( + tmp_path: Path, fake: FakeImmich, ttl: int = 60 +) -> tuple[PeopleDirectory, ConfigStore, Clock]: + store = ConfigStore( + tmp_path / "config.json", + { + "immich": { + "accounts": {"home": {"url": fake.base, "api_key": fake.key}}, + "people_cache_ttl_s": ttl, + } + }, + ) + clock = Clock() + directory = PeopleDirectory(store, ImmichGateway(store, URLPolicy()), clock=clock) + return directory, store, clock + + +def people_calls(fake: FakeImmich) -> int: + return len([1 for _, path, _ in fake.calls if path == "/api/people"]) + + +async def test_directory_caches_until_ttl_or_refresh(tmp_path: Path) -> None: + fake = FakeImmich() + fake.add_person("1", "Alice") + directory, _, clock = make_directory(tmp_path, fake, ttl=60) + with mocked(fake): + first = await directory.get("home") + assert await directory.get("home") is first + assert people_calls(fake) == 1 + + fake.add_person("2", "Bob") + assert (await directory.get("home", refresh=True)).names() == ["Alice", "Bob"] + assert people_calls(fake) == 2 + + clock.now += 61 + await directory.get("home") + assert people_calls(fake) == 3 + + +async def test_directory_refetches_when_the_account_changes(tmp_path: Path) -> None: + fake = FakeImmich() + fake.add_person("1", "Alice") + directory, store, _ = make_directory(tmp_path, fake) + with mocked(fake): + await directory.get("home") + await store.update( + {"immich": {"accounts": {"home": {"url": fake.base, "api_key": "good-key"}}}} + ) # same values: cache stays valid + await directory.get("home") + assert people_calls(fake) == 1 + fake.key = "rotated-key" + await store.update( + {"immich": {"accounts": {"home": {"url": fake.base, "api_key": "rotated-key"}}}} + ) + await directory.get("home") + assert people_calls(fake) == 2 + + +async def test_ttl_zero_disables_the_cache(tmp_path: Path) -> None: + fake = FakeImmich() + fake.add_person("1", "Alice") + directory, _, _ = make_directory(tmp_path, fake, ttl=0) + with mocked(fake): + await directory.get("home") + await directory.get("home") + assert people_calls(fake) == 2 + + +async def test_snapshot_reports_ambiguity_and_errors_per_account(tmp_path: Path) -> None: + fake = FakeImmich() + fake.add_person("1", "Marie") + fake.add_person("2", "marie") + fake.add_person("3", "Bob") + directory, _, _ = make_directory(tmp_path, fake) + with mocked(fake): + [entry] = await directory.snapshot(["home"], refresh=True) + assert entry.error is None and entry.ambiguous == ["Marie"] + fake.key = "changed" # the stored key no longer matches the server + [failed] = await directory.snapshot(["home"], refresh=True) + assert failed.people is None and failed.error and "rejected the API key" in failed.error diff --git a/tests/test_immich_provider.py b/tests/test_immich_provider.py new file mode 100644 index 0000000..9cfac03 --- /dev/null +++ b/tests/test_immich_provider.py @@ -0,0 +1,552 @@ +from __future__ import annotations + +import io +import random +from pathlib import Path +from typing import Any + +import pytest +from PIL import Image + +from app.core.config_store import ConfigStore +from app.core.history_store import HistoryStore +from app.core.security import URLPolicy +from app.providers.base import ( + InvalidSelectionError, + NoCandidateError, + ProviderNotConfiguredError, + ProviderUnavailableError, +) +from app.providers.immich.client import ImmichAuthError, ImmichGateway +from app.providers.immich.models import ImmichDisplayRequest +from app.providers.immich.people import AmbiguousPersonError, PeopleDirectory +from app.providers.immich.provider import ImmichProvider, build_title_and_details, is_raw +from tests.immich_fake import FakeImmich, face, heic +from tests.test_immich_client import mocked + +MAX_BYTES = 20 * 1024 * 1024 + + +class Cycle(random.Random): + """Deterministic ``choice``: walks the eligible candidates in order, round-robin.""" + + def __init__(self) -> None: + super().__init__(0) + self.turn = 0 + + def choice(self, seq: Any) -> Any: + self.turn += 1 + return seq[(self.turn - 1) % len(seq)] + + +class Env: + def __init__(self, tmp_path: Path, fakes: dict[str, FakeImmich], **immich: Any) -> None: + accounts = {n: {"url": f.base, "api_key": f.key} for n, f in fakes.items()} + self.store = ConfigStore( + tmp_path / "config.json", {"immich": {"accounts": accounts, **immich}} + ) + self.gateway = ImmichGateway(self.store, URLPolicy()) + self.history = HistoryStore(tmp_path / "history.json") + self.provider = ImmichProvider( + self.store, + self.gateway, + PeopleDirectory(self.store, self.gateway), + self.history, + max_bytes=MAX_BYTES, + rng=Cycle(), + ) + + async def fetch(self, **request: Any) -> Any: + return await self.provider.fetch(ImmichDisplayRequest(**request)) + + +def family(fake: FakeImmich | None = None) -> FakeImmich: + fake = fake or FakeImmich() + for pid, name in (("p1", "Alice"), ("p2", "Bob"), ("p3", "Kid")): + fake.add_person(pid, name) + fake.add_asset("a1", people=[("p1", "Alice")], faces=[face("p1", (300, 100, 400, 200))]) + fake.add_asset("a2", people=[("p2", "Bob")]) + fake.add_asset( + "a3", + people=[("p1", "Alice"), ("p2", "Bob")], + faces=[ + face("p1", (50, 100, 150, 200)), + face("p2", (400, 100, 500, 200)), + face(None, (0, 0, 30, 30)), + ], + ) + fake.add_asset("a4", people=[("p3", "Kid")]) + fake.add_asset("a5", isFavorite=True) + fake.add_asset("a6", people=[("p1", "Alice")], isArchived=True) + return fake + + +def bodies(fake: FakeImmich) -> list[dict[str, Any]]: + return fake.bodies("/api/search/random") + + +# --- basics ------------------------------------------------------------------- +async def test_random_pick_returns_asset_with_title_details_and_regions(tmp_path: Path) -> None: + fake = FakeImmich() + fake.add_person("p1", "Alice") + fake.add_asset("a1", people=[("p1", "Alice")], faces=[face("p1", (300, 100, 400, 200))]) + env = Env(tmp_path, {"home": fake}) + with mocked(fake): + asset = await env.fetch() + + assert asset.source == "immich" and asset.history_key == "sha1:sum-a1" + assert asset.title == "Alice · 14 Jul 2024 · Lyon, France" + assert asset.details == { + "account": "home", + "asset_id": "a1", + "filename": "a1.jpg", + "taken_at": "2024-07-14T10:22:11+00:00", + "location": "Lyon, France", + "people": ["Alice"], + "quality": "original", + "faces_used": 1, + } + assert Image.open(io.BytesIO(asset.data)).size == (640, 480) + assert len(asset.regions) == 1 and asset.recommended_fit is None + assert bodies(fake)[0]["visibility"] == "timeline" and bodies(fake)[0]["type"] == "IMAGE" + + +async def test_archived_and_trashed_assets_are_never_picked(tmp_path: Path) -> None: + fake = FakeImmich() + fake.add_asset("only", isArchived=True) + fake.add_asset("gone", isTrashed=True) + env = Env(tmp_path, {"home": fake}) + with mocked(fake), pytest.raises(NoCandidateError): + await env.fetch() + # Archived assets are allowed when the config says so (the server filter is dropped too). + env = Env(tmp_path, {"home": fake}, exclude_archived=False) + with mocked(fake): + asset = await env.fetch() + assert asset.details["asset_id"] == "only" + assert "visibility" not in bodies(fake)[-1] + + +async def test_no_account_is_not_configured(tmp_path: Path) -> None: + with pytest.raises(ProviderNotConfiguredError): + await Env(tmp_path, {}).fetch() + + +async def test_rejected_api_key_is_an_auth_error(tmp_path: Path) -> None: + server = family() + env = Env(tmp_path, {"home": server}) + server.key = "rotated" # the stored key no longer matches the server + with mocked(server), pytest.raises(ImmichAuthError): + await env.fetch() + + +# --- people ------------------------------------------------------------------- +async def test_any_runs_one_query_per_person_and_all_runs_one_combined_query( + tmp_path: Path, +) -> None: + fake = family() + env = Env(tmp_path, {"home": fake}) + with mocked(fake): + any_asset = await env.fetch(persons=["Alice", "Bob"], match_mode="any") + assert any_asset.details["asset_id"] in {"a1", "a2", "a3"} + assert [b["personIds"] for b in bodies(fake)] == [["p1"], ["p2"]] + + fake.calls.clear() + all_asset = await env.fetch(persons=["alice", "BOB"], match_mode="all") + assert [b["personIds"] for b in bodies(fake)] == [["p1", "p2"]] + assert all_asset.details["asset_id"] == "a3" + assert all_asset.details["people"] == ["Alice", "Bob"] + + +async def test_person_defaults_always_include_merge_and_override(tmp_path: Path) -> None: + fake = family() + env = Env(tmp_path, {"home": fake}, persons=["Alice"], always_include=["Kid"]) + with mocked(fake): + await env.fetch() # config persons + always_include + assert [b["personIds"] for b in bodies(fake)] == [["p1"], ["p3"]] + + fake.calls.clear() + await env.fetch(persons=["Bob"]) # request persons replace config persons, keep always + assert [b["personIds"] for b in bodies(fake)] == [["p2"], ["p3"]] + + fake.calls.clear() + await env.fetch(persons=["Bob"], always_include=[]) # explicit [] switches it off + assert [b["personIds"] for b in bodies(fake)] == [["p2"]] + + fake.calls.clear() + await env.fetch(persons=[], always_include=[]) # nothing requested: unfiltered + assert "personIds" not in bodies(fake)[0] + + +async def test_persons_and_always_include_are_deduplicated_case_insensitively( + tmp_path: Path, +) -> None: + fake = family() + env = Env(tmp_path, {"home": fake}, always_include=["ALICE"]) + with mocked(fake): + await env.fetch(persons=["alice", "Alice"], match_mode="all") + assert [b["personIds"] for b in bodies(fake)] == [["p1"]] + + +async def test_unknown_person_is_rejected_with_suggestions(tmp_path: Path) -> None: + fake = family() + env = Env(tmp_path, {"home": fake}) + with mocked(fake): + with pytest.raises(InvalidSelectionError, match="Did you mean: Alice"): + await env.fetch(persons=["Alise"]) + with pytest.raises(InvalidSelectionError, match="Unknown person 'Zed'"): + await env.fetch(persons=["Zed"]) + assert not bodies(fake) # rejected before any search + + +async def test_ambiguous_person_needs_an_alias_that_pins_an_id(tmp_path: Path) -> None: + fake = family() + fake.add_person("p9", "Alice") # a second Alice + fake.add_asset("a9", people=[("p9", "Alice")]) + with mocked(fake): + with pytest.raises(AmbiguousPersonError): + await Env(tmp_path, {"home": fake}).fetch(persons=["Alice"]) + pinned = Env(tmp_path, {"home": fake}, person_aliases={"Alice": {"home": ["p9"]}}) + asset = await pinned.fetch(persons=["Alice"]) + assert asset.details["asset_id"] == "a9" + + +async def test_aliases_map_one_person_across_accounts(tmp_path: Path) -> None: + home, partner = ( + family(FakeImmich("http://home.test", "k-home")), + FakeImmich("http://partner.test", "k-partner"), + ) + partner.add_person("q1", "Maman") + partner.add_asset("b1", people=[("q1", "Maman")], checksum="sum-b1") + env = Env( + tmp_path, + {"home": home, "partner": partner}, + person_aliases={"Alice": {"partner": ["Maman"]}}, + ) + with mocked(home, partner): + seen = { + (await env.fetch(persons=["Alice"], ignore_history=True)).details["account"] + for _ in range(4) + } + assert seen == {"home", "partner"} + assert partner.bodies("/api/search/random")[0]["personIds"] == ["q1"] + assert home.bodies("/api/search/random")[0]["personIds"] == ["p1"] + + +async def test_account_without_the_person_contributes_nothing_in_all_mode(tmp_path: Path) -> None: + home, partner = ( + family(FakeImmich("http://home.test", "k-home")), + FakeImmich("http://partner.test", "k-partner"), + ) + partner.add_person("q1", "Alice") + partner.add_asset("b1", people=[("q1", "Alice")]) + partner_only = FakeImmich("http://third.test", "k-third") + partner_only.add_asset("c1") + env = Env(tmp_path, {"home": home, "partner": partner, "third": partner_only}) + with mocked(home, partner, partner_only): + await env.fetch(persons=["Alice", "Bob"], match_mode="all") + assert not partner.bodies("/api/search/random") # no Bob there: not queried + assert not partner_only.bodies("/api/search/random") + assert home.bodies("/api/search/random")[0]["personIds"] == ["p1", "p2"] + + +# --- modes -------------------------------------------------------------------- +async def test_favorites_mode_and_config_flag(tmp_path: Path) -> None: + fake = family() + env = Env(tmp_path, {"home": fake}) + with mocked(fake): + asset = await env.fetch(mode="favorites") + assert asset.details["asset_id"] == "a5" and bodies(fake)[0]["isFavorite"] is True + fake.calls.clear() + await Env(tmp_path, {"home": fake}, favorites_only=True).fetch() + assert bodies(fake)[0]["isFavorite"] is True + + +async def test_album_mode_by_name_by_id_and_default_from_config(tmp_path: Path) -> None: + fake = family() + fake.add_album("al1", "Summer", ["a4"]) + env = Env(tmp_path, {"home": fake}) + with mocked(fake): + by_name = await env.fetch(mode="album", album_name="summer") + by_id = await env.fetch(mode="album", album_id="al1") + assert by_name.details["asset_id"] == by_id.details["asset_id"] == "a4" + assert bodies(fake)[0]["albumIds"] == ["al1"] + + configured = await Env(tmp_path, {"home": fake}, album="SUMMER").fetch() + assert configured.details["asset_id"] == "a4" + + with pytest.raises(InvalidSelectionError, match="needs album_name or album_id"): + await env.fetch(mode="album") + with pytest.raises(InvalidSelectionError, match="Album 'Nope' was not found"): + await env.fetch(mode="album", album_name="Nope") + + +async def test_clip_search_queries_each_phrase_and_picks_among_candidates(tmp_path: Path) -> None: + fake = family() + fake.smart_results = {"beach": ["a2", "a4"], "sunset": ["a5"]} + env = Env(tmp_path, {"home": fake}, search_candidates=12) + with mocked(fake): + picks = { + ( + await env.fetch( + mode="search", clip_queries=["beach", " sunset "], ignore_history=True + ) + ).details["asset_id"] + for _ in range(4) + } + smart = fake.bodies("/api/search/smart") + assert [b["query"] for b in smart[:2]] == ["beach", "sunset"] + assert all(b["size"] == 12 for b in smart) + assert picks == {"a2", "a4", "a5"} + + +async def test_clip_search_combines_with_people_and_albums(tmp_path: Path) -> None: + fake = family() + fake.add_album("al1", "Trips", ["a1", "a3"]) + env = Env(tmp_path, {"home": fake}) + with mocked(fake): + await env.fetch( + mode="search", clip_queries=["mountain"], persons=["Alice"], album_name="Trips" + ) + body = fake.bodies("/api/search/smart")[0] + assert body["personIds"] == ["p1"] and body["albumIds"] == ["al1"] + + +def test_search_mode_requires_a_query() -> None: + with pytest.raises(ValueError, match="clip_queries"): + ImmichDisplayRequest(mode="search") + with pytest.raises(ValueError, match="clip_queries"): + ImmichDisplayRequest(mode="search", clip_queries=[" "]) + + +# --- accounts, dedupe, history ------------------------------------------------ +async def test_same_photo_in_two_accounts_is_one_candidate_and_one_history_key( + tmp_path: Path, +) -> None: + home, partner = ( + FakeImmich("http://home.test", "k-home"), + FakeImmich("http://partner.test", "k-partner"), + ) + home.add_asset("h1", checksum="same-photo") + partner.add_asset("p-copy", checksum="same-photo") + env = Env(tmp_path, {"home": home, "partner": partner}) + with mocked(home, partner): + asset = await env.fetch() + assert asset.history_key == "sha1:same-photo" + assert asset.details["account"] == "home" # first configured account wins + + await env.history.record(asset.history_key, "immich") + with mocked(home, partner), pytest.raises(NoCandidateError, match="were shown within"): + await env.fetch() # the copy in the other account is on cooldown too + + +async def test_assets_without_checksum_fall_back_to_account_and_id(tmp_path: Path) -> None: + fake = FakeImmich() + fake.add_asset("n1", checksum=None) + env = Env(tmp_path, {"home": fake}) + with mocked(fake): + assert (await env.fetch()).history_key == "home:n1" + + +async def test_history_cooldown_excludes_recent_photos_and_can_be_ignored(tmp_path: Path) -> None: + fake = FakeImmich() + fake.add_asset("a1") + fake.add_asset("a2") + env = Env(tmp_path, {"home": fake}, anti_repeat_days=30) + await env.history.record("sha1:sum-a1", "immich") + with mocked(fake): + assert {(await env.fetch()).details["asset_id"] for _ in range(2)} == {"a2"} + await env.history.record("sha1:sum-a2", "immich") + with pytest.raises(NoCandidateError, match="ignore_history"): + await env.fetch() + assert (await env.fetch(ignore_history=True)).details["asset_id"] in {"a1", "a2"} + + +async def test_history_of_other_sources_does_not_block_immich(tmp_path: Path) -> None: + fake = FakeImmich() + fake.add_asset("a1") + env = Env(tmp_path, {"home": fake}) + await env.history.record("sha1:sum-a1", "media") # same key, different source + with mocked(fake): + assert (await env.fetch()).details["asset_id"] == "a1" + + +async def test_zero_day_cooldown_disables_the_history_filter(tmp_path: Path) -> None: + fake = FakeImmich() + fake.add_asset("a1") + env = Env(tmp_path, {"home": fake}, anti_repeat_days=0) + await env.history.record("sha1:sum-a1", "immich") + with mocked(fake): + assert (await env.fetch()).details["asset_id"] == "a1" + + +async def test_a_failing_account_is_skipped_but_all_failing_raises(tmp_path: Path) -> None: + good, bad = FakeImmich("http://good.test", "k-good"), FakeImmich("http://bad.test", "k-bad") + good.add_asset("g1") + bad.search_error = 500 + env = Env(tmp_path, {"bad": bad, "good": good}) + with mocked(good, bad): + assert (await env.fetch()).details["account"] == "good" + good.search_error = 503 + with pytest.raises(ProviderUnavailableError): + await env.fetch() + + +async def test_account_subset_and_unknown_account(tmp_path: Path) -> None: + home, partner = ( + FakeImmich("http://home.test", "k-home"), + FakeImmich("http://partner.test", "k-partner"), + ) + home.add_asset("h1") + partner.add_asset("p1") + env = Env(tmp_path, {"home": home, "partner": partner}) + with mocked(home, partner): + for _ in range(2): + assert (await env.fetch(accounts=["partner"], ignore_history=True)).details[ + "account" + ] == "partner" + with pytest.raises(InvalidSelectionError, match="Unknown Immich account"): + await env.fetch(accounts=["nobody"]) + assert not home.bodies("/api/search/random") + + +# --- download variants -------------------------------------------------------- +async def test_original_is_used_and_heic_decodes(tmp_path: Path) -> None: + fake = FakeImmich() + fake.add_asset( + "h1", original=heic(), originalMimeType="image/heic", originalFileName="IMG_1.HEIC" + ) + env = Env(tmp_path, {"home": fake}) + with mocked(fake): + asset = await env.fetch() + assert asset.details["quality"] == "original" + assert Image.open(io.BytesIO(asset.data)).format == "HEIF" + assert [p for p, _ in fake.downloads()] == ["/api/assets/h1/original"] + + +@pytest.mark.parametrize( + ("name", "mime"), + [("IMG_1.DNG", "image/x-adobe-dng"), ("x.NEF", "image/jpeg"), ("x.bin", "image/x-canon-cr2")], +) +async def test_raw_files_use_the_converted_jpeg_never_the_original( + tmp_path: Path, name: str, mime: str +) -> None: + fake = FakeImmich() + fake.add_asset("r1", original=b"RAW-DATA", originalFileName=name, originalMimeType=mime) + env = Env(tmp_path, {"home": fake}) + with mocked(fake): + asset = await env.fetch() + assert asset.details["quality"] == "fullsize" + assert [p for p, _ in fake.downloads()] == ["/api/assets/r1/thumbnail"] + assert fake.downloads()[0][1] == {"size": "fullsize"} + + +async def test_fullsize_missing_falls_back_to_preview(tmp_path: Path) -> None: + fake = FakeImmich() + fake.add_asset("r1", originalFileName="a.ARW") + fake.files[("r1", "fullsize")] = 404 + env = Env(tmp_path, {"home": fake}) + with mocked(fake): + asset = await env.fetch() + assert asset.details["quality"] == "preview" + assert [q.get("size") for _, q in fake.downloads()] == ["fullsize", "preview"] + + +async def test_oversized_original_and_undecodable_original_fall_back(tmp_path: Path) -> None: + fake = FakeImmich() + fake.add_asset("big", exifInfo={"fileSizeInByte": MAX_BYTES + 1, "orientation": "1"}) + fake.add_asset("bad", original=b"definitely not an image") + env = Env(tmp_path, {"home": fake}) + with mocked(fake): + picks = {(await env.fetch(ignore_history=True)).details["asset_id"]: None for _ in range(4)} + assert set(picks) == {"big", "bad"} + paths = [p for p, _ in fake.downloads()] + assert "/api/assets/big/original" not in paths # skipped on size alone + assert "/api/assets/bad/original" in paths # tried, rejected, replaced by fullsize + + +async def test_every_variant_failing_is_a_provider_error(tmp_path: Path) -> None: + fake = FakeImmich() + fake.add_asset("x1") + for variant in ("original", "fullsize", "preview"): + fake.files[("x1", variant)] = 500 + env = Env(tmp_path, {"home": fake}) + with mocked(fake), pytest.raises(ProviderUnavailableError, match="Could not download"): + await env.fetch() + + +async def test_edited_assets_download_the_edit_and_skip_face_regions(tmp_path: Path) -> None: + fake = FakeImmich() + fake.add_person("p1", "Alice") + fake.add_asset( + "e1", people=[("p1", "Alice")], isEdited=True, faces=[face("p1", (300, 100, 400, 200))] + ) + env = Env(tmp_path, {"home": fake}) + with mocked(fake): + asset = await env.fetch() + assert asset.regions == () + assert fake.downloads()[0][1] == {"edited": "true"} + assert not [c for c in fake.calls if c[1] == "/api/faces"] + + +async def test_face_lookup_failure_only_loses_the_regions(tmp_path: Path) -> None: + fake = family() + env = Env(tmp_path, {"home": fake}) + fake.faces_error = 500 + with mocked(fake): + asset = await env.fetch(persons=["Alice"], match_mode="all", ignore_history=True) + assert asset.regions == () and asset.data + + +async def test_target_faces_are_prioritized_in_the_returned_regions(tmp_path: Path) -> None: + fake = family() + env = Env(tmp_path, {"home": fake}) + with mocked(fake): + asset = await env.fetch(persons=["Alice", "Bob"], match_mode="all") + assert asset.details["asset_id"] == "a3" and asset.details["faces_used"] == 2 + assert len(asset.regions) == 2 # the unassigned background face is ignored + assert asset.regions[0].area >= asset.regions[1].area + + +# --- albums listing ----------------------------------------------------------- +async def test_albums_across_accounts_with_per_account_errors(tmp_path: Path) -> None: + home, partner = ( + FakeImmich("http://home.test", "k-home"), + FakeImmich("http://partner.test", "k-partner"), + ) + home.add_album("h-al", "Zoo", ["a"]) + partner.add_album("p-al", "Alps", ["a", "b"]) + env = Env(tmp_path, {"home": home, "partner": partner}) + with mocked(home, partner) as router: + albums, errors = await env.provider.albums() + assert [(a.name, a.account, a.asset_count) for a in albums] == [ + ("Alps", "partner", 2), + ("Zoo", "home", 1), + ] + assert errors == {} + router.route(host="partner.test").respond(500) + albums, errors = await env.provider.albums() + assert [a.name for a in albums] == ["Zoo"] and "partner" in errors + + +# --- helpers ------------------------------------------------------------------ +def test_title_falls_back_to_the_file_name_and_caps_people() -> None: + from app.providers.immich.models import AssetDto + + bare = AssetDto(id="x", originalFileName="IMG_9.jpg") + assert build_title_and_details("home", bare, "original", 0)[0] == "IMG_9.jpg" + crowd = AssetDto.model_validate( + {"id": "y", "people": [{"id": str(i), "name": f"P{i}"} for i in range(6)]} + ) + title, details = build_title_and_details("home", crowd, "preview", 2) + assert title == "P0, P1, P2, P3" and details["people"] == [f"P{i}" for i in range(6)] + assert details["taken_at"] is None and details["location"] is None + + +def test_raw_detection() -> None: + from app.providers.immich.models import AssetDto + + assert is_raw(AssetDto(id="a", originalFileName="x.CR3")) + assert is_raw(AssetDto(id="a", originalMimeType="image/x-fuji-raf")) + assert not is_raw(AssetDto(id="a", originalFileName="x.jpg", originalMimeType="image/jpeg")) + assert not is_raw(AssetDto(id="a", originalMimeType="image/x-ms-bmp")) + assert not is_raw(AssetDto(id="a", originalFileName="x.heic", originalMimeType="image/heic")) From 745c00ab22000b48de710191ef9c2cd1bd8b7829 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sat, 14 Nov 2026 20:16:34 +0100 Subject: [PATCH 29/86] feat: add Immich display, albums and people endpoints POST /api/display/immich selects, renders (face-aware crop), delivers and records history; GET /api/immich/albums, GET /api/immich/people and POST /api/immich/people/refresh expose discovery. Provider errors map to 404/409/ 422/502/504. GET /api/immich/* requires the API key when one is set because it lists family member names. DisplayService.display_asset writes the history entry only after rendering succeeded. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- app/api/deps.py | 13 ++ app/api/routes/immich.py | 196 +++++++++++++++++++++++ app/core/auth.py | 5 +- app/main.py | 21 ++- app/providers/immich/people.py | 6 +- app/services/display.py | 27 ++++ tests/test_api_immich.py | 279 +++++++++++++++++++++++++++++++++ 7 files changed, 543 insertions(+), 4 deletions(-) create mode 100644 app/api/routes/immich.py create mode 100644 tests/test_api_immich.py diff --git a/app/api/deps.py b/app/api/deps.py index 9eb4eba..8dc454d 100644 --- a/app/api/deps.py +++ b/app/api/deps.py @@ -9,6 +9,7 @@ from app.core.config_store import ConfigStore from app.core.history_store import HistoryStore from app.core.settings import EnvSettings +from app.providers.immich import ImmichProvider, PeopleDirectory from app.services.current_image import CurrentImageStore from app.services.delivery import DeliveryService from app.services.display import DisplayService @@ -44,9 +45,21 @@ def get_display_service(request: Request) -> DisplayService: return cast(DisplayService, request.app.state.display_service) +def get_immich_provider(request: Request) -> ImmichProvider: + """The Immich image provider.""" + return cast(ImmichProvider, request.app.state.immich_provider) + + +def get_people_directory(request: Request) -> PeopleDirectory: + """Cache of the people known to each Immich account.""" + return cast(PeopleDirectory, request.app.state.people_directory) + + SettingsDep = Annotated[EnvSettings, Depends(get_settings)] ConfigStoreDep = Annotated[ConfigStore, Depends(get_config_store)] HistoryStoreDep = Annotated[HistoryStore, Depends(get_history_store)] CurrentImageStoreDep = Annotated[CurrentImageStore, Depends(get_current_image_store)] DeliveryServiceDep = Annotated[DeliveryService, Depends(get_delivery_service)] DisplayServiceDep = Annotated[DisplayService, Depends(get_display_service)] +ImmichProviderDep = Annotated[ImmichProvider, Depends(get_immich_provider)] +PeopleDirectoryDep = Annotated[PeopleDirectory, Depends(get_people_directory)] diff --git a/app/api/routes/immich.py b/app/api/routes/immich.py new file mode 100644 index 0000000..e900ff6 --- /dev/null +++ b/app/api/routes/immich.py @@ -0,0 +1,196 @@ +"""Immich endpoints: display a photo, list albums, inspect and refresh the people mapping.""" + +from __future__ import annotations + +from datetime import datetime +from typing import Annotated, Any + +from fastapi import APIRouter, HTTPException, Query, Security +from pydantic import BaseModel, Field + +from app.api.deps import ( + ConfigStoreDep, + DisplayServiceDep, + ImmichProviderDep, + PeopleDirectoryDep, +) +from app.core.auth import api_key_scheme +from app.core.security import InvalidImageError +from app.providers.base import ( + InvalidSelectionError, + NoCandidateError, + ProviderError, + ProviderNotConfiguredError, + ProviderUnavailableError, +) +from app.providers.immich.models import AlbumInfo, ImmichDisplayRequest +from app.providers.immich.people import PeopleSnapshot, resolve_person +from app.services.display import DisplayResult + +display_router = APIRouter( + prefix="/api/display", tags=["display"], dependencies=[Security(api_key_scheme)] +) +router = APIRouter(prefix="/api/immich", tags=["immich"], dependencies=[Security(api_key_scheme)]) + +AccountsQuery = Annotated[ + list[str] | None, Query(description="Only these account names (default: all)") +] + +_ERRORS: dict[int | str, dict[str, Any]] = { + 404: {"description": "No eligible photo matched (or all are on the anti-repeat cooldown)"}, + 409: {"description": "No Immich account is configured"}, + 422: {"description": "Unknown or ambiguous person, album or account"}, + 502: {"description": "Immich failed or rejected the API key"}, + 504: {"description": "Immich did not respond in time"}, +} + + +def http_error(exc: ProviderError) -> HTTPException: + """Map a provider error to an HTTP error (messages never contain secrets).""" + if isinstance(exc, ProviderNotConfiguredError): + return HTTPException(status_code=409, detail=str(exc)) + if isinstance(exc, InvalidSelectionError): + return HTTPException(status_code=422, detail=str(exc)) + if isinstance(exc, NoCandidateError): + return HTTPException(status_code=404, detail=str(exc)) + if isinstance(exc, ProviderUnavailableError): + return HTTPException(status_code=504 if exc.timeout else 502, detail=str(exc)) + return HTTPException(status_code=500, detail="Image provider error") + + +@display_router.post( + "/immich", + response_model=DisplayResult, + responses=_ERRORS, + summary="Select and display an Immich photo", +) +async def display_immich( + request: ImmichDisplayRequest, provider: ImmichProviderDep, display: DisplayServiceDep +) -> DisplayResult: + """Pick a photo from Immich, render it (face-aware crop) and make it the current image. + + People are plain names resolved per account; ``persons``, ``match_mode``, ``album_*`` + and ``always_include`` fall back to the ``immich`` section of the configuration. + The photo is recorded in the history so it is not shown again within + ``immich.anti_repeat_days``. + """ + try: + asset = await provider.fetch(request) + except ProviderError as exc: + raise http_error(exc) from exc + try: + return await display.display_asset(asset, fit=request.fit, push=request.push_to_fraimic) + except InvalidImageError as exc: + raise HTTPException( + status_code=502, detail="Immich returned an image that cannot be decoded" + ) from exc + + +class AlbumsResponse(BaseModel): + """Albums across the configured accounts.""" + + albums: list[AlbumInfo] + errors: dict[str, str] = Field( + default_factory=dict, description="Accounts that could not be queried, with the reason" + ) + + +@router.get("/albums", response_model=AlbumsResponse, responses=_ERRORS, summary="List albums") +async def list_albums( + provider: ImmichProviderDep, accounts: AccountsQuery = None +) -> AlbumsResponse: + """Albums (owned and shared) of every selected account.""" + try: + albums, errors = await provider.albums(accounts) + except ProviderError as exc: + raise http_error(exc) from exc + return AlbumsResponse(albums=albums, errors=errors) + + +class PersonView(BaseModel): + id: str + name: str + + +class AccountPeopleView(BaseModel): + """People of one account as the provider sees them.""" + + account: str + people: list[PersonView] = Field(default_factory=list) + cached_at: datetime | None = Field(default=None, description="When the list was fetched") + ambiguous: list[str] = Field( + default_factory=list, + description="Names shared by several people; pin one in immich.person_aliases", + ) + aliases: dict[str, list[str]] = Field( + default_factory=dict, + description="Configured canonical names resolved to person IDs in this account", + ) + error: str | None = None + + +class PeopleResponse(BaseModel): + accounts: list[AccountPeopleView] + + +def _view(snapshot: PeopleSnapshot, aliases: dict[str, dict[str, list[str]]]) -> AccountPeopleView: + view = AccountPeopleView(account=snapshot.account, error=snapshot.error) + if snapshot.people is None: + return view + people = snapshot.people + view.cached_at = people.fetched_at + view.ambiguous = snapshot.ambiguous + view.people = [ + PersonView(id=person_id, name=name) + for person_id, name in sorted(people.by_id.items(), key=lambda item: item[1].casefold()) + ] + for canonical, per_account in aliases.items(): + if snapshot.account not in per_account: + continue + try: + view.aliases[canonical] = resolve_person(canonical, snapshot.account, people, aliases) + except InvalidSelectionError: + view.aliases[canonical] = [] + return view + + +async def _people_response( + directory: PeopleDirectoryDep, + config: ConfigStoreDep, + accounts: list[str] | None, + *, + refresh: bool, +) -> PeopleResponse: + try: + names = list(directory.account_names(accounts)) + except ProviderError as exc: + raise http_error(exc) from exc + snapshots = await directory.snapshot(names, refresh=refresh) + aliases = config.config.immich.person_aliases + return PeopleResponse(accounts=[_view(snapshot, aliases) for snapshot in snapshots]) + + +@router.get( + "/people", + response_model=PeopleResponse, + responses=_ERRORS, + summary="People known to each account (cached)", +) +async def list_people( + directory: PeopleDirectoryDep, config: ConfigStoreDep, accounts: AccountsQuery = None +) -> PeopleResponse: + """Named people per account (name to ID), served from the cache while it is fresh.""" + return await _people_response(directory, config, accounts, refresh=False) + + +@router.post( + "/people/refresh", + response_model=PeopleResponse, + responses=_ERRORS, + summary="Reload the people lists from Immich", +) +async def refresh_people( + directory: PeopleDirectoryDep, config: ConfigStoreDep, accounts: AccountsQuery = None +) -> PeopleResponse: + """Bypass the cache and fetch the people lists again.""" + return await _people_response(directory, config, accounts, refresh=True) diff --git a/app/core/auth.py b/app/core/auth.py index 865ea7b..a53f67a 100644 --- a/app/core/auth.py +++ b/app/core/auth.py @@ -3,7 +3,8 @@ Rules when ``APP_API_KEY`` is set (no-op when it is empty): * ``POST``/``PUT``/``PATCH``/``DELETE`` on any route require the key. -* ``/api/config`` and everything below it require the key for every method. +* ``/api/config`` and ``/api/immich`` (family member names, albums) and everything + below them require the key for every method. * ``/api/current.jpg``, ``/api/current.bin`` and ``/api/current_dithered.png`` require the key only when ``PUBLIC_IMAGE_ENDPOINTS=false``. @@ -28,7 +29,7 @@ API_KEY_QUERY_PARAM: Final = "api_key" MUTATING_METHODS: Final = frozenset({"POST", "PUT", "PATCH", "DELETE"}) -PROTECTED_PREFIXES: Final = ("/api/config",) +PROTECTED_PREFIXES: Final = ("/api/config", "/api/immich") IMAGE_ENDPOINTS: Final = frozenset( {"/api/current.jpg", "/api/current.bin", "/api/current_dithered.png"} ) diff --git a/app/main.py b/app/main.py index e3b7860..233edbf 100644 --- a/app/main.py +++ b/app/main.py @@ -23,6 +23,7 @@ from app.api.routes import display as display_routes from app.api.routes import fraimic as fraimic_routes from app.api.routes import images as image_routes +from app.api.routes import immich as immich_routes from app.api.routes import system as system_routes from app.core.auth import APIKeyMiddleware from app.core.config_models import RuntimeConfig @@ -31,7 +32,9 @@ from app.core.limits import MULTIPART_OVERHEAD_BYTES, BodySizeLimitMiddleware from app.core.logging_config import masking_filter, setup_logging from app.core.proxy import RootPathMiddleware +from app.core.security import URLPolicy from app.core.settings import EnvSettings, get_env_settings +from app.providers.immich import ImmichGateway, ImmichProvider, PeopleDirectory from app.services.current_image import CurrentImageStore from app.services.delivery import DeliveryService from app.services.display import DisplayService @@ -89,13 +92,27 @@ async def _on_config_change(_: RuntimeConfig) -> None: current_store.load() delivery = DeliveryService(settings.queue_dir, config_store) delivery.load() - display = DisplayService(config_store, current_store, delivery) + display = DisplayService(config_store, current_store, delivery, history_store) + url_policy = URLPolicy.from_entries( + settings.block_private_urls, settings.url_allowlist_entries + ) + immich_gateway = ImmichGateway(config_store, url_policy) + people = PeopleDirectory(config_store, immich_gateway) + immich = ImmichProvider( + config_store, + immich_gateway, + people, + history_store, + max_bytes=settings.max_upload_bytes, + ) app.state.config_store = config_store app.state.history_store = history_store app.state.current_image_store = current_store app.state.delivery_service = delivery app.state.display_service = display + app.state.people_directory = people + app.state.immich_provider = immich await delivery.start() config = config_store.config @@ -161,6 +178,8 @@ async def _validation_handler(_: Request, exc: RequestValidationError) -> JSONRe app.include_router(config_routes.router) app.include_router(image_routes.router) app.include_router(display_routes.router) + app.include_router(immich_routes.display_router) + app.include_router(immich_routes.router) app.include_router(fraimic_routes.router) @app.get("/", include_in_schema=False) diff --git a/app/providers/immich/people.py b/app/providers/immich/people.py index ad6d01c..ea47b51 100644 --- a/app/providers/immich/people.py +++ b/app/providers/immich/people.py @@ -15,7 +15,7 @@ import difflib import re import time -from collections.abc import Callable, Iterable, Mapping +from collections.abc import Callable, Iterable, Mapping, Sequence from dataclasses import dataclass, field from datetime import UTC, datetime from typing import Final @@ -129,6 +129,10 @@ def __init__( self._now = now self._cache: dict[str, tuple[float, AccountPeople]] = {} + def account_names(self, names: Sequence[str] | None = None) -> list[str]: + """Selected configured account names (validates ``names``).""" + return list(self._gateway.accounts(names)) + def _fingerprint(self, account: str) -> tuple[str, str]: config = self._gateway.accounts([account])[account] return config.url, config.api_key.get_secret_value() diff --git a/app/services/display.py b/app/services/display.py index 832919b..c192391 100644 --- a/app/services/display.py +++ b/app/services/display.py @@ -14,8 +14,10 @@ from app.core.config_models import FitMode from app.core.config_store import ConfigStore +from app.core.history_store import HistoryStore from app.processor.fit import FocusRegion from app.processor.pipeline import RenderOptions, render_bytes +from app.providers.base import ImageAsset from app.services.current_image import CurrentImageMeta, CurrentImageStore from app.services.delivery import DeliveryOutcome, DeliveryService @@ -41,10 +43,12 @@ def __init__( config_store: ConfigStore, current_store: CurrentImageStore, delivery: DeliveryService, + history: HistoryStore, ) -> None: self._config_store = config_store self._current = current_store self._delivery = delivery + self._history = history self._render_lock = asyncio.Lock() async def display_bytes( @@ -74,6 +78,29 @@ async def display_bytes( ) return DisplayResult(image=meta, delivery=delivery) + async def display_asset( + self, asset: ImageAsset, *, fit: FitMode | None = None, push: bool = True + ) -> DisplayResult: + """Display a provider asset and record it in the anti-repeat history. + + The fit mode is the explicit ``fit``, else the asset's recommended one, else the + configured default. The history entry is written only after rendering succeeded. + + Raises: + InvalidImageError: If the asset's bytes are not a supported image. + """ + result = await self.display_bytes( + asset.data, + source=asset.source, + title=asset.title, + details=asset.details, + fit=fit or asset.recommended_fit, + regions=asset.regions, + push=push, + ) + await self._history.record(asset.history_key, asset.source) + return result + async def push_current(self) -> DeliveryOutcome: """Send the current image to the frame now, whatever the power mode. diff --git a/tests/test_api_immich.py b/tests/test_api_immich.py new file mode 100644 index 0000000..bba2a15 --- /dev/null +++ b/tests/test_api_immich.py @@ -0,0 +1,279 @@ +"""API tests for the Immich display, albums and people endpoints (fake Immich + fake frame).""" + +from __future__ import annotations + +import io +from collections.abc import Iterator +from contextlib import contextmanager +from typing import Any + +import httpx +import numpy as np +import pytest +import respx +from fastapi.testclient import TestClient +from PIL import Image + +from app.core.security import InvalidImageError +from tests.conftest import ClientFactory +from tests.immich_fake import FakeImmich, face + +FRAME = "http://frame.test" +KEY = "api-secret" + + +@contextmanager +def servers(*fakes: FakeImmich, frame: bool = True) -> Iterator[respx.MockRouter]: + with respx.mock(assert_all_called=False) as router: + for fake in fakes: + fake.mount(router) + if frame: + router.get(f"{FRAME}/api/info").respond( + json={"battery": {"percent": 70}, "firmware_version": "1"} + ) + router.post(f"{FRAME}/api/image").respond(200) + yield router + + +def family() -> FakeImmich: + fake = FakeImmich() + fake.add_person("p1", "Alice") + fake.add_person("p2", "Bob") + fake.add_asset("a1", people=[("p1", "Alice")], faces=[face("p1", (300, 100, 400, 200))]) + fake.add_asset("a2", people=[("p2", "Bob")]) + return fake + + +def immich_client(make_client: ClientFactory, **overrides: Any) -> TestClient: + overrides.setdefault("immich_url", "http://immich.test") + overrides.setdefault("immich_api_key", "good-key") + overrides.setdefault("fraimic_host", "frame.test") + return make_client(**overrides) + + +def show(client: TestClient, **body: Any) -> httpx.Response: + return client.post("/api/display/immich", json=body) + + +def people_calls(fake: FakeImmich) -> int: + return len([1 for _, path, _ in fake.calls if path == "/api/people"]) + + +# --- display ------------------------------------------------------------------ +def test_display_renders_delivers_and_records_history(make_client: ClientFactory) -> None: + fake = family() + client = immich_client(make_client) + with servers(fake): + response = show(client, persons=["Alice"]) + assert response.status_code == 200, response.text + body = response.json() + assert body["image"]["source"] == "immich" + assert body["image"]["title"] == "Alice · 14 Jul 2024 · Lyon, France" + assert body["image"]["details"]["account"] == "default" + assert body["image"]["bin_size"] == 960_000 + assert body["delivery"]["status"] == "delivered" + + history = client.app.state.history_store # type: ignore[attr-defined] + assert history.recent_ids("immich", 30) == {"sha1:sum-a1"} + assert client.get("/api/status").json()["current_image"]["source"] == "immich" + + with servers(fake): + # The only matching photo is now on cooldown... + again = show(client, persons=["Alice"]) + assert again.status_code == 404 and "ignore_history" in again.json()["detail"] + # ...unless the request says otherwise. + assert show(client, persons=["Alice"], ignore_history=True).status_code == 200 + + +def test_push_to_fraimic_false_does_not_contact_the_frame(make_client: ClientFactory) -> None: + fake = family() + client = immich_client(make_client) + with servers(fake) as router: + response = show(client, push_to_fraimic=False) + assert response.status_code == 200 + assert response.json()["delivery"] is None + assert not [c for c in router.calls if c.request.url.host == "frame.test"] + + +def test_display_uses_face_regions_for_the_crop(make_client: ClientFactory) -> None: + # Wide photo, portrait frame: a centered crop would miss the red face at the far right. + image = Image.new("RGB", (1600, 900), (255, 255, 255)) + image.paste((255, 0, 0), (1450, 300, 1550, 400)) + buffer = io.BytesIO() + image.save(buffer, format="JPEG", quality=95) + fake = FakeImmich() + fake.add_person("p1", "Alice") + fake.add_asset( + "wide", + people=[("p1", "Alice")], + faces=[face("p1", (1450, 300, 1550, 400), frame=(1600, 900))], + original=buffer.getvalue(), + width=1600, + height=900, + ) + client = immich_client(make_client) + with servers(fake, frame=False): + assert show(client, persons=["Alice"], push_to_fraimic=False).status_code == 200 + current = np.asarray(Image.open(io.BytesIO(client.get("/api/current.jpg").content))) + red = (current[..., 0] > 200) & (current[..., 1] < 80) & (current[..., 2] < 80) + assert red.sum() > 1000 # the face is inside the 1200x1600 crop + + +def test_fit_override_is_forwarded(make_client: ClientFactory) -> None: + fake = family() + client = immich_client(make_client) + with servers(fake, frame=False): + response = show(client, fit="contain", push_to_fraimic=False) + assert response.json()["image"]["fit"] == "contain" + + +# --- errors ------------------------------------------------------------------- +def test_error_statuses(make_client: ClientFactory) -> None: + fake = family() + client = immich_client(make_client) + with servers(fake, frame=False): + unknown = show(client, persons=["Zed"], push_to_fraimic=False) + assert unknown.status_code == 422 and "Unknown person" in unknown.json()["detail"] + assert show(client, mode="album", push_to_fraimic=False).status_code == 422 + assert show(client, accounts=["nope"], push_to_fraimic=False).status_code == 422 + assert show(client, mode="search").status_code == 422 # body validation + assert show(client, bogus=1).status_code == 422 + + fake.search_error = 500 + assert show(client, push_to_fraimic=False).status_code == 502 + + with servers(fake, frame=False) as router: + router.route(host="immich.test").mock(side_effect=httpx.ReadTimeout("slow")) + assert show(client, push_to_fraimic=False).status_code == 504 + + fake.key = "rotated" + fake.search_error = None + with servers(fake, frame=False): + rejected = show(client, push_to_fraimic=False) + assert rejected.status_code == 502 and "rejected the API key" in rejected.json()["detail"] + assert "good-key" not in rejected.text + + +def test_not_configured_is_a_conflict(make_client: ClientFactory) -> None: + client = make_client() + assert show(client).status_code == 409 + assert client.get("/api/immich/albums").status_code == 409 + assert client.get("/api/immich/people").status_code == 409 + + +def test_undecodable_image_is_a_bad_gateway( + make_client: ClientFactory, monkeypatch: pytest.MonkeyPatch +) -> None: + fake = FakeImmich() + fake.add_asset("x1") + client = immich_client(make_client) + + def broken(*args: object, **kwargs: object) -> object: + raise InvalidImageError("boom") + + monkeypatch.setattr("app.services.display.render_bytes", broken) + with servers(fake, frame=False): + response = show(client, push_to_fraimic=False) + assert response.status_code == 502 and "cannot be decoded" in response.json()["detail"] + history = client.app.state.history_store # type: ignore[attr-defined] + assert history.recent_ids("immich", 30) == set() # nothing recorded for a failed render + + +# --- albums & people ---------------------------------------------------------- +def test_albums_endpoint(make_client: ClientFactory) -> None: + fake = family() + fake.add_album("al1", "Summer", ["a1", "a2"]) + client = immich_client(make_client) + with servers(fake, frame=False): + body = client.get("/api/immich/albums").json() + assert body["albums"] == [ + {"account": "default", "id": "al1", "name": "Summer", "asset_count": 2, "shared": False} + ] + assert body["errors"] == {} + + +def test_people_endpoint_cache_refresh_ambiguity_and_aliases(make_client: ClientFactory) -> None: + fake = family() + fake.add_person("p9", "Alice") # ambiguous name + client = immich_client(make_client) + aliases = {"Ali": {"default": ["p9"]}, "Ghost": {"default": []}} + saved = client.put("/api/config", json={"immich": {"person_aliases": aliases}}) + assert saved.status_code == 200 + with servers(fake, frame=False): + first = client.get("/api/immich/people").json()["accounts"][0] + assert first["account"] == "default" and first["error"] is None + assert [p["name"] for p in first["people"]] == ["Alice", "Alice", "Bob"] + assert first["ambiguous"] == ["Alice"] + assert first["aliases"] == {"Ali": ["p9"], "Ghost": []} + assert first["cached_at"] + + calls = people_calls(fake) + client.get("/api/immich/people") + assert people_calls(fake) == calls # served from the cache + + fake.add_person("p5", "Carol") + refreshed = client.post("/api/immich/people/refresh").json()["accounts"][0] + assert "Carol" in [p["name"] for p in refreshed["people"]] + assert people_calls(fake) == calls + 1 + + +def test_people_and_albums_report_a_failing_account(make_client: ClientFactory) -> None: + fake = family() + client = immich_client(make_client) + fake.key = "rotated" + with servers(fake, frame=False): + people = client.get("/api/immich/people").json()["accounts"][0] + albums = client.get("/api/immich/albums").json() + assert people["people"] == [] and "rejected the API key" in people["error"] + assert albums["albums"] == [] and "default" in albums["errors"] + + +def test_unknown_account_filter_is_rejected(make_client: ClientFactory) -> None: + client = immich_client(make_client) + assert client.get("/api/immich/people", params={"accounts": "nope"}).status_code == 422 + + +# --- auth --------------------------------------------------------------------- +def test_immich_routes_require_the_api_key(make_client: ClientFactory) -> None: + fake = family() + client = immich_client(make_client, app_api_key=KEY) + headers = {"X-API-Key": KEY} + with servers(fake, frame=False): + assert show(client).status_code == 401 + assert client.get("/api/immich/albums").status_code == 401 # lists personal data + assert client.get("/api/immich/people").status_code == 401 + assert client.post("/api/immich/people/refresh").status_code == 401 + assert client.get("/api/immich/albums", headers=headers).status_code == 200 + shown = client.post("/api/display/immich", json={"push_to_fraimic": False}, headers=headers) + assert shown.status_code == 200 + + +def test_multi_account_configuration_over_the_api(make_client: ClientFactory) -> None: + home = FakeImmich("http://home.test", "k-home") + partner = FakeImmich("http://partner.test", "k-partner") + home.add_asset("h1", checksum="dup") + partner.add_asset("p1", checksum="dup") + partner.add_asset("p2", checksum="uniq-partner") + client = make_client(fraimic_host="frame.test") + saved = client.put( + "/api/config", + json={ + "immich": { + "accounts": { + "home": {"url": home.base, "api_key": "k-home"}, + "partner": {"url": partner.base, "api_key": "k-partner"}, + } + } + }, + ) + assert saved.status_code == 200 and "k-home" not in saved.text + with servers(home, partner, frame=False): + picked = { + show(client, push_to_fraimic=False, ignore_history=True).json()["image"]["details"][ + "asset_id" + ] + for _ in range(4) + } + only = show(client, accounts=["partner"], push_to_fraimic=False, ignore_history=True) + assert picked <= {"h1", "p1", "p2"} + assert only.json()["image"]["details"]["account"] == "partner" From 3ff77aa1c92db483c43adfdd7372522f8c18418e Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sat, 14 Nov 2026 20:18:40 +0100 Subject: [PATCH 30/86] docs: document Immich provider, accounts, aliases and safe margin Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- .env.example | 3 ++ CLAUDE.md | 3 +- README.md | 79 +++++++++++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 83 insertions(+), 2 deletions(-) diff --git a/.env.example b/.env.example index e0ae194..8198b06 100644 --- a/.env.example +++ b/.env.example @@ -46,6 +46,9 @@ LOG_LEVEL=INFO # DATA_DIR=/data # --- Immich (runtime default) ------------------------------------------------ +# Seeds one Immich account named "default". Add more accounts (a partner, a shared +# library) under immich.accounts in the settings / PUT /api/config. +# A LAN address needs URL_ALLOWLIST when BLOCK_PRIVATE_URLS=true. IMMICH_URL=http://immich.local:2283 IMMICH_API_KEY= diff --git a/CLAUDE.md b/CLAUDE.md index 0f0f3e1..a1f09a3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -53,7 +53,8 @@ Clean, responsive (mobile/desktop) English web interface allowing users to: - Configure all application settings without editing files manually (persisted to `/data/config.json`). ### 5. REST API (`GET /docs`) -- `POST /api/display/immich`: Select and display an Immich photo (`persons`, `match_mode`, `album`, `push_to_fraimic`). +- `POST /api/display/immich`: Select and display an Immich photo (`mode` random|album|favorites|search, `persons` as plain names, `match_mode`, `always_include`, `album_name`/`album_id`, `clip_queries`, `accounts`, `fit`, `push_to_fraimic`, `ignore_history`). +- `GET /api/immich/albums`, `GET /api/immich/people`, `POST /api/immich/people/refresh`: Discovery across the configured Immich accounts (`immich.accounts`; keys are masked and `GET /api/immich/*` is API-key protected when `APP_API_KEY` is set). - `POST /api/display/media`: Search and display an HD poster (`title`, `media_type`, `fallback_url`, `push_to_fraimic`). - `POST /api/fraimic/wakeup`: Webhook signaling frame wake-up to flush any queued upload immediately. - `POST /api/refresh`: Re-run the currently active source rule. diff --git a/README.md b/README.md index cb1816d..cdbdf0c 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,13 @@ black / white background), enhanced (brightness 1.1, contrast 1.2, saturation 1. edge-enhance, smooth, sharpen) and dithered onto the 6-color Spectra 6 palette with the official tuned color metric. Dithering is vectorized along anti-diagonals: the Atkinson output is byte-identical to the official Fraimic converter while running in -about 0.7 s (13.3") / 1.1 s (31.5") instead of ~40 s. +about 0.7 s (13.3") / 1.1 s (31.5") instead of ~40 s. Landscape mode rotates the image +into the panel's portrait buffer *before* dithering, like the official `--fit rotate`, +so its `.bin` is byte-identical too. HEIC/HEIF (iPhone) images decode natively. + +If a mat or bezel hides the panel edges, set `display.safe_margin_px` (default `0`): +the picture is inset by that many pixels on every side and the margin is filled with +`display.contain_background`. Generated files (`./data/cache/`): @@ -41,6 +47,77 @@ Generated files (`./data/cache/`): | `current_dithered.png` | `GET /api/current_dithered.png` | Exact 6-color preview of the panel | | `current.bin` | `GET /api/current.bin` | Frame buffer sent to the frame (960,000 / 2,304,000 bytes) | +## Immich + +Photos come from one or several [Immich](https://immich.app) accounts. Pinned against +Immich 3.3.5 (`/api/spec.json`); payloads are parsed leniently. + +```bash +# Quickstart: one account from .env (named "default") +IMMICH_URL=http://immich.lan:2283 +IMMICH_API_KEY=... + +# A random photo with Alice and Bob together +curl -X POST http://localhost:8000/api/display/immich -H 'Content-Type: application/json' \ + -d '{"persons": ["Alice", "Bob"], "match_mode": "all"}' + +# CLIP search, favorites, or an album +curl -X POST .../api/display/immich -H 'Content-Type: application/json' -d '{"mode": "search", "clip_queries": ["snowy mountains"]}' +curl -X POST .../api/display/immich -H 'Content-Type: application/json' -d '{"mode": "favorites"}' +curl -X POST .../api/display/immich -H 'Content-Type: application/json' -d '{"mode": "album", "album_name": "Holidays"}' +``` + +| Request field | Meaning | +| --- | --- | +| `mode` | `random` (default), `album`, `favorites` or `search` (CLIP, needs `clip_queries`) | +| `persons`, `match_mode` | Plain person **names** (never Home Assistant entity IDs); `any` or `all` of them | +| `always_include` | Names merged into every selection (e.g. a child without an HA account). Defaults to `immich.always_include`; send `[]` to switch it off | +| `album_name` / `album_id` | Restrict to an album (names are case-insensitive) | +| `accounts` | Limit to some accounts | +| `fit`, `push_to_fraimic`, `ignore_history` | Fit override, push to the frame (default true), allow recently shown photos | + +Unset filters fall back to the `immich` section of the settings. All modes share one +query path, so persons, albums and favorites combine freely. + +**Accounts.** `immich.accounts` is a named map (`url` + `api_key`); `IMMICH_URL` / +`IMMICH_API_KEY` seed an account called `default` (saved settings win over `.env`). API keys +are masked in `GET /api/config`, and sending the masked view back keeps the stored key. + +```json +{"immich": { + "accounts": {"home": {"url": "http://immich.lan:2283", "api_key": "..."}, + "partner": {"url": "https://photos.example.org", "api_key": "..."}}, + "always_include": ["Kid"], + "person_aliases": {"Marie": {"partner": ["Maman", "0b7e1c3a-0000-0000-0000-000000000000"]}} +}} +``` + +**People.** Names are resolved per account from `GET /api/immich/people` (cached for +`people_cache_ttl_s`, refresh with `POST /api/immich/people/refresh`). Two people with the +same name in one account are rejected with a hint to pin an ID in `person_aliases`; +unknown names get "did you mean" suggestions. `person_aliases` maps a canonical name to +IDs or names that exist in a given account. + +**Selection.** Candidates of all accounts are merged, de-duplicated by content checksum +(the same photo in two accounts counts once) and filtered by the anti-repeat history +(`immich.anti_repeat_days`, shared across accounts), then one is picked at random. The +original is downloaded at full resolution (HEIC works); RAW files and files larger than +`MAX_UPLOAD_MB` use Immich's converted JPEG (`fullsize`, then `preview`). + +**Face-aware crop.** Face boxes of the requested people drive `smart_crop` (all faces are +the fallback), padded by 25% for hair and shoulders. When two faces are too far apart for +the crop window, the larger one is kept whole instead of slicing both. Edited Immich assets +are cropped without face boxes. + +| Endpoint | Purpose | +| --- | --- | +| `POST /api/display/immich` | Select, render, deliver and record a photo | +| `GET /api/immich/albums` | Albums across accounts (`?accounts=`) | +| `GET /api/immich/people` / `POST /api/immich/people/refresh` | Resolved people per account, ambiguity and alias mapping | + +`GET /api/immich/*` requires the API key when `APP_API_KEY` is set (it lists family member +names). A LAN Immich needs `URL_ALLOWLIST` when `BLOCK_PRIVATE_URLS=true`. + ## Frame delivery The frame is driven through its local REST API (`GET /api/info`, `POST /api/image`). From 6c10bb970729ee77e6b1ab6a4338b827cc8542eb Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sat, 14 Nov 2026 20:30:26 +0100 Subject: [PATCH 31/86] fix: reschedule the delivery worker after a failed attempt An idle worker kept the sleep it computed before a failed immediate attempt (e.g. POST /api/fraimic/push against a sleeping frame): in deepsleep mode it waited for a wake-up that never came, so the queued image was never retried. A failed attempt now makes the worker recompute its schedule without flushing, and explicit wake-ups (submit, webhook, config change) stay distinct from it. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- app/services/delivery.py | 26 +++++++++++++++++++------- tests/test_delivery.py | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 7 deletions(-) diff --git a/app/services/delivery.py b/app/services/delivery.py index 376d4ee..e85c57d 100644 --- a/app/services/delivery.py +++ b/app/services/delivery.py @@ -139,6 +139,7 @@ def __init__( self._state_lock = asyncio.Lock() # pending files + in-memory pending state self._upload_lock = asyncio.Lock() # one upload at a time self._wake = asyncio.Event() + self._signalled = False # an explicit wake-up (vs. a mere reschedule) self._task: asyncio.Task[None] | None = None self._background: set[asyncio.Task[DeliveryOutcome]] = set() @@ -248,7 +249,7 @@ async def submit( attempt_now = config.fraimic.power_mode == "continuous" if immediate is None else immediate if attempt_now: return await self.flush("force" if immediate else "submit") - self._wake.set() + self._signal() return DeliveryOutcome(status="queued", reason="submit", sha256=pending.sha256) async def flush(self, reason: DeliveryReason = "wakeup") -> DeliveryOutcome: @@ -289,7 +290,7 @@ async def flush(self, reason: DeliveryReason = "wakeup") -> DeliveryOutcome: await asyncio.to_thread(remove_quietly, self._bin_path, self._meta_path) self._pending = None else: - self._wake.set() # a newer image arrived during the upload + self._signal() # a newer image arrived during the upload logger.info("Delivered image %s to the frame (%s)", pending.sha256[:12], reason) return DeliveryOutcome( status="delivered", @@ -335,6 +336,15 @@ async def refresh_info(self) -> FrameInfo: def wake(self) -> None: """Wake the worker so it re-evaluates immediately.""" + self._signal() + + def _signal(self) -> None: + """Explicit wake-up: the worker acts now (flush) instead of waiting for its timer.""" + self._signalled = True + self._wake.set() + + def _reschedule(self) -> None: + """The schedule changed (e.g. a failed attempt): recompute the sleep, do not flush.""" self._wake.set() # --- Worker --------------------------------------------------------------------------- @@ -354,18 +364,19 @@ def next_wait(self) -> float | None: async def _run(self) -> None: while True: - woken = False + timed_out = False try: timeout = self.next_wait() if timeout is None: await self._wake.wait() - woken = True else: await asyncio.wait_for(self._wake.wait(), timeout) - woken = True except TimeoutError: - pass + timed_out = True self._wake.clear() + woken, self._signalled = self._signalled, False + if not timed_out and not woken: + continue # only the schedule changed: recompute the sleep first try: await self._tick(woken) except asyncio.CancelledError: @@ -450,6 +461,7 @@ async def _record_failure( else: level = logging.INFO logger.log(level, "Frame delivery failed (%s, attempt %d): %s", reason, attempts, exc) + self._reschedule() # the worker may be sleeping on a timer computed before this failure async def _refresh_quietly(self) -> DeliveryOutcome: with contextlib.suppress(FraimicError): @@ -472,7 +484,7 @@ async def _on_config_change(self, config: RuntimeConfig) -> None: ) await asyncio.to_thread(remove_quietly, self._bin_path, self._meta_path) self._pending = None - self._wake.set() + self._signal() def _write_pending(self, data: bytes, pending: PendingUpload) -> None: atomic_write_bytes(self._bin_path, data) diff --git a/tests/test_delivery.py b/tests/test_delivery.py index 88b0db5..31f22fa 100644 --- a/tests/test_delivery.py +++ b/tests/test_delivery.py @@ -207,6 +207,44 @@ async def test_deepsleep_worker_delivers_once_frame_answers(make_service: Servic assert service.snapshot().telemetry.online is True +@respx.mock +async def test_failed_forced_push_reschedules_an_idle_deepsleep_worker( + make_service: ServiceFactory, monkeypatch: pytest.MonkeyPatch +) -> None: + """Regression: the worker kept the sleep it computed *before* a failed forced push. + + An idle deepsleep worker waits "until woken"; after ``POST /api/fraimic/push`` failed + against a sleeping frame nothing woke it, so the frame stayed unreachable for the + app even after it woke up. + """ + info = respx.get(INFO_URL).mock(side_effect=httpx.ConnectTimeout("asleep")) + upload = respx.post(IMAGE_URL).respond(200) + service = make_service("deepsleep") + monkeypatch.setattr(service, "next_wait", lambda: None if service.pending is None else 0.05) + await service.start() + await asyncio.sleep(0.05) # the worker is now sleeping on its idle timer + + outcome = await service.submit(BIN_A, immediate=True) # e.g. POST /api/fraimic/push + assert outcome.status == "queued" + + info.mock(return_value=httpx.Response(200, json=INFO)) # the frame wakes up + await eventually(lambda: service.pending is None) # no manual wake() + assert upload.call_count == 1 + + +@respx.mock +async def test_retry_schedule_does_not_spin( + make_service: ServiceFactory, monkeypatch: pytest.MonkeyPatch +) -> None: + info = respx.get(INFO_URL).mock(side_effect=httpx.ConnectTimeout("asleep")) + service = make_service("deepsleep") + monkeypatch.setattr(service, "next_wait", lambda: None if service.pending is None else 0.1) + await service.start() + await service.submit(BIN_A, immediate=True) + await asyncio.sleep(0.5) + assert 2 <= info.call_count <= 8 # roughly one probe per 0.1 s, never a hot loop + + @respx.mock async def test_wakeup_wait_delivers(make_service: ServiceFactory) -> None: respx.get(INFO_URL).respond(json=INFO) From 0abe8558c0d5c0b89f0d72b9c1455f68c009338f Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sat, 14 Nov 2026 20:52:17 +0100 Subject: [PATCH 32/86] feat: add eink.profile with a softer photo preset The official edge-enhance/sharpen chain and +20% saturation/contrast make dim indoor photos look outlined, over-saturated and grainy on the Spectra 6 panel. eink.profile=photo applies softer values (no edge filters, saturation 0.85, sharpness 0.8); official stays the default so output remains byte-identical to the official converter. RenderOptions.from_config accepts a per-source profile override for later poster sources. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- README.md | 8 ++++++++ app/core/config_models.py | 29 +++++++++++++++++++++++++++++ app/processor/pipeline.py | 20 ++++++++++++++++---- tests/test_api.py | 8 ++++++++ tests/test_config_models.py | 29 +++++++++++++++++++++++++++++ tests/test_pipeline.py | 19 +++++++++++++++++++ 6 files changed, 109 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index cdbdf0c..206b12f 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,14 @@ about 0.7 s (13.3") / 1.1 s (31.5") instead of ~40 s. Landscape mode rotates the into the panel's portrait buffer *before* dithering, like the official `--fit rotate`, so its `.bin` is byte-identical too. HEIC/HEIF (iPhone) images decode natively. +**Photos vs the official look.** The official settings (contrast and saturation +20%, +edge-enhance/sharpen chain) suit posters and graphics, but make dim indoor photos look +outlined, over-saturated and grainy on the panel. Set `eink.profile` to `photo` for a softer +result (no edge filters, saturation 0.85, sharpness 0.8, brightness and contrast 1.0; dithering +stays as configured). `official` (default) keeps the values of the `eink` fields, whose +defaults are the official converter's. Tested on a real 13.3" panel: lifting brightness, +white-balance correction and dither jitter did not improve on it. + If a mat or bezel hides the panel edges, set `display.safe_margin_px` (default `0`): the picture is inset by that many pixels on every side and the margin is filled with `display.contain_background`. diff --git a/app/core/config_models.py b/app/core/config_models.py index a1ffd4c..cfef066 100644 --- a/app/core/config_models.py +++ b/app/core/config_models.py @@ -29,6 +29,7 @@ Orientation = Literal["portrait", "landscape"] FitMode = Literal["smart_crop", "contain"] DitherAlgorithm = Literal["atkinson", "floyd_steinberg"] +EinkProfile = Literal["official", "photo"] PowerMode = Literal["continuous", "deepsleep"] @@ -280,9 +281,27 @@ class DisplayConfig(_Section): ) +#: Values of the ``photo`` profile, tuned on a real Spectra 6 panel with indoor photos: the +#: official edge-enhance/sharpen chain and +20% saturation/contrast make photos look +#: outlined, over-saturated and grainy. Dithering stays as configured. +PHOTO_PROFILE: Final[dict[str, float | bool]] = { + "brightness": 1.0, + "contrast": 1.0, + "saturation": 0.85, + "sharpness": 0.8, + "edge_filters": False, +} + + class EinkConfig(_Section): """Color eInk optimization. Defaults mirror the official Fraimic converter.""" + profile: EinkProfile = Field( + default="official", + description="official = the values below (defaults = official converter); photo = softer " + "preset for photographs that overrides brightness, contrast, saturation, sharpness " + "and edge_filters", + ) brightness: float = Field(default=1.1, ge=0.1, le=3.0, description="1.0 = unchanged") contrast: float = Field(default=1.2, ge=0.1, le=3.0, description="1.0 = unchanged") saturation: float = Field(default=1.2, ge=0.0, le=3.0, description="1.0 = unchanged") @@ -295,6 +314,16 @@ class EinkConfig(_Section): description="atkinson = tuned color metric (official default); floyd_steinberg = classic", ) + def effective(self, profile: EinkProfile | None = None) -> EinkConfig: + """The values actually used for rendering after applying the profile. + + Args: + profile: Overrides :attr:`profile` (e.g. a poster source forcing ``official``). + """ + if (profile or self.profile) == "official": + return self + return self.model_copy(update=PHOTO_PROFILE) + class SourceRule(BaseModel): """The last source request, replayed by ``/api/refresh`` and the scheduler.""" diff --git a/app/processor/pipeline.py b/app/processor/pipeline.py index 572684e..190dbd3 100644 --- a/app/processor/pipeline.py +++ b/app/processor/pipeline.py @@ -26,7 +26,7 @@ import numpy.typing as npt from PIL import Image, ImageOps -from app.core.config_models import EinkConfig, FitMode, PanelSpec, RuntimeConfig +from app.core.config_models import EinkConfig, EinkProfile, FitMode, PanelSpec, RuntimeConfig from app.core.security import verify_image_bytes from app.processor.dither import dither from app.processor.enhance import enhance @@ -90,8 +90,20 @@ def __post_init__(self) -> None: raise ValueError("safe_margin_px must be between 0 and a quarter of the short side") @classmethod - def from_config(cls, config: RuntimeConfig, *, fit: FitMode | None = None) -> RenderOptions: - """Build options from the effective config, optionally overriding the fit mode.""" + def from_config( + cls, + config: RuntimeConfig, + *, + fit: FitMode | None = None, + eink_profile: EinkProfile | None = None, + ) -> RenderOptions: + """Build options from the effective config. + + Args: + config: Effective runtime configuration. + fit: Overrides the default fit mode. + eink_profile: Overrides ``eink.profile`` (e.g. posters always use ``official``). + """ rotation: Rotation = ( 0 if config.display.orientation == "portrait" else config.display.landscape_rotation ) @@ -101,7 +113,7 @@ def from_config(cls, config: RuntimeConfig, *, fit: FitMode | None = None) -> Re rotation=rotation, fit=fit or config.display.default_fit, background=config.display.contain_background, - eink=config.eink, + eink=config.eink.effective(eink_profile), safe_margin_px=config.display.safe_margin_px, ) diff --git a/tests/test_api.py b/tests/test_api.py index 71f2dfb..28b2bd3 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -136,3 +136,11 @@ def test_config_api_masks_immich_account_keys(make_client: ClientFactory) -> Non ) assert rejected.status_code == 422 assert "home-secret-key-1111" not in rejected.text + + +def test_eink_profile_is_configurable_over_the_api(make_client: ClientFactory) -> None: + client = make_client() + assert client.get("/api/config").json()["config"]["eink"]["profile"] == "official" + assert client.put("/api/config", json={"eink": {"profile": "photo"}}).status_code == 200 + assert client.get("/api/config").json()["config"]["eink"]["profile"] == "photo" + assert client.put("/api/config", json={"eink": {"profile": "poster"}}).status_code == 422 diff --git a/tests/test_config_models.py b/tests/test_config_models.py index c511ab0..67573a6 100644 --- a/tests/test_config_models.py +++ b/tests/test_config_models.py @@ -182,3 +182,32 @@ def test_dump_config_reveals_or_masks_secrets() -> None: assert "immich-secret-key-1234" not in str(masked) assert masked["tmdb"]["api_key"] == MASK_PREFIX assert RuntimeConfig.model_validate(revealed) == config + + +# --- eInk profiles ----------------------------------------------------------------------------- +def test_official_profile_is_the_default_and_leaves_values_untouched() -> None: + from app.core.config_models import EinkConfig + + config = EinkConfig(contrast=1.4, dither="floyd_steinberg") + assert config.profile == "official" + assert config.effective() is config + + +def test_photo_profile_overrides_the_five_tuning_fields_but_keeps_dithering() -> None: + from app.core.config_models import PHOTO_PROFILE, EinkConfig + + config = EinkConfig(profile="photo", contrast=1.5, dither="floyd_steinberg") + effective = config.effective() + for name, value in PHOTO_PROFILE.items(): + assert getattr(effective, name) == value + assert effective.dither == "floyd_steinberg" + assert effective.edge_filters is False and effective.saturation == 0.85 + assert config.contrast == 1.5 # the stored configuration is not modified + + +def test_effective_profile_can_be_forced_per_source() -> None: + from app.core.config_models import EinkConfig + + photo = EinkConfig(profile="photo") + assert photo.effective("official") is photo + assert EinkConfig().effective("photo").saturation == 0.85 diff --git a/tests/test_pipeline.py b/tests/test_pipeline.py index 1b92fe6..a0b45b7 100644 --- a/tests/test_pipeline.py +++ b/tests/test_pipeline.py @@ -278,3 +278,22 @@ def test_safe_margin_validation() -> None: config(display={"safe_margin_px": -1}) with pytest.raises(ValueError): config(display={"safe_margin_px": 251}) + + +# --- eInk profiles ------------------------------------------------------------------------------- +def test_photo_profile_reaches_the_render_options_and_changes_the_output() -> None: + official = RenderOptions.from_config(config()) + photo = RenderOptions.from_config(config(eink={"profile": "photo"})) + assert official.eink.edge_filters is True and official.eink.saturation == 1.2 + assert photo.eink.edge_filters is False and photo.eink.saturation == 0.85 + + rng = np.random.default_rng(41) + image = Image.fromarray(rng.integers(0, 256, (900, 1600, 3), dtype=np.uint8)) + assert not np.array_equal( + np.asarray(compose(image, official)), np.asarray(compose(image, photo)) + ) + + +def test_profile_can_be_forced_when_building_options() -> None: + forced = RenderOptions.from_config(config(eink={"profile": "photo"}), eink_profile="official") + assert forced.eink.saturation == 1.2 and forced.eink.edge_filters is True From f3f4562513cd1f899ca44fdea3be27e85b5bb18a Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sat, 14 Nov 2026 21:59:57 +0100 Subject: [PATCH 33/86] feat: persist taken_at in the history and detect bursts HistoryEntry gains an optional taken_at (older files still load). HistoryStore.near_recent tells whether a recently shown picture was taken within N hours of a candidate, so rapid-fire shots of one moment are not shown back-to-back. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- app/core/history_store.py | 48 ++++++++++++++++++++++++-- tests/test_history_store.py | 68 +++++++++++++++++++++++++++++++++++++ 2 files changed, 114 insertions(+), 2 deletions(-) diff --git a/app/core/history_store.py b/app/core/history_store.py index a9936ec..0db5547 100644 --- a/app/core/history_store.py +++ b/app/core/history_store.py @@ -17,6 +17,13 @@ HISTORY_FORMAT_VERSION = 1 +def _as_utc(value: datetime | None) -> datetime | None: + """Normalize a datetime to UTC (naive values are assumed to already be UTC).""" + if value is None: + return None + return value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC) + + class HistoryEntry(BaseModel): """One image that was displayed on the frame.""" @@ -25,6 +32,10 @@ class HistoryEntry(BaseModel): asset_id: str = Field(min_length=1, description="Provider-specific asset identifier") source: str = Field(min_length=1, description="Provider name, e.g. 'immich'") shown_at: AwareDatetime = Field(description="When the image was displayed (UTC)") + taken_at: AwareDatetime | None = Field( + default=None, + description="When the picture was taken (UTC), if the source knows; enables burst cooldown", + ) class HistoryStore: @@ -69,7 +80,11 @@ def load(self) -> None: self._entries = self._prune(entries, datetime.now(UTC)) async def record( - self, asset_id: str, source: str, shown_at: datetime | None = None + self, + asset_id: str, + source: str, + shown_at: datetime | None = None, + taken_at: datetime | None = None, ) -> HistoryEntry: """Append an entry and persist the history. @@ -77,10 +92,14 @@ async def record( asset_id: Provider-specific identifier of the displayed asset. source: Provider name. shown_at: Display time (timezone-aware); defaults to now. + taken_at: When the picture was taken (naive values are treated as UTC). """ now = datetime.now(UTC) entry = HistoryEntry( - asset_id=asset_id, source=source, shown_at=(shown_at or now).astimezone(UTC) + asset_id=asset_id, + source=source, + shown_at=(shown_at or now).astimezone(UTC), + taken_at=_as_utc(taken_at), ) async with self._lock: entries = sorted([*self._entries, entry], key=lambda item: item.shown_at) @@ -100,6 +119,31 @@ def recent_ids(self, source: str, within_days: int) -> set[str]: if entry.source == source and entry.shown_at >= cutoff } + def near_recent( + self, source: str, taken_at: datetime | None, *, within_hours: float, shown_within_days: int + ) -> bool: + """Whether a recently shown picture was taken close to ``taken_at`` (a "burst"). + + Rapid-fire shots of one moment look alike; once one was shown, the others of the + same moment should not follow back-to-back. + + Args: + source: Provider name. + taken_at: Capture time of the candidate (``None`` = unknown, never a burst). + within_hours: Maximum distance between the two capture times (either direction). + shown_within_days: Only entries displayed within this many days count. + """ + moment = _as_utc(taken_at) + if moment is None or within_hours <= 0 or shown_within_days <= 0: + return False + shown_cutoff = datetime.now(UTC) - timedelta(days=shown_within_days) + window = timedelta(hours=within_hours) + return any( + entry.taken_at is not None and abs(entry.taken_at - moment) <= window + for entry in self._entries + if entry.source == source and entry.shown_at >= shown_cutoff + ) + def entries(self, limit: int | None = None) -> list[HistoryEntry]: """Entries, newest first, optionally limited.""" newest_first = list(reversed(self._entries)) diff --git a/tests/test_history_store.py b/tests/test_history_store.py index 98c46bd..95e1efc 100644 --- a/tests/test_history_store.py +++ b/tests/test_history_store.py @@ -77,3 +77,71 @@ def test_malformed_entries_are_skipped(history_path: Path) -> None: def test_invalid_limits_rejected(history_path: Path) -> None: with pytest.raises(ValueError): HistoryStore(history_path, max_entries=0) + + +# --- taken_at and burst detection --------------------------------------------------------------- +async def test_taken_at_is_persisted_and_naive_values_are_utc(history_path: Path) -> None: + store = HistoryStore(history_path) + store.load() + await store.record("a1", "immich", taken_at=datetime(2024, 7, 14, 10, 0, tzinfo=UTC)) + await store.record("a2", "immich", taken_at=datetime(2024, 7, 14, 12, 30)) # naive + await store.record("a3", "immich") + + reloaded = HistoryStore(history_path) + reloaded.load() + by_id = {entry.asset_id: entry for entry in reloaded.entries()} + assert by_id["a1"].taken_at == datetime(2024, 7, 14, 10, 0, tzinfo=UTC) + assert by_id["a2"].taken_at == datetime(2024, 7, 14, 12, 30, tzinfo=UTC) + assert by_id["a3"].taken_at is None + + +def test_entries_written_before_taken_at_existed_still_load(history_path: Path) -> None: + old = { + "version": 1, + "entries": [ + {"asset_id": "a1", "source": "immich", "shown_at": datetime.now(UTC).isoformat()} + ], + } + history_path.write_text(json.dumps(old), encoding="utf-8") + store = HistoryStore(history_path) + store.load() + assert store.entries()[0].taken_at is None + assert store.recent_ids("immich", 30) == {"a1"} + + +async def test_near_recent_detects_bursts_in_both_directions(history_path: Path) -> None: + store = HistoryStore(history_path) + store.load() + shot = datetime(2024, 7, 14, 10, 0, tzinfo=UTC) + await store.record("a1", "immich", taken_at=shot) + + def near(offset_hours: float, **kwargs: float) -> bool: + taken = shot + timedelta(hours=offset_hours) + return store.near_recent( + "immich", taken, within_hours=kwargs.get("hours", 2), shown_within_days=30 + ) + + assert near(0.5) and near(-0.5) and near(2) and near(-2) # the window is inclusive + assert not near(2.01) and not near(-3) and not near(48) + assert near(5, hours=6) and not near(7, hours=6) + + +async def test_near_recent_ignores_unknown_times_old_entries_and_other_sources( + history_path: Path, +) -> None: + store = HistoryStore(history_path) + store.load() + shot = datetime(2024, 7, 14, 10, 0, tzinfo=UTC) + now = datetime.now(UTC) + await store.record("old", "immich", now - timedelta(days=40), taken_at=shot) + await store.record("poster", "media", now, taken_at=shot) + await store.record("no-time", "immich", now) + + def near(taken: datetime | None, *, days: int = 30, hours: float = 2) -> bool: + return store.near_recent("immich", taken, within_hours=hours, shown_within_days=days) + + assert not near(shot) # the match was shown too long ago / by another source + assert near(shot, days=60) # ... but counts when the shown-window is wide enough + assert not near(None, days=60) # unknown capture time is never a burst + assert not near(shot, days=60, hours=0) # disabled + assert not near(shot, days=0) From 3eb39d79643875aa9634368f9425616cbe6d9ff5 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sat, 14 Nov 2026 21:59:57 +0100 Subject: [PATCH 34/86] feat: add photo quality gate rules with progressive relaxation Cheap thumbnail statistics plus metadata decide whether a photo suits the 6-color panel: blank frames, tiny images, screenshots/graphics and document scans are rejected; black-and-white portraits, night shots and scans stay. Thresholds come from a calibration on ~400 real photos and live in the new quality config section. Four relaxation levels loosen the rules when a whole batch fails. Adds immich.burst_cooldown_hours (default 2). Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- app/core/config_models.py | 56 ++++++++++++ app/processor/quality.py | 145 ++++++++++++++++++++++++++++++ tests/test_api.py | 1 + tests/test_quality.py | 179 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 381 insertions(+) create mode 100644 app/processor/quality.py create mode 100644 tests/test_quality.py diff --git a/app/core/config_models.py b/app/core/config_models.py index cfef066..bbf59ee 100644 --- a/app/core/config_models.py +++ b/app/core/config_models.py @@ -140,6 +140,13 @@ class ImmichConfig(_Section): anti_repeat_days: int = Field( default=30, ge=0, le=3650, description="Do not show the same photo again within N days" ) + burst_cooldown_hours: float = Field( + default=2.0, + ge=0, + le=168, + description="After a photo was shown, skip photos taken within this many hours of it " + "(rapid-fire shots of one moment); 0 = off. Uses anti_repeat_days as the memory.", + ) people_cache_ttl_s: int = Field( default=3600, ge=0, le=604_800, description="How long the people list is cached (0 = off)" ) @@ -325,6 +332,54 @@ def effective(self, profile: EinkProfile | None = None) -> EinkConfig: return self.model_copy(update=PHOTO_PROFILE) +class QualityConfig(_Section): + """Photo suitability gate: skips images a 6-color eInk panel renders badly. + + Thresholds were calibrated on ~400 real photos (thumbnails): they catch blank frames, + tiny images, screenshots/graphics and document scans while keeping black-and-white + portraits and night shots. If a whole batch of candidates fails, the gate relaxes + step by step instead of finding nothing (see ``app.processor.quality``). + """ + + enabled: bool = Field(default=True, description="Check photos before downloading them") + candidates_checked: int = Field( + default=8, ge=1, le=50, description="Max candidates inspected per request" + ) + min_dimension: int = Field( + default=600, ge=0, le=4000, description="Reject images whose short side is below this (px)" + ) + blank_luma_mean: float = Field( + default=15.0, ge=0, le=255, description="Reject near-black frames (mean luma below)" + ) + blank_luma_std: float = Field( + default=8.0, ge=0, le=128, description="Reject flat frames (luma std-dev below)" + ) + screenshot_flat_share: float = Field( + default=35.0, + ge=1, + le=100, + description="No camera EXIF and this % of pixels one bright color", + ) + screenshot_flat_luma: float = Field( + default=128.0, ge=0, le=255, description="Luma above which the flat color counts as bright" + ) + screenshot_aspect: float = Field( + default=1.9, + ge=1, + le=10, + description="No camera EXIF and aspect at least this (phone screen)", + ) + screenshot_max_dimension: int = Field( + default=1300, ge=0, le=10000, description="... and short side at most this (px)" + ) + document_colorfulness: float = Field( + default=15.0, ge=0, le=255, description="No camera EXIF, colorfulness below this ..." + ) + document_white_share: float = Field( + default=15.0, ge=0, le=100, description="... and at least this % of near-white pixels" + ) + + class SourceRule(BaseModel): """The last source request, replayed by ``/api/refresh`` and the scheduler.""" @@ -390,6 +445,7 @@ class RuntimeConfig(BaseModel): display: DisplayConfig = Field(default_factory=DisplayConfig) eink: EinkConfig = Field(default_factory=EinkConfig) scheduler: SchedulerConfig = Field(default_factory=SchedulerConfig) + quality: QualityConfig = Field(default_factory=QualityConfig) @property def frame_size(self) -> tuple[int, int]: diff --git a/app/processor/quality.py b/app/processor/quality.py new file mode 100644 index 0000000..22a4177 --- /dev/null +++ b/app/processor/quality.py @@ -0,0 +1,145 @@ +"""Photo suitability gate for the 6-color eInk panel. + +Instead of degrading a poor photo with heavy processing, the gate decides cheaply (on a +~250 px thumbnail and a little metadata) whether a photo is worth showing at all. It never +modifies pixels. The rules and defaults come from a calibration run on ~400 real photos: + +* ``blank`` - near-black or flat frames. +* ``tiny`` - images whose short side is below ``min_dimension`` (avatars, icons). +* ``screenshot`` - no camera EXIF and either one bright flat color covering a large share + of the image (UI, graphics) or a tall phone-screen shape. +* ``document`` - no camera EXIF, washed out and mostly white (scans, pages). + +Deliberately *not* rejected: black-and-white portraits (they dither beautifully), night +shots, scanned family photos and low-contrast snow scenes. "No camera EXIF" alone is never +enough because scans and shared pictures lack it. + +Progressive relaxation (:data:`LEVELS`) lets callers loosen the rules step by step when a +whole batch of candidates fails, so a request never dead-ends. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Final + +import numpy as np +from PIL import Image + +from app.core.config_models import QualityConfig + +#: Rule sets, strictest first. Level ``LEVELS`` (and above) means "accept anything". +LEVELS: Final = 4 +THUMBNAIL_LIMIT: Final = 256 +_BRIGHT_PIXEL: Final = 250 + + +@dataclass(frozen=True, slots=True) +class ImageStats: + """Cheap pixel statistics of a (thumbnail-sized) image.""" + + luma_mean: float + luma_std: float + flat_share: float # % of pixels sharing the most common (5-bit quantized) color + flat_luma: float # luma of that most common color + colorfulness: float # Hasler-Susstrunk colorfulness + white_share: float # % of near-white pixels + + +@dataclass(frozen=True, slots=True) +class AssetFacts: + """What the source knows about the picture without looking at pixels.""" + + has_camera: bool + width: int | None = None + height: int | None = None + + @property + def short_side(self) -> int | None: + if not self.width or not self.height: + return None + return min(self.width, self.height) + + @property + def aspect(self) -> float | None: + if not self.width or not self.height: + return None + return max(self.width, self.height) / min(self.width, self.height) + + +def measure(image: Image.Image) -> ImageStats: + """Compute :class:`ImageStats` (works on a copy downscaled to at most 256 px).""" + small = image.convert("RGB") + small.thumbnail((THUMBNAIL_LIMIT, THUMBNAIL_LIMIT)) + rgb = np.asarray(small, dtype=np.float32) + luma = rgb @ np.array([0.299, 0.587, 0.114], dtype=np.float32) + + rg = rgb[..., 0] - rgb[..., 1] + yb = 0.5 * (rgb[..., 0] + rgb[..., 1]) - rgb[..., 2] + colorfulness = float(np.hypot(rg.std(), yb.std()) + 0.3 * np.hypot(rg.mean(), yb.mean())) + + quantized = rgb.astype(np.uint8) >> 3 + codes = ( + quantized[..., 0].astype(np.int32) * 1024 + + quantized[..., 1].astype(np.int32) * 32 + + quantized[..., 2].astype(np.int32) + ).ravel() + counts = np.bincount(codes) + top = int(np.argmax(counts)) + flat_rgb = np.array([(top >> 10) & 31, (top >> 5) & 31, top & 31], dtype=np.float32) * 8 + 4 + flat_luma = float(flat_rgb @ np.array([0.299, 0.587, 0.114], dtype=np.float32)) + + return ImageStats( + luma_mean=float(luma.mean()), + luma_std=float(luma.std()), + flat_share=float(counts[top] / codes.size * 100), + flat_luma=flat_luma, + colorfulness=colorfulness, + white_share=float((rgb >= _BRIGHT_PIXEL).all(axis=2).mean() * 100), + ) + + +def violations( + stats: ImageStats, facts: AssetFacts, config: QualityConfig, level: int = 0 +) -> list[str]: + """Rule names the image breaks at relaxation ``level`` (empty list = suitable). + + Levels: ``0`` all rules; ``1`` halves ``min_dimension`` and drops the phone-shape and + document rules; ``2`` keeps only ``blank`` and the flat-color screenshot rule; ``3`` + keeps only ``blank``; ``4`` and above accept anything. + """ + if level >= LEVELS: + return [] + broken: list[str] = [] + if stats.luma_mean < config.blank_luma_mean or stats.luma_std < config.blank_luma_std: + broken.append("blank") + + short = facts.short_side + min_dimension = config.min_dimension if level == 0 else config.min_dimension // 2 + if level <= 1 and short is not None and short < min_dimension: + broken.append("tiny") + + if level <= 2 and not facts.has_camera: + flat_graphic = ( + stats.flat_share >= config.screenshot_flat_share + and stats.flat_luma >= config.screenshot_flat_luma + ) + aspect = facts.aspect + phone_shape = ( + level == 0 + and aspect is not None + and short is not None + and aspect >= config.screenshot_aspect + and short <= config.screenshot_max_dimension + ) + if flat_graphic or phone_shape: + broken.append("screenshot") + + if ( + level == 0 + and not facts.has_camera + and stats.colorfulness < config.document_colorfulness + and stats.white_share >= config.document_white_share + ): + broken.append("document") + return broken diff --git a/tests/test_api.py b/tests/test_api.py index 28b2bd3..6a21c51 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -100,6 +100,7 @@ def test_config_schema(make_client: ClientFactory) -> None: "display", "eink", "scheduler", + "quality", } diff --git a/tests/test_quality.py b/tests/test_quality.py new file mode 100644 index 0000000..2754401 --- /dev/null +++ b/tests/test_quality.py @@ -0,0 +1,179 @@ +from __future__ import annotations + +import numpy as np +import pytest +from PIL import Image, ImageDraw +from pydantic import ValidationError + +from app.core.config_models import QualityConfig +from app.processor.quality import LEVELS, AssetFacts, ImageStats, measure, violations + +CONFIG = QualityConfig() +CAMERA = AssetFacts(has_camera=True, width=4000, height=3000) +NO_CAMERA = AssetFacts(has_camera=False, width=4000, height=3000) + + +def photo(seed: int = 1, size: tuple[int, int] = (320, 240)) -> Image.Image: + """A busy, colorful, photo-like image.""" + rng = np.random.default_rng(seed) + base = rng.integers(20, 235, (size[1] // 8, size[0] // 8, 3), dtype=np.uint8) + return Image.fromarray(base).resize(size, Image.Resampling.BICUBIC) + + +def ui_screenshot(size: tuple[int, int] = (270, 600)) -> Image.Image: + """White background with a few gray widgets, like an app screen.""" + image = Image.new("RGB", size, "white") + draw = ImageDraw.Draw(image) + for top in range(40, size[1] - 40, 80): + draw.rectangle((20, top, size[0] - 20, top + 30), fill=(225, 228, 235)) + draw.rectangle((0, 0, size[0], 24), fill=(40, 120, 200)) + return image + + +def check(image: Image.Image, facts: AssetFacts, level: int = 0) -> list[str]: + return violations(measure(image), facts, CONFIG, level) + + +# --- measure ------------------------------------------------------------------------------------ +def test_measure_flat_and_busy_images() -> None: + black = measure(Image.new("RGB", (100, 80), "black")) + assert black.luma_mean == 0 and black.luma_std == 0 and black.flat_share == 100 + assert black.flat_luma < 10 and black.white_share == 0 + + white = measure(Image.new("RGB", (100, 80), "white")) + assert white.luma_mean > 250 and white.flat_share == 100 + assert white.flat_luma > 240 and white.white_share == 100 + + busy = measure(photo()) + assert 60 < busy.luma_mean < 190 and busy.luma_std > 30 + assert busy.flat_share < 10 and busy.colorfulness > 25 + + +def test_measure_works_on_a_downscaled_copy_and_does_not_touch_the_input() -> None: + big = photo(size=(2000, 1500)) + before = big.tobytes() + stats = measure(big) + assert big.size == (2000, 1500) and big.tobytes() == before + assert 60 < stats.luma_mean < 190 + + +def test_measure_colorfulness_separates_gray_from_color() -> None: + gray = Image.fromarray(np.tile(np.linspace(0, 255, 200, dtype=np.uint8), (100, 1))) + assert measure(gray).colorfulness < 1 + assert measure(photo()).colorfulness > measure(gray).colorfulness + 20 + + +# --- rules ---------------------------------------------------------------------------------------- +def test_a_normal_photo_passes() -> None: + assert check(photo(), CAMERA) == [] + assert check(photo(), NO_CAMERA) == [] # missing EXIF alone is never a reason + + +@pytest.mark.parametrize( + "image", + [Image.new("RGB", (200, 150), "black"), Image.new("RGB", (200, 150), (9, 9, 9))], +) +def test_blank_frames_are_rejected_even_with_camera_exif(image: Image.Image) -> None: + assert "blank" in check(image, CAMERA) + + +def test_flat_mid_gray_is_blank_by_contrast() -> None: + assert "blank" in check(Image.new("RGB", (200, 150), (120, 120, 120)), CAMERA) + + +def test_tiny_images_are_rejected_by_their_short_side() -> None: + assert check(photo(), AssetFacts(True, 800, 599)) == ["tiny"] + assert check(photo(), AssetFacts(True, 600, 4000)) == [] # exactly at the limit + assert check(photo(), AssetFacts(True, None, None)) == [] # unknown size: not tiny + + +def test_screenshots_need_missing_exif() -> None: + shot = ui_screenshot() + assert "screenshot" in check(shot, AssetFacts(False, 1080, 2400)) + assert check(shot, AssetFacts(True, 1080, 2400)) == [] # a camera took it: keep + + +def test_phone_shaped_images_without_exif_are_screenshots_even_when_busy() -> None: + assert check(photo(), AssetFacts(False, 1080, 2400)) == ["screenshot"] + # Wide or large images are not phone screens. + assert check(photo(), AssetFacts(False, 4000, 3000)) == [] + assert check(photo(), AssetFacts(False, 3024, 6000)) == [] # short side above the limit + + +def test_dark_flat_backgrounds_are_not_screenshots() -> None: + """A lit subject on black (night shot, studio model) must survive without EXIF.""" + image = Image.new("RGB", (320, 240), (4, 4, 6)) + ImageDraw.Draw(image).ellipse((100, 60, 220, 180), fill=(250, 190, 60)) + stats = measure(image) + assert stats.flat_share > 35 and stats.flat_luma < 20 + assert check(image, NO_CAMERA) == [] + + +def test_documents_are_pale_and_mostly_white() -> None: + rng = np.random.default_rng(5) + page = rng.integers(236, 256, (240, 320), dtype=np.uint8) + page[40:44, 30:290] = 40 # a printed line + image = Image.fromarray(np.dstack([page, page, page])) + assert "document" in check(image, NO_CAMERA) + assert "document" not in check(image, CAMERA) + + +def test_black_and_white_portraits_and_night_shots_are_kept() -> None: + ramp = np.tile(np.linspace(10, 245, 320, dtype=np.uint8), (240, 1)) + noise = np.random.default_rng(7).integers(-25, 25, ramp.shape) + gray = np.clip(ramp.astype(int) + noise, 0, 255).astype(np.uint8) + portrait = Image.fromarray(np.dstack([gray, gray, gray])) + assert measure(portrait).colorfulness < 1 + assert check(portrait, NO_CAMERA) == [] # scanned B&W family photo + assert check(portrait, CAMERA) == [] + + night = Image.new("RGB", (320, 240), (3, 3, 5)) + ImageDraw.Draw(night).polygon([(160, 20), (190, 220), (130, 220)], fill=(255, 200, 80)) + assert check(night, CAMERA) == [] + + +def test_reasons_accumulate() -> None: + reasons = check(Image.new("RGB", (100, 100), "black"), AssetFacts(False, 300, 300)) + assert reasons == ["blank", "tiny"] + + +# --- progressive relaxation ----------------------------------------------------------------------- +def test_relaxation_loosens_rules_step_by_step() -> None: + small_ui = ui_screenshot((400, 300)) + facts = AssetFacts(False, 400, 300) + assert check(small_ui, facts, 0) == ["tiny", "screenshot"] + assert check(small_ui, facts, 1) == ["screenshot"] # tiny limit halved to 300 + assert check(small_ui, facts, 2) == ["screenshot"] # the flat-color rule still applies + assert check(small_ui, facts, 3) == [] # only blank frames remain + assert check(small_ui, facts, LEVELS) == [] + + +def test_relaxation_keeps_blank_until_the_last_level() -> None: + black = Image.new("RGB", (400, 300), "black") + for level in range(LEVELS): + assert "blank" in check(black, CAMERA, level) + assert check(black, CAMERA, LEVELS) == [] + + +def test_phone_shape_and_document_rules_only_apply_at_level_zero() -> None: + assert check(photo(), AssetFacts(False, 1080, 2400), 0) == ["screenshot"] + assert check(photo(), AssetFacts(False, 1080, 2400), 1) == [] + + +def test_thresholds_come_from_the_config() -> None: + strict = QualityConfig(min_dimension=1000, blank_luma_mean=100) + stats = ImageStats(80, 40, 2, 100, 40, 0) + assert violations(stats, AssetFacts(True, 900, 900), strict) == ["blank", "tiny"] + assert violations(stats, AssetFacts(True, 900, 900), QualityConfig()) == [] + + +def test_quality_config_validation() -> None: + assert QualityConfig().enabled and QualityConfig().min_dimension == 600 + with pytest.raises(ValidationError): + QualityConfig(min_dimension=-1) + with pytest.raises(ValidationError): + QualityConfig(screenshot_flat_share=0) + with pytest.raises(ValidationError): + QualityConfig(candidates_checked=0) + with pytest.raises(ValidationError): + QualityConfig(unknown_field=1) # type: ignore[call-arg] From 179fb6a3b71def4361c697ef8e96dac9761a9d27 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sat, 14 Nov 2026 22:07:31 +0100 Subject: [PATCH 35/86] feat: vet Immich photos with the quality gate and a burst cooldown ImmichProvider inspects random candidates on their ~250 px thumbnail (and metadata) before downloading any original, rejecting blank frames, tiny images, screenshots/graphics and document scans. If no candidate of a batch passes, the rules relax in four levels so a request never dead-ends; a thumbnail that cannot be read never blocks a photo. skip_quality_gate bypasses it (default: skipped in album mode). Shown photos record taken_at, and photos taken within immich.burst_cooldown_hours of one are skipped. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- CLAUDE.md | 2 +- README.md | 23 ++- app/providers/base.py | 3 + app/providers/immich/models.py | 10 +- app/providers/immich/provider.py | 125 +++++++++++-- app/services/display.py | 2 +- tests/immich_fake.py | 3 + tests/test_api_immich.py | 50 ++++++ tests/test_immich_provider.py | 15 +- tests/test_immich_quality.py | 298 +++++++++++++++++++++++++++++++ 10 files changed, 515 insertions(+), 16 deletions(-) create mode 100644 tests/test_immich_quality.py diff --git a/CLAUDE.md b/CLAUDE.md index a1f09a3..6e6dd58 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -53,7 +53,7 @@ Clean, responsive (mobile/desktop) English web interface allowing users to: - Configure all application settings without editing files manually (persisted to `/data/config.json`). ### 5. REST API (`GET /docs`) -- `POST /api/display/immich`: Select and display an Immich photo (`mode` random|album|favorites|search, `persons` as plain names, `match_mode`, `always_include`, `album_name`/`album_id`, `clip_queries`, `accounts`, `fit`, `push_to_fraimic`, `ignore_history`). +- `POST /api/display/immich`: Select and display an Immich photo (`mode` random|album|favorites|search, `persons` as plain names, `match_mode`, `always_include`, `album_name`/`album_id`, `clip_queries`, `accounts`, `fit`, `push_to_fraimic`, `ignore_history`, `skip_quality_gate`). Photos are vetted by a thumbnail-based quality gate (`quality` settings section) and a burst cooldown before the original is downloaded. - `GET /api/immich/albums`, `GET /api/immich/people`, `POST /api/immich/people/refresh`: Discovery across the configured Immich accounts (`immich.accounts`; keys are masked and `GET /api/immich/*` is API-key protected when `APP_API_KEY` is set). - `POST /api/display/media`: Search and display an HD poster (`title`, `media_type`, `fallback_url`, `push_to_fraimic`). - `POST /api/fraimic/wakeup`: Webhook signaling frame wake-up to flush any queued upload immediately. diff --git a/README.md b/README.md index 206b12f..aca2e97 100644 --- a/README.md +++ b/README.md @@ -82,7 +82,9 @@ curl -X POST .../api/display/immich -H 'Content-Type: application/json' -d '{"mo | `always_include` | Names merged into every selection (e.g. a child without an HA account). Defaults to `immich.always_include`; send `[]` to switch it off | | `album_name` / `album_id` | Restrict to an album (names are case-insensitive) | | `accounts` | Limit to some accounts | -| `fit`, `push_to_fraimic`, `ignore_history` | Fit override, push to the frame (default true), allow recently shown photos | +| `fit`, `push_to_fraimic` | Fit override, push to the frame (default true) | +| `ignore_history` | Allow photos shown within `anti_repeat_days` or taken close to one | +| `skip_quality_gate` | Skip the suitability check (default: skipped in `album` mode, checked otherwise) | Unset filters fall back to the `immich` section of the settings. All modes share one query path, so persons, albums and favorites combine freely. @@ -112,6 +114,25 @@ IDs or names that exist in a given account. original is downloaded at full resolution (HEIC works); RAW files and files larger than `MAX_UPLOAD_MB` use Immich's converted JPEG (`fullsize`, then `preview`). +**Quality gate.** Rather than force an unsuitable image onto a 6-color panel, photos are +vetted *before* the full-size download, using a ~250 px thumbnail and metadata (no pixels +are ever modified; about 10 ms of NumPy per candidate, and normally one candidate is +enough). Rejected: blank/near-black frames, tiny images (short side below +`quality.min_dimension`, default 600 px), screenshots and graphics (no camera EXIF *and* a +large bright flat area or a tall phone-screen shape) and document scans. Kept on purpose: +black-and-white portraits, night shots, scanned family photos and low-contrast snow +scenes. Thresholds come from a calibration on ~400 real photos (4.3% rejected) and live in +the `quality` settings section. If none of `quality.candidates_checked` (default 8) +passes, the rules relax in four steps (halve the size limit, drop the phone-shape and +document rules, keep only blank and flat-color screenshots, keep only blank) so a request +never dead-ends; the outcome is reported in the image details under `suitability` +(`level`, `checked`, `rejected`). A thumbnail that cannot be read never blocks a photo. + +**Burst cooldown.** The history stores each photo's capture time. After a photo was +shown, others taken within `immich.burst_cooldown_hours` (default 2) of it are skipped for +`anti_repeat_days`, so rapid-fire shots of one moment are not shown back-to-back +(`0` disables it; `ignore_history` bypasses it). + **Face-aware crop.** Face boxes of the requested people drive `smart_crop` (all faces are the fallback), padded by 25% for hair and shoulders. When two faces are too far apart for the crop window, the larger one is kept whole instead of slicing both. Edited Immich assets diff --git a/app/providers/base.py b/app/providers/base.py index b55081e..5a581cf 100644 --- a/app/providers/base.py +++ b/app/providers/base.py @@ -13,6 +13,7 @@ from abc import ABC, abstractmethod from dataclasses import dataclass, field +from datetime import datetime from typing import Generic, TypeVar from pydantic import JsonValue @@ -60,6 +61,7 @@ class ImageAsset: recommended_fit: Fit mode this source prefers (e.g. posters: ``contain``); ``None`` means "use the configured default". regions: Regions of interest (faces) in normalized coordinates, most relevant first. + taken_at: When the picture was taken, if known (burst cooldown in the history). """ data: bytes = field(repr=False) @@ -69,6 +71,7 @@ class ImageAsset: details: dict[str, JsonValue] = field(default_factory=dict) recommended_fit: FitMode | None = None regions: tuple[FocusRegion, ...] = () + taken_at: datetime | None = None RequestT = TypeVar("RequestT", contravariant=True) diff --git a/app/providers/immich/models.py b/app/providers/immich/models.py index ffe4ffe..5816ec5 100644 --- a/app/providers/immich/models.py +++ b/app/providers/immich/models.py @@ -33,6 +33,8 @@ class AlbumDto(_Dto): class ExifDto(_Dto): + make: str | None = None + model: str | None = None city: str | None = None state: str | None = None country: str | None = None @@ -142,7 +144,13 @@ class ImmichDisplayRequest(BaseModel): default=True, description="Send the result to the frame (or queue it in deepsleep mode)" ) ignore_history: bool = Field( - default=False, description="Allow photos that were shown within anti_repeat_days" + default=False, + description="Allow photos shown within anti_repeat_days or taken close to one", + ) + skip_quality_gate: bool | None = Field( + default=None, + description="Skip the photo suitability check. Default: skipped in album mode " + "(you picked the album yourself), checked otherwise", ) @model_validator(mode="after") diff --git a/app/providers/immich/provider.py b/app/providers/immich/provider.py index 8dc7ddd..628440c 100644 --- a/app/providers/immich/provider.py +++ b/app/providers/immich/provider.py @@ -8,6 +8,7 @@ from __future__ import annotations +import io import itertools import logging import random @@ -17,13 +18,15 @@ from pathlib import PurePath from typing import Final +from PIL import Image from pydantic import JsonValue -from app.core.config_models import ImmichConfig +from app.core.config_models import ImmichConfig, QualityConfig from app.core.config_store import ConfigStore from app.core.history_store import HistoryStore from app.core.security import InvalidImageError, verify_image_bytes from app.processor.fit import FocusRegion +from app.processor.quality import LEVELS, AssetFacts, ImageStats, measure, violations from app.providers.base import ( BaseImageProvider, ImageAsset, @@ -47,6 +50,7 @@ MAX_QUERIES_PER_ACCOUNT: Final = 10 MAX_PERSON_COMBINATIONS: Final = 8 MAX_TITLE_PEOPLE: Final = 4 +THUMBNAIL_MAX_BYTES: Final = 2 * 1024 * 1024 RAW_EXTENSIONS: Final = frozenset( { @@ -83,6 +87,19 @@ class _Candidate: asset: AssetDto key: str + @property + def taken_at(self) -> datetime | None: + return _parse_date(self.asset) + + @property + def facts(self) -> AssetFacts: + exif = self.asset.exifInfo + return AssetFacts( + has_camera=bool(exif and (exif.make or exif.model)), + width=self.asset.width, + height=self.asset.height, + ) + def history_key(account: str, asset: AssetDto) -> str: """Content-based key (SHA-1 checksum) so one photo in two accounts is one photo.""" @@ -184,7 +201,14 @@ async def fetch(self, request: ImmichDisplayRequest) -> ImageAsset: self._check_resolution(plan, results) candidates = self._merge(results) - chosen = self._choose(candidates, config, request.ignore_history) + eligible = self._eligible(candidates, config, request.ignore_history) + gate_config = self._config_store.config.quality + skip = ( + request.mode == "album" + if request.skip_quality_gate is None + else (request.skip_quality_gate) + ) + chosen, suitability = await self._select(eligible, gate_config, gate=not skip) account_result = results[chosen.account] async with self._gateway.client(chosen.account) as client: @@ -192,6 +216,8 @@ async def fetch(self, request: ImmichDisplayRequest) -> ImageAsset: data, quality = await self._download(client, asset) regions = await self._regions(client, asset, account_result.target_ids) title, details = build_title_and_details(chosen.account, asset, quality, len(regions)) + if suitability is not None: + details["suitability"] = suitability return ImageAsset( data=data, source=SOURCE, @@ -199,6 +225,7 @@ async def fetch(self, request: ImmichDisplayRequest) -> ImageAsset: title=title, details=details, regions=tuple(regions), + taken_at=_parse_date(asset), ) async def albums( @@ -341,23 +368,101 @@ def _merge(results: dict[str, _AccountResult]) -> list[_Candidate]: merged.append(_Candidate(account, asset, key)) return merged - def _choose( + def _eligible( self, candidates: list[_Candidate], config: ImmichConfig, ignore_history: bool - ) -> _Candidate: + ) -> list[_Candidate]: + """Candidates left after the archive filter, anti-repeat history and burst cooldown.""" if config.exclude_archived: candidates = [c for c in candidates if not c.asset.isArchived] if not candidates: raise NoCandidateError("No photo matched the request") - recent = ( - set() if ignore_history else self._history.recent_ids(SOURCE, config.anti_repeat_days) - ) - eligible = [c for c in candidates if c.key not in recent] + if ignore_history: + return candidates + recent = self._history.recent_ids(SOURCE, config.anti_repeat_days) + eligible = [ + c + for c in candidates + if c.key not in recent + and not self._history.near_recent( + SOURCE, + c.taken_at, + within_hours=config.burst_cooldown_hours, + shown_within_days=config.anti_repeat_days, + ) + ] if not eligible: raise NoCandidateError( f"All {len(candidates)} matching photo(s) were shown within the last " - f"{config.anti_repeat_days} day(s); retry with ignore_history or widen the filters" + f"{config.anti_repeat_days} day(s) or were taken within " + f"{config.burst_cooldown_hours:g} h of one; retry with ignore_history " + "or widen the filters" ) - return self._rng.choice(eligible) + return eligible + + async def _select( + self, eligible: list[_Candidate], quality: QualityConfig, *, gate: bool + ) -> tuple[_Candidate, dict[str, JsonValue] | None]: + """Pick one candidate, vetting random ones against the quality gate. + + Candidates are inspected one at a time (thumbnail + metadata, never the original) + until one passes the strict rules; typically that is the first. If none of the + ``candidates_checked`` passes, the rules relax level by level over the inspected + ones, so a request never dead-ends. A candidate whose thumbnail cannot be read is + accepted as is (the gate never blocks on its own failures). + """ + if not gate or not quality.enabled: + return self._rng.choice(eligible), None + + pool = list(eligible) + inspected: list[tuple[_Candidate, ImageStats]] = [] + rejected: list[str] = [] + while pool and len(inspected) < quality.candidates_checked: + candidate = self._rng.choice(pool) + pool.remove(candidate) + stats = await self._inspect(candidate) + if stats is None: + return candidate, self._suitability(0, len(inspected) + 1, rejected, unchecked=True) + inspected.append((candidate, stats)) + broken = violations(stats, candidate.facts, quality, 0) + if not broken: + return candidate, self._suitability(0, len(inspected), rejected) + rejected.append("+".join(broken)) + + for level in range(1, LEVELS + 1): + for candidate, stats in inspected: + if not violations(stats, candidate.facts, quality, level): + logger.info( + "Quality gate relaxed to level %d after %d rejections", level, len(rejected) + ) + return candidate, self._suitability(level, len(inspected), rejected) + raise AssertionError("unreachable: the last relaxation level accepts everything") + + @staticmethod + def _suitability( + level: int, checked: int, rejected: list[str], *, unchecked: bool = False + ) -> dict[str, JsonValue]: + info: dict[str, JsonValue] = { + "level": level, + "checked": checked, + "rejected": list(rejected), + } + if unchecked: + info["unchecked"] = True + return info + + async def _inspect(self, candidate: _Candidate) -> ImageStats | None: + """Pixel statistics of a candidate's thumbnail, or ``None`` if it cannot be read.""" + try: + async with self._gateway.client(candidate.account) as client: + data = await client.download( + candidate.asset.id, variant="thumbnail", max_bytes=THUMBNAIL_MAX_BYTES + ) + with Image.open(io.BytesIO(data)) as image: + image.load() + return measure(image) + except (ProviderUnavailableError, OSError, ValueError, Image.DecompressionBombError) as exc: + logger.info("Quality gate could not inspect a candidate (%s); accepting it", exc) + return None # --- download -------------------------------------------------------------------------------- async def _download(self, client: ImmichClient, asset: AssetDto) -> tuple[bytes, str]: diff --git a/app/services/display.py b/app/services/display.py index c192391..75c0721 100644 --- a/app/services/display.py +++ b/app/services/display.py @@ -98,7 +98,7 @@ async def display_asset( regions=asset.regions, push=push, ) - await self._history.record(asset.history_key, asset.source) + await self._history.record(asset.history_key, asset.source, taken_at=asset.taken_at) return result async def push_current(self) -> DeliveryOutcome: diff --git a/tests/immich_fake.py b/tests/immich_fake.py index fd1d093..30acd0e 100644 --- a/tests/immich_fake.py +++ b/tests/immich_fake.py @@ -98,6 +98,7 @@ def add_asset( people: list[tuple[str, str]] = (), # type: ignore[assignment] faces: list[dict[str, Any]] | None = None, original: bytes | int | None = None, + thumbnail: bytes | int | None = None, **overrides: Any, ) -> dict[str, Any]: overrides.setdefault("people", [{"id": pid, "name": name} for pid, name in people]) @@ -107,6 +108,8 @@ def add_asset( self.files[(asset_id, "original")] = jpeg() if original is None else original self.files[(asset_id, "fullsize")] = jpeg((1440, 1080)) self.files[(asset_id, "preview")] = jpeg((1440, 1080)) + if thumbnail is not None: # without one the server answers 404 for the thumbnail + self.files[(asset_id, "thumbnail")] = thumbnail return data def add_album(self, album_id: str, name: str, asset_ids: list[str]) -> None: diff --git a/tests/test_api_immich.py b/tests/test_api_immich.py index bba2a15..dca2531 100644 --- a/tests/test_api_immich.py +++ b/tests/test_api_immich.py @@ -277,3 +277,53 @@ def test_multi_account_configuration_over_the_api(make_client: ClientFactory) -> only = show(client, accounts=["partner"], push_to_fraimic=False, ignore_history=True) assert picked <= {"h1", "p1", "p2"} assert only.json()["image"]["details"]["account"] == "partner" + + +# --- quality gate and burst cooldown ------------------------------------------------------------ +def test_display_records_taken_at_and_blocks_the_same_moment(make_client: ClientFactory) -> None: + from datetime import UTC, datetime + + fake = family() + # Same capture time as a1 (shown below): a rapid-fire shot of the same moment. + fake.add_asset("a1b", people=[("p1", "Alice")], checksum="sum-a1b") + client = immich_client(make_client) + with servers(fake, frame=False): + assert show(client, persons=["Alice"], push_to_fraimic=False).status_code == 200 + history = client.app.state.history_store # type: ignore[attr-defined] + assert history.entries()[0].taken_at == datetime(2024, 7, 14, 10, 22, 11, tzinfo=UTC) + + blocked = show(client, persons=["Alice"], push_to_fraimic=False) + assert blocked.status_code == 404 and "taken within 2 h" in blocked.json()["detail"] + again = show(client, persons=["Alice"], ignore_history=True, push_to_fraimic=False) + assert again.status_code == 200 + + +def test_quality_gate_over_the_api(make_client: ClientFactory) -> None: + from tests.test_immich_quality import add_good, ui_screen + + fake = FakeImmich() + fake.add_asset("shot", thumbnail=ui_screen(), width=1080, height=2400) + add_good(fake, "good") + client = immich_client(make_client) + with servers(fake, frame=False): + body = show(client, push_to_fraimic=False, ignore_history=True).json() + suitability = body["image"]["details"]["suitability"] + assert suitability["level"] == 0 and suitability["checked"] in {1, 2} + if suitability["checked"] == 2: + assert body["image"]["details"]["asset_id"] == "good" + + skipped = show(client, skip_quality_gate=True, push_to_fraimic=False, ignore_history=True) + assert "suitability" not in skipped.json()["image"]["details"] + + +def test_quality_settings_over_the_api(make_client: ClientFactory) -> None: + client = make_client() + quality = client.get("/api/config").json()["config"]["quality"] + assert quality["enabled"] is True and quality["min_dimension"] == 600 + assert client.put("/api/config", json={"quality": {"min_dimension": 800}}).status_code == 200 + assert client.get("/api/config").json()["config"]["quality"]["min_dimension"] == 800 + assert client.put("/api/config", json={"quality": {"min_dimension": -1}}).status_code == 422 + assert client.put("/api/config", json={"quality": {"nope": 1}}).status_code == 400 + assert ( + client.put("/api/config", json={"immich": {"burst_cooldown_hours": 0}}).status_code == 200 + ) diff --git a/tests/test_immich_provider.py b/tests/test_immich_provider.py index 9cfac03..8055aa6 100644 --- a/tests/test_immich_provider.py +++ b/tests/test_immich_provider.py @@ -40,10 +40,21 @@ def choice(self, seq: Any) -> Any: class Env: - def __init__(self, tmp_path: Path, fakes: dict[str, FakeImmich], **immich: Any) -> None: + def __init__( + self, + tmp_path: Path, + fakes: dict[str, FakeImmich], + quality: dict[str, Any] | None = None, + **immich: Any, + ) -> None: accounts = {n: {"url": f.base, "api_key": f.key} for n, f in fakes.items()} self.store = ConfigStore( - tmp_path / "config.json", {"immich": {"accounts": accounts, **immich}} + tmp_path / "config.json", + { + "immich": {"accounts": accounts, **immich}, + # The quality gate has its own tests (test_immich_quality.py). + "quality": {"enabled": False} if quality is None else quality, + }, ) self.gateway = ImmichGateway(self.store, URLPolicy()) self.history = HistoryStore(tmp_path / "history.json") diff --git a/tests/test_immich_quality.py b/tests/test_immich_quality.py new file mode 100644 index 0000000..d2feb4b --- /dev/null +++ b/tests/test_immich_quality.py @@ -0,0 +1,298 @@ +"""Quality gate and burst cooldown inside the Immich provider (fake Immich, no network).""" + +from __future__ import annotations + +import io +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +import numpy as np +import pytest +from PIL import Image, ImageDraw + +from app.providers.base import NoCandidateError +from app.providers.immich.models import ImmichDisplayRequest +from tests.immich_fake import FakeImmich +from tests.test_immich_client import mocked +from tests.test_immich_provider import Env + +GATE_ON: dict[str, Any] = {"enabled": True} + + +def encode(image: Image.Image) -> bytes: + buffer = io.BytesIO() + image.save(buffer, format="JPEG", quality=90) + return buffer.getvalue() + + +def good_photo(seed: int = 1) -> bytes: + rng = np.random.default_rng(seed) + base = rng.integers(20, 235, (24, 32, 3), dtype=np.uint8) + return encode(Image.fromarray(base).resize((250, 188), Image.Resampling.BICUBIC)) + + +def ui_screen(size: tuple[int, int] = (140, 250)) -> bytes: + image = Image.new("RGB", size, "white") + draw = ImageDraw.Draw(image) + for top in range(20, size[1] - 20, 40): + draw.rectangle((10, top, size[0] - 10, top + 14), fill=(225, 228, 235)) + return encode(image) + + +def black_frame() -> bytes: + return encode(Image.new("RGB", (250, 188), "black")) + + +def camera_exif() -> dict[str, Any]: + return {"make": "Google", "model": "Pixel", "orientation": "1", "fileSizeInByte": 50_000} + + +def add_good(fake: FakeImmich, asset_id: str, seed: int = 1, **overrides: Any) -> None: + """A normal photo: camera EXIF, full-size dimensions, busy thumbnail.""" + overrides.setdefault("width", 4000) + overrides.setdefault("height", 3000) + fake.add_asset(asset_id, thumbnail=good_photo(seed), exifInfo=camera_exif(), **overrides) + + +def thumbnail_requests(fake: FakeImmich) -> list[str]: + return [p for p, q in fake.downloads() if q.get("size") == "thumbnail"] + + +def originals(fake: FakeImmich) -> list[str]: + return [p for p, _ in fake.downloads() if p.endswith("/original")] + + +async def fetch(env: Env, **request: Any) -> Any: + return await env.fetch(**request) + + +# --- the gate ----------------------------------------------------------------- +async def test_first_good_photo_is_taken_after_a_single_thumbnail_check(tmp_path: Path) -> None: + fake = FakeImmich() + add_good(fake, "g1") + add_good(fake, "g2", 2) + env = Env(tmp_path, {"home": fake}, quality=GATE_ON) + with mocked(fake): + asset = await fetch(env) + assert asset.details["suitability"] == {"level": 0, "checked": 1, "rejected": []} + assert len(thumbnail_requests(fake)) == 1 # lazy: no wasted checks + assert len(originals(fake)) == 1 # the full-size file is downloaded only for the winner + + +async def test_a_screenshot_is_skipped_for_the_next_candidate(tmp_path: Path) -> None: + fake = FakeImmich() + fake.add_asset("shot", thumbnail=ui_screen(), width=1080, height=2400) + add_good(fake, "good") + env = Env(tmp_path, {"home": fake}, quality=GATE_ON) + with mocked(fake): + asset = await fetch(env) + assert asset.details["asset_id"] == "good" + # A white UI is both a screenshot and (pale, mostly white) a document. + suitability = {"level": 0, "checked": 2, "rejected": ["screenshot+document"]} + assert asset.details["suitability"] == suitability + assert originals(fake) == ["/api/assets/good/original"] # the junk was never downloaded + + +async def test_rejected_reasons_are_reported_and_junk_is_never_downloaded(tmp_path: Path) -> None: + fake = FakeImmich() + fake.add_asset( + "black", thumbnail=black_frame(), exifInfo=camera_exif(), width=4000, height=3000 + ) + add_good(fake, "tiny", width=300, height=200) + add_good(fake, "good", 3) + env = Env(tmp_path, {"home": fake}, quality=GATE_ON) + with mocked(fake): + asset = await fetch(env) + assert asset.details["asset_id"] == "good" + rejected = asset.details["suitability"]["rejected"] # type: ignore[index] + assert rejected[0] == "blank" and asset.details["suitability"]["level"] == 0 # type: ignore[index] + + +async def test_the_gate_can_be_switched_off_in_the_configuration(tmp_path: Path) -> None: + fake = FakeImmich() + fake.add_asset("shot", thumbnail=ui_screen(), width=1080, height=2400) + env = Env(tmp_path, {"home": fake}, quality={"enabled": False}) + with mocked(fake): + asset = await fetch(env) + assert asset.details["asset_id"] == "shot" and "suitability" not in asset.details + assert not thumbnail_requests(fake) + + +async def test_album_mode_skips_the_gate_unless_asked(tmp_path: Path) -> None: + fake = FakeImmich() + fake.add_asset("shot", thumbnail=ui_screen(), width=1080, height=2400) + fake.add_album("al1", "Receipts", ["shot"]) + env = Env(tmp_path, {"home": fake}, quality=GATE_ON) + with mocked(fake): + picked = await fetch(env, mode="album", album_name="Receipts") + assert picked.details["asset_id"] == "shot" and "suitability" not in picked.details + assert not thumbnail_requests(fake) + + # Forcing the gate on in album mode checks the photo (and relaxes, never fails). + forced = await fetch(env, mode="album", album_name="Receipts", skip_quality_gate=False) + assert forced.details["suitability"]["level"] == 3 # type: ignore[index] + assert len(thumbnail_requests(fake)) == 1 + + +async def test_skip_flag_bypasses_the_gate_in_other_modes(tmp_path: Path) -> None: + fake = FakeImmich() + fake.add_asset("shot", thumbnail=ui_screen(), width=1080, height=2400) + env = Env(tmp_path, {"home": fake}, quality=GATE_ON) + with mocked(fake): + asset = await fetch(env, skip_quality_gate=True) + assert "suitability" not in asset.details and not thumbnail_requests(fake) + + +def test_skip_flag_defaults_to_automatic() -> None: + assert ImmichDisplayRequest().skip_quality_gate is None + assert ImmichDisplayRequest(skip_quality_gate=False).skip_quality_gate is False + + +# --- progressive relaxation --------------------------------------------------- +async def test_relaxation_level_one_accepts_a_small_but_real_photo(tmp_path: Path) -> None: + fake = FakeImmich() + add_good(fake, "small", width=400, height=300) + env = Env(tmp_path, {"home": fake}, quality=GATE_ON) + with mocked(fake): + asset = await fetch(env) + assert asset.details["suitability"] == {"level": 1, "checked": 1, "rejected": ["tiny"]} + + +async def test_all_junk_still_returns_a_photo_at_a_relaxed_level(tmp_path: Path) -> None: + fake = FakeImmich() + for index in range(3): + fake.add_asset(f"s{index}", thumbnail=ui_screen((140, 250)), width=400, height=300) + env = Env(tmp_path, {"home": fake}, quality=GATE_ON) + with mocked(fake): + asset = await fetch(env) # never a 404: tiny + screenshot rules relax away + suitability = asset.details["suitability"] + assert suitability["level"] == 3 and suitability["checked"] == 3 # type: ignore[index] + assert suitability["rejected"] == ["tiny+screenshot+document"] * 3 # type: ignore[index] + + +async def test_even_all_blank_candidates_end_with_a_result(tmp_path: Path) -> None: + fake = FakeImmich() + for name in ("b1", "b2"): + fake.add_asset( + name, thumbnail=black_frame(), exifInfo=camera_exif(), width=4000, height=3000 + ) + env = Env(tmp_path, {"home": fake}, quality=GATE_ON) + with mocked(fake): + asset = await fetch(env) + assert asset.details["suitability"]["level"] == 4 # type: ignore[index] + + +async def test_candidates_checked_caps_the_thumbnail_downloads(tmp_path: Path) -> None: + fake = FakeImmich() + for index in range(6): + fake.add_asset(f"j{index}", thumbnail=ui_screen(), width=1080, height=2400) + add_good(fake, "good") + env = Env(tmp_path, {"home": fake}, quality={"enabled": True, "candidates_checked": 3}) + with mocked(fake): + asset = await fetch(env) + assert len(thumbnail_requests(fake)) == 3 + assert asset.details["suitability"]["checked"] == 3 # type: ignore[index] + + +async def test_configured_thresholds_are_honoured(tmp_path: Path) -> None: + fake = FakeImmich() + add_good(fake, "p1", width=700, height=700) + strict = Env(tmp_path, {"home": fake}, quality={"enabled": True, "min_dimension": 800}) + with mocked(fake): + asset = await fetch(strict) + assert asset.details["suitability"]["rejected"] == ["tiny"] # type: ignore[index] + + +# --- the gate never blocks on its own failures -------------------------------- +@pytest.mark.parametrize("thumbnail", [500, b"not an image at all", b""]) +async def test_unreadable_thumbnails_fail_open(tmp_path: Path, thumbnail: bytes | int) -> None: + fake = FakeImmich() + fake.add_asset("x1", thumbnail=thumbnail, width=1080, height=2400) + env = Env(tmp_path, {"home": fake}, quality=GATE_ON) + with mocked(fake): + asset = await fetch(env) + assert asset.details["asset_id"] == "x1" + assert asset.details["suitability"]["unchecked"] is True # type: ignore[index] + + +async def test_missing_thumbnail_endpoint_fails_open(tmp_path: Path) -> None: + fake = FakeImmich() + fake.add_asset("x1") # no thumbnail registered: the fake answers 404 + env = Env(tmp_path, {"home": fake}, quality=GATE_ON) + with mocked(fake): + assert (await fetch(env)).details["asset_id"] == "x1" + + +# --- burst cooldown ----------------------------------------------------------- +SHOT = datetime(2024, 7, 14, 10, tzinfo=UTC) + + +def moment(hour: int, day: int = 14) -> str: + return f"2024-07-{day:02d}T{hour:02d}:00:00.000Z" + + +async def burst_env(tmp_path: Path, **immich: Any) -> tuple[Env, FakeImmich]: + fake = FakeImmich() + fake.add_asset("a1", localDateTime=moment(10)) + fake.add_asset("a2", localDateTime=moment(11)) # 1 h after a1: same moment + fake.add_asset("a3", localDateTime=moment(14)) # 4 h after + fake.add_asset("a4", localDateTime=moment(10, day=20)) # another day + env = Env(tmp_path, {"home": fake}, **immich) + # a1 was shown a moment ago, with its capture time recorded. + await env.history.record( + "sha1:sum-a1", "immich", taken_at=datetime(2024, 7, 14, 10, tzinfo=UTC) + ) + return env, fake + + +async def test_photos_taken_close_to_a_shown_one_are_skipped(tmp_path: Path) -> None: + env, fake = await burst_env(tmp_path) + with mocked(fake): + picked = {(await fetch(env)).details["asset_id"] for _ in range(3)} + assert picked == {"a3", "a4"} # a1 (shown) and a2 (same moment) are out + + +async def test_burst_window_is_configurable_and_can_be_disabled(tmp_path: Path) -> None: + env, fake = await burst_env(tmp_path, burst_cooldown_hours=6) + with mocked(fake): + assert {(await fetch(env)).details["asset_id"] for _ in range(2)} == {"a4"} + env, fake = await burst_env(tmp_path / "off", burst_cooldown_hours=0) + with mocked(fake): + picked = {(await fetch(env)).details["asset_id"] for _ in range(3)} + assert picked == {"a2", "a3", "a4"} # only the shown photo itself stays excluded + + +async def test_ignore_history_also_ignores_the_burst_cooldown(tmp_path: Path) -> None: + env, fake = await burst_env(tmp_path) + with mocked(fake): + picked = {(await fetch(env, ignore_history=True)).details["asset_id"] for _ in range(4)} + assert picked == {"a1", "a2", "a3", "a4"} + + +async def test_all_candidates_in_a_burst_explains_why(tmp_path: Path) -> None: + fake = FakeImmich() + fake.add_asset("a1", localDateTime=moment(10)) + fake.add_asset("a2", localDateTime=moment(11)) + env = Env(tmp_path, {"home": fake}) + await env.history.record( + "sha1:sum-a1", "immich", taken_at=datetime(2024, 7, 14, 10, tzinfo=UTC) + ) + with mocked(fake), pytest.raises(NoCandidateError, match=r"taken within 2 h"): + await fetch(env) + + +async def test_burst_memory_follows_anti_repeat_days(tmp_path: Path) -> None: + env, fake = await burst_env(tmp_path, anti_repeat_days=0) + with mocked(fake): + picked = {(await fetch(env)).details["asset_id"] for _ in range(4)} + assert "a2" in picked # history memory off: neither the repeat nor the burst rule applies + + +async def test_the_fetched_asset_carries_its_capture_time(tmp_path: Path) -> None: + fake = FakeImmich() + fake.add_asset("a1", localDateTime=moment(10)) + env = Env(tmp_path, {"home": fake}) + with mocked(fake): + asset = await fetch(env) + assert asset.taken_at == datetime(2024, 7, 14, 10, tzinfo=UTC) From 5337e8094adb2182d7c27025c43f1b76d5e4f0e6 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sat, 14 Nov 2026 22:20:55 +0100 Subject: [PATCH 36/86] feat: give the burst cooldown its own memory (burst_cooldown_days) Burst blocking no longer reuses anti_repeat_days (30 days is right for exact duplicates but too long to lock out a 2-hour event window). immich.burst_cooldown_days (default 3, 0 = off) bounds how long a shown photo blocks others from its burst. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- README.md | 6 ++++-- app/core/config_models.py | 9 ++++++++- app/providers/immich/provider.py | 5 +++-- tests/test_immich_quality.py | 34 ++++++++++++++++++++++---------- 4 files changed, 39 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index aca2e97..ad5224e 100644 --- a/README.md +++ b/README.md @@ -130,8 +130,10 @@ never dead-ends; the outcome is reported in the image details under `suitability **Burst cooldown.** The history stores each photo's capture time. After a photo was shown, others taken within `immich.burst_cooldown_hours` (default 2) of it are skipped for -`anti_repeat_days`, so rapid-fire shots of one moment are not shown back-to-back -(`0` disables it; `ignore_history` bypasses it). +`immich.burst_cooldown_days` (default 3), so rapid-fire shots of one moment are not shown +back-to-back while other photos of the same trip can still appear later (`0` for either +setting disables it; `ignore_history` bypasses it). The exact-repeat memory stays +`anti_repeat_days` (default 30). **Face-aware crop.** Face boxes of the requested people drive `smart_crop` (all faces are the fallback), padded by 25% for hair and shoulders. When two faces are too far apart for diff --git a/app/core/config_models.py b/app/core/config_models.py index bbf59ee..d92074f 100644 --- a/app/core/config_models.py +++ b/app/core/config_models.py @@ -145,7 +145,14 @@ class ImmichConfig(_Section): ge=0, le=168, description="After a photo was shown, skip photos taken within this many hours of it " - "(rapid-fire shots of one moment); 0 = off. Uses anti_repeat_days as the memory.", + "(rapid-fire shots of one moment); 0 = off", + ) + burst_cooldown_days: int = Field( + default=3, + ge=0, + le=365, + description="How long a shown photo blocks others from its burst (days); 0 = off. " + "Shorter than anti_repeat_days so other photos of the same trip can appear later", ) people_cache_ttl_s: int = Field( default=3600, ge=0, le=604_800, description="How long the people list is cached (0 = off)" diff --git a/app/providers/immich/provider.py b/app/providers/immich/provider.py index 628440c..e08aa6e 100644 --- a/app/providers/immich/provider.py +++ b/app/providers/immich/provider.py @@ -387,14 +387,15 @@ def _eligible( SOURCE, c.taken_at, within_hours=config.burst_cooldown_hours, - shown_within_days=config.anti_repeat_days, + shown_within_days=config.burst_cooldown_days, ) ] if not eligible: raise NoCandidateError( f"All {len(candidates)} matching photo(s) were shown within the last " f"{config.anti_repeat_days} day(s) or were taken within " - f"{config.burst_cooldown_hours:g} h of one; retry with ignore_history " + f"{config.burst_cooldown_hours:g} h of a photo shown in the last " + f"{config.burst_cooldown_days} day(s); retry with ignore_history " "or widen the filters" ) return eligible diff --git a/tests/test_immich_quality.py b/tests/test_immich_quality.py index d2feb4b..78b0f50 100644 --- a/tests/test_immich_quality.py +++ b/tests/test_immich_quality.py @@ -3,7 +3,7 @@ from __future__ import annotations import io -from datetime import UTC, datetime +from datetime import UTC, datetime, timedelta from pathlib import Path from typing import Any @@ -232,17 +232,17 @@ def moment(hour: int, day: int = 14) -> str: return f"2024-07-{day:02d}T{hour:02d}:00:00.000Z" -async def burst_env(tmp_path: Path, **immich: Any) -> tuple[Env, FakeImmich]: +async def burst_env( + tmp_path: Path, shown_ago: timedelta = timedelta(0), **immich: Any +) -> tuple[Env, FakeImmich]: fake = FakeImmich() fake.add_asset("a1", localDateTime=moment(10)) fake.add_asset("a2", localDateTime=moment(11)) # 1 h after a1: same moment fake.add_asset("a3", localDateTime=moment(14)) # 4 h after fake.add_asset("a4", localDateTime=moment(10, day=20)) # another day env = Env(tmp_path, {"home": fake}, **immich) - # a1 was shown a moment ago, with its capture time recorded. - await env.history.record( - "sha1:sum-a1", "immich", taken_at=datetime(2024, 7, 14, 10, tzinfo=UTC) - ) + # a1 was shown ``shown_ago`` ago (default: just now), with its capture time recorded. + await env.history.record("sha1:sum-a1", "immich", datetime.now(UTC) - shown_ago, taken_at=SHOT) return env, fake @@ -282,11 +282,25 @@ async def test_all_candidates_in_a_burst_explains_why(tmp_path: Path) -> None: await fetch(env) -async def test_burst_memory_follows_anti_repeat_days(tmp_path: Path) -> None: - env, fake = await burst_env(tmp_path, anti_repeat_days=0) +async def test_burst_memory_has_its_own_duration(tmp_path: Path) -> None: + """a1 was shown 5 days ago: with the default 3-day burst memory a2 is free again.""" + env, fake = await burst_env(tmp_path / "default", shown_ago=timedelta(days=5)) + with mocked(fake): + assert "a2" in {(await fetch(env)).details["asset_id"] for _ in range(3)} + + wide, fake = await burst_env( + tmp_path / "wide", shown_ago=timedelta(days=5), burst_cooldown_days=7 + ) + with mocked(fake): + picked = {(await fetch(wide)).details["asset_id"] for _ in range(3)} + assert "a2" not in picked # a 7-day burst memory still remembers it + + +async def test_zero_burst_days_disables_the_cooldown(tmp_path: Path) -> None: + env, fake = await burst_env(tmp_path, burst_cooldown_days=0) with mocked(fake): - picked = {(await fetch(env)).details["asset_id"] for _ in range(4)} - assert "a2" in picked # history memory off: neither the repeat nor the burst rule applies + picked = {(await fetch(env)).details["asset_id"] for _ in range(3)} + assert "a2" in picked # exact repeats stay excluded (anti_repeat_days), bursts are allowed async def test_the_fetched_asset_carries_its_capture_time(tmp_path: Path) -> None: From 3a29c8fb3b5f79a8500caae54c2b3d0133015de2 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sat, 14 Nov 2026 22:33:05 +0100 Subject: [PATCH 37/86] feat: add quiet-hours planning for the scheduler Pure helpers (no clock, no I/O) for the autonomous refresh: a daily QuietWindow in local wall-clock time (start inclusive, end exclusive, may cross midnight), in_quiet, quiet_end_after and next_run_at, which postpones a due refresh to the end of the window. Local times are resolved through the IANA database, so DST gaps and repeated hours are handled. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- app/services/schedule.py | 129 ++++++++++++++++++++++++++++++++++++ tests/test_schedule.py | 137 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 266 insertions(+) create mode 100644 app/services/schedule.py create mode 100644 tests/test_schedule.py diff --git a/app/services/schedule.py b/app/services/schedule.py new file mode 100644 index 0000000..d5aff74 --- /dev/null +++ b/app/services/schedule.py @@ -0,0 +1,129 @@ +"""Pure scheduling helpers: quiet-hours windows and the next refresh time. + +Everything here is side-effect free and works on timezone-aware datetimes, so it can be +tested without a clock or an event loop. Quiet hours are expressed in local wall-clock +time of a configured IANA timezone (Docker containers usually run in UTC), and local +times are built with ``datetime.combine(..., tzinfo=ZoneInfo)`` so daylight saving +transitions are resolved by the timezone database: + +* a window boundary that does not exist on a spring-forward day (e.g. 02:30 in Paris) + is normalized to the equivalent instant just after the jump (03:30); +* on a fall-back day the repeated hour is read literally from the wall clock, so a + window ending at 02:30 ends at the first 02:30 that follows the moment considered. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from datetime import UTC, datetime, time, timedelta, tzinfo + + +def _parse_hhmm(value: str) -> time: + hours, _, minutes = value.strip().partition(":") + return time(int(hours), int(minutes)) + + +@dataclass(frozen=True, slots=True) +class QuietWindow: + """A daily no-refresh window in local wall-clock time. + + ``start`` is inclusive and ``end`` exclusive. A window whose end is earlier than its + start crosses midnight (e.g. 22:00 -> 07:00). + """ + + start: time + end: time + + def __post_init__(self) -> None: + if self.start.tzinfo is not None or self.end.tzinfo is not None: + raise ValueError("quiet window times must be naive wall-clock times") + if self.start == self.end: + raise ValueError("quiet window start and end must differ") + + @classmethod + def parse(cls, start: str | None, end: str | None) -> QuietWindow | None: + """Build a window from ``HH:MM`` strings; ``None`` when either is unset. + + Raises: + ValueError: If a value is not ``HH:MM`` or both values are equal. + """ + if not start or not end: + return None + return cls(_parse_hhmm(start), _parse_hhmm(end)) + + @property + def crosses_midnight(self) -> bool: + """Whether the window spans two calendar days.""" + return self.end < self.start + + def contains(self, local: time) -> bool: + """Whether the wall-clock time ``local`` falls inside the window.""" + local = local.replace(tzinfo=None) + if self.crosses_midnight: + return local >= self.start or local < self.end + return self.start <= local < self.end + + +def _require_aware(moment: datetime) -> None: + if moment.tzinfo is None or moment.utcoffset() is None: + raise ValueError("expected a timezone-aware datetime") + + +def _local(moment: datetime, tz: tzinfo) -> datetime: + """``moment`` as a normalized local time of ``tz``. + + Going through UTC matters: ``astimezone`` returns its input untouched when it already + uses ``tz``, which would keep a non-existent local time or a stale ``fold``. + """ + return moment.astimezone(UTC).astimezone(tz) + + +def in_quiet(moment: datetime, window: QuietWindow | None, tz: tzinfo) -> bool: + """Whether ``moment`` falls inside ``window`` in the local time of ``tz``. + + Args: + moment: Timezone-aware instant. + window: Quiet window, or ``None`` (never quiet). + tz: Timezone the window is expressed in. + """ + _require_aware(moment) + if window is None: + return False + return window.contains(_local(moment, tz).time()) + + +def quiet_end_after(moment: datetime, window: QuietWindow, tz: tzinfo) -> datetime: + """The first end of ``window`` strictly after ``moment`` (aware, in ``tz``). + + When ``moment`` is inside the window this is the instant the window closes. + """ + _require_aware(moment) + after = moment.astimezone(UTC) # compare in UTC: same-zone comparisons ignore fold + local_date = _local(moment, tz).date() + candidates: list[datetime] = [] + for offset in range(3): # today, tomorrow, and one spare day for DST oddities + day = local_date + timedelta(days=offset) + for fold in (0, 1): + # fold=1 selects the second occurrence of a repeated (fall-back) local time; + # converting to UTC maps a non-existent local time to a real instant. + candidate = datetime.combine(day, window.end, tzinfo=tz).replace(fold=fold) + instant = candidate.astimezone(UTC) + # A non-existent end read with fold=1 maps to an instant *before* the jump, + # which is still inside the window: it is not a real end. + if instant > after and not window.contains(instant.astimezone(tz).time()): + candidates.append(instant) + if not candidates: + raise AssertionError("unreachable: a daily window always ends within two days") + return min(candidates).astimezone(tz) + + +def next_run_at(base: datetime, window: QuietWindow | None, tz: tzinfo) -> datetime: + """When a refresh due at ``base`` may actually run (aware, in ``tz``). + + A due time inside the quiet window is postponed to the moment the window ends; + otherwise ``base`` is returned unchanged (converted to ``tz``). + """ + _require_aware(base) + if window is not None and in_quiet(base, window, tz): + return quiet_end_after(base, window, tz) + return _local(base, tz) diff --git a/tests/test_schedule.py b/tests/test_schedule.py new file mode 100644 index 0000000..c9857d2 --- /dev/null +++ b/tests/test_schedule.py @@ -0,0 +1,137 @@ +"""Quiet-hours planning (pure functions, no clock).""" + +from __future__ import annotations + +from datetime import UTC, datetime, time, timedelta +from zoneinfo import ZoneInfo + +import pytest + +from app.services.schedule import QuietWindow, in_quiet, next_run_at, quiet_end_after + +PARIS = ZoneInfo("Europe/Paris") +NIGHT = QuietWindow(time(22, 0), time(7, 0)) # crosses midnight +NAP = QuietWindow(time(13, 0), time(15, 30)) # same day + + +def paris(*args: int, fold: int = 0) -> datetime: + return datetime(*args, tzinfo=PARIS, fold=fold) # type: ignore[misc] + + +def utc(moment: datetime) -> datetime: + return moment.astimezone(UTC) + + +# --- QuietWindow -------------------------------------------------------------- +def test_parse() -> None: + assert QuietWindow.parse("22:00", "07:00") == NIGHT + assert QuietWindow.parse(None, "07:00") is None + assert QuietWindow.parse("", "") is None + with pytest.raises(ValueError, match="differ"): + QuietWindow.parse("07:00", "07:00") + with pytest.raises(ValueError): + QuietWindow.parse("7h", "08:00") + + +def test_window_times_must_be_naive() -> None: + with pytest.raises(ValueError, match="naive"): + QuietWindow(time(1, 0, tzinfo=UTC), time(2, 0)) + + +@pytest.mark.parametrize( + ("local", "expected"), + [ + (time(21, 59), False), + (time(22, 0), True), # start inclusive + (time(23, 59), True), + (time(0, 0), True), + (time(6, 59), True), + (time(7, 0), False), # end exclusive + (time(12, 0), False), + ], +) +def test_contains_across_midnight(local: time, expected: bool) -> None: + assert NIGHT.crosses_midnight + assert NIGHT.contains(local) is expected + + +@pytest.mark.parametrize( + ("local", "expected"), + [(time(12, 59), False), (time(13, 0), True), (time(15, 29), True), (time(15, 30), False)], +) +def test_contains_same_day(local: time, expected: bool) -> None: + assert not NAP.crosses_midnight + assert NAP.contains(local) is expected + + +# --- in_quiet ----------------------------------------------------------------- +def test_same_instant_differs_between_timezones() -> None: + instant = datetime(2026, 11, 14, 22, 30, tzinfo=UTC) # 23:30 in Paris (CET) + assert in_quiet(instant, NIGHT, PARIS) is True + assert in_quiet(instant, QuietWindow(time(23, 0), time(23, 15)), UTC) is False + early = datetime(2026, 11, 14, 21, 30, tzinfo=UTC) # 22:30 Paris, 21:30 UTC + assert in_quiet(early, NIGHT, PARIS) is True + assert in_quiet(early, NIGHT, UTC) is False + + +def test_no_window_is_never_quiet() -> None: + assert in_quiet(datetime(2026, 1, 1, 3, 0, tzinfo=UTC), None, PARIS) is False + + +def test_naive_datetimes_are_rejected() -> None: + with pytest.raises(ValueError, match="aware"): + in_quiet(datetime(2026, 1, 1, 3, 0), NIGHT, PARIS) + with pytest.raises(ValueError, match="aware"): + next_run_at(datetime(2026, 1, 1, 3, 0), NIGHT, PARIS) + + +# --- quiet_end_after / next_run_at ---------------------------------------------- +def test_end_after_before_and_after_midnight() -> None: + assert quiet_end_after(paris(2026, 11, 14, 23, 0), NIGHT, PARIS) == paris(2026, 11, 15, 7, 0) + assert quiet_end_after(paris(2026, 11, 15, 3, 0), NIGHT, PARIS) == paris(2026, 11, 15, 7, 0) + # Exactly at the end: the next end is tomorrow's. + assert quiet_end_after(paris(2026, 11, 15, 7, 0), NIGHT, PARIS) == paris(2026, 11, 16, 7, 0) + + +def test_next_run_at_pushes_into_the_window_end() -> None: + due = datetime(2026, 11, 14, 23, 0, tzinfo=UTC) # 00:00 Paris, inside the window + result = next_run_at(due, NIGHT, PARIS) + assert result == paris(2026, 11, 15, 7, 0) + assert result.tzinfo is PARIS + assert result.utcoffset() is not None + + +def test_next_run_at_keeps_times_outside_the_window() -> None: + due = paris(2026, 11, 14, 12, 0) + assert next_run_at(due, NIGHT, PARIS) == due + assert next_run_at(due, None, PARIS) == due + # Converted into the scheduler timezone. + assert next_run_at(datetime(2026, 11, 14, 11, 0, tzinfo=UTC), None, PARIS).hour == 12 + + +def test_dst_spring_forward() -> None: + # 29 Mar 2026: Paris jumps from 02:00 CET to 03:00 CEST; 02:30 does not exist. + window = QuietWindow(time(1, 0), time(2, 30)) + end = quiet_end_after(paris(2026, 3, 29, 1, 15), window, PARIS) + assert end == datetime(2026, 3, 29, 1, 30, tzinfo=UTC) # 03:30 CEST, right after the jump + assert (end.hour, end.minute) == (3, 30) + # A normal window keeps its wall-clock end across the jump (7 h of wall time, 6 h real). + start = paris(2026, 3, 29, 0, 30) + night_end = quiet_end_after(start, NIGHT, PARIS) + assert night_end == paris(2026, 3, 29, 7, 0) + assert night_end.astimezone(UTC) - start.astimezone(UTC) == timedelta(hours=5, minutes=30) + + +def test_dst_fall_back() -> None: + # 25 Oct 2026: Paris goes from 03:00 CEST back to 02:00 CET; 02:15 happens twice. + window = QuietWindow(time(22, 0), time(2, 30)) + first = paris(2026, 10, 25, 2, 15) # CEST occurrence + second = paris(2026, 10, 25, 2, 15, fold=1) # CET occurrence, one hour later + assert second.astimezone(UTC) - first.astimezone(UTC) == timedelta(hours=1) + assert in_quiet(first, window, PARIS) and in_quiet(second, window, PARIS) + # Ambiguous local times never compare equal across zones (PEP 495): compare in UTC. + assert utc(quiet_end_after(first, window, PARIS)) == datetime(2026, 10, 25, 0, 30, tzinfo=UTC) + assert utc(quiet_end_after(second, window, PARIS)) == datetime(2026, 10, 25, 1, 30, tzinfo=UTC) + # Autumn evening: the 22:00 -> 07:00 window spans 10 real hours. + night_end = quiet_end_after(paris(2026, 10, 24, 22, 0), NIGHT, PARIS) + assert night_end == datetime(2026, 10, 25, 6, 0, tzinfo=UTC) From 65cb3e1cbca09331591ea6c01b4496653b1047c5 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sat, 14 Nov 2026 22:33:41 +0100 Subject: [PATCH 38/86] feat: add scheduler options and quiet-hours env seeds SchedulerConfig gains skip_if_pending (do not replace an image a sleeping frame never showed) and retry_minutes (first retry delay after a failed refresh), rejects a quiet window whose start equals its end, and documents source_rule as an optional pinned rule. QUIET_HOURS_START / QUIET_HOURS_END seed the quiet window from .env. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- .env.example | 8 +++++++- app/core/config_models.py | 28 +++++++++++++++++++++++++--- app/core/settings.py | 6 ++++++ tests/test_config_models.py | 25 +++++++++++++++++++++++++ tests/test_settings.py | 18 +++++++++++++++++- 5 files changed, 80 insertions(+), 5 deletions(-) diff --git a/.env.example b/.env.example index 8198b06..424d818 100644 --- a/.env.example +++ b/.env.example @@ -71,7 +71,13 @@ FRAIMIC_PANEL=133 ORIENTATION=portrait # --- Scheduler (runtime default) --------------------------------------------- +# Replays the active source rule (the pinned scheduler.source_rule, else the last +# manual display) every REFRESH_INTERVAL_HOURS hours. Any display resets the timer. SCHEDULER_ENABLED=false REFRESH_INTERVAL_HOURS=6 -# IANA timezone used for quiet hours, e.g. Europe/Paris +# Optional no-refresh window in local time (24h HH:MM, may cross midnight). A refresh +# that falls inside runs when the window ends. Leave both empty to disable. +QUIET_HOURS_START= +QUIET_HOURS_END= +# IANA timezone of the quiet hours, e.g. Europe/Paris (containers run in UTC otherwise) TZ=UTC diff --git a/app/core/config_models.py b/app/core/config_models.py index d92074f..6f12959 100644 --- a/app/core/config_models.py +++ b/app/core/config_models.py @@ -388,7 +388,11 @@ class QualityConfig(_Section): class SourceRule(BaseModel): - """The last source request, replayed by ``/api/refresh`` and the scheduler.""" + """A replayable source request (``/api/refresh`` and the scheduler). + + ``params`` holds the request body of the matching display endpoint, e.g. for + ``immich`` the fields of ``POST /api/display/immich`` (``persons``, ``album_name``...). + """ model_config = ConfigDict(extra="forbid") @@ -409,9 +413,25 @@ class SchedulerConfig(_Section): quiet_hours_end: str | None = Field( default=None, description="HH:MM end of the no-refresh window (local time)" ) - timezone: str = Field(default="UTC", description="IANA timezone, e.g. Europe/Paris") + timezone: str = Field( + default="UTC", description="IANA timezone of the quiet hours, e.g. Europe/Paris" + ) source_rule: SourceRule | None = Field( - default=None, description="Source rule replayed on refresh (set by display actions)" + default=None, + description="Pinned rule replayed on refresh (optional). When empty, the last manual " + "display request is replayed", + ) + skip_if_pending: bool = Field( + default=True, + description="Skip a scheduled refresh while the previous image still waits for the " + "frame (deepsleep), so an image the frame never showed is not replaced", + ) + retry_minutes: int = Field( + default=15, + ge=1, + le=1440, + description="First retry delay after a failed refresh; doubles on each failure, " + "capped by interval_hours", ) @field_validator("quiet_hours_start", "quiet_hours_end") @@ -438,6 +458,8 @@ def _validate_timezone(cls, value: str) -> str: def _quiet_hours_pair(self) -> SchedulerConfig: if (self.quiet_hours_start is None) != (self.quiet_hours_end is None): raise ValueError("quiet_hours_start and quiet_hours_end must be set together") + if self.quiet_hours_start is not None and self.quiet_hours_start == self.quiet_hours_end: + raise ValueError("quiet_hours_start and quiet_hours_end must differ") return self diff --git a/app/core/settings.py b/app/core/settings.py index 1541219..ab5dcea 100644 --- a/app/core/settings.py +++ b/app/core/settings.py @@ -79,6 +79,8 @@ class EnvSettings(BaseSettings): orientation: str | None = None scheduler_enabled: bool | None = None refresh_interval_hours: float | None = None + quiet_hours_start: str | None = None + quiet_hours_end: str | None = None tz: str | None = None @field_validator("root_path") @@ -99,6 +101,8 @@ def _upper_log_level(cls, value: object) -> object: "fraimic_power_mode", "fraimic_panel", "orientation", + "quiet_hours_start", + "quiet_hours_end", "tz", mode="before", ) @@ -193,6 +197,8 @@ def runtime_seed(self) -> dict[str, dict[str, Any]]: ("display", "orientation"): self.orientation, ("scheduler", "enabled"): self.scheduler_enabled, ("scheduler", "interval_hours"): self.refresh_interval_hours, + ("scheduler", "quiet_hours_start"): self.quiet_hours_start, + ("scheduler", "quiet_hours_end"): self.quiet_hours_end, ("scheduler", "timezone"): self.tz, } seed: dict[str, dict[str, Any]] = {} diff --git a/tests/test_config_models.py b/tests/test_config_models.py index 67573a6..94cca11 100644 --- a/tests/test_config_models.py +++ b/tests/test_config_models.py @@ -135,6 +135,31 @@ def test_scheduler_quiet_hours_must_be_paired() -> None: assert SchedulerConfig(quiet_hours_start="", quiet_hours_end=" ").quiet_hours_start is None +def test_scheduler_quiet_hours_must_differ() -> None: + with pytest.raises(ValidationError, match="must differ"): + SchedulerConfig(quiet_hours_start="07:00", quiet_hours_end="07:00") + + +def test_scheduler_retry_and_pending_options() -> None: + config = SchedulerConfig() + assert config.skip_if_pending is True + assert config.retry_minutes == 15 + assert SchedulerConfig(retry_minutes=1440, skip_if_pending=False).retry_minutes == 1440 + for bad in (0, 1441): + with pytest.raises(ValidationError): + SchedulerConfig(retry_minutes=bad) + + +def test_scheduler_pinned_rule() -> None: + config = SchedulerConfig.model_validate( + {"source_rule": {"kind": "immich", "params": {"persons": ["Alice"]}}} + ) + assert config.source_rule is not None + assert config.source_rule.params == {"persons": ["Alice"]} + with pytest.raises(ValidationError): + SchedulerConfig.model_validate({"source_rule": {"kind": "ftp"}}) + + @pytest.mark.parametrize("value", ["24:00", "7:30", "12:60"]) def test_scheduler_rejects_bad_times(value: str) -> None: with pytest.raises(ValidationError): diff --git a/tests/test_settings.py b/tests/test_settings.py index 84c21e0..e8fa8d0 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -46,6 +46,8 @@ def test_reads_environment(monkeypatch: pytest.MonkeyPatch, data_dir: Path) -> N monkeypatch.setenv("FRAIMIC_PANEL", "315") monkeypatch.setenv("SCHEDULER_ENABLED", "true") monkeypatch.setenv("REFRESH_INTERVAL_HOURS", "3") + monkeypatch.setenv("QUIET_HOURS_START", " 22:30 ") + monkeypatch.setenv("QUIET_HOURS_END", "07:00") monkeypatch.setenv("TZ", "Europe/Paris") settings = EnvSettings(_env_file=None) @@ -62,7 +64,13 @@ def test_reads_environment(monkeypatch: pytest.MonkeyPatch, data_dir: Path) -> N "accounts": {"default": {"url": "http://immich.local:2283", "api_key": "immich-key"}} }, "fraimic": {"panel": "315"}, - "scheduler": {"enabled": True, "interval_hours": 3.0, "timezone": "Europe/Paris"}, + "scheduler": { + "enabled": True, + "interval_hours": 3.0, + "quiet_hours_start": "22:30", + "quiet_hours_end": "07:00", + "timezone": "Europe/Paris", + }, } assert sorted(settings.secret_values()) == ["immich-key", "topsecret"] @@ -84,3 +92,11 @@ def test_settings_are_frozen(make_settings: SettingsFactory) -> None: settings = make_settings() with pytest.raises(ValidationError): settings.port = 1234 + + +def test_blank_quiet_hours_are_unset(monkeypatch: pytest.MonkeyPatch, data_dir: Path) -> None: + monkeypatch.setenv("QUIET_HOURS_START", "") + monkeypatch.setenv("QUIET_HOURS_END", " ") + settings = EnvSettings(_env_file=None, data_dir=data_dir) + assert settings.quiet_hours_start is None and settings.quiet_hours_end is None + assert "scheduler" not in settings.runtime_seed() From 9e1f425a61836fa62debfe304ffb8326278ccde3 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sat, 14 Nov 2026 22:39:12 +0100 Subject: [PATCH 39/86] feat: add scheduler service with persisted state and APScheduler timer SchedulerService replays the active source rule (the pinned scheduler.source_rule, else the last manual display request) on a self-rearming APScheduler DateTrigger job: - the next refresh is due interval_hours after the last display (any display resets the timer) and is postponed to the end of the quiet window in the configured timezone; - failures retry after retry_minutes, doubling and capped by the interval; success resets the backoff; - a scheduled refresh is skipped while an image still waits for a sleeping frame (skip_if_pending), when there is no rule, or when the rule's source cannot be replayed yet; - manual runs ignore quiet hours and the pending check and share one lock with scheduled runs; - state (last rule, timer, retry, last run) is kept atomically in /data/scheduler_state.json and survives restarts; config changes re-arm or remove the job. Immich rules are the only replayable kind for now. APScheduler's own per-job INFO logs are silenced unless LOG_LEVEL=DEBUG. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- app/api/deps.py | 7 + app/core/logging_config.py | 5 + app/core/settings.py | 5 + app/main.py | 14 +- app/services/scheduler.py | 505 ++++++++++++++++++++++++++++++++ pyproject.toml | 4 + tests/test_scheduler_service.py | 434 +++++++++++++++++++++++++++ 7 files changed, 973 insertions(+), 1 deletion(-) create mode 100644 app/services/scheduler.py create mode 100644 tests/test_scheduler_service.py diff --git a/app/api/deps.py b/app/api/deps.py index 8dc454d..c408989 100644 --- a/app/api/deps.py +++ b/app/api/deps.py @@ -13,6 +13,7 @@ from app.services.current_image import CurrentImageStore from app.services.delivery import DeliveryService from app.services.display import DisplayService +from app.services.scheduler import SchedulerService def get_settings(request: Request) -> EnvSettings: @@ -50,6 +51,11 @@ def get_immich_provider(request: Request) -> ImmichProvider: return cast(ImmichProvider, request.app.state.immich_provider) +def get_scheduler_service(request: Request) -> SchedulerService: + """The autonomous refresh scheduler.""" + return cast(SchedulerService, request.app.state.scheduler_service) + + def get_people_directory(request: Request) -> PeopleDirectory: """Cache of the people known to each Immich account.""" return cast(PeopleDirectory, request.app.state.people_directory) @@ -63,3 +69,4 @@ def get_people_directory(request: Request) -> PeopleDirectory: DisplayServiceDep = Annotated[DisplayService, Depends(get_display_service)] ImmichProviderDep = Annotated[ImmichProvider, Depends(get_immich_provider)] PeopleDirectoryDep = Annotated[PeopleDirectory, Depends(get_people_directory)] +SchedulerDep = Annotated[SchedulerService, Depends(get_scheduler_service)] diff --git a/app/core/logging_config.py b/app/core/logging_config.py index 1b57fe3..7e148d7 100644 --- a/app/core/logging_config.py +++ b/app/core/logging_config.py @@ -73,6 +73,11 @@ def setup_logging(level: str = "INFO") -> None: stream_handler.setFormatter(logging.Formatter(LOG_FORMAT)) root.addHandler(stream_handler) + # APScheduler logs every job execution at INFO; the scheduler service logs its own. + logging.getLogger("apscheduler").setLevel( + logging.DEBUG if root.level <= logging.DEBUG else logging.WARNING + ) + handlers: list[logging.Handler] = list(root.handlers) for name in _UVICORN_LOGGERS: handlers.extend(logging.getLogger(name).handlers) diff --git a/app/core/settings.py b/app/core/settings.py index ab5dcea..c3d05c9 100644 --- a/app/core/settings.py +++ b/app/core/settings.py @@ -172,6 +172,11 @@ def queue_dir(self) -> Path: """Directory holding the upload waiting for the frame (``pending.bin``).""" return self.data_dir / "queue" + @property + def scheduler_state_path(self) -> Path: + """Location of the scheduler state (replayable rule, timer, last run).""" + return self.data_dir / "scheduler_state.json" + def secret_values(self) -> list[str]: """All secret values provided through the environment (for log masking).""" values = [self.api_key] diff --git a/app/main.py b/app/main.py index 233edbf..01be3c4 100644 --- a/app/main.py +++ b/app/main.py @@ -38,6 +38,7 @@ from app.services.current_image import CurrentImageStore from app.services.delivery import DeliveryService from app.services.display import DisplayService +from app.services.scheduler import SchedulerService, immich_runner logger = logging.getLogger(__name__) @@ -105,6 +106,13 @@ async def _on_config_change(_: RuntimeConfig) -> None: history_store, max_bytes=settings.max_upload_bytes, ) + scheduler = SchedulerService( + settings.scheduler_state_path, + config_store, + {"immich": immich_runner(immich, display)}, + has_pending=lambda: delivery.pending is not None, + ) + scheduler.load() app.state.config_store = config_store app.state.history_store = history_store @@ -113,12 +121,14 @@ async def _on_config_change(_: RuntimeConfig) -> None: app.state.display_service = display app.state.people_directory = people app.state.immich_provider = immich + app.state.scheduler_service = scheduler await delivery.start() + await scheduler.start() config = config_store.config logger.info( "Smart Frame Engine %s started (data_dir=%s, auth=%s, root_path=%r, panel=%s, " - "power_mode=%s, pending=%s)", + "power_mode=%s, pending=%s, scheduler=%s)", __version__, settings.data_dir, "enabled" if settings.auth_enabled else "disabled", @@ -126,10 +136,12 @@ async def _on_config_change(_: RuntimeConfig) -> None: config.fraimic.panel, config.fraimic.power_mode, delivery.pending is not None, + scheduler.next_run_at.isoformat() if scheduler.next_run_at else "off", ) try: yield finally: + await scheduler.stop() await delivery.stop() logger.info("Smart Frame Engine stopped") diff --git a/app/services/scheduler.py b/app/services/scheduler.py new file mode 100644 index 0000000..50eef64 --- /dev/null +++ b/app/services/scheduler.py @@ -0,0 +1,505 @@ +"""Autonomous refresh: replay the active source rule on a timer, outside quiet hours. + +The **active rule** is the pinned ``scheduler.source_rule`` from the configuration, or +else the last manual display request (kept in ``/data/scheduler_state.json`` so that +showing a photo does not rewrite the user's settings). + +Timing: + +* The next refresh is due ``interval_hours`` after the timer was last reset. **Any + display resets the timer** (a manual photo, an upload, a scheduled refresh), so a + picture chosen by hand stays up for a full interval. +* A refresh that falls inside the quiet window runs when the window ends. +* After a failure (Immich down, nothing eligible...) the refresh is retried after + ``retry_minutes``, doubling on each consecutive failure and capped by the interval. +* A scheduled refresh is skipped while the previous image still waits for a sleeping + frame (``skip_if_pending``); skipped slots restart the timer. + +A single APScheduler ``DateTrigger`` job re-arms itself after every run and whenever +the configuration changes. The state survives restarts; a refresh that became due while +the app was down runs shortly after startup. Manual refreshes (``POST /api/refresh``) +ignore quiet hours and the pending check, and share a lock with scheduled ones. +""" + +from __future__ import annotations + +import asyncio +import logging +from collections.abc import Awaitable, Callable, Mapping +from dataclasses import dataclass +from datetime import UTC, datetime, timedelta +from pathlib import Path +from typing import Any, Final, Literal +from zoneinfo import ZoneInfo + +from apscheduler.schedulers.asyncio import AsyncIOScheduler +from apscheduler.triggers.date import DateTrigger +from pydantic import AwareDatetime, BaseModel, ConfigDict, Field, ValidationError + +from app.core.config_models import RuntimeConfig, SchedulerConfig, SourceRule +from app.core.config_store import ConfigStore +from app.core.json_store import atomic_write_json, read_json +from app.core.security import InvalidImageError +from app.providers.base import ProviderError +from app.providers.immich import ImmichDisplayRequest, ImmichProvider +from app.services.display import DisplayResult, DisplayService +from app.services.schedule import QuietWindow, in_quiet, next_run_at + +logger = logging.getLogger(__name__) + +JOB_ID: Final = "refresh" +DEFAULT_MIN_DELAY_S: Final = 30.0 +_MAX_BACKOFF_EXPONENT: Final = 16 + +RefreshReason = Literal["scheduled", "manual"] +RunStatus = Literal["ok", "failed", "skipped"] +RuleSource = Literal["pinned", "last"] +Clock = Callable[[], datetime] +RuleRunner = Callable[[SourceRule], Awaitable[DisplayResult]] + +#: Request fields that describe one action rather than the selection; never replayed. +NON_REPLAYED_FIELDS: Final = frozenset({"push_to_fraimic", "ignore_history"}) + + +def _utcnow() -> datetime: + return datetime.now(UTC) + + +# --- Errors ------------------------------------------------------------------------- +class RefreshError(Exception): + """Base class of refresh errors (messages are safe to show to API clients).""" + + +class RefreshBusyError(RefreshError): + """Another refresh is already running.""" + + +class NoRuleError(RefreshError): + """There is no rule to replay yet.""" + + +class UnsupportedRuleError(RefreshError): + """The active rule's source cannot be replayed (its provider is not available).""" + + +class InvalidRuleError(RefreshError): + """The active rule's parameters are not a valid request for its source.""" + + +# --- State -------------------------------------------------------------------------- +class LastRun(BaseModel): + """Outcome of the most recent refresh attempt (scheduled or manual).""" + + at: AwareDatetime + reason: RefreshReason + status: RunStatus + rule_kind: str | None = None + detail: str | None = Field(default=None, description="Skip reason or error message") + + +class SchedulerState(BaseModel): + """Scheduler bookkeeping persisted to ``scheduler_state.json``.""" + + model_config = ConfigDict(extra="ignore") + + last_rule: SourceRule | None = Field( + default=None, description="Last manual display request (replayed when nothing is pinned)" + ) + last_display_at: AwareDatetime | None = None + timer_reset_at: AwareDatetime | None = Field( + default=None, description="When the refresh timer last restarted (display or skip)" + ) + retry_at: AwareDatetime | None = Field( + default=None, description="When a failed scheduled refresh is retried" + ) + last_run: LastRun | None = None + consecutive_failures: int = Field(default=0, ge=0) + + +@dataclass(frozen=True, slots=True) +class ActiveRule: + """The rule a refresh replays, and where it comes from.""" + + rule: SourceRule + source: RuleSource + + +@dataclass(frozen=True, slots=True) +class RefreshOutcome: + """Result of a successful refresh.""" + + reason: RefreshReason + active: ActiveRule + display: DisplayResult + + +def quiet_window(config: SchedulerConfig) -> QuietWindow | None: + """The configured quiet window, or ``None`` when quiet hours are off.""" + return QuietWindow.parse(config.quiet_hours_start, config.quiet_hours_end) + + +def _safe_detail(exc: BaseException) -> str: + """A client-safe description of a refresh failure.""" + if isinstance(exc, ProviderError | RefreshError | InvalidImageError): + return str(exc) or type(exc).__name__ + return "Unexpected error (see the application logs)" + + +# --- Service ------------------------------------------------------------------------ +class SchedulerService: + """Owns the refresh timer, the replayable rule and the scheduler state file.""" + + def __init__( + self, + state_path: Path, + config_store: ConfigStore, + runners: Mapping[str, RuleRunner], + *, + has_pending: Callable[[], bool] = lambda: False, + clock: Clock = _utcnow, + min_delay_s: float = DEFAULT_MIN_DELAY_S, + ) -> None: + """Create the service (call :meth:`load` then :meth:`start`). + + Args: + state_path: Location of ``scheduler_state.json``. + config_store: Runtime configuration (the ``scheduler`` section). + runners: Coroutine replaying a rule, per :attr:`SourceRule.kind`. + has_pending: Whether an image still waits for the frame. + clock: Returns the current aware time (tests inject a fake clock). + min_delay_s: Minimum delay before a refresh, so an overdue run does not + fire in the middle of startup or of a configuration edit. + """ + self._path = state_path + self._config_store = config_store + self._runners = dict(runners) + self._has_pending = has_pending + self._clock = clock + self._min_delay = timedelta(seconds=min_delay_s) + self._lock = asyncio.Lock() + self._state = SchedulerState() + self._scheduler: AsyncIOScheduler | None = None + self._next_run_at: datetime | None = None + self._listening = False + + # --- Lifecycle ---------------------------------------------------------------------- + def load(self) -> SchedulerState: + """Restore the state file, ignoring it (with a warning) when it is malformed.""" + raw = read_json(self._path, lambda: None) + state = SchedulerState() + if raw is not None: + try: + state = SchedulerState.model_validate(raw) + except ValidationError: + logger.warning("Ignoring malformed scheduler state in %s", self._path) + self._state = state + self._next_run_at = self.compute_next_run() + return state + + async def start(self) -> None: + """Start the timer and follow configuration changes.""" + if not self._listening: + self._config_store.add_listener(self._on_config_change) + self._listening = True + if self._scheduler is None: + scheduler = AsyncIOScheduler(timezone=UTC) + scheduler.start() + self._scheduler = scheduler + self._arm() + + async def stop(self) -> None: + """Stop the timer (a refresh in progress is cancelled).""" + scheduler, self._scheduler = self._scheduler, None + if scheduler is not None and scheduler.running: + scheduler.shutdown(wait=False) + # AsyncIOScheduler shuts down on the next loop iteration; let it run. + await asyncio.sleep(0) + await asyncio.sleep(0) + + # --- Read access ------------------------------------------------------------------ + @property + def state(self) -> SchedulerState: + """The current scheduler state.""" + return self._state + + @property + def next_run_at(self) -> datetime | None: + """When the next scheduled refresh runs (``None`` when disabled).""" + return self._next_run_at + + @property + def running(self) -> bool: + """Whether a refresh is in progress.""" + return self._lock.locked() + + def active_rule(self) -> ActiveRule | None: + """The pinned rule, else the last manual one, else ``None``.""" + pinned = self._config.scheduler.source_rule + if pinned is not None: + return ActiveRule(pinned, "pinned") + if self._state.last_rule is not None: + return ActiveRule(self._state.last_rule, "last") + return None + + def in_quiet_hours(self) -> bool: + """Whether the current time falls inside the configured quiet window.""" + config = self._config.scheduler + return in_quiet(self._clock(), quiet_window(config), ZoneInfo(config.timezone)) + + def compute_next_run(self) -> datetime | None: + """When the next scheduled refresh should run, from the state and the config.""" + config = self._config.scheduler + if not config.enabled: + return None + now = self._clock() + state = self._state + if state.retry_at is not None: + due = state.retry_at + elif state.timer_reset_at is not None: + due = state.timer_reset_at + timedelta(hours=config.interval_hours) + else: + due = now + due = max(due, now + self._min_delay) + return next_run_at(due, quiet_window(config), ZoneInfo(config.timezone)) + + # --- Operations ------------------------------------------------------------------- + async def run(self, reason: RefreshReason = "manual") -> RefreshOutcome: + """Replay the active rule now, ignoring quiet hours and the pending check. + + A successful refresh resets the timer. A failed manual refresh is recorded in + :attr:`SchedulerState.last_run` but does not count as a scheduled failure. + + Raises: + RefreshBusyError: Another refresh is running. + NoRuleError: Nothing to replay yet. + UnsupportedRuleError: The rule's source cannot be replayed. + InvalidRuleError: The rule's parameters are invalid. + ProviderError: The image source failed (see :mod:`app.providers.base`). + InvalidImageError: The source returned bytes that are not an image. + """ + if self._lock.locked(): + raise RefreshBusyError("A refresh is already running") + try: + async with self._lock: + active = self.active_rule() + if active is None: + raise NoRuleError( + "Nothing to refresh yet: display a photo first, or pin a rule in " + "scheduler.source_rule" + ) + runner = self._runner(active.rule) + try: + display = await runner(active.rule) + except Exception as exc: + await self._save( + last_run=self._last_run(reason, "failed", active, _safe_detail(exc)) + ) + raise + await self._record_success(reason, active) + return RefreshOutcome(reason=reason, active=active, display=display) + finally: + self._arm() + + async def tick(self) -> LastRun | None: + """Scheduled refresh (the timer callback). Never raises. + + Returns: + The recorded outcome, or ``None`` when nothing was attempted (disabled, or a + manual refresh is already running and will re-arm the timer itself). + """ + if self._lock.locked(): + logger.info("Scheduled refresh skipped: a refresh is already running") + return None + try: + async with self._lock: + return await self._scheduled() + except Exception: + logger.exception("Scheduled refresh crashed") + return None + finally: + self._arm() + + async def record_manual(self, rule: SourceRule | None) -> None: + """Note a successful manual display: it resets the timer. + + Args: + rule: The request to replay from now on, or ``None`` for sources that cannot + be replayed (e.g. an uploaded file), which keep the previous rule. + """ + update: dict[str, Any] = self._timer_reset(self._clock()) + if rule is not None: + update["last_rule"] = rule + await self._save(**update) + self._arm() + + # --- Internals -------------------------------------------------------------------- + @property + def _config(self) -> RuntimeConfig: + return self._config_store.config + + def _runner(self, rule: SourceRule) -> RuleRunner: + runner = self._runners.get(rule.kind) + if runner is None: + raise UnsupportedRuleError(f"Replaying {rule.kind!r} rules is not supported yet") + return runner + + async def _scheduled(self) -> LastRun | None: + config = self._config.scheduler + if not config.enabled: + return None + if self.in_quiet_hours(): + # The configuration changed after the timer was armed: wait for the window + # end without restarting the interval. + return await self._skip("Quiet hours", None, restart_timer=False) + active = self.active_rule() + if active is None: + return await self._skip( + "No rule to replay yet: display a photo or pin scheduler.source_rule", None + ) + if config.skip_if_pending and self._has_pending(): + return await self._skip("The previous image is still waiting for the frame", active) + try: + runner = self._runner(active.rule) + except UnsupportedRuleError as exc: + return await self._skip(str(exc), active) + + try: + await runner(active.rule) + except asyncio.CancelledError: + raise + except Exception as exc: + if not isinstance(exc, ProviderError | RefreshError | InvalidImageError): + logger.exception("Scheduled refresh failed") + return await self._record_failure(active, exc) + return await self._record_success("scheduled", active) + + def _last_run( + self, + reason: RefreshReason, + status: RunStatus, + active: ActiveRule | None, + detail: str | None = None, + ) -> LastRun: + return LastRun( + at=self._clock(), + reason=reason, + status=status, + rule_kind=active.rule.kind if active else None, + detail=detail, + ) + + @staticmethod + def _timer_reset(now: datetime) -> dict[str, Any]: + return { + "last_display_at": now, + "timer_reset_at": now, + "retry_at": None, + "consecutive_failures": 0, + } + + async def _record_success(self, reason: RefreshReason, active: ActiveRule) -> LastRun: + last_run = self._last_run(reason, "ok", active) + await self._save(last_run=last_run, **self._timer_reset(last_run.at)) + logger.info("Refresh done (%s, %s rule %s)", reason, active.source, active.rule.kind) + return last_run + + async def _skip( + self, detail: str, active: ActiveRule | None, *, restart_timer: bool = True + ) -> LastRun: + last_run = self._last_run("scheduled", "skipped", active, detail) + update: dict[str, Any] = {"last_run": last_run} + if restart_timer: + update.update(timer_reset_at=last_run.at, retry_at=None) + await self._save(**update) + logger.info("Scheduled refresh skipped: %s", detail) + return last_run + + async def _record_failure(self, active: ActiveRule, exc: Exception) -> LastRun: + config = self._config.scheduler + failures = self._state.consecutive_failures + 1 + exponent = min(failures - 1, _MAX_BACKOFF_EXPONENT) + delay = min( + timedelta(minutes=config.retry_minutes * 2**exponent), + timedelta(hours=config.interval_hours), + ) + last_run = self._last_run("scheduled", "failed", active, _safe_detail(exc)) + await self._save( + last_run=last_run, consecutive_failures=failures, retry_at=last_run.at + delay + ) + logger.warning( + "Scheduled refresh failed (%d in a row), retrying in %s: %s", + failures, + delay, + last_run.detail, + ) + return last_run + + async def _save(self, **update: Any) -> None: + """Apply ``update`` to the state and persist it (a write error is only logged).""" + self._state = self._state.model_copy(update=update) + payload = self._state.model_dump(mode="json") + try: + await asyncio.to_thread(atomic_write_json, self._path, payload) + except OSError: + logger.exception("Could not write the scheduler state to %s", self._path) + + def _arm(self) -> None: + """Recompute the next refresh and (re)schedule or remove the timer job.""" + if self._lock.locked(): + return # the refresh in progress re-arms the timer when it finishes + previous, self._next_run_at = self._next_run_at, self.compute_next_run() + scheduler = self._scheduler + if scheduler is None: + return + if self._next_run_at is None: + if scheduler.get_job(JOB_ID) is not None: + scheduler.remove_job(JOB_ID) + logger.info("Scheduled refresh disabled") + return + scheduler.add_job( + self.tick, + trigger=DateTrigger(run_date=self._next_run_at), + id=JOB_ID, + name="Scheduled refresh", + replace_existing=True, + misfire_grace_time=None, # run late rather than never (e.g. after a suspend) + coalesce=True, + max_instances=1, + ) + if self._next_run_at != previous: + logger.info("Next scheduled refresh at %s", self._next_run_at.isoformat()) + + async def _on_config_change(self, _: RuntimeConfig) -> None: + self._arm() + + +# --- Runners -------------------------------------------------------------------------- +def _validation_summary(exc: ValidationError) -> str: + """Field errors without echoing input values.""" + return "; ".join( + f"{'.'.join(str(part) for part in err['loc']) or 'params'}: {err['msg']}" + for err in exc.errors(include_url=False, include_input=False, include_context=False) + ) + + +def immich_rule(request: ImmichDisplayRequest) -> SourceRule: + """The replayable rule of an Immich display request (only the fields it set).""" + params = request.model_dump(mode="json", exclude_unset=True, exclude=set(NON_REPLAYED_FIELDS)) + return SourceRule(kind="immich", params=params) + + +def immich_runner(provider: ImmichProvider, display: DisplayService) -> RuleRunner: + """Replay ``immich`` rules: pick a new photo with the same filters and push it.""" + + async def run(rule: SourceRule) -> DisplayResult: + params = { + key: value for key, value in rule.params.items() if key not in NON_REPLAYED_FIELDS + } + try: + request = ImmichDisplayRequest.model_validate(params) + except ValidationError as exc: + raise InvalidRuleError(f"Invalid immich rule: {_validation_summary(exc)}") from None + asset = await provider.fetch(request) + return await display.display_asset(asset, fit=request.fit, push=True) + + return run diff --git a/pyproject.toml b/pyproject.toml index d175422..1db39b8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -86,6 +86,10 @@ strict = true plugins = ["pydantic.mypy"] exclude = ["fraimic-docs/", "build/", "tests/reference/"] +[[tool.mypy.overrides]] +module = ["apscheduler.*"] +ignore_missing_imports = true + [tool.pydantic-mypy] init_forbid_extra = true init_typed = true diff --git a/tests/test_scheduler_service.py b/tests/test_scheduler_service.py new file mode 100644 index 0000000..0a0ea4d --- /dev/null +++ b/tests/test_scheduler_service.py @@ -0,0 +1,434 @@ +"""SchedulerService: timer planning, quiet hours, backoff, lock and persistence.""" + +from __future__ import annotations + +import asyncio +import json +from collections.abc import AsyncIterator, Callable +from datetime import UTC, datetime, timedelta +from pathlib import Path +from typing import Any, cast +from zoneinfo import ZoneInfo + +import pytest + +from app.core.config_models import SourceRule +from app.core.config_store import ConfigStore +from app.providers.base import ProviderUnavailableError +from app.providers.immich import ImmichDisplayRequest +from app.services.display import DisplayResult +from app.services.scheduler import ( + JOB_ID, + InvalidRuleError, + NoRuleError, + RefreshBusyError, + SchedulerService, + UnsupportedRuleError, + immich_rule, + immich_runner, +) + +PARIS = ZoneInfo("Europe/Paris") +# Far in the future so a timer armed from the fake clock never fires during a test. +T0 = datetime(2099, 1, 14, 12, 0, tzinfo=UTC) +ALICE = SourceRule(kind="immich", params={"persons": ["Alice"]}) +BOB = SourceRule(kind="immich", params={"persons": ["Bob"]}) +DISPLAY = cast(DisplayResult, object()) + + +class FakeClock: + def __init__(self, now: datetime = T0) -> None: + self.now = now + + def __call__(self) -> datetime: + return self.now + + def advance(self, **delta: float) -> None: + self.now += timedelta(**delta) + + +class FakeRunner: + def __init__(self) -> None: + self.calls: list[SourceRule] = [] + self.error: Exception | None = None + self.gate: asyncio.Event | None = None + + async def __call__(self, rule: SourceRule) -> DisplayResult: + self.calls.append(rule) + if self.gate is not None: + await self.gate.wait() + if self.error is not None: + raise self.error + return DISPLAY + + +class Harness: + def __init__(self, tmp_path: Path, clock: FakeClock, **scheduler: Any) -> None: + self.tmp_path = tmp_path + self.clock = clock + self.runner = FakeRunner() + self.pending = False + scheduler.setdefault("enabled", True) + self.store = ConfigStore(tmp_path / "config.json", {"scheduler": scheduler}) + self.store.load() + self.services: list[SchedulerService] = [] + + @property + def state_path(self) -> Path: + return self.tmp_path / "scheduler_state.json" + + def service(self, *, clock: Callable[[], datetime] | None = None, **kwargs: Any) -> Any: + service = SchedulerService( + self.state_path, + self.store, + {"immich": self.runner}, + has_pending=lambda: self.pending, + clock=clock or self.clock, + **kwargs, + ) + service.load() + self.services.append(service) + return service + + async def configure(self, **scheduler: Any) -> None: + await self.store.update({"scheduler": scheduler}) + + +HarnessFactory = Callable[..., Harness] + + +@pytest.fixture +async def harness(tmp_path: Path) -> AsyncIterator[HarnessFactory]: + made: list[Harness] = [] + + def _make(clock: FakeClock | None = None, **scheduler: Any) -> Harness: + h = Harness(tmp_path, clock or FakeClock(), **scheduler) + made.append(h) + return h + + yield _make + for h in made: + for service in h.services: + await service.stop() + + +async def eventually(condition: Callable[[], bool], timeout: float = 3.0) -> None: + deadline = asyncio.get_running_loop().time() + timeout + while not condition(): + assert asyncio.get_running_loop().time() < deadline, "condition not met in time" + await asyncio.sleep(0.01) + + +# --- Timer planning ------------------------------------------------------------------- +async def test_success_rearms_at_last_display_plus_interval(harness: HarnessFactory) -> None: + h = harness(interval_hours=6) + service = h.service() + await service.record_manual(ALICE) + assert service.next_run_at == T0 + timedelta(hours=6) + + h.clock.advance(hours=6) + last_run = await service.tick() + assert last_run is not None and last_run.status == "ok" and last_run.reason == "scheduled" + assert h.runner.calls == [ALICE] + assert service.state.last_display_at == T0 + timedelta(hours=6) + assert service.next_run_at == T0 + timedelta(hours=12) + + +async def test_any_display_resets_the_timer_and_uploads_keep_the_rule( + harness: HarnessFactory, +) -> None: + h = harness(interval_hours=6) + service = h.service() + await service.record_manual(ALICE) + h.clock.advance(hours=5) + await service.record_manual(None) # e.g. an uploaded file + assert service.next_run_at == T0 + timedelta(hours=11) + active = service.active_rule() + assert active is not None and (active.rule, active.source) == (ALICE, "last") + + +async def test_first_run_and_overdue_runs_wait_the_minimum_delay( + harness: HarnessFactory, +) -> None: + h = harness(interval_hours=1, source_rule=ALICE.model_dump()) + service = h.service(min_delay_s=30) + assert service.next_run_at == T0 + timedelta(seconds=30) # never displayed anything + await service.record_manual(None) + h.clock.advance(hours=5) # e.g. the app was down + assert service.compute_next_run() == h.clock.now + timedelta(seconds=30) + + +async def test_disabled_has_no_next_run(harness: HarnessFactory) -> None: + h = harness(enabled=False) + service = h.service() + await service.record_manual(ALICE) + assert service.next_run_at is None + assert await service.tick() is None + assert h.runner.calls == [] + + +# --- Quiet hours ------------------------------------------------------------------- +async def test_due_time_inside_quiet_hours_moves_to_the_window_end( + harness: HarnessFactory, +) -> None: + # 18:00 in Paris (CET, UTC+1) + 6 h = midnight, inside 22:00 -> 07:00. + clock = FakeClock(datetime(2099, 1, 14, 18, 0, tzinfo=PARIS)) + h = harness(clock, interval_hours=6, timezone="Europe/Paris") + await h.configure(quiet_hours_start="22:00", quiet_hours_end="07:00") + service = h.service() + await service.record_manual(ALICE) + assert service.next_run_at == datetime(2099, 1, 15, 7, 0, tzinfo=PARIS) + # The same window in UTC would end at 08:00 Paris time. + await h.configure(timezone="UTC") + service._arm() + assert service.next_run_at == datetime(2099, 1, 15, 7, 0, tzinfo=UTC) + + +async def test_tick_inside_quiet_hours_skips_and_waits_for_the_window_end( + harness: HarnessFactory, +) -> None: + clock = FakeClock(datetime(2099, 1, 14, 12, 0, tzinfo=PARIS)) + h = harness(clock, interval_hours=6, timezone="Europe/Paris") + service = h.service() + await service.record_manual(ALICE) + # The window is added after the timer was armed; the tick then lands inside it. + await h.configure(quiet_hours_start="17:00", quiet_hours_end="19:30") + clock.now = datetime(2099, 1, 14, 18, 0, tzinfo=PARIS) + last_run = await service.tick() + assert last_run is not None and last_run.status == "skipped" + assert last_run.detail == "Quiet hours" + assert h.runner.calls == [] + assert service.state.timer_reset_at == datetime(2099, 1, 14, 12, 0, tzinfo=PARIS) + assert service.next_run_at == datetime(2099, 1, 14, 19, 30, tzinfo=PARIS) + assert service.in_quiet_hours() is True + + +async def test_manual_run_ignores_quiet_hours_and_pending(harness: HarnessFactory) -> None: + clock = FakeClock(datetime(2099, 1, 14, 23, 0, tzinfo=PARIS)) + h = harness(clock, interval_hours=6, timezone="Europe/Paris") + await h.configure(quiet_hours_start="22:00", quiet_hours_end="07:00") + service = h.service() + await service.record_manual(ALICE) + h.pending = True + outcome = await service.run() + assert outcome.reason == "manual" and outcome.active.source == "last" + assert outcome.display is DISPLAY + assert h.runner.calls == [ALICE] + assert service.state.last_run is not None and service.state.last_run.reason == "manual" + # 23:00 + 6 h = 05:00, inside the window. + assert service.next_run_at == datetime(2099, 1, 15, 7, 0, tzinfo=PARIS) + + +# --- Skips and failures ------------------------------------------------------------ +async def test_skip_if_pending(harness: HarnessFactory) -> None: + h = harness(interval_hours=2) + service = h.service() + await service.record_manual(ALICE) + h.pending = True + h.clock.advance(hours=2) + last_run = await service.tick() + assert last_run is not None and last_run.status == "skipped" + assert last_run.detail is not None and "waiting for the frame" in last_run.detail + assert h.runner.calls == [] + assert service.next_run_at == h.clock.now + timedelta(hours=2) # the slot is consumed + + await h.configure(skip_if_pending=False) + h.clock.advance(hours=2) + last_run = await service.tick() + assert last_run is not None and last_run.status == "ok" + assert h.runner.calls == [ALICE] + + +async def test_failure_backoff_is_capped_and_reset_on_success(harness: HarnessFactory) -> None: + h = harness(interval_hours=1, retry_minutes=15) + service = h.service() + await service.record_manual(ALICE) + h.runner.error = ProviderUnavailableError("Immich is down") + + delays = [] + for _ in range(4): + h.clock.now = service.next_run_at + last_run = await service.tick() + assert last_run is not None and last_run.status == "failed" + assert last_run.detail == "Immich is down" + delays.append(service.next_run_at - h.clock.now) + assert delays == [timedelta(minutes=m) for m in (15, 30, 60, 60)] + assert service.state.consecutive_failures == 4 + + h.runner.error = None + h.clock.now = service.next_run_at + last_run = await service.tick() + assert last_run is not None and last_run.status == "ok" + assert service.state.consecutive_failures == 0 + assert service.state.retry_at is None + assert service.next_run_at == h.clock.now + timedelta(hours=1) + + +async def test_unexpected_errors_are_recorded_without_details(harness: HarnessFactory) -> None: + h = harness() + service = h.service() + await service.record_manual(ALICE) + h.runner.error = RuntimeError("secret internals") + last_run = await service.tick() + assert last_run is not None and last_run.status == "failed" + assert last_run.detail is not None and "secret" not in last_run.detail + + +async def test_manual_failure_does_not_count(harness: HarnessFactory) -> None: + h = harness(interval_hours=6) + service = h.service() + await service.record_manual(ALICE) + h.runner.error = ProviderUnavailableError("down") + with pytest.raises(ProviderUnavailableError): + await service.run() + assert service.state.consecutive_failures == 0 + assert service.state.last_run is not None + assert (service.state.last_run.reason, service.state.last_run.status) == ("manual", "failed") + assert service.next_run_at == T0 + timedelta(hours=6) # timer untouched + + +async def test_pinned_rule_beats_the_last_rule(harness: HarnessFactory) -> None: + h = harness() + service = h.service() + await service.record_manual(ALICE) + await h.configure(source_rule=BOB.model_dump()) + active = service.active_rule() + assert active is not None and (active.rule, active.source) == (BOB, "pinned") + await service.tick() + assert h.runner.calls == [BOB] + assert service.state.last_rule == ALICE # the manual rule is kept for later + + +async def test_no_rule(harness: HarnessFactory) -> None: + h = harness() + service = h.service() + last_run = await service.tick() + assert last_run is not None and last_run.status == "skipped" + assert last_run.detail is not None and "No rule" in last_run.detail + with pytest.raises(NoRuleError): + await service.run() + assert service.state.last_run == last_run # a refused manual run records nothing + + +async def test_unsupported_rule_kind(harness: HarnessFactory) -> None: + h = harness(source_rule={"kind": "media", "params": {"title": "Alien"}}) + service = h.service() + last_run = await service.tick() + assert last_run is not None and last_run.status == "skipped" + assert last_run.rule_kind == "media" + with pytest.raises(UnsupportedRuleError, match="media"): + await service.run() + + +async def test_concurrent_refresh_is_refused(harness: HarnessFactory) -> None: + h = harness() + service = h.service() + await service.record_manual(ALICE) + h.runner.gate = asyncio.Event() + first = asyncio.create_task(service.run()) + await eventually(lambda: bool(h.runner.calls)) + assert service.running + with pytest.raises(RefreshBusyError): + await service.run() + assert await service.tick() is None + h.runner.gate.set() + await first + assert len(h.runner.calls) == 1 + assert not service.running + + +# --- Persistence -------------------------------------------------------------------- +async def test_state_survives_a_restart(harness: HarnessFactory) -> None: + h = harness(interval_hours=4) + service = h.service() + await service.record_manual(ALICE) + h.clock.advance(hours=4) + h.runner.error = ProviderUnavailableError("down") + await service.tick() + + restarted = h.service() + assert restarted.state == service.state + assert restarted.state.last_rule == ALICE + assert restarted.state.consecutive_failures == 1 + assert restarted.next_run_at == service.next_run_at == h.clock.now + timedelta(minutes=15) + saved = json.loads(h.state_path.read_text(encoding="utf-8")) + assert saved["last_rule"] == {"kind": "immich", "params": {"persons": ["Alice"]}} + + +@pytest.mark.parametrize( + "content", ['{"consecutive_failures": -3}', '{"last_rule": {"kind": "ftp"}}', "[1, 2]"] +) +async def test_malformed_state_is_ignored( + harness: HarnessFactory, content: str, caplog: pytest.LogCaptureFixture +) -> None: + h = harness() + h.state_path.write_text(content, encoding="utf-8") + service = h.service() + assert service.state.last_rule is None + assert "malformed scheduler state" in caplog.text + + +async def test_corrupt_state_file_is_moved_aside(harness: HarnessFactory) -> None: + h = harness() + h.state_path.write_text("{oops", encoding="utf-8") + service = h.service() + assert service.state.last_rule is None + assert list(h.tmp_path.glob("scheduler_state.json.corrupt-*")) + + +# --- Timer job ---------------------------------------------------------------------- +async def test_config_changes_rearm_and_disabling_removes_the_job( + harness: HarnessFactory, +) -> None: + h = harness(interval_hours=6) + service = h.service() + await service.start() + await service.record_manual(ALICE) + job = service._scheduler.get_job(JOB_ID) + assert job is not None and job.next_run_time == T0 + timedelta(hours=6) + + await h.configure(interval_hours=2) + assert service.next_run_at == T0 + timedelta(hours=2) + assert service._scheduler.get_job(JOB_ID).next_run_time == T0 + timedelta(hours=2) + + await h.configure(enabled=False) + assert service.next_run_at is None + assert service._scheduler.get_job(JOB_ID) is None + + await h.configure(enabled=True) + assert service._scheduler.get_job(JOB_ID) is not None + + +async def test_real_timer_fires_once(harness: HarnessFactory) -> None: + h = harness(interval_hours=6, source_rule=ALICE.model_dump()) + service = h.service(clock=lambda: datetime.now(UTC), min_delay_s=0.05) + started = datetime.now(UTC) + await service.start() + await eventually(lambda: service.state.last_run is not None and not service.running, 5) + assert h.runner.calls == [ALICE] + assert service.state.last_run is not None and service.state.last_run.status == "ok" + assert service.next_run_at is not None + assert service.next_run_at - started > timedelta(hours=5, minutes=59) + await asyncio.sleep(0.2) + assert len(h.runner.calls) == 1 + await service.stop() + + +# --- Immich rules ------------------------------------------------------------------- +def test_immich_rule_keeps_only_replayable_fields() -> None: + request = ImmichDisplayRequest( + persons=["Alice"], album_name="Summer", push_to_fraimic=False, ignore_history=True + ) + rule = immich_rule(request) + assert rule.kind == "immich" + assert rule.params == {"persons": ["Alice"], "album_name": "Summer", "clip_queries": []} + + +async def test_immich_runner_rejects_invalid_params() -> None: + runner = immich_runner(cast(Any, None), cast(Any, None)) + rule = SourceRule(kind="immich", params={"mode": "bogus-mode", "extra": "x"}) + with pytest.raises(InvalidRuleError) as excinfo: + await runner(rule) + message = str(excinfo.value) + assert "mode" in message and "extra" in message + assert "bogus-mode" not in message From 758d80f5706c89a3383363c1754ba491874b80a3 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sat, 14 Nov 2026 22:42:12 +0100 Subject: [PATCH 40/86] feat: add POST /api/refresh and record manual displays POST /api/refresh replays the active rule now (pinned scheduler.source_rule, else the last manual display) and pushes the result, ignoring quiet hours and a pending upload. Errors: 409 when there is nothing to replay, the rule's source is not replayable yet or a refresh is already running; 422 for invalid rule parameters; provider errors keep their 404/409/422/502/504 mapping, now shared in app/api/errors.py. Pushed Immich displays become the replayable rule (without push_to_fraimic/ignore_history) and restart the timer; pushed uploads restart the timer but keep the previous rule. Previews (push_to_fraimic=false) change neither. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- app/api/errors.py | 37 ++++++++++ app/api/routes/display.py | 11 ++- app/api/routes/immich.py | 48 +++++-------- app/api/routes/refresh.py | 72 +++++++++++++++++++ app/main.py | 2 + tests/test_api_refresh.py | 144 ++++++++++++++++++++++++++++++++++++++ 6 files changed, 281 insertions(+), 33 deletions(-) create mode 100644 app/api/errors.py create mode 100644 app/api/routes/refresh.py create mode 100644 tests/test_api_refresh.py diff --git a/app/api/errors.py b/app/api/errors.py new file mode 100644 index 0000000..60a680e --- /dev/null +++ b/app/api/errors.py @@ -0,0 +1,37 @@ +"""HTTP mapping of the errors image providers raise on purpose.""" + +from __future__ import annotations + +from typing import Any, Final + +from fastapi import HTTPException + +from app.providers.base import ( + InvalidSelectionError, + NoCandidateError, + ProviderError, + ProviderNotConfiguredError, + ProviderUnavailableError, +) + +#: OpenAPI ``responses`` documenting :func:`provider_http_error`. +PROVIDER_ERROR_RESPONSES: Final[dict[int | str, dict[str, Any]]] = { + 404: {"description": "No eligible photo matched (or all are on the anti-repeat cooldown)"}, + 409: {"description": "The source is not configured"}, + 422: {"description": "Unknown or ambiguous person, album or account"}, + 502: {"description": "The source failed or rejected its API key"}, + 504: {"description": "The source did not respond in time"}, +} + + +def provider_http_error(exc: ProviderError) -> HTTPException: + """Map a provider error to an HTTP error (messages never contain secrets).""" + if isinstance(exc, ProviderNotConfiguredError): + return HTTPException(status_code=409, detail=str(exc)) + if isinstance(exc, InvalidSelectionError): + return HTTPException(status_code=422, detail=str(exc)) + if isinstance(exc, NoCandidateError): + return HTTPException(status_code=404, detail=str(exc)) + if isinstance(exc, ProviderUnavailableError): + return HTTPException(status_code=504 if exc.timeout else 502, detail=str(exc)) + return HTTPException(status_code=500, detail="Image provider error") diff --git a/app/api/routes/display.py b/app/api/routes/display.py index 3159aa3..e109b86 100644 --- a/app/api/routes/display.py +++ b/app/api/routes/display.py @@ -8,7 +8,7 @@ from fastapi import APIRouter, File, Form, HTTPException, Security, UploadFile -from app.api.deps import DisplayServiceDep, SettingsDep +from app.api.deps import DisplayServiceDep, SchedulerDep, SettingsDep from app.core.auth import api_key_scheme from app.core.config_models import FitMode from app.core.security import InvalidImageError, PayloadTooLargeError, read_upload @@ -44,6 +44,7 @@ def _clean_filename(name: str | None) -> str | None: async def display_upload( settings: SettingsDep, display: DisplayServiceDep, + scheduler: SchedulerDep, file: Annotated[UploadFile, File(description="Image file (max MAX_UPLOAD_MB)")], fit: Annotated[FitMode | None, Form(description="Override the default fit mode")] = None, push_to_fraimic: Annotated[ @@ -53,7 +54,8 @@ async def display_upload( """Render an uploaded image for the frame and make it the current image. In ``continuous`` mode the response includes the delivery outcome; in ``deepsleep`` - mode the image is queued until the frame wakes up. + mode the image is queued until the frame wakes up. A pushed upload restarts the + refresh timer but keeps the rule replayed by ``POST /api/refresh``. """ try: data = await read_upload(file, settings.max_upload_bytes) @@ -64,7 +66,7 @@ async def display_upload( title = _clean_filename(file.filename) try: - return await display.display_bytes( + result = await display.display_bytes( data, source="upload", title=title, @@ -74,3 +76,6 @@ async def display_upload( ) except InvalidImageError as exc: raise HTTPException(status_code=415, detail=str(exc)) from exc + if push_to_fraimic: + await scheduler.record_manual(None) + return result diff --git a/app/api/routes/immich.py b/app/api/routes/immich.py index e900ff6..38ea4f4 100644 --- a/app/api/routes/immich.py +++ b/app/api/routes/immich.py @@ -13,19 +13,16 @@ DisplayServiceDep, ImmichProviderDep, PeopleDirectoryDep, + SchedulerDep, ) +from app.api.errors import PROVIDER_ERROR_RESPONSES, provider_http_error from app.core.auth import api_key_scheme from app.core.security import InvalidImageError -from app.providers.base import ( - InvalidSelectionError, - NoCandidateError, - ProviderError, - ProviderNotConfiguredError, - ProviderUnavailableError, -) +from app.providers.base import InvalidSelectionError, ProviderError from app.providers.immich.models import AlbumInfo, ImmichDisplayRequest from app.providers.immich.people import PeopleSnapshot, resolve_person from app.services.display import DisplayResult +from app.services.scheduler import immich_rule display_router = APIRouter( prefix="/api/display", tags=["display"], dependencies=[Security(api_key_scheme)] @@ -37,27 +34,11 @@ ] _ERRORS: dict[int | str, dict[str, Any]] = { - 404: {"description": "No eligible photo matched (or all are on the anti-repeat cooldown)"}, + **PROVIDER_ERROR_RESPONSES, 409: {"description": "No Immich account is configured"}, - 422: {"description": "Unknown or ambiguous person, album or account"}, - 502: {"description": "Immich failed or rejected the API key"}, - 504: {"description": "Immich did not respond in time"}, } -def http_error(exc: ProviderError) -> HTTPException: - """Map a provider error to an HTTP error (messages never contain secrets).""" - if isinstance(exc, ProviderNotConfiguredError): - return HTTPException(status_code=409, detail=str(exc)) - if isinstance(exc, InvalidSelectionError): - return HTTPException(status_code=422, detail=str(exc)) - if isinstance(exc, NoCandidateError): - return HTTPException(status_code=404, detail=str(exc)) - if isinstance(exc, ProviderUnavailableError): - return HTTPException(status_code=504 if exc.timeout else 502, detail=str(exc)) - return HTTPException(status_code=500, detail="Image provider error") - - @display_router.post( "/immich", response_model=DisplayResult, @@ -65,25 +46,32 @@ def http_error(exc: ProviderError) -> HTTPException: summary="Select and display an Immich photo", ) async def display_immich( - request: ImmichDisplayRequest, provider: ImmichProviderDep, display: DisplayServiceDep + request: ImmichDisplayRequest, + provider: ImmichProviderDep, + display: DisplayServiceDep, + scheduler: SchedulerDep, ) -> DisplayResult: """Pick a photo from Immich, render it (face-aware crop) and make it the current image. People are plain names resolved per account; ``persons``, ``match_mode``, ``album_*`` and ``always_include`` fall back to the ``immich`` section of the configuration. The photo is recorded in the history so it is not shown again within - ``immich.anti_repeat_days``. + ``immich.anti_repeat_days``. When pushed to the frame, the request becomes the rule + replayed by ``POST /api/refresh`` and the scheduler, and the refresh timer restarts. """ try: asset = await provider.fetch(request) except ProviderError as exc: - raise http_error(exc) from exc + raise provider_http_error(exc) from exc try: - return await display.display_asset(asset, fit=request.fit, push=request.push_to_fraimic) + result = await display.display_asset(asset, fit=request.fit, push=request.push_to_fraimic) except InvalidImageError as exc: raise HTTPException( status_code=502, detail="Immich returned an image that cannot be decoded" ) from exc + if request.push_to_fraimic: + await scheduler.record_manual(immich_rule(request)) + return result class AlbumsResponse(BaseModel): @@ -103,7 +91,7 @@ async def list_albums( try: albums, errors = await provider.albums(accounts) except ProviderError as exc: - raise http_error(exc) from exc + raise provider_http_error(exc) from exc return AlbumsResponse(albums=albums, errors=errors) @@ -164,7 +152,7 @@ async def _people_response( try: names = list(directory.account_names(accounts)) except ProviderError as exc: - raise http_error(exc) from exc + raise provider_http_error(exc) from exc snapshots = await directory.snapshot(names, refresh=refresh) aliases = config.config.immich.person_aliases return PeopleResponse(accounts=[_view(snapshot, aliases) for snapshot in snapshots]) diff --git a/app/api/routes/refresh.py b/app/api/routes/refresh.py new file mode 100644 index 0000000..ddb83fb --- /dev/null +++ b/app/api/routes/refresh.py @@ -0,0 +1,72 @@ +"""``POST /api/refresh``: replay the active source rule now.""" + +from __future__ import annotations + +from typing import Any, Literal + +from fastapi import APIRouter, HTTPException, Security +from pydantic import BaseModel, Field + +from app.api.deps import SchedulerDep +from app.api.errors import PROVIDER_ERROR_RESPONSES, provider_http_error +from app.core.auth import api_key_scheme +from app.core.security import InvalidImageError +from app.providers.base import ProviderError +from app.services.display import DisplayResult +from app.services.scheduler import InvalidRuleError, RefreshError, RuleSource + +router = APIRouter(prefix="/api", tags=["display"], dependencies=[Security(api_key_scheme)]) + + +class RefreshResult(BaseModel): + """Outcome of a manual refresh.""" + + reason: Literal["manual"] = "manual" + rule_kind: str = Field(description="Source of the replayed rule (immich, media, url)") + rule_source: RuleSource = Field( + description="pinned = scheduler.source_rule; last = the last manual display request" + ) + display: DisplayResult + + +_RESPONSES: dict[int | str, dict[str, Any]] = { + **PROVIDER_ERROR_RESPONSES, + 409: { + "description": "Nothing to replay yet, the rule's source cannot be replayed, the " + "source is not configured, or a refresh is already running" + }, + 422: {"description": "The rule's parameters are invalid, or name unknown people/albums"}, + 502: {"description": "The source failed or returned an image that cannot be decoded"}, +} + + +@router.post( + "/refresh", + response_model=RefreshResult, + responses=_RESPONSES, + summary="Re-run the active source rule", +) +async def refresh(scheduler: SchedulerDep) -> RefreshResult: + """Show a new image chosen by the active rule and push it to the frame. + + The active rule is the pinned ``scheduler.source_rule`` when set, otherwise the last + request made through ``POST /api/display/immich``. Unlike scheduled refreshes, a + manual refresh ignores quiet hours and a pending upload. It restarts the timer. + """ + try: + outcome = await scheduler.run("manual") + except InvalidRuleError as exc: + raise HTTPException(status_code=422, detail=str(exc)) from exc + except RefreshError as exc: + raise HTTPException(status_code=409, detail=str(exc)) from exc + except ProviderError as exc: + raise provider_http_error(exc) from exc + except InvalidImageError as exc: + raise HTTPException( + status_code=502, detail="The source returned an image that cannot be decoded" + ) from exc + return RefreshResult( + rule_kind=outcome.active.rule.kind, + rule_source=outcome.active.source, + display=outcome.display, + ) diff --git a/app/main.py b/app/main.py index 01be3c4..1c28fad 100644 --- a/app/main.py +++ b/app/main.py @@ -24,6 +24,7 @@ from app.api.routes import fraimic as fraimic_routes from app.api.routes import images as image_routes from app.api.routes import immich as immich_routes +from app.api.routes import refresh as refresh_routes from app.api.routes import system as system_routes from app.core.auth import APIKeyMiddleware from app.core.config_models import RuntimeConfig @@ -192,6 +193,7 @@ async def _validation_handler(_: Request, exc: RequestValidationError) -> JSONRe app.include_router(display_routes.router) app.include_router(immich_routes.display_router) app.include_router(immich_routes.router) + app.include_router(refresh_routes.router) app.include_router(fraimic_routes.router) @app.get("/", include_in_schema=False) diff --git a/tests/test_api_refresh.py b/tests/test_api_refresh.py new file mode 100644 index 0000000..77ecee4 --- /dev/null +++ b/tests/test_api_refresh.py @@ -0,0 +1,144 @@ +"""API tests for POST /api/refresh and the scheduler block of /api/status.""" + +from __future__ import annotations + +import io +from typing import Any + +import httpx +from fastapi.testclient import TestClient +from PIL import Image + +from tests.conftest import ClientFactory +from tests.immich_fake import FakeImmich +from tests.test_api_immich import KEY, immich_client, servers, show + + +def alice_and_bob() -> FakeImmich: + """Three Alice photos taken on different days (no burst cooldown) and one of Bob.""" + fake = FakeImmich() + fake.add_person("p1", "Alice") + fake.add_person("p2", "Bob") + for index, day in enumerate(("2024-07-01", "2024-08-01", "2024-09-01"), start=1): + fake.add_asset(f"a{index}", people=[("p1", "Alice")], localDateTime=f"{day}T10:00:00.000Z") + fake.add_asset("b1", people=[("p2", "Bob")], localDateTime="2023-01-01T10:00:00.000Z") + return fake + + +def refresh(client: TestClient, **headers: str) -> httpx.Response: + return client.post("/api/refresh", headers=headers) + + +def searched_person_ids(fake: FakeImmich) -> list[list[str]]: + return [body.get("personIds", []) for body in fake.bodies("/api/search/random")] + + +def upload(client: TestClient) -> httpx.Response: + buffer = io.BytesIO() + Image.new("RGB", (640, 480), (200, 80, 40)).save(buffer, format="JPEG") + return client.post( + "/api/display/upload", + files={"file": ("holiday.jpg", buffer.getvalue(), "image/jpeg")}, + data={"push_to_fraimic": "true"}, + ) + + +def pin(client: TestClient, rule: dict[str, Any] | None) -> None: + response = client.put("/api/config", json={"scheduler": {"source_rule": rule}}) + assert response.status_code == 200, response.text + + +# --- Replay ----------------------------------------------------------------------------- +def test_refresh_replays_the_last_display(make_client: ClientFactory) -> None: + fake = alice_and_bob() + client = immich_client(make_client) + with servers(fake) as router: + first = show(client, persons=["Alice"], fit="contain") + assert first.status_code == 200, first.text + response = refresh(client) + assert response.status_code == 200, response.text + uploads = [c for c in router.calls if c.request.url.path == "/api/image"] + + body = response.json() + assert (body["reason"], body["rule_kind"], body["rule_source"]) == ("manual", "immich", "last") + assert body["display"]["image"]["source"] == "immich" + assert body["display"]["image"]["fit"] == "contain" # the fit is replayed too + assert body["display"]["image"]["title"].startswith("Alice") + assert ( + body["display"]["image"]["details"]["asset_id"] + != first.json()["image"]["details"]["asset_id"] + ) # anti-repeat history still applies + assert body["display"]["delivery"]["status"] == "delivered" + assert len(uploads) == 2 + assert searched_person_ids(fake)[-1] == searched_person_ids(fake)[0] == ["p1"] + + +def test_refresh_without_a_rule_is_a_conflict(make_client: ClientFactory) -> None: + client = make_client() + response = refresh(client) + assert response.status_code == 409 + assert "Nothing to refresh" in response.json()["detail"] + + +def test_previews_do_not_become_the_rule(make_client: ClientFactory) -> None: + fake = alice_and_bob() + client = immich_client(make_client) + with servers(fake, frame=False): + assert show(client, persons=["Alice"], push_to_fraimic=False).status_code == 200 + assert refresh(client).status_code == 409 + + +def test_uploads_keep_the_replayable_rule(make_client: ClientFactory) -> None: + fake = alice_and_bob() + fake.add_asset("b2", people=[("p2", "Bob")], localDateTime="2022-01-01T10:00:00.000Z") + client = immich_client(make_client) + with servers(fake): + assert show(client, persons=["Bob"]).status_code == 200 + assert upload(client).status_code == 200 + assert client.get("/api/status").json()["current_image"]["source"] == "upload" + response = refresh(client) + assert response.status_code == 200, response.text + assert response.json()["display"]["image"]["title"].startswith("Bob") + + +# --- Pinned rule --------------------------------------------------------------------- +def test_pinned_rule_wins(make_client: ClientFactory) -> None: + fake = alice_and_bob() + client = immich_client(make_client) + with servers(fake): + assert show(client, persons=["Alice"]).status_code == 200 + pin(client, {"kind": "immich", "params": {"persons": ["Bob"]}}) + response = refresh(client) + assert response.status_code == 200, response.text + assert response.json()["rule_source"] == "pinned" + assert response.json()["display"]["image"]["title"].startswith("Bob") + + +def test_pinned_rule_errors(make_client: ClientFactory) -> None: + client = immich_client(make_client) + pin(client, {"kind": "media", "params": {"title": "Alien"}}) + unsupported = refresh(client) + assert unsupported.status_code == 409 and "media" in unsupported.json()["detail"] + + pin(client, {"kind": "immich", "params": {"mode": "teleport"}}) + invalid = refresh(client) + assert invalid.status_code == 422 and "mode" in invalid.json()["detail"] + assert "teleport" not in invalid.text + + +# --- Provider errors --------------------------------------------------------------- +def test_provider_errors_are_mapped(make_client: ClientFactory) -> None: + fake = alice_and_bob() + client = immich_client(make_client) + with servers(fake): + assert show(client, persons=["Bob"]).status_code == 200 + exhausted = refresh(client) # Bob's only photo is on the anti-repeat cooldown + assert exhausted.status_code == 404 + fake.search_error = 500 + assert refresh(client).status_code == 502 + + +def test_refresh_requires_the_api_key(make_client: ClientFactory) -> None: + client = make_client(app_api_key=KEY) + assert refresh(client).status_code == 401 + assert refresh(client, **{"X-API-Key": KEY}).status_code == 409 From 4526cd4ba6b36d80654134bbf9e4816c0be85d3b Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sat, 14 Nov 2026 22:43:56 +0100 Subject: [PATCH 41/86] feat: expose scheduler state in /api/status The scheduler block of GET /api/status now reports the quiet window, whether it is currently quiet, the next scheduled refresh (in the configured timezone), whether a refresh is running, the last run with its outcome, the last display time, consecutive failures and which rule would be replayed (pinned or last). Still network-free. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- app/api/routes/system.py | 19 ++++--------- app/services/scheduler.py | 59 ++++++++++++++++++++++++++++++++++++++ tests/test_api_refresh.py | 60 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 124 insertions(+), 14 deletions(-) diff --git a/app/api/routes/system.py b/app/api/routes/system.py index 565eb84..b5c68d7 100644 --- a/app/api/routes/system.py +++ b/app/api/routes/system.py @@ -13,10 +13,12 @@ ConfigStoreDep, CurrentImageStoreDep, DeliveryServiceDep, + SchedulerDep, SettingsDep, ) from app.services.current_image import CurrentImageMeta from app.services.delivery import FrameTelemetry, LastDelivery, PendingUpload +from app.services.scheduler import SchedulerSnapshot router = APIRouter(prefix="/api", tags=["system"]) @@ -48,14 +50,6 @@ class DeliveryStatus(BaseModel): last_delivery: LastDelivery | None = None -class SchedulerStatus(BaseModel): - """Configured autonomous refresh.""" - - enabled: bool - interval_hours: float - timezone: str - - class ServiceConfigured(BaseModel): """Whether each external service has the settings it needs.""" @@ -75,7 +69,7 @@ class StatusResponse(BaseModel): current_image: CurrentImageMeta | None = Field( default=None, description="Metadata of the current image (null before the first one)" ) - scheduler: SchedulerStatus + scheduler: SchedulerSnapshot = Field(description="Autonomous refresh: timer and last run") services: ServiceConfigured @@ -92,6 +86,7 @@ async def status( store: ConfigStoreDep, current: CurrentImageStoreDep, delivery: DeliveryServiceDep, + scheduler: SchedulerDep, ) -> StatusResponse: """Overall system status, queue state and current image (no secrets, no network).""" config = store.config @@ -117,11 +112,7 @@ async def status( last_delivery=snapshot.last_delivery, ), current_image=current.meta, - scheduler=SchedulerStatus( - enabled=config.scheduler.enabled, - interval_hours=config.scheduler.interval_hours, - timezone=config.scheduler.timezone, - ), + scheduler=scheduler.snapshot(), services=ServiceConfigured( immich=bool(config.immich.accounts), tmdb=bool(config.tmdb.api_key.get_secret_value()), diff --git a/app/services/scheduler.py b/app/services/scheduler.py index 50eef64..193ce7a 100644 --- a/app/services/scheduler.py +++ b/app/services/scheduler.py @@ -133,6 +133,40 @@ class RefreshOutcome: display: DisplayResult +class QuietHoursView(BaseModel): + """The configured quiet window (local time of ``timezone``).""" + + start: str + end: str + + +class ActiveRuleView(BaseModel): + """Which rule a refresh would replay.""" + + kind: str + source: RuleSource = Field( + description="pinned = scheduler.source_rule; last = the last manual display request" + ) + + +class SchedulerSnapshot(BaseModel): + """Scheduler state exposed through ``GET /api/status`` (no network access).""" + + enabled: bool + interval_hours: float + timezone: str + quiet_hours: QuietHoursView | None = Field(description="null when quiet hours are off") + in_quiet_hours: bool + next_run_at: AwareDatetime | None = Field( + description="Next scheduled refresh in the scheduler timezone (null when disabled)" + ) + running: bool = Field(description="Whether a refresh is in progress") + last_run: LastRun | None + last_display_at: AwareDatetime | None + consecutive_failures: int + active_rule: ActiveRuleView | None = Field(description="null until something can be replayed") + + def quiet_window(config: SchedulerConfig) -> QuietWindow | None: """The configured quiet window, or ``None`` when quiet hours are off.""" return QuietWindow.parse(config.quiet_hours_start, config.quiet_hours_end) @@ -246,6 +280,31 @@ def in_quiet_hours(self) -> bool: config = self._config.scheduler return in_quiet(self._clock(), quiet_window(config), ZoneInfo(config.timezone)) + def snapshot(self) -> SchedulerSnapshot: + """Current scheduler state for the status endpoint.""" + config = self._config.scheduler + active = self.active_rule() + quiet = ( + QuietHoursView(start=config.quiet_hours_start, end=config.quiet_hours_end) + if config.quiet_hours_start and config.quiet_hours_end + else None + ) + return SchedulerSnapshot( + enabled=config.enabled, + interval_hours=config.interval_hours, + timezone=config.timezone, + quiet_hours=quiet, + in_quiet_hours=self.in_quiet_hours(), + next_run_at=self._next_run_at, + running=self.running, + last_run=self._state.last_run, + last_display_at=self._state.last_display_at, + consecutive_failures=self._state.consecutive_failures, + active_rule=( + ActiveRuleView(kind=active.rule.kind, source=active.source) if active else None + ), + ) + def compute_next_run(self) -> datetime | None: """When the next scheduled refresh should run, from the state and the config.""" config = self._config.scheduler diff --git a/tests/test_api_refresh.py b/tests/test_api_refresh.py index 77ecee4..3c6087d 100644 --- a/tests/test_api_refresh.py +++ b/tests/test_api_refresh.py @@ -3,7 +3,9 @@ from __future__ import annotations import io +from datetime import datetime, timedelta from typing import Any +from zoneinfo import ZoneInfo import httpx from fastapi.testclient import TestClient @@ -136,9 +138,67 @@ def test_provider_errors_are_mapped(make_client: ClientFactory) -> None: assert exhausted.status_code == 404 fake.search_error = 500 assert refresh(client).status_code == 502 + status = client.get("/api/status").json()["scheduler"] + assert status["last_run"]["status"] == "failed" + assert status["last_run"]["reason"] == "manual" + assert status["last_run"]["detail"] + assert status["consecutive_failures"] == 0 # manual failures do not back off def test_refresh_requires_the_api_key(make_client: ClientFactory) -> None: client = make_client(app_api_key=KEY) assert refresh(client).status_code == 401 assert refresh(client, **{"X-API-Key": KEY}).status_code == 409 + + +# --- Status --------------------------------------------------------------------------- +def test_status_when_disabled(make_client: ClientFactory) -> None: + status = make_client().get("/api/status").json()["scheduler"] + assert status == { + "enabled": False, + "interval_hours": 6.0, + "timezone": "UTC", + "quiet_hours": None, + "in_quiet_hours": False, + "next_run_at": None, + "running": False, + "last_run": None, + "last_display_at": None, + "consecutive_failures": 0, + "active_rule": None, + } + + +def test_status_after_a_display(make_client: ClientFactory) -> None: + fake = alice_and_bob() + client = immich_client( + make_client, scheduler_enabled=True, refresh_interval_hours=2, tz="Europe/Paris" + ) + with servers(fake): + assert show(client, persons=["Alice"]).status_code == 200 + status = client.get("/api/status").json()["scheduler"] + assert status["enabled"] is True and status["timezone"] == "Europe/Paris" + assert status["active_rule"] == {"kind": "immich", "source": "last"} + shown = datetime.fromisoformat(status["last_display_at"]) + next_run = datetime.fromisoformat(status["next_run_at"]) + assert next_run - shown == timedelta(hours=2) + assert next_run.utcoffset() == next_run.astimezone(ZoneInfo("Europe/Paris")).utcoffset() + + +def test_status_inside_quiet_hours(make_client: ClientFactory) -> None: + paris = ZoneInfo("Europe/Paris") + now = datetime.now(paris) + start = (now - timedelta(hours=1)).strftime("%H:%M") + end_at = now + timedelta(hours=1) + client = make_client( + scheduler_enabled=True, + refresh_interval_hours=0.25, + tz="Europe/Paris", + quiet_hours_start=start, + quiet_hours_end=end_at.strftime("%H:%M"), + ) + status = client.get("/api/status").json()["scheduler"] + assert status["quiet_hours"] == {"start": start, "end": end_at.strftime("%H:%M")} + assert status["in_quiet_hours"] is True + next_run = datetime.fromisoformat(status["next_run_at"]).astimezone(paris) + assert next_run.strftime("%Y-%m-%d %H:%M") == end_at.strftime("%Y-%m-%d %H:%M") From ce3de2eb1e2b7a8f0345b813908867ae55fa8770 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sat, 14 Nov 2026 22:44:24 +0100 Subject: [PATCH 42/86] docs: document the scheduler, quiet hours and refresh README gains a Scheduler section: the active rule (last manual display or pinned scheduler.source_rule), the timer reset on every display, quiet hours with TZ, retry backoff, skip_if_pending, POST /api/refresh, the new /api/status fields and a Home Assistant rest_command example. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- README.md | 56 +++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 52 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index ad5224e..2764bbc 100644 --- a/README.md +++ b/README.md @@ -5,9 +5,9 @@ TMDB movie/TV posters, direct URLs), optimizes them for a color eInk panel (Spec and pushes them to a [Fraimic](https://fraimic.com) picture frame. Home Assistant friendly, runs standalone in Docker. -> **Status:** early development (`v0.x`). The core service, the eInk pipeline and frame -> delivery (continuous and deep-sleep) are in place; image providers and the web UI are -> being added milestone by milestone. +> **Status:** early development (`v0.x`). The core service, the eInk pipeline, frame +> delivery (continuous and deep-sleep), the Immich provider and the autonomous scheduler +> are in place; more providers and the web UI are being added milestone by milestone. ## Quickstart @@ -165,7 +165,55 @@ The frame is driven through its local REST API (`GET /api/info`, `POST /api/imag | `POST /api/fraimic/push` | Force push the current image now (200 delivered, 202 queued) | | `POST /api/fraimic/wakeup` | Frame is awake: flush the queue (202, or `?wait=true` for the outcome) | | `GET /api/fraimic/info` | Last known battery / Wi-Fi / firmware (`?refresh=true` queries the frame) | -| `GET /api/status` | Frame telemetry, queue state and current image metadata | +| `GET /api/status` | Frame telemetry, queue state, current image metadata and scheduler state | + +## Scheduler + +The frame can update itself without Home Assistant. The scheduler replays the **active +rule** every `scheduler.interval_hours` hours (`REFRESH_INTERVAL_HOURS`, default 6, minimum +0.25) once `scheduler.enabled` is on (`SCHEDULER_ENABLED=true`): + +- **Active rule.** The last request made through `POST /api/display/immich` (pushed to the + frame; previews with `push_to_fraimic=false` do not count), so showing "Alice and Bob + at the beach" once keeps rotating through those photos with the anti-repeat history. + Pin a fixed rule in `scheduler.source_rule` to override it: + + ```bash + curl -X PUT http://localhost:8000/api/config -H 'Content-Type: application/json' -d '{"scheduler": {"enabled": true, "source_rule": + {"kind": "immich", "params": {"mode": "favorites", "persons": ["Alice"]}}}}' + ``` + + `params` takes the fields of `POST /api/display/immich` (except `push_to_fraimic` and + `ignore_history`). Only Immich rules can be replayed for now. The last rule is kept in + `./data/scheduler_state.json`, so displaying a photo never rewrites your settings. +- **Timer.** Any display (a manual photo, an upload, a refresh) restarts the interval, so + a picture chosen by hand stays up for a full interval. A refresh that became due while + the app was down runs about 30 s after startup. +- **Quiet hours.** `QUIET_HOURS_START` / `QUIET_HOURS_END` (24h `HH:MM`, may cross + midnight, e.g. `22:00` -> `07:00`) in the timezone `TZ` (IANA, e.g. `Europe/Paris`; the + container otherwise runs in UTC). A refresh due inside the window runs when it ends; + daylight saving changes are handled. +- **Failures.** If Immich is down or nothing matches, the refresh is retried after + `scheduler.retry_minutes` (default 15), doubling each time, capped by the interval. +- **Sleeping frames.** With `scheduler.skip_if_pending` (default on), a scheduled refresh + is skipped while the previous image still waits in the deep-sleep queue, so an image the + frame never showed is not replaced. + +| Endpoint | Purpose | +| --- | --- | +| `POST /api/refresh` | Replay the active rule now and push the result (ignores quiet hours; 409 when there is nothing to replay or a refresh is running) | +| `GET /api/status` | `scheduler`: `next_run_at`, `in_quiet_hours`, `last_run` (`ok`/`failed`/`skipped` and why), `consecutive_failures`, `active_rule` (`pinned` or `last`) | + +```yaml +# Home Assistant: a "next photo" button +rest_command: + frame_next_photo: + url: http://smart-frame.lan:8000/api/refresh + method: POST + timeout: 60 # selecting, downloading and dithering a photo takes a few seconds + headers: + X-API-Key: !secret smart_frame_api_key # only when APP_API_KEY is set +``` ## Development From 078c274f91ca9fcdcc42077788b13d66a7c7a118 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sun, 15 Nov 2026 14:35:40 +0100 Subject: [PATCH 43/86] feat: add date filters and on_this_day to Immich search Add taken_after/taken_before and an on_this_day memory mode (one date window per past year around today's date) to ImmichDisplayRequest. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- app/providers/immich/dates.py | 36 ++++++++++++++++++++ app/providers/immich/models.py | 49 ++++++++++++++++++++++++++- app/providers/immich/provider.py | 35 +++++++++++++++---- tests/immich_fake.py | 7 ++++ tests/test_immich_dates.py | 43 +++++++++++++++++++++++ tests/test_immich_provider.py | 58 ++++++++++++++++++++++++++++++++ 6 files changed, 221 insertions(+), 7 deletions(-) create mode 100644 app/providers/immich/dates.py create mode 100644 tests/test_immich_dates.py diff --git a/app/providers/immich/dates.py b/app/providers/immich/dates.py new file mode 100644 index 0000000..b769a27 --- /dev/null +++ b/app/providers/immich/dates.py @@ -0,0 +1,36 @@ +"""Date windows for "on this day" memories.""" + +from __future__ import annotations + +from datetime import UTC, date, datetime, time, timedelta, tzinfo + +from app.providers.immich.models import OnThisDay + +DateWindow = tuple[datetime | None, datetime | None] + + +def _same_day(year: int, month: int, day: int) -> date: + """``month/day`` in ``year``; Feb 29 falls back to Feb 28 in non-leap years.""" + try: + return date(year, month, day) + except ValueError: + return date(year, month, 28) + + +def on_this_day_windows(now: datetime, tz: tzinfo, spec: OnThisDay) -> list[DateWindow]: + """One inclusive UTC window per past year, centred on today's date (in ``tz``). + + Newest year first. Window bounds are local midnight to local end-of-day so the days at the + edge are fully covered whatever the time zone. + """ + today = now.astimezone(tz).date() + windows: list[DateWindow] = [] + for years_ago in range(spec.min_years_ago, spec.years_back + 1): + year = today.year - years_ago + if year < 1: + break + centre = _same_day(year, today.month, today.day) + start = datetime.combine(centre - timedelta(days=spec.window_days), time.min, tzinfo=tz) + end = datetime.combine(centre + timedelta(days=spec.window_days), time.max, tzinfo=tz) + windows.append((start.astimezone(UTC), end.astimezone(UTC))) + return windows diff --git a/app/providers/immich/models.py b/app/providers/immich/models.py index 5816ec5..94466cf 100644 --- a/app/providers/immich/models.py +++ b/app/providers/immich/models.py @@ -3,9 +3,10 @@ from __future__ import annotations from dataclasses import dataclass +from datetime import UTC, datetime from typing import Literal -from pydantic import BaseModel, ConfigDict, Field, model_validator +from pydantic import AwareDatetime, BaseModel, ConfigDict, Field, model_validator from app.core.config_models import FitMode @@ -73,6 +74,11 @@ class FaceDto(_Dto): person: PersonDto | None = None +def _utc_iso(moment: datetime) -> str: + """ISO 8601 UTC timestamp (``...Z``) as Immich expects for date filters.""" + return moment.astimezone(UTC).isoformat(timespec="milliseconds").replace("+00:00", "Z") + + @dataclass(frozen=True, slots=True) class SearchFilters: """Filters shared by the random and smart search endpoints.""" @@ -81,6 +87,8 @@ class SearchFilters: album_ids: tuple[str, ...] = () favorites_only: bool = False exclude_archived: bool = True + taken_after: datetime | None = None + taken_before: datetime | None = None def body(self, size: int) -> dict[str, object]: """JSON body for ``/search/random`` and ``/search/smart``.""" @@ -93,6 +101,10 @@ def body(self, size: int) -> dict[str, object]: body["isFavorite"] = True if self.exclude_archived: body["visibility"] = "timeline" + if self.taken_after is not None: + body["takenAfter"] = _utc_iso(self.taken_after) + if self.taken_before is not None: + body["takenBefore"] = _utc_iso(self.taken_before) return body @@ -106,6 +118,26 @@ class AlbumInfo(BaseModel): shared: bool +class OnThisDay(BaseModel): + """ "On this day" memories: photos taken around today's date in previous years.""" + + model_config = ConfigDict(extra="forbid") + + window_days: int = Field( + default=3, ge=0, le=31, description="Days before and after today's date to include" + ) + years_back: int = Field(default=10, ge=1, le=20, description="How many past years to search") + min_years_ago: int = Field( + default=1, ge=1, le=20, description="Skip the most recent years (1 = exclude this year)" + ) + + @model_validator(mode="after") + def _check_years(self) -> OnThisDay: + if self.min_years_ago > self.years_back: + raise ValueError("min_years_ago must not exceed years_back") + return self + + class ImmichDisplayRequest(BaseModel): """Which Immich photo to show (``POST /api/display/immich``). @@ -147,6 +179,17 @@ class ImmichDisplayRequest(BaseModel): default=False, description="Allow photos shown within anti_repeat_days or taken close to one", ) + taken_after: AwareDatetime | None = Field( + default=None, description="Only photos taken at or after this moment (ISO 8601)" + ) + taken_before: AwareDatetime | None = Field( + default=None, description="Only photos taken at or before this moment (ISO 8601)" + ) + on_this_day: OnThisDay | None = Field( + default=None, + description="Memories: photos taken around today's date in previous years " + "(evaluated at display time; exclusive with taken_after/taken_before)", + ) skip_quality_gate: bool | None = Field( default=None, description="Skip the photo suitability check. Default: skipped in album mode " @@ -158,4 +201,8 @@ def _check_mode(self) -> ImmichDisplayRequest: self.clip_queries = [query.strip() for query in self.clip_queries if query.strip()] if self.mode == "search" and not self.clip_queries: raise ValueError("mode 'search' needs at least one clip_queries entry") + if self.on_this_day is not None and (self.taken_after or self.taken_before): + raise ValueError("on_this_day cannot be combined with taken_after/taken_before") + if self.taken_after and self.taken_before and self.taken_after >= self.taken_before: + raise ValueError("taken_after must be earlier than taken_before") return self diff --git a/app/providers/immich/provider.py b/app/providers/immich/provider.py index e08aa6e..24c4681 100644 --- a/app/providers/immich/provider.py +++ b/app/providers/immich/provider.py @@ -12,11 +12,12 @@ import itertools import logging import random -from collections.abc import Sequence +from collections.abc import Callable, Sequence from dataclasses import dataclass, field -from datetime import datetime +from datetime import UTC, datetime from pathlib import PurePath from typing import Final +from zoneinfo import ZoneInfo from PIL import Image from pydantic import JsonValue @@ -35,6 +36,7 @@ ProviderUnavailableError, ) from app.providers.immich.client import ImmichClient, ImmichGateway, ImmichResponseError +from app.providers.immich.dates import DateWindow, on_this_day_windows from app.providers.immich.faces import face_regions from app.providers.immich.models import ( AlbumInfo, @@ -49,6 +51,7 @@ SOURCE: Final = "immich" MAX_QUERIES_PER_ACCOUNT: Final = 10 MAX_PERSON_COMBINATIONS: Final = 8 +MAX_DATED_QUERIES: Final = 30 MAX_TITLE_PEOPLE: Final = 4 THUMBNAIL_MAX_BYTES: Final = 2 * 1024 * 1024 @@ -70,6 +73,7 @@ class _Plan: exclude_archived: bool queries: tuple[str, ...] size: int + windows: tuple[DateWindow | None, ...] = (None,) @dataclass(slots=True) @@ -173,6 +177,7 @@ def __init__( *, max_bytes: int, rng: random.Random | None = None, + clock: Callable[[], datetime] | None = None, ) -> None: self._config_store = config_store self._gateway = gateway @@ -180,6 +185,7 @@ def __init__( self._history = history self._max_bytes = max_bytes self._rng = rng or random.Random() # noqa: S311 - not security relevant + self._clock = clock or (lambda: datetime.now(UTC)) # --- public API ---------------------------------------------------------------------- async def fetch(self, request: ImmichDisplayRequest) -> ImageAsset: @@ -253,8 +259,7 @@ async def albums( return found, errors # --- planning ------------------------------------------------------------------------ - @staticmethod - def _plan(request: ImmichDisplayRequest, config: ImmichConfig) -> _Plan: + def _plan(self, request: ImmichDisplayRequest, config: ImmichConfig) -> _Plan: persons = config.persons if request.persons is None else request.persons always = config.always_include if request.always_include is None else request.always_include album_id = (request.album_id or "").strip() @@ -272,8 +277,18 @@ def _plan(request: ImmichDisplayRequest, config: ImmichConfig) -> _Plan: exclude_archived=config.exclude_archived, queries=tuple(request.clip_queries) if request.mode == "search" else (), size=config.search_candidates, + windows=self._windows(request), ) + def _windows(self, request: ImmichDisplayRequest) -> tuple[DateWindow | None, ...]: + """Date windows to query: one explicit range, one per past year, or no restriction.""" + if request.on_this_day is not None: + tz = ZoneInfo(self._config_store.config.scheduler.timezone) + return tuple(on_this_day_windows(self._clock(), tz, request.on_this_day)) + if request.taken_after is not None or request.taken_before is not None: + return ((request.taken_after, request.taken_before),) + return (None,) + # --- candidate gathering --------------------------------------------------------------- async def _gather(self, account: str, plan: _Plan, config: ImmichConfig) -> _AccountResult: result = _AccountResult() @@ -301,8 +316,16 @@ async def _gather(self, account: str, plan: _Plan, config: ImmichConfig) -> _Acc return result seen: set[str] = set() queries = plan.queries or ("",) - for query, combo in itertools.product(queries, combos): - filters = SearchFilters(combo, album_ids, plan.favorites, plan.exclude_archived) + plan_queries = itertools.product(queries, combos, plan.windows) + for query, combo, window in itertools.islice(plan_queries, MAX_DATED_QUERIES): + filters = SearchFilters( + combo, + album_ids, + plan.favorites, + plan.exclude_archived, + taken_after=window[0] if window else None, + taken_before=window[1] if window else None, + ) found = ( await client.search_smart(query, filters, plan.size) if query diff --git a/tests/immich_fake.py b/tests/immich_fake.py index 30acd0e..1273baf 100644 --- a/tests/immich_fake.py +++ b/tests/immich_fake.py @@ -5,6 +5,7 @@ import io import json from collections.abc import Callable +from datetime import datetime from typing import Any import httpx @@ -192,6 +193,12 @@ def _matches(self, data: dict[str, Any], body: dict[str, Any]) -> bool: members = {aid for a in self.albums if a["id"] in album_ids for aid in a["assetIds"]} if data["id"] not in members: return False + taken = datetime.fromisoformat(data["localDateTime"].replace("Z", "+00:00")) + after, before = body.get("takenAfter"), body.get("takenBefore") + if after and taken < datetime.fromisoformat(after.replace("Z", "+00:00")): + return False + if before and taken > datetime.fromisoformat(before.replace("Z", "+00:00")): + return False return not data["isTrashed"] def _search(self, path: str, body: dict[str, Any]) -> httpx.Response: diff --git a/tests/test_immich_dates.py b/tests/test_immich_dates.py new file mode 100644 index 0000000..16f375d --- /dev/null +++ b/tests/test_immich_dates.py @@ -0,0 +1,43 @@ +from __future__ import annotations + +from datetime import UTC, datetime +from zoneinfo import ZoneInfo + +from app.providers.immich.dates import on_this_day_windows +from app.providers.immich.models import OnThisDay + + +def test_one_window_per_past_year_newest_first() -> None: + now = datetime(2026, 11, 15, 12, 0, tzinfo=UTC) + windows = on_this_day_windows(now, UTC, OnThisDay(window_days=2, years_back=3)) + + assert [w[0].year for w in windows] == [2025, 2024, 2023] + assert windows[0] == ( + datetime(2025, 11, 13, 0, 0, tzinfo=UTC), + datetime(2025, 11, 17, 23, 59, 59, 999999, tzinfo=UTC), + ) + + +def test_min_years_ago_skips_recent_years() -> None: + now = datetime(2026, 11, 15, tzinfo=UTC) + windows = on_this_day_windows(now, UTC, OnThisDay(years_back=4, min_years_ago=3)) + assert [w[0].year for w in windows] == [2023, 2022] + + +def test_leap_day_falls_back_to_feb_28_in_non_leap_years() -> None: + now = datetime(2028, 2, 29, 12, 0, tzinfo=UTC) + windows = on_this_day_windows(now, UTC, OnThisDay(window_days=0, years_back=4)) + assert [(w[0].year, w[0].month, w[0].day) for w in windows] == [ + (2027, 2, 28), + (2026, 2, 28), + (2025, 2, 28), + (2024, 2, 29), + ] + + +def test_local_day_is_used_for_the_window_bounds() -> None: + paris = ZoneInfo("Europe/Paris") + now = datetime(2026, 11, 14, 23, 30, tzinfo=UTC) # already Nov 15 in Paris + start, end = on_this_day_windows(now, paris, OnThisDay(window_days=0, years_back=1))[0] + assert start == datetime(2025, 11, 14, 23, 0, tzinfo=UTC) + assert end.date().isoformat() == "2025-11-15" diff --git a/tests/test_immich_provider.py b/tests/test_immich_provider.py index 8055aa6..6149bd1 100644 --- a/tests/test_immich_provider.py +++ b/tests/test_immich_provider.py @@ -2,6 +2,7 @@ import io import random +from datetime import UTC, datetime from pathlib import Path from typing import Any @@ -561,3 +562,60 @@ def test_raw_detection() -> None: assert not is_raw(AssetDto(id="a", originalFileName="x.jpg", originalMimeType="image/jpeg")) assert not is_raw(AssetDto(id="a", originalMimeType="image/x-ms-bmp")) assert not is_raw(AssetDto(id="a", originalFileName="x.heic", originalMimeType="image/heic")) + + +# --- date filters and "on this day" -------------------------------------------- +def dated(fake: FakeImmich) -> FakeImmich: + fake.add_asset("old", localDateTime="2021-11-15T09:00:00.000Z") + fake.add_asset("edge", localDateTime="2022-11-17T20:00:00.000Z") + fake.add_asset("far", localDateTime="2022-11-25T09:00:00.000Z") + fake.add_asset("now", localDateTime="2026-11-15T09:00:00.000Z") + return fake + + +async def test_taken_after_and_before_filter_the_search(tmp_path: Path) -> None: + fake = dated(FakeImmich()) + env = Env(tmp_path, {"home": fake}) + with mocked(fake): + asset = await env.fetch( + taken_after="2022-01-01T00:00:00Z", taken_before="2022-12-31T00:00:00Z" + ) + + assert asset.details["asset_id"] in {"edge", "far"} + body = bodies(fake)[0] + assert body["takenAfter"] == "2022-01-01T00:00:00.000Z" + assert body["takenBefore"] == "2022-12-31T00:00:00.000Z" + + +async def test_on_this_day_queries_one_window_per_past_year(tmp_path: Path) -> None: + fake = dated(FakeImmich()) + clock = lambda: datetime(2026, 11, 15, 12, 0, tzinfo=UTC) # noqa: E731 + env = Env(tmp_path, {"home": fake}) + env.provider._clock = clock + with mocked(fake): + asset = await env.fetch(on_this_day={"window_days": 3, "years_back": 5}) + + # 2021 and 2022 hold matches; 2026 (this year) is excluded; 'far' is outside the window. + assert asset.details["asset_id"] in {"old", "edge"} + sent = bodies(fake) + assert len(sent) == 5 + assert sent[0]["takenAfter"] == "2025-11-12T00:00:00.000Z" + assert sent[0]["takenBefore"] == "2025-11-18T23:59:59.999Z" + + +async def test_on_this_day_without_matches_raises_no_candidate(tmp_path: Path) -> None: + fake = FakeImmich() + fake.add_asset("a1", localDateTime="2024-03-01T09:00:00.000Z") + env = Env(tmp_path, {"home": fake}) + env.provider._clock = lambda: datetime(2026, 11, 15, 12, 0, tzinfo=UTC) + with mocked(fake), pytest.raises(NoCandidateError): + await env.fetch(on_this_day={}) + + +def test_on_this_day_rejects_explicit_dates() -> None: + with pytest.raises(ValueError, match="on_this_day"): + ImmichDisplayRequest(on_this_day={}, taken_after="2022-01-01T00:00:00Z") + with pytest.raises(ValueError, match="earlier"): + ImmichDisplayRequest( + taken_after="2022-02-01T00:00:00Z", taken_before="2022-01-01T00:00:00Z" + ) From 7798fb86f1e40b3d7fea5503e7679b7266b7053a Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sun, 15 Nov 2026 14:36:12 +0100 Subject: [PATCH 44/86] feat: add context placeholders for source rules Expand {season}, {month}, {month_name} and {year} in rule params at run time so stored rules follow the calendar without hard-coded album IDs. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- app/core/context.py | 78 +++++++++++++++++++++++++++++++++++++++++++ tests/test_context.py | 58 ++++++++++++++++++++++++++++++++ 2 files changed, 136 insertions(+) create mode 100644 app/core/context.py create mode 100644 tests/test_context.py diff --git a/app/core/context.py b/app/core/context.py new file mode 100644 index 0000000..fab1deb --- /dev/null +++ b/app/core/context.py @@ -0,0 +1,78 @@ +"""Runtime context for source rules: ``{season}``, ``{month}``... placeholders. + +Stored rules stay templated (e.g. ``"clip_queries": ["{season} landscape"]``) and are expanded +right before they run, so one rule follows the calendar without hard-coded album IDs. +Unknown placeholders are left untouched rather than failing the refresh. +""" + +from __future__ import annotations + +import calendar +from dataclasses import dataclass +from datetime import datetime +from typing import Final, Literal +from zoneinfo import ZoneInfo + +from pydantic import JsonValue + +Hemisphere = Literal["north", "south"] +Season = Literal["spring", "summer", "autumn", "winter"] + +_NORTH: Final[dict[int, Season]] = { + 12: "winter", 1: "winter", 2: "winter", + 3: "spring", 4: "spring", 5: "spring", + 6: "summer", 7: "summer", 8: "summer", + 9: "autumn", 10: "autumn", 11: "autumn", +} # fmt: skip +_OPPOSITE: Final[dict[Season, Season]] = { + "winter": "summer", + "summer": "winter", + "spring": "autumn", + "autumn": "spring", +} + + +@dataclass(frozen=True, slots=True) +class RuleContext: + """Calendar facts for one evaluation moment (meteorological seasons).""" + + now: datetime + tz: ZoneInfo + hemisphere: Hemisphere = "north" + + @property + def local(self) -> datetime: + return self.now.astimezone(self.tz) + + @property + def season(self) -> Season: + season = _NORTH[self.local.month] + return season if self.hemisphere == "north" else _OPPOSITE[season] + + @property + def variables(self) -> dict[str, str]: + local = self.local + return { + "season": self.season, + "month": f"{local.month:02d}", + "month_name": calendar.month_name[local.month].lower(), + "year": str(local.year), + } + + +def expand_text(text: str, context: RuleContext) -> str: + """Replace the known ``{placeholders}`` in one string.""" + for key, value in context.variables.items(): + text = text.replace("{" + key + "}", value) + return text + + +def expand_params(value: JsonValue, context: RuleContext) -> JsonValue: + """Recursively expand placeholders in every string of a rule's ``params``.""" + if isinstance(value, str): + return expand_text(value, context) + if isinstance(value, list): + return [expand_params(item, context) for item in value] + if isinstance(value, dict): + return {key: expand_params(item, context) for key, item in value.items()} + return value diff --git a/tests/test_context.py b/tests/test_context.py new file mode 100644 index 0000000..b3ea18f --- /dev/null +++ b/tests/test_context.py @@ -0,0 +1,58 @@ +from __future__ import annotations + +from datetime import UTC, datetime +from zoneinfo import ZoneInfo + +import pytest + +from app.core.context import RuleContext, expand_params, expand_text + + +def ctx(month: int, hemisphere: str = "north", tz: str = "UTC") -> RuleContext: + return RuleContext( + datetime(2026, month, 15, 12, 0, tzinfo=UTC), + ZoneInfo(tz), + hemisphere, # type: ignore[arg-type] + ) + + +@pytest.mark.parametrize( + ("month", "north", "south"), + [ + (1, "winter", "summer"), + (4, "spring", "autumn"), + (7, "summer", "winter"), + (10, "autumn", "spring"), + (12, "winter", "summer"), + ], +) +def test_season_by_hemisphere(month: int, north: str, south: str) -> None: + assert ctx(month).season == north + assert ctx(month, "south").season == south + + +def test_placeholders_are_expanded_recursively() -> None: + params = { + "clip_queries": ["{season} landscape", "{month_name} {year}"], + "nested": {"m": "{month}"}, + "n": 3, + "flag": True, + "none": None, + } + assert expand_params(params, ctx(11)) == { + "clip_queries": ["autumn landscape", "november 2026"], + "nested": {"m": "11"}, + "n": 3, + "flag": True, + "none": None, + } + + +def test_unknown_placeholders_are_left_untouched() -> None: + assert expand_text("{weather} {season}", ctx(1)) == "{weather} winter" + + +def test_local_timezone_decides_the_month() -> None: + late = RuleContext(datetime(2026, 11, 30, 23, 30, tzinfo=UTC), ZoneInfo("Europe/Paris")) + assert late.season == "winter" # already Dec 1 in Paris + assert late.variables["month_name"] == "december" From f75647b5f1b53ec6865996dcc7fb764fb8297b56 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sun, 15 Nov 2026 14:38:14 +0100 Subject: [PATCH 45/86] feat: add smart_mix config section Add SmartMixConfig/SmartMixEntry (weighted, provider-agnostic entries) and make SourceRule.kind an open validated identifier so new providers need no config model changes. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- .env.example | 5 +++ app/core/config_models.py | 59 +++++++++++++++++++++++++++++++-- app/core/settings.py | 6 +++- tests/test_api.py | 1 + tests/test_config_models.py | 39 +++++++++++++++++++++- tests/test_scheduler_service.py | 2 +- 6 files changed, 107 insertions(+), 5 deletions(-) diff --git a/.env.example b/.env.example index 424d818..9e5196a 100644 --- a/.env.example +++ b/.env.example @@ -70,6 +70,11 @@ FRAIMIC_PANEL=133 # portrait | landscape ORIENTATION=portrait +# --- Smart Mix (runtime default) --------------------------------------------- +# Weighted playlist of source rules for scheduled refreshes (entries are configured in +# smart_mix.entries via the API/UI). A pinned scheduler.source_rule still takes precedence. +SMART_MIX_ENABLED=false + # --- Scheduler (runtime default) --------------------------------------------- # Replays the active source rule (the pinned scheduler.source_rule, else the last # manual display) every REFRESH_INTERVAL_HOURS hours. Any display resets the timer. diff --git a/app/core/config_models.py b/app/core/config_models.py index 6f12959..c6c6780 100644 --- a/app/core/config_models.py +++ b/app/core/config_models.py @@ -11,7 +11,7 @@ import re from dataclasses import dataclass -from typing import Any, Final, Literal +from typing import Annotated, Any, Final, Literal from urllib.parse import urlsplit from zoneinfo import ZoneInfo, ZoneInfoNotFoundError @@ -21,6 +21,7 @@ Field, JsonValue, SecretStr, + StringConstraints, field_validator, model_validator, ) @@ -387,6 +388,14 @@ class QualityConfig(_Section): ) +SourceKind = Annotated[str, StringConstraints(min_length=1, max_length=64, pattern=r"^[a-z0-9_]+$")] +"""Open identifier of a source (``immich``, ``tmdb``...). + +Which kinds exist is decided at runtime by the scheduler's runner registry, not here, so +adding a provider never changes the configuration models. +""" + + class SourceRule(BaseModel): """A replayable source request (``/api/refresh`` and the scheduler). @@ -396,8 +405,53 @@ class SourceRule(BaseModel): model_config = ConfigDict(extra="forbid") - kind: Literal["immich", "media", "url"] + kind: SourceKind + params: dict[str, JsonValue] = Field(default_factory=dict) + + +class SmartMixEntry(BaseModel): + """One weighted entry of the Smart Mix playlist: a :class:`SourceRule` plus a weight. + + ``params`` may contain context placeholders (``{season}``, ``{month_name}``...) that are + expanded each time the entry runs. + """ + + model_config = ConfigDict(extra="forbid") + + kind: SourceKind params: dict[str, JsonValue] = Field(default_factory=dict) + weight: float = Field(default=1.0, gt=0, le=1000, description="Relative chance of being picked") + label: str | None = Field(default=None, max_length=80, description="Name shown in the UI") + enabled: bool = Field(default=True, description="Disabled entries are never picked") + + def to_rule(self) -> SourceRule: + """The replayable rule this entry wraps.""" + return SourceRule(kind=self.kind, params=dict(self.params)) + + +class SmartMixConfig(_Section): + """Weighted, source-agnostic playlist used by scheduled refreshes.""" + + enabled: bool = Field( + default=False, + description="Pick the next scheduled photo from the entries (a pinned " + "scheduler.source_rule still wins)", + ) + entries: list[SmartMixEntry] = Field( + default_factory=list, max_length=50, description="Weighted playlist entries" + ) + max_attempts: int = Field( + default=3, + ge=1, + le=10, + description="Entries tried per refresh when one has no candidate or fails", + ) + avoid_consecutive: bool = Field( + default=True, description="Do not pick the same entry twice in a row when others exist" + ) + hemisphere: Literal["north", "south"] = Field( + default="north", description="Used to map months to {season}" + ) class SchedulerConfig(_Section): @@ -474,6 +528,7 @@ class RuntimeConfig(BaseModel): display: DisplayConfig = Field(default_factory=DisplayConfig) eink: EinkConfig = Field(default_factory=EinkConfig) scheduler: SchedulerConfig = Field(default_factory=SchedulerConfig) + smart_mix: SmartMixConfig = Field(default_factory=SmartMixConfig) quality: QualityConfig = Field(default_factory=QualityConfig) @property diff --git a/app/core/settings.py b/app/core/settings.py index c3d05c9..2f6ec60 100644 --- a/app/core/settings.py +++ b/app/core/settings.py @@ -78,6 +78,7 @@ class EnvSettings(BaseSettings): fraimic_panel: str | None = None orientation: str | None = None scheduler_enabled: bool | None = None + smart_mix_enabled: bool | None = None refresh_interval_hours: float | None = None quiet_hours_start: str | None = None quiet_hours_end: str | None = None @@ -119,7 +120,9 @@ def _blank_secret_to_none(cls, value: object) -> object: return None return value - @field_validator("scheduler_enabled", "refresh_interval_hours", mode="before") + @field_validator( + "scheduler_enabled", "smart_mix_enabled", "refresh_interval_hours", mode="before" + ) @classmethod def _blank_scalar_to_none(cls, value: object) -> object: if isinstance(value, str) and not value.strip(): @@ -205,6 +208,7 @@ def runtime_seed(self) -> dict[str, dict[str, Any]]: ("scheduler", "quiet_hours_start"): self.quiet_hours_start, ("scheduler", "quiet_hours_end"): self.quiet_hours_end, ("scheduler", "timezone"): self.tz, + ("smart_mix", "enabled"): self.smart_mix_enabled, } seed: dict[str, dict[str, Any]] = {} for (section, name), value in candidates.items(): diff --git a/tests/test_api.py b/tests/test_api.py index 6a21c51..a1d8ad9 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -100,6 +100,7 @@ def test_config_schema(make_client: ClientFactory) -> None: "display", "eink", "scheduler", + "smart_mix", "quality", } diff --git a/tests/test_config_models.py b/tests/test_config_models.py index 94cca11..157e335 100644 --- a/tests/test_config_models.py +++ b/tests/test_config_models.py @@ -13,6 +13,9 @@ ImmichConfig, RuntimeConfig, SchedulerConfig, + SmartMixConfig, + SmartMixEntry, + SourceRule, TmdbConfig, dump_config, is_masked, @@ -157,7 +160,7 @@ def test_scheduler_pinned_rule() -> None: assert config.source_rule is not None assert config.source_rule.params == {"persons": ["Alice"]} with pytest.raises(ValidationError): - SchedulerConfig.model_validate({"source_rule": {"kind": "ftp"}}) + SchedulerConfig.model_validate({"source_rule": {"kind": "Not A Kind"}}) @pytest.mark.parametrize("value", ["24:00", "7:30", "12:60"]) @@ -236,3 +239,37 @@ def test_effective_profile_can_be_forced_per_source() -> None: photo = EinkConfig(profile="photo") assert photo.effective("official") is photo assert EinkConfig().effective("photo").saturation == 0.85 + + +def test_source_kind_is_an_open_identifier() -> None: + assert SourceRule(kind="now_playing").kind == "now_playing" + for bad in ("", "Immich", "a b", "x" * 65): + with pytest.raises(ValidationError): + SourceRule(kind=bad) + + +def test_smart_mix_defaults_are_inert() -> None: + config = SmartMixConfig() + assert config.enabled is False and config.entries == [] + assert config.max_attempts == 3 and config.avoid_consecutive is True + + +def test_smart_mix_entry_wraps_a_rule() -> None: + entry = SmartMixEntry.model_validate( + {"kind": "immich", "params": {"persons": ["Alice"]}, "weight": 2.5, "label": "Alice"} + ) + assert entry.enabled is True + assert entry.to_rule() == SourceRule(kind="immich", params={"persons": ["Alice"]}) + + +@pytest.mark.parametrize("weight", [0, -1, 1001]) +def test_smart_mix_entry_rejects_bad_weights(weight: float) -> None: + with pytest.raises(ValidationError): + SmartMixEntry(kind="immich", weight=weight) + + +def test_smart_mix_rejects_unknown_fields_and_too_many_entries() -> None: + with pytest.raises(ValidationError): + SmartMixEntry.model_validate({"kind": "immich", "bogus": 1}) + with pytest.raises(ValidationError): + SmartMixConfig(entries=[SmartMixEntry(kind="immich")] * 51) diff --git a/tests/test_scheduler_service.py b/tests/test_scheduler_service.py index 0a0ea4d..3a1706c 100644 --- a/tests/test_scheduler_service.py +++ b/tests/test_scheduler_service.py @@ -356,7 +356,7 @@ async def test_state_survives_a_restart(harness: HarnessFactory) -> None: @pytest.mark.parametrize( - "content", ['{"consecutive_failures": -3}', '{"last_rule": {"kind": "ftp"}}', "[1, 2]"] + "content", ['{"consecutive_failures": -3}', '{"last_rule": {"kind": "Not A Kind"}}', "[1, 2]"] ) async def test_malformed_state_is_ignored( harness: HarnessFactory, content: str, caplog: pytest.LogCaptureFixture From 236eefe14cad609194205c64a062a94082f8038d Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sun, 15 Nov 2026 14:42:44 +0100 Subject: [PATCH 46/86] feat: resolve weighted smart mix in scheduler with re-roll Add SmartMixResolver (weighted order without replacement) and let the scheduler pick the active rule as pinned > smart mix > last manual rule. A refresh re-rolls up to max_attempts entries; mix runs never rewrite last_rule. Expand context placeholders before running an entry. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- app/api/routes/refresh.py | 9 +- app/services/scheduler.py | 159 +++++++++++++++++++---- app/services/smart_mix.py | 99 +++++++++++++++ tests/test_smart_mix.py | 259 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 499 insertions(+), 27 deletions(-) create mode 100644 app/services/smart_mix.py create mode 100644 tests/test_smart_mix.py diff --git a/app/api/routes/refresh.py b/app/api/routes/refresh.py index ddb83fb..3e5dc7a 100644 --- a/app/api/routes/refresh.py +++ b/app/api/routes/refresh.py @@ -24,7 +24,11 @@ class RefreshResult(BaseModel): reason: Literal["manual"] = "manual" rule_kind: str = Field(description="Source of the replayed rule (immich, media, url)") rule_source: RuleSource = Field( - description="pinned = scheduler.source_rule; last = the last manual display request" + description="pinned = scheduler.source_rule; smart_mix = the weighted playlist; " + "last = the last manual display request" + ) + entry_label: str | None = Field( + default=None, description="Smart Mix entry that was shown (smart_mix only)" ) display: DisplayResult @@ -66,7 +70,8 @@ async def refresh(scheduler: SchedulerDep) -> RefreshResult: status_code=502, detail="The source returned an image that cannot be decoded" ) from exc return RefreshResult( - rule_kind=outcome.active.rule.kind, + rule_kind=outcome.rule.kind, rule_source=outcome.active.source, + entry_label=outcome.entry_label, display=outcome.display, ) diff --git a/app/services/scheduler.py b/app/services/scheduler.py index 193ce7a..7a652dc 100644 --- a/app/services/scheduler.py +++ b/app/services/scheduler.py @@ -1,8 +1,13 @@ """Autonomous refresh: replay the active source rule on a timer, outside quiet hours. -The **active rule** is the pinned ``scheduler.source_rule`` from the configuration, or -else the last manual display request (kept in ``/data/scheduler_state.json`` so that -showing a photo does not rewrite the user's settings). +The **active rule** is, in order of precedence: + +1. the pinned ``scheduler.source_rule`` from the configuration; +2. the Smart Mix playlist (``smart_mix.enabled`` with at least one enabled entry, or a live + context boost): each refresh tries entries in weighted random order and re-rolls when one + has no candidate or fails; +3. the last manual display request (kept in ``/data/scheduler_state.json`` so that showing a + photo does not rewrite the user's settings). Timing: @@ -34,16 +39,18 @@ from apscheduler.schedulers.asyncio import AsyncIOScheduler from apscheduler.triggers.date import DateTrigger -from pydantic import AwareDatetime, BaseModel, ConfigDict, Field, ValidationError +from pydantic import AwareDatetime, BaseModel, ConfigDict, Field, JsonValue, ValidationError from app.core.config_models import RuntimeConfig, SchedulerConfig, SourceRule from app.core.config_store import ConfigStore +from app.core.context import RuleContext, expand_params from app.core.json_store import atomic_write_json, read_json from app.core.security import InvalidImageError from app.providers.base import ProviderError from app.providers.immich import ImmichDisplayRequest, ImmichProvider from app.services.display import DisplayResult, DisplayService from app.services.schedule import QuietWindow, in_quiet, next_run_at +from app.services.smart_mix import MixCandidate, MixContext, SmartMixResolver logger = logging.getLogger(__name__) @@ -53,7 +60,7 @@ RefreshReason = Literal["scheduled", "manual"] RunStatus = Literal["ok", "failed", "skipped"] -RuleSource = Literal["pinned", "last"] +RuleSource = Literal["pinned", "smart_mix", "last"] Clock = Callable[[], datetime] RuleRunner = Callable[[SourceRule], Awaitable[DisplayResult]] @@ -94,6 +101,8 @@ class LastRun(BaseModel): reason: RefreshReason status: RunStatus rule_kind: str | None = None + entry_label: str | None = Field(default=None, description="Smart Mix entry that was shown") + entry_index: int | None = Field(default=None, description="Position in smart_mix.entries") detail: str | None = Field(default=None, description="Skip reason or error message") @@ -114,15 +123,30 @@ class SchedulerState(BaseModel): ) last_run: LastRun | None = None consecutive_failures: int = Field(default=0, ge=0) + last_mix_index: int | None = Field( + default=None, description="Smart Mix entry shown last (avoid_consecutive)" + ) + context: MixContext | None = Field( + default=None, description="Temporary Smart Mix boost or override" + ) @dataclass(frozen=True, slots=True) class ActiveRule: - """The rule a refresh replays, and where it comes from.""" + """What a refresh replays, and where it comes from. - rule: SourceRule + ``rule`` is the single rule of a pinned/last source; it is ``None`` for ``smart_mix``, + where the rule is chosen per refresh. + """ + + rule: SourceRule | None source: RuleSource + @property + def kind(self) -> str: + """Source kind of the rule, or ``smart_mix`` for the playlist.""" + return self.rule.kind if self.rule is not None else "smart_mix" + @dataclass(frozen=True, slots=True) class RefreshOutcome: @@ -131,6 +155,8 @@ class RefreshOutcome: reason: RefreshReason active: ActiveRule display: DisplayResult + rule: SourceRule + entry_label: str | None = None class QuietHoursView(BaseModel): @@ -145,7 +171,8 @@ class ActiveRuleView(BaseModel): kind: str source: RuleSource = Field( - description="pinned = scheduler.source_rule; last = the last manual display request" + description="pinned = scheduler.source_rule; smart_mix = the weighted playlist; " + "last = the last manual display request" ) @@ -192,6 +219,7 @@ def __init__( has_pending: Callable[[], bool] = lambda: False, clock: Clock = _utcnow, min_delay_s: float = DEFAULT_MIN_DELAY_S, + resolver: SmartMixResolver | None = None, ) -> None: """Create the service (call :meth:`load` then :meth:`start`). @@ -203,6 +231,7 @@ def __init__( clock: Returns the current aware time (tests inject a fake clock). min_delay_s: Minimum delay before a refresh, so an overdue run does not fire in the middle of startup or of a configuration edit. + resolver: Weighted Smart Mix ordering (tests inject a seeded one). """ self._path = state_path self._config_store = config_store @@ -210,6 +239,7 @@ def __init__( self._has_pending = has_pending self._clock = clock self._min_delay = timedelta(seconds=min_delay_s) + self._resolver = resolver or SmartMixResolver() self._lock = asyncio.Lock() self._state = SchedulerState() self._scheduler: AsyncIOScheduler | None = None @@ -266,11 +296,24 @@ def running(self) -> bool: """Whether a refresh is in progress.""" return self._lock.locked() + @property + def supported_kinds(self) -> list[str]: + """Source kinds that can be replayed (the runner registry).""" + return sorted(self._runners) + + def live_context(self) -> MixContext | None: + """The Smart Mix context boost, unless it has expired.""" + context = self._state.context + return context if context is not None and context.live(self._clock()) else None + def active_rule(self) -> ActiveRule | None: - """The pinned rule, else the last manual one, else ``None``.""" + """The pinned rule, else the Smart Mix, else the last manual rule, else ``None``.""" pinned = self._config.scheduler.source_rule if pinned is not None: return ActiveRule(pinned, "pinned") + mix = self._config.smart_mix + if mix.enabled and self._resolver.pool(mix, self.live_context()): + return ActiveRule(None, "smart_mix") if self._state.last_rule is not None: return ActiveRule(self._state.last_rule, "last") return None @@ -301,7 +344,7 @@ def snapshot(self) -> SchedulerSnapshot: last_display_at=self._state.last_display_at, consecutive_failures=self._state.consecutive_failures, active_rule=( - ActiveRuleView(kind=active.rule.kind, source=active.source) if active else None + ActiveRuleView(kind=active.kind, source=active.source) if active else None ), ) @@ -346,16 +389,21 @@ async def run(self, reason: RefreshReason = "manual") -> RefreshOutcome: "Nothing to refresh yet: display a photo first, or pin a rule in " "scheduler.source_rule" ) - runner = self._runner(active.rule) try: - display = await runner(active.rule) + display, chosen = await self._play(active) except Exception as exc: await self._save( last_run=self._last_run(reason, "failed", active, _safe_detail(exc)) ) raise - await self._record_success(reason, active) - return RefreshOutcome(reason=reason, active=active, display=display) + await self._record_success(reason, active, chosen) + return RefreshOutcome( + reason=reason, + active=active, + display=display, + rule=chosen.rule, + entry_label=chosen.label, + ) finally: self._arm() @@ -391,6 +439,11 @@ async def record_manual(self, rule: SourceRule | None) -> None: await self._save(**update) self._arm() + async def set_context(self, context: MixContext | None) -> None: + """Set (or clear with ``None``) the temporary Smart Mix boost.""" + await self._save(context=context) + self._arm() + # --- Internals -------------------------------------------------------------------- @property def _config(self) -> RuntimeConfig: @@ -417,20 +470,67 @@ async def _scheduled(self) -> LastRun | None: ) if config.skip_if_pending and self._has_pending(): return await self._skip("The previous image is still waiting for the frame", active) - try: - runner = self._runner(active.rule) - except UnsupportedRuleError as exc: - return await self._skip(str(exc), active) + if active.rule is not None: + try: + self._runner(active.rule) + except UnsupportedRuleError as exc: + return await self._skip(str(exc), active) try: - await runner(active.rule) + _, chosen = await self._play(active) except asyncio.CancelledError: raise except Exception as exc: if not isinstance(exc, ProviderError | RefreshError | InvalidImageError): logger.exception("Scheduled refresh failed") return await self._record_failure(active, exc) - return await self._record_success("scheduled", active) + return await self._record_success("scheduled", active, chosen) + + async def _play(self, active: ActiveRule) -> tuple[DisplayResult, MixCandidate]: + """Run the active rule; a Smart Mix tries up to ``max_attempts`` entries. + + Raises: + The error of the last attempt when every attempt failed. + """ + if active.rule is not None: + return await self._attempt(MixCandidate(active.rule)) + mix = self._config.smart_mix + order = self._resolver.order( + mix, self.live_context(), last_index=self._state.last_mix_index + ) + failure: Exception | None = None + for candidate in order[: mix.max_attempts]: + try: + return await self._attempt(candidate) + except asyncio.CancelledError: + raise + except Exception as exc: + if not isinstance(exc, ProviderError | RefreshError | InvalidImageError): + logger.exception("Smart Mix entry %r crashed", candidate.label) + logger.info( + "Smart Mix entry %r skipped, trying another: %s", + candidate.label or candidate.rule.kind, + _safe_detail(exc), + ) + failure = exc + if failure is None: # pragma: no cover - active_rule() guarantees a candidate + raise NoRuleError("Smart Mix has no enabled entry") + raise failure + + async def _attempt(self, candidate: MixCandidate) -> tuple[DisplayResult, MixCandidate]: + rule = candidate.rule.model_copy(update={"params": self._expand(candidate.rule.params)}) + runner = self._runner(rule) + return await runner(rule), candidate + + def _expand(self, params: dict[str, JsonValue]) -> dict[str, JsonValue]: + """Resolve ``{season}``-style placeholders against the current time.""" + context = RuleContext( + self._clock(), + ZoneInfo(self._config.scheduler.timezone), + self._config.smart_mix.hemisphere, + ) + expanded = expand_params(params, context) + return expanded if isinstance(expanded, dict) else params def _last_run( self, @@ -438,12 +538,16 @@ def _last_run( status: RunStatus, active: ActiveRule | None, detail: str | None = None, + chosen: MixCandidate | None = None, ) -> LastRun: + rule = chosen.rule if chosen is not None else (active.rule if active else None) return LastRun( at=self._clock(), reason=reason, status=status, - rule_kind=active.rule.kind if active else None, + rule_kind=rule.kind if rule is not None else None, + entry_label=chosen.label if chosen is not None else None, + entry_index=chosen.index if chosen is not None else None, detail=detail, ) @@ -456,10 +560,15 @@ def _timer_reset(now: datetime) -> dict[str, Any]: "consecutive_failures": 0, } - async def _record_success(self, reason: RefreshReason, active: ActiveRule) -> LastRun: - last_run = self._last_run(reason, "ok", active) - await self._save(last_run=last_run, **self._timer_reset(last_run.at)) - logger.info("Refresh done (%s, %s rule %s)", reason, active.source, active.rule.kind) + async def _record_success( + self, reason: RefreshReason, active: ActiveRule, chosen: MixCandidate + ) -> LastRun: + last_run = self._last_run(reason, "ok", active, chosen=chosen) + update = self._timer_reset(last_run.at) + if active.source == "smart_mix": + update["last_mix_index"] = chosen.index + await self._save(last_run=last_run, **update) + logger.info("Refresh done (%s, %s rule %s)", reason, active.source, last_run.rule_kind) return last_run async def _skip( diff --git a/app/services/smart_mix.py b/app/services/smart_mix.py new file mode 100644 index 0000000..155012e --- /dev/null +++ b/app/services/smart_mix.py @@ -0,0 +1,99 @@ +"""Smart Mix: weighted, source-agnostic choice of the next :class:`SourceRule`. + +The resolver knows nothing about providers: it only orders configured entries (and an +optional temporary context boost) by weight. The scheduler walks that order, re-rolling when +an entry has no candidate or fails. +""" + +from __future__ import annotations + +import math +import random +from dataclasses import dataclass +from datetime import datetime + +from pydantic import AwareDatetime, BaseModel, ConfigDict, Field + +from app.core.config_models import SmartMixConfig, SourceRule + +DEFAULT_CONTEXT_WEIGHT = 3.0 + + +class MixContext(BaseModel): + """A temporary boost (or override) of the playlist, e.g. pushed by Home Assistant. + + The rule joins the playlist with ``weight`` until ``expires_at``. With ``exclusive`` it is + the only candidate meanwhile. + """ + + model_config = ConfigDict(extra="ignore") + + rule: SourceRule + weight: float = Field(default=DEFAULT_CONTEXT_WEIGHT, gt=0, le=1000) + expires_at: AwareDatetime + exclusive: bool = False + label: str | None = Field(default=None, max_length=80) + + def live(self, now: datetime) -> bool: + """Whether the context has not expired yet.""" + return now < self.expires_at + + +@dataclass(frozen=True, slots=True) +class MixCandidate: + """One pickable rule. ``index`` is the position in ``smart_mix.entries`` (``None`` for + the context boost or a plain pinned/last rule).""" + + rule: SourceRule + weight: float = 1.0 + index: int | None = None + label: str | None = None + + +class SmartMixResolver: + """Orders candidates by weighted random sampling without replacement.""" + + def __init__(self, rng: random.Random | None = None) -> None: + self._rng = rng or random.Random() # noqa: S311 - not security relevant + + @staticmethod + def pool(config: SmartMixConfig, context: MixContext | None = None) -> list[MixCandidate]: + """Enabled entries plus the live context (alone when it is exclusive).""" + boost = ( + MixCandidate(context.rule, context.weight, None, context.label or "context") + if context is not None + else None + ) + if boost is not None and context is not None and context.exclusive: + return [boost] + pool = [ + MixCandidate(entry.to_rule(), entry.weight, index, entry.label) + for index, entry in enumerate(config.entries) + if entry.enabled + ] + if boost is not None: + pool.append(boost) + return pool + + def order( + self, + config: SmartMixConfig, + context: MixContext | None = None, + *, + last_index: int | None = None, + ) -> list[MixCandidate]: + """Every candidate once, in the order they should be tried. + + Higher weights tend to come first (Efraimidis-Spirakis keys). With + ``avoid_consecutive`` the entry shown last is moved to the end, so it is still a + fallback when everything else fails. + """ + pool = self.pool(config, context) + keyed = sorted( + pool, + key=lambda candidate: math.log(1.0 - self._rng.random()) / candidate.weight, + reverse=True, + ) + if config.avoid_consecutive and last_index is not None and len(keyed) > 1: + keyed.sort(key=lambda candidate: candidate.index == last_index) # stable + return keyed diff --git a/tests/test_smart_mix.py b/tests/test_smart_mix.py new file mode 100644 index 0000000..345c4e2 --- /dev/null +++ b/tests/test_smart_mix.py @@ -0,0 +1,259 @@ +"""Smart Mix: weighted resolver and its integration in the scheduler.""" + +from __future__ import annotations + +import random +from datetime import timedelta +from pathlib import Path +from typing import Any + +import pytest + +from app.core.config_models import SmartMixConfig, SmartMixEntry, SourceRule +from app.core.config_store import ConfigStore +from app.providers.base import NoCandidateError +from app.services.scheduler import NoRuleError, SchedulerService +from app.services.smart_mix import MixContext, SmartMixResolver +from tests.test_scheduler_service import ALICE, BOB, T0, FakeClock, FakeRunner + + +def seeded(seed: int) -> random.Random: + return random.Random(seed) # noqa: S311 + + +class Scripted(random.Random): + """``random()`` returns scripted values (a small value sorts that candidate first).""" + + def __init__(self, *values: float) -> None: + super().__init__(0) + self.values = list(values) + + def random(self) -> float: + return self.values.pop(0) + + +def entry(kind: str = "immich", weight: float = 1.0, **extra: Any) -> SmartMixEntry: + return SmartMixEntry(kind=kind, weight=weight, **extra) + + +def mix(*entries: SmartMixEntry, **config: Any) -> SmartMixConfig: + return SmartMixConfig(enabled=True, entries=list(entries), **config) + + +# --- Resolver ------------------------------------------------------------------------- +def test_weights_drive_the_first_pick() -> None: + resolver = SmartMixResolver(seeded(7)) + config = mix(entry(weight=3, label="a"), entry(weight=1, label="b"), avoid_consecutive=False) + firsts = [resolver.order(config)[0].label for _ in range(4000)] + assert 0.72 < firsts.count("a") / len(firsts) < 0.78 + + +def test_order_contains_every_enabled_entry_once() -> None: + config = mix(entry(label="a"), entry(label="b", enabled=False), entry(label="c")) + order = SmartMixResolver(seeded(1)).order(config) + assert sorted(c.label or "" for c in order) == ["a", "c"] + assert sorted(c.index for c in order if c.index is not None) == [0, 2] + + +def test_avoid_consecutive_moves_the_last_entry_to_the_end() -> None: + config = mix(entry(label="a"), entry(label="b"), entry(label="c")) + resolver = SmartMixResolver(Scripted(0.01, 0.5, 0.9)) # natural order: a, b, c + assert [c.label for c in resolver.order(config, last_index=0)] == ["b", "c", "a"] + + +def test_avoid_consecutive_can_be_disabled_and_ignores_single_entries() -> None: + config = mix(entry(label="a"), entry(label="b"), avoid_consecutive=False) + resolver = SmartMixResolver(Scripted(0.01, 0.9)) + assert [c.label for c in resolver.order(config, last_index=0)] == ["a", "b"] + single = mix(entry(label="a")) + assert [c.label for c in SmartMixResolver().order(single, last_index=0)] == ["a"] + + +def test_context_joins_the_pool_or_replaces_it() -> None: + config = mix(entry(label="a")) + context = MixContext(rule=BOB, expires_at=T0 + timedelta(hours=1), label="rainy") + resolver = SmartMixResolver(seeded(1)) + assert sorted(c.label or "" for c in resolver.order(config, context)) == ["a", "rainy"] + exclusive = context.model_copy(update={"exclusive": True}) + assert [c.label for c in resolver.order(config, exclusive)] == ["rainy"] + + +def test_context_liveness() -> None: + context = MixContext(rule=BOB, expires_at=T0 + timedelta(minutes=5)) + assert context.live(T0) and not context.live(T0 + timedelta(minutes=5)) + + +# --- Scheduler integration -------------------------------------------------------------- +class MixHarness: + def __init__(self, tmp_path: Path, **smart_mix: Any) -> None: + self.clock = FakeClock() + self.immich = FakeRunner() + self.other = FakeRunner() + self.store = ConfigStore( + tmp_path / "config.json", + {"scheduler": {"enabled": True}, "smart_mix": {"enabled": True, **smart_mix}}, + ) + self.store.load() + self.state_path = tmp_path / "scheduler_state.json" + + def service(self, *order: float) -> SchedulerService: + service = SchedulerService( + self.state_path, + self.store, + {"immich": self.immich, "other": self.other}, + clock=self.clock, + resolver=SmartMixResolver(Scripted(*order) if order else seeded(3)), + ) + service.load() + return service + + +def entries(*specs: tuple[str, str, dict[str, Any]]) -> list[dict[str, Any]]: + return [ + {"kind": kind, "label": label, "params": params, "weight": 1} + for kind, label, params in specs + ] + + +@pytest.fixture +def h(tmp_path: Path) -> MixHarness: + return MixHarness( + tmp_path, + entries=entries(("immich", "alice", {"persons": ["Alice"]}), ("other", "film", {})), + ) + + +async def test_precedence_pinned_then_mix_then_last(h: MixHarness) -> None: + service = h.service() + await service.record_manual(ALICE) + active = service.active_rule() + assert active is not None and (active.source, active.kind) == ("smart_mix", "smart_mix") + + await h.store.update({"scheduler": {"source_rule": BOB.model_dump()}}) + active = service.active_rule() + assert active is not None and (active.source, active.rule) == ("pinned", BOB) + + await h.store.update({"scheduler": {"source_rule": None}, "smart_mix": {"enabled": False}}) + active = service.active_rule() + assert active is not None and (active.source, active.rule) == ("last", ALICE) + + +async def test_mix_without_enabled_entries_falls_back_to_last_rule(tmp_path: Path) -> None: + h = MixHarness(tmp_path, entries=[{"kind": "immich", "enabled": False}]) + service = h.service() + assert service.active_rule() is None + await service.record_manual(ALICE) + active = service.active_rule() + assert active is not None and active.source == "last" + + +async def test_refresh_picks_a_weighted_entry_and_keeps_last_rule(h: MixHarness) -> None: + service = h.service(0.01, 0.9) # alice first + await service.record_manual(BOB) + h.clock.advance(hours=1) + + outcome = await service.run("manual") + + assert outcome.active.source == "smart_mix" + assert outcome.entry_label == "alice" and outcome.rule.kind == "immich" + assert h.immich.calls == [SourceRule(kind="immich", params={"persons": ["Alice"]})] + assert service.state.last_rule == BOB # mix runs never rewrite the last manual rule + assert service.state.last_mix_index == 0 + assert service.state.last_run is not None + assert (service.state.last_run.entry_label, service.state.last_run.entry_index) == ("alice", 0) + assert service.state.timer_reset_at == h.clock.now + + +async def test_no_candidate_rerolls_to_the_next_entry(h: MixHarness) -> None: + h.immich.error = NoCandidateError("nothing") + service = h.service(0.01, 0.9) # alice (fails), then film + + outcome = await service.run("manual") + + assert outcome.entry_label == "film" + assert len(h.immich.calls) == 1 and len(h.other.calls) == 1 + assert service.state.last_mix_index == 1 + + +async def test_all_entries_failing_raises_the_last_error_and_backs_off(h: MixHarness) -> None: + h.immich.error = NoCandidateError("nothing") + h.other.error = NoCandidateError("still nothing") + service = h.service(0.01, 0.9, 0.01, 0.9) + + with pytest.raises(NoCandidateError, match="still nothing"): + await service.run("manual") + assert service.state.last_run is not None and service.state.last_run.status == "failed" + + last_run = await service.tick() + assert last_run is not None and last_run.status == "failed" + assert service.state.consecutive_failures == 1 and service.state.retry_at is not None + + +async def test_max_attempts_limits_the_rerolls(tmp_path: Path) -> None: + h = MixHarness( + tmp_path, + max_attempts=1, + entries=entries(("immich", "a", {}), ("other", "b", {})), + ) + h.immich.error = NoCandidateError("nothing") + service = h.service(0.01, 0.9) + with pytest.raises(NoCandidateError): + await service.run("manual") + assert h.other.calls == [] + + +async def test_unsupported_kind_is_rerolled(tmp_path: Path) -> None: + h = MixHarness(tmp_path, entries=entries(("tmdb", "poster", {}), ("immich", "a", {}))) + service = h.service(0.01, 0.9) # tmdb first: no runner registered + outcome = await service.run("manual") + assert outcome.entry_label == "a" + assert service.supported_kinds == ["immich", "other"] + + +async def test_placeholders_are_expanded_before_running(tmp_path: Path) -> None: + h = MixHarness( + tmp_path, + entries=entries(("immich", "season", {"clip_queries": ["{season} {month_name}"]})), + ) + await h.service().run("manual") + assert h.immich.calls[0].params == {"clip_queries": ["winter january"]} # T0 = January + + +async def test_context_boost_and_expiry(h: MixHarness) -> None: + service = h.service() + context = MixContext( + rule=SourceRule(kind="other", params={"q": "beach"}), + expires_at=h.clock.now + timedelta(hours=1), + exclusive=True, + label="beach", + ) + await service.set_context(context) + + outcome = await service.run("manual") + assert outcome.entry_label == "beach" and h.other.calls[-1].params == {"q": "beach"} + + h.clock.advance(hours=2) + assert service.live_context() is None + outcome = await service.run("manual") + assert outcome.entry_label in {"alice", "film"} + + await service.set_context(context) + await service.set_context(None) + assert service.state.context is None + + +async def test_context_makes_an_otherwise_empty_mix_active(tmp_path: Path) -> None: + h = MixHarness(tmp_path, entries=[]) + service = h.service() + with pytest.raises(NoRuleError): + await service.run("manual") + await service.set_context( + MixContext(rule=ALICE, expires_at=h.clock.now + timedelta(minutes=10)) + ) + assert (await service.run("manual")).rule == ALICE + + +async def test_snapshot_reports_the_mix(h: MixHarness) -> None: + snapshot = h.service().snapshot() + assert snapshot.active_rule is not None + assert (snapshot.active_rule.kind, snapshot.active_rule.source) == ("smart_mix", "smart_mix") From 25c31860770f8b7faf750301c1566f629f44c9d6 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sun, 15 Nov 2026 14:45:19 +0100 Subject: [PATCH 47/86] feat: add ephemeral and hold to direct pushes Direct pushes (Immich display, upload) accept ephemeral (not stored as last_rule) and hold_minutes (scheduled refreshes wait at least that long). They always reset the timer and never touch the configuration. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- app/api/routes/display.py | 11 +- app/api/routes/immich.py | 4 +- app/providers/immich/models.py | 11 ++ app/services/scheduler.py | 45 +++++++- tests/test_api_refresh.py | 1 + tests/test_direct_push.py | 181 +++++++++++++++++++++++++++++++++ 6 files changed, 246 insertions(+), 7 deletions(-) create mode 100644 tests/test_direct_push.py diff --git a/app/api/routes/display.py b/app/api/routes/display.py index e109b86..fb3fb9d 100644 --- a/app/api/routes/display.py +++ b/app/api/routes/display.py @@ -50,6 +50,15 @@ async def display_upload( push_to_fraimic: Annotated[ bool, Form(description="Send the result to the frame (or queue it in deepsleep mode)") ] = True, + ephemeral: Annotated[ + bool, Form(description="Temporary push (accepted for symmetry; uploads are never replayed)") + ] = False, + hold_minutes: Annotated[ + int | None, + Form( + ge=1, le=10080, description="Keep it up at least this long before a scheduled refresh" + ), + ] = None, ) -> DisplayResult: """Render an uploaded image for the frame and make it the current image. @@ -77,5 +86,5 @@ async def display_upload( except InvalidImageError as exc: raise HTTPException(status_code=415, detail=str(exc)) from exc if push_to_fraimic: - await scheduler.record_manual(None) + await scheduler.record_manual(None, ephemeral=ephemeral, hold_minutes=hold_minutes) return result diff --git a/app/api/routes/immich.py b/app/api/routes/immich.py index 38ea4f4..4c68174 100644 --- a/app/api/routes/immich.py +++ b/app/api/routes/immich.py @@ -70,7 +70,9 @@ async def display_immich( status_code=502, detail="Immich returned an image that cannot be decoded" ) from exc if request.push_to_fraimic: - await scheduler.record_manual(immich_rule(request)) + await scheduler.record_manual( + immich_rule(request), ephemeral=request.ephemeral, hold_minutes=request.hold_minutes + ) return result diff --git a/app/providers/immich/models.py b/app/providers/immich/models.py index 94466cf..5eb0909 100644 --- a/app/providers/immich/models.py +++ b/app/providers/immich/models.py @@ -190,6 +190,17 @@ class ImmichDisplayRequest(BaseModel): description="Memories: photos taken around today's date in previous years " "(evaluated at display time; exclusive with taken_after/taken_before)", ) + ephemeral: bool = Field( + default=False, + description="Temporary push: do not make this request the rule replayed by " + "POST /api/refresh when nothing is pinned", + ) + hold_minutes: int | None = Field( + default=None, + ge=1, + le=10080, + description="Keep this image up for at least this long before a scheduled refresh", + ) skip_quality_gate: bool | None = Field( default=None, description="Skip the photo suitability check. Default: skipped in album mode " diff --git a/app/services/scheduler.py b/app/services/scheduler.py index 7a652dc..f3733a2 100644 --- a/app/services/scheduler.py +++ b/app/services/scheduler.py @@ -65,7 +65,9 @@ RuleRunner = Callable[[SourceRule], Awaitable[DisplayResult]] #: Request fields that describe one action rather than the selection; never replayed. -NON_REPLAYED_FIELDS: Final = frozenset({"push_to_fraimic", "ignore_history"}) +NON_REPLAYED_FIELDS: Final = frozenset( + {"push_to_fraimic", "ignore_history", "ephemeral", "hold_minutes"} +) def _utcnow() -> datetime: @@ -129,6 +131,9 @@ class SchedulerState(BaseModel): context: MixContext | None = Field( default=None, description="Temporary Smart Mix boost or override" ) + hold_until: AwareDatetime | None = Field( + default=None, description="A pushed image stays up at least until then" + ) @dataclass(frozen=True, slots=True) @@ -191,6 +196,9 @@ class SchedulerSnapshot(BaseModel): last_run: LastRun | None last_display_at: AwareDatetime | None consecutive_failures: int + hold_until: AwareDatetime | None = Field( + description="A directly pushed image is protected from scheduled refreshes until then" + ) active_rule: ActiveRuleView | None = Field(description="null until something can be replayed") @@ -301,6 +309,10 @@ def supported_kinds(self) -> list[str]: """Source kinds that can be replayed (the runner registry).""" return sorted(self._runners) + def _live_hold(self) -> datetime | None: + hold = self._state.hold_until + return hold if hold is not None and hold > self._clock() else None + def live_context(self) -> MixContext | None: """The Smart Mix context boost, unless it has expired.""" context = self._state.context @@ -343,6 +355,7 @@ def snapshot(self) -> SchedulerSnapshot: last_run=self._state.last_run, last_display_at=self._state.last_display_at, consecutive_failures=self._state.consecutive_failures, + hold_until=self._live_hold(), active_rule=( ActiveRuleView(kind=active.kind, source=active.source) if active else None ), @@ -361,6 +374,8 @@ def compute_next_run(self) -> datetime | None: due = state.timer_reset_at + timedelta(hours=config.interval_hours) else: due = now + if state.hold_until is not None: + due = max(due, state.hold_until) due = max(due, now + self._min_delay) return next_run_at(due, quiet_window(config), ZoneInfo(config.timezone)) @@ -426,16 +441,29 @@ async def tick(self) -> LastRun | None: finally: self._arm() - async def record_manual(self, rule: SourceRule | None) -> None: - """Note a successful manual display: it resets the timer. + async def record_manual( + self, + rule: SourceRule | None, + *, + ephemeral: bool = False, + hold_minutes: int | None = None, + ) -> None: + """Note a direct display: it resets the timer and never touches the configuration. Args: rule: The request to replay from now on, or ``None`` for sources that cannot be replayed (e.g. an uploaded file), which keep the previous rule. + ephemeral: A temporary push (movie poster, now playing...): it does not become + the fallback ``last_rule``. + hold_minutes: Protect the image from scheduled refreshes for at least this long + (the next refresh is not due before then, even if the interval is shorter). """ - update: dict[str, Any] = self._timer_reset(self._clock()) - if rule is not None: + now = self._clock() + update: dict[str, Any] = self._timer_reset(now) + if rule is not None and not ephemeral: update["last_rule"] = rule + if hold_minutes: + update["hold_until"] = now + timedelta(minutes=hold_minutes) await self._save(**update) self._arm() @@ -463,6 +491,12 @@ async def _scheduled(self) -> LastRun | None: # The configuration changed after the timer was armed: wait for the window # end without restarting the interval. return await self._skip("Quiet hours", None, restart_timer=False) + hold = self._live_hold() + if hold is not None: + # A direct push arrived after the timer was armed: leave it up until the hold ends. + return await self._skip( + f"A pushed image is held until {hold.isoformat()}", None, restart_timer=False + ) active = self.active_rule() if active is None: return await self._skip( @@ -558,6 +592,7 @@ def _timer_reset(now: datetime) -> dict[str, Any]: "timer_reset_at": now, "retry_at": None, "consecutive_failures": 0, + "hold_until": None, } async def _record_success( diff --git a/tests/test_api_refresh.py b/tests/test_api_refresh.py index 3c6087d..53495af 100644 --- a/tests/test_api_refresh.py +++ b/tests/test_api_refresh.py @@ -165,6 +165,7 @@ def test_status_when_disabled(make_client: ClientFactory) -> None: "last_run": None, "last_display_at": None, "consecutive_failures": 0, + "hold_until": None, "active_rule": None, } diff --git a/tests/test_direct_push.py b/tests/test_direct_push.py new file mode 100644 index 0000000..b9fb875 --- /dev/null +++ b/tests/test_direct_push.py @@ -0,0 +1,181 @@ +"""Direct pushes: ephemeral rules and hold windows never fight the scheduler.""" + +from __future__ import annotations + +import asyncio +from datetime import timedelta +from pathlib import Path +from typing import Any + +import pytest + +from app.core.config_store import ConfigStore +from app.services.scheduler import SchedulerService, immich_rule +from tests.conftest import ClientFactory +from tests.immich_fake import FakeImmich +from tests.test_api_immich import immich_client, servers, show +from tests.test_api_refresh import alice_and_bob, pin, refresh, upload +from tests.test_scheduler_service import ALICE, BOB, T0, FakeClock, FakeRunner + + +def make_service(tmp_path: Path, clock: FakeClock, runner: FakeRunner, **config: Any) -> Any: + store = ConfigStore( + tmp_path / "config.json", + {"scheduler": {"enabled": True, "interval_hours": 2, **config}}, + ) + store.load() + service = SchedulerService( + tmp_path / "scheduler_state.json", store, {"immich": runner}, clock=clock + ) + service.load() + return service + + +async def test_ephemeral_push_resets_the_timer_but_keeps_last_rule(tmp_path: Path) -> None: + clock, runner = FakeClock(), FakeRunner() + service = make_service(tmp_path, clock, runner) + await service.record_manual(ALICE) + clock.advance(hours=1) + + await service.record_manual(BOB, ephemeral=True) + + assert service.state.last_rule == ALICE + assert service.state.timer_reset_at == clock.now + assert service.next_run_at == clock.now + timedelta(hours=2) + + +async def test_hold_postpones_the_next_refresh(tmp_path: Path) -> None: + clock, runner = FakeClock(), FakeRunner() + service = make_service(tmp_path, clock, runner) + + await service.record_manual(None, ephemeral=True, hold_minutes=300) + + assert service.next_run_at == T0 + timedelta(minutes=300) # not 2 h + assert service.snapshot().hold_until == T0 + timedelta(minutes=300) + + +async def test_tick_during_a_hold_is_skipped_without_restarting_the_timer(tmp_path: Path) -> None: + clock, runner = FakeClock(), FakeRunner() + service = make_service(tmp_path, clock, runner) + await service.record_manual(ALICE, hold_minutes=300) + clock.advance(hours=3) # the plain interval elapsed; the hold has not + + last_run = await service.tick() + + assert last_run is not None and last_run.status == "skipped" + assert "held" in (last_run.detail or "") + assert runner.calls == [] + assert service.state.timer_reset_at == T0 + assert service.next_run_at == T0 + timedelta(minutes=300) + + +async def test_hold_expires_and_a_refresh_clears_it(tmp_path: Path) -> None: + clock, runner = FakeClock(), FakeRunner() + service = make_service(tmp_path, clock, runner) + await service.record_manual(ALICE, hold_minutes=60) + clock.advance(hours=2) + + assert service.snapshot().hold_until is None + last_run = await service.tick() + assert last_run is not None and last_run.status == "ok" + assert service.state.hold_until is None + + +async def test_a_plain_push_clears_a_previous_hold(tmp_path: Path) -> None: + clock, runner = FakeClock(), FakeRunner() + service = make_service(tmp_path, clock, runner) + await service.record_manual(None, hold_minutes=600) + await service.record_manual(ALICE) + assert service.state.hold_until is None + assert service.next_run_at == T0 + timedelta(hours=2) + + +async def test_manual_refresh_ignores_the_hold(tmp_path: Path) -> None: + clock, runner = FakeClock(), FakeRunner() + service = make_service(tmp_path, clock, runner) + await service.record_manual(ALICE, hold_minutes=600) + + await service.run("manual") + + assert runner.calls == [ALICE] + assert service.state.hold_until is None + + +async def test_push_during_a_running_refresh_does_not_block_or_corrupt_state( + tmp_path: Path, +) -> None: + clock, runner = FakeClock(), FakeRunner() + runner.gate = asyncio.Event() + service = make_service(tmp_path, clock, runner) + await service.record_manual(ALICE) + + refreshing = asyncio.create_task(service.run("manual")) + await asyncio.sleep(0) + assert service.running + + clock.advance(minutes=1) + await service.record_manual(BOB, ephemeral=True, hold_minutes=90) # not blocked by the lock + assert service.state.hold_until == clock.now + timedelta(minutes=90) + + runner.gate.set() + await refreshing + # The refresh finished last, so the timer state is the refresh's; the rule is untouched. + assert service.state.last_rule == ALICE + assert service.state.hold_until is None + await service.record_manual(None, hold_minutes=30) # a later push wins again + assert service.state.hold_until == clock.now + timedelta(minutes=30) + + +def test_non_replayed_fields_stay_out_of_the_rule() -> None: + from app.providers.immich import ImmichDisplayRequest + + request = ImmichDisplayRequest(persons=["Alice"], ephemeral=True, hold_minutes=30) + params = immich_rule(request).params + assert params["persons"] == ["Alice"] + assert "ephemeral" not in params and "hold_minutes" not in params + + +# --- API -------------------------------------------------------------------------------- +def test_ephemeral_immich_push_keeps_the_previous_rule(make_client: ClientFactory) -> None: + fake: FakeImmich = alice_and_bob() + client = immich_client(make_client) + with servers(fake): + assert show(client, persons=["Alice"]).status_code == 200 + assert show(client, persons=["Bob"], ephemeral=True, hold_minutes=120).status_code == 200 + response = refresh(client) + + assert response.status_code == 200, response.text + assert response.json()["display"]["image"]["title"].startswith("Alice") # Bob was ephemeral + + +def test_hold_is_reported_in_the_status(make_client: ClientFactory) -> None: + fake = alice_and_bob() + client = immich_client(make_client) + with servers(fake): + assert show(client, persons=["Alice"], hold_minutes=45).status_code == 200 + scheduler = client.get("/api/status").json()["scheduler"] + assert scheduler["hold_until"] is not None + + +def test_upload_accepts_hold_and_ephemeral(make_client: ClientFactory) -> None: + fake = alice_and_bob() + client = immich_client(make_client) + with servers(fake): + assert upload(client).status_code == 200 + assert client.get("/api/status").json()["scheduler"]["hold_until"] is None + + +def test_direct_push_never_changes_the_configuration(make_client: ClientFactory) -> None: + fake = alice_and_bob() + client = immich_client(make_client) + pin(client, {"kind": "immich", "params": {"persons": ["Bob"]}}) + before = client.get("/api/config").json() + with servers(fake): + assert show(client, persons=["Alice"], ephemeral=True, hold_minutes=10).status_code == 200 + assert client.get("/api/config").json() == before + + +@pytest.mark.parametrize("minutes", [0, -5, 10081]) +def test_hold_minutes_are_validated(make_client: ClientFactory, minutes: int) -> None: + client = immich_client(make_client) + assert show(client, hold_minutes=minutes).status_code == 422 From 3ccb3a208e20c61eba97f9db38fe3e3f96623271 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sun, 15 Nov 2026 14:54:40 +0100 Subject: [PATCH 48/86] feat: add smart-search and smart-mix context endpoints POST /api/display/smart-search pushes a contextual search (phrases, people names, on_this_day) as an ephemeral direct push. /api/smart-mix shows the playlist and sets/clears a temporary context boost. The prefix is API-key protected and /api/status reports the mix. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- app/api/routes/immich.py | 17 ++- app/api/routes/smart_mix.py | 297 ++++++++++++++++++++++++++++++++++++ app/core/auth.py | 2 +- app/main.py | 3 + app/services/scheduler.py | 53 ++++++- tests/test_api_refresh.py | 1 + tests/test_api_smart_mix.py | 232 ++++++++++++++++++++++++++++ 7 files changed, 598 insertions(+), 7 deletions(-) create mode 100644 app/api/routes/smart_mix.py create mode 100644 tests/test_api_smart_mix.py diff --git a/app/api/routes/immich.py b/app/api/routes/immich.py index 4c68174..49b9ce5 100644 --- a/app/api/routes/immich.py +++ b/app/api/routes/immich.py @@ -21,8 +21,9 @@ from app.providers.base import InvalidSelectionError, ProviderError from app.providers.immich.models import AlbumInfo, ImmichDisplayRequest from app.providers.immich.people import PeopleSnapshot, resolve_person -from app.services.display import DisplayResult -from app.services.scheduler import immich_rule +from app.providers.immich.provider import ImmichProvider +from app.services.display import DisplayResult, DisplayService +from app.services.scheduler import SchedulerService, immich_rule display_router = APIRouter( prefix="/api/display", tags=["display"], dependencies=[Security(api_key_scheme)] @@ -58,7 +59,19 @@ async def display_immich( The photo is recorded in the history so it is not shown again within ``immich.anti_repeat_days``. When pushed to the frame, the request becomes the rule replayed by ``POST /api/refresh`` and the scheduler, and the refresh timer restarts. + With ``ephemeral`` the request is not stored as that rule; ``hold_minutes`` keeps the + image up for at least that long. A direct push never changes the Smart Mix playlist. """ + return await show_immich(request, provider, display, scheduler) + + +async def show_immich( + request: ImmichDisplayRequest, + provider: ImmichProvider, + display: DisplayService, + scheduler: SchedulerService, +) -> DisplayResult: + """Fetch, render and (when pushed) record one Immich display request.""" try: asset = await provider.fetch(request) except ProviderError as exc: diff --git a/app/api/routes/smart_mix.py b/app/api/routes/smart_mix.py new file mode 100644 index 0000000..10d8e46 --- /dev/null +++ b/app/api/routes/smart_mix.py @@ -0,0 +1,297 @@ +"""Smart Mix and Smart Search endpoints (built for Home Assistant automations). + +* ``POST /api/display/smart-search``: an immediate, contextual push ("beach vacation", + "rainy sunday", a person, "on this day"...) without knowing any Immich ID. It is a direct + push: it resets the refresh timer, is ephemeral by default and never changes the playlist. +* ``/api/smart-mix``: inspect the playlist and set a temporary context boost that shapes the + next scheduled refreshes (and expires by itself). +""" + +from __future__ import annotations + +from datetime import timedelta +from typing import Any + +from fastapi import APIRouter, HTTPException, Security +from pydantic import AwareDatetime, BaseModel, ConfigDict, Field, JsonValue, ValidationError + +from app.api.deps import ( + ConfigStoreDep, + DisplayServiceDep, + ImmichProviderDep, + SchedulerDep, +) +from app.api.errors import PROVIDER_ERROR_RESPONSES +from app.api.routes.immich import show_immich +from app.core.auth import api_key_scheme +from app.core.config_models import FitMode, SourceKind, SourceRule +from app.providers.immich.models import ImmichDisplayRequest, MatchMode, OnThisDay +from app.services.display import DisplayResult +from app.services.scheduler import ContextView, validation_summary +from app.services.smart_mix import DEFAULT_CONTEXT_WEIGHT, MixContext + +display_router = APIRouter( + prefix="/api/display", tags=["smart-mix"], dependencies=[Security(api_key_scheme)] +) +router = APIRouter( + prefix="/api/smart-mix", tags=["smart-mix"], dependencies=[Security(api_key_scheme)] +) + +_MAX_MINUTES = 10080 # one week + + +# --- Smart search ---------------------------------------------------------------------- +class SmartSearchRequest(BaseModel): + """A contextual search over the photo library (people are plain names).""" + + model_config = ConfigDict(extra="forbid") + + query: str | None = Field(default=None, description='One semantic phrase, e.g. "rainy sunday"') + queries: list[str] = Field( + default_factory=list, max_length=10, description="More phrases (a photo matching any)" + ) + persons: list[str] | None = Field(default=None, description="Person names (optional)") + match_mode: MatchMode | None = None + accounts: list[str] | None = None + on_this_day: bool | OnThisDay | None = Field( + default=None, + description="Memories around today's date in past years (true = defaults)", + ) + taken_after: AwareDatetime | None = None + taken_before: AwareDatetime | None = None + fit: FitMode | None = None + push_to_fraimic: bool = True + ephemeral: bool = Field( + default=True, + description="Temporary push: not stored as the rule replayed by POST /api/refresh", + ) + hold_minutes: int | None = Field( + default=None, + ge=1, + le=_MAX_MINUTES, + description="Protect the image from scheduled refreshes", + ) + ignore_history: bool = False + skip_quality_gate: bool | None = None + + def phrases(self) -> list[str]: + """All non-empty search phrases.""" + return [p.strip() for p in [self.query or "", *self.queries] if p.strip()] + + +@display_router.post( + "/smart-search", + response_model=DisplayResult, + responses=PROVIDER_ERROR_RESPONSES, + summary="Display a photo found by a contextual search", +) +async def display_smart_search( + body: SmartSearchRequest, + provider: ImmichProviderDep, + display: DisplayServiceDep, + scheduler: SchedulerDep, +) -> DisplayResult: + """Search the library by meaning, time or people and display the best fresh match. + + Phrases may use ``{season}``, ``{month_name}``, ``{month}`` and ``{year}`` placeholders. + Without a phrase, ``on_this_day`` or a date range is required. + """ + phrases = body.phrases() + if not phrases and not body.on_this_day and not (body.taken_after or body.taken_before): + raise HTTPException( + status_code=422, + detail="Give a query, or on_this_day / a taken_after-taken_before range", + ) + fields: dict[str, Any] = body.model_dump( + mode="json", + exclude_none=True, + exclude={"query", "queries", "on_this_day"}, + ) + fields["mode"] = "search" if phrases else "random" + if phrases: + fields["clip_queries"] = phrases + if body.on_this_day: + fields["on_this_day"] = ( + body.on_this_day.model_dump() if isinstance(body.on_this_day, OnThisDay) else {} + ) + try: + request = ImmichDisplayRequest.model_validate(scheduler.expand(fields)) + except ValidationError as exc: + raise HTTPException(status_code=422, detail=validation_summary(exc)) from exc + return await show_immich(request, provider, display, scheduler) + + +# --- Context boost --------------------------------------------------------------------- +class ContextRequest(BaseModel): + """A temporary boost of the Smart Mix, e.g. "it is raining: favour cosy photos".""" + + model_config = ConfigDict(extra="forbid") + + kind: SourceKind = Field(default="immich", description="Source of the boosted rule") + params: dict[str, JsonValue] = Field( + default_factory=dict, description="Raw rule parameters (the display endpoint body)" + ) + queries: list[str] = Field( + default_factory=list, max_length=10, description="Immich shorthand: search phrases" + ) + persons: list[str] | None = Field(default=None, description="Immich shorthand: names") + on_this_day: bool = Field(default=False, description="Immich shorthand: memories") + weight: float = Field(default=DEFAULT_CONTEXT_WEIGHT, gt=0, le=1000) + ttl_minutes: int = Field(default=60, ge=1, le=_MAX_MINUTES, description="Boost lifetime") + exclusive: bool = Field( + default=False, description="Only the boost is used until it expires (an override)" + ) + label: str | None = Field(default=None, max_length=80) + + +class ContextResponse(ContextView): + """The boost that was set.""" + + rule: SourceRule + effective: bool = Field( + description="false while a pinned scheduler.source_rule takes precedence over the mix" + ) + + +def _rule_from(body: ContextRequest) -> SourceRule: + params: dict[str, JsonValue] = dict(body.params) + shorthand = bool(body.queries or body.persons or body.on_this_day) + if shorthand and body.kind != "immich": + raise HTTPException( + status_code=422, detail="queries/persons/on_this_day only apply to kind 'immich'" + ) + if body.queries: + params["mode"] = "search" + params["clip_queries"] = list(body.queries) + if body.persons is not None: + params["persons"] = list(body.persons) + if body.on_this_day: + params["on_this_day"] = {} + if not params: + raise HTTPException(status_code=422, detail="Give params or queries for the boost") + if body.kind == "immich": + try: + ImmichDisplayRequest.model_validate(params) + except ValidationError as exc: + raise HTTPException(status_code=422, detail=validation_summary(exc)) from exc + return SourceRule(kind=body.kind, params=params) + + +@router.post( + "/context", + response_model=ContextResponse, + responses={ + 409: {"description": "Smart Mix is disabled (smart_mix.enabled)"}, + 422: {"description": "Unknown source kind or invalid parameters"}, + }, + summary="Boost or override the Smart Mix temporarily", +) +async def set_context( + body: ContextRequest, scheduler: SchedulerDep, config: ConfigStoreDep +) -> ContextResponse: + """Add a rule to the playlist (or use it alone) until ``ttl_minutes`` pass. + + Scheduled refreshes pick it according to ``weight``; nothing is displayed right now (use + ``POST /api/display/smart-search`` for that). A new boost replaces the previous one. + """ + if not config.config.smart_mix.enabled: + raise HTTPException(status_code=409, detail="Smart Mix is disabled (smart_mix.enabled)") + if body.kind not in scheduler.supported_kinds: + raise HTTPException( + status_code=422, + detail=f"Unsupported kind {body.kind!r}; supported: {scheduler.supported_kinds}", + ) + rule = _rule_from(body) + context = MixContext( + rule=rule, + weight=body.weight, + expires_at=scheduler.now() + timedelta(minutes=body.ttl_minutes), + exclusive=body.exclusive, + label=body.label, + ) + await scheduler.set_context(context) + active = scheduler.active_rule() + return ContextResponse( + label=context.label, + kind=rule.kind, + weight=context.weight, + exclusive=context.exclusive, + expires_at=context.expires_at, + rule=rule, + effective=active is not None and active.source == "smart_mix", + ) + + +class ClearedResponse(BaseModel): + cleared: bool = Field(description="Whether a boost was active") + + +@router.delete("/context", response_model=ClearedResponse, summary="Remove the Smart Mix boost") +async def clear_context(scheduler: SchedulerDep) -> ClearedResponse: + """Drop the temporary boost immediately.""" + had = scheduler.live_context() is not None + await scheduler.set_context(None) + return ClearedResponse(cleared=had) + + +# --- Inspection ------------------------------------------------------------------------ +class MixEntryView(BaseModel): + index: int + label: str | None + kind: str + weight: float + enabled: bool + probability: float = Field(description="Chance of being tried first at the next refresh") + params: dict[str, JsonValue] + resolved_params: dict[str, JsonValue] = Field( + description="params with {season}/{month_name}... expanded for now" + ) + + +class SmartMixView(BaseModel): + enabled: bool + effective: bool = Field(description="Whether scheduled refreshes currently use the mix") + supported_kinds: list[str] = Field(description="Source kinds that can run (runner registry)") + max_attempts: int + avoid_consecutive: bool + hemisphere: str + entries: list[MixEntryView] + context: ContextView | None + last_entry_index: int | None + last_entry_label: str | None + + +@router.get("", response_model=SmartMixView, summary="Show the Smart Mix playlist") +async def get_smart_mix(scheduler: SchedulerDep, config: ConfigStoreDep) -> SmartMixView: + """The playlist with each entry's effective probability and the live boost.""" + mix = config.config.smart_mix + pool = scheduler.mix_pool() if mix.enabled else [] + total = sum(candidate.weight for candidate in pool) + chance = {c.index: c.weight / total for c in pool if c.index is not None and total > 0} + entries = [ + MixEntryView( + index=index, + label=entry.label, + kind=entry.kind, + weight=entry.weight, + enabled=entry.enabled, + probability=round(chance.get(index, 0.0), 4), + params=entry.params, + resolved_params=scheduler.expand(entry.params), + ) + for index, entry in enumerate(mix.entries) + ] + active = scheduler.active_rule() + last = scheduler.state.last_run + return SmartMixView( + enabled=mix.enabled, + effective=active is not None and active.source == "smart_mix", + supported_kinds=scheduler.supported_kinds, + max_attempts=mix.max_attempts, + avoid_consecutive=mix.avoid_consecutive, + hemisphere=mix.hemisphere, + entries=entries, + context=scheduler.context_view(), + last_entry_index=scheduler.state.last_mix_index, + last_entry_label=last.entry_label if last else None, + ) diff --git a/app/core/auth.py b/app/core/auth.py index a53f67a..5c1b312 100644 --- a/app/core/auth.py +++ b/app/core/auth.py @@ -29,7 +29,7 @@ API_KEY_QUERY_PARAM: Final = "api_key" MUTATING_METHODS: Final = frozenset({"POST", "PUT", "PATCH", "DELETE"}) -PROTECTED_PREFIXES: Final = ("/api/config", "/api/immich") +PROTECTED_PREFIXES: Final = ("/api/config", "/api/immich", "/api/smart-mix") IMAGE_ENDPOINTS: Final = frozenset( {"/api/current.jpg", "/api/current.bin", "/api/current_dithered.png"} ) diff --git a/app/main.py b/app/main.py index 1c28fad..0b030c2 100644 --- a/app/main.py +++ b/app/main.py @@ -25,6 +25,7 @@ from app.api.routes import images as image_routes from app.api.routes import immich as immich_routes from app.api.routes import refresh as refresh_routes +from app.api.routes import smart_mix as smart_mix_routes from app.api.routes import system as system_routes from app.core.auth import APIKeyMiddleware from app.core.config_models import RuntimeConfig @@ -194,6 +195,8 @@ async def _validation_handler(_: Request, exc: RequestValidationError) -> JSONRe app.include_router(immich_routes.display_router) app.include_router(immich_routes.router) app.include_router(refresh_routes.router) + app.include_router(smart_mix_routes.display_router) + app.include_router(smart_mix_routes.router) app.include_router(fraimic_routes.router) @app.get("/", include_in_schema=False) diff --git a/app/services/scheduler.py b/app/services/scheduler.py index f3733a2..7d1ae1e 100644 --- a/app/services/scheduler.py +++ b/app/services/scheduler.py @@ -181,6 +181,24 @@ class ActiveRuleView(BaseModel): ) +class ContextView(BaseModel): + """The temporary Smart Mix boost, as exposed by the API.""" + + label: str | None + kind: str + weight: float + exclusive: bool + expires_at: AwareDatetime + + +class SmartMixStatus(BaseModel): + """Smart Mix summary for ``GET /api/status``.""" + + enabled: bool + entries: int = Field(description="Enabled playlist entries") + context: ContextView | None = Field(description="Live temporary boost, if any") + + class SchedulerSnapshot(BaseModel): """Scheduler state exposed through ``GET /api/status`` (no network access).""" @@ -199,6 +217,7 @@ class SchedulerSnapshot(BaseModel): hold_until: AwareDatetime | None = Field( description="A directly pushed image is protected from scheduled refreshes until then" ) + smart_mix: SmartMixStatus active_rule: ActiveRuleView | None = Field(description="null until something can be replayed") @@ -304,6 +323,10 @@ def running(self) -> bool: """Whether a refresh is in progress.""" return self._lock.locked() + def now(self) -> datetime: + """The current time of the service clock.""" + return self._clock() + @property def supported_kinds(self) -> list[str]: """Source kinds that can be replayed (the runner registry).""" @@ -313,6 +336,23 @@ def _live_hold(self) -> datetime | None: hold = self._state.hold_until return hold if hold is not None and hold > self._clock() else None + def context_view(self) -> ContextView | None: + """API view of the live context boost.""" + context = self.live_context() + if context is None: + return None + return ContextView( + label=context.label, + kind=context.rule.kind, + weight=context.weight, + exclusive=context.exclusive, + expires_at=context.expires_at, + ) + + def mix_pool(self) -> list[MixCandidate]: + """Candidates currently in the Smart Mix (enabled entries plus the live context).""" + return self._resolver.pool(self._config.smart_mix, self.live_context()) + def live_context(self) -> MixContext | None: """The Smart Mix context boost, unless it has expired.""" context = self._state.context @@ -356,6 +396,11 @@ def snapshot(self) -> SchedulerSnapshot: last_display_at=self._state.last_display_at, consecutive_failures=self._state.consecutive_failures, hold_until=self._live_hold(), + smart_mix=SmartMixStatus( + enabled=self._config.smart_mix.enabled, + entries=sum(1 for e in self._config.smart_mix.entries if e.enabled), + context=self.context_view(), + ), active_rule=( ActiveRuleView(kind=active.kind, source=active.source) if active else None ), @@ -552,11 +597,11 @@ async def _play(self, active: ActiveRule) -> tuple[DisplayResult, MixCandidate]: raise failure async def _attempt(self, candidate: MixCandidate) -> tuple[DisplayResult, MixCandidate]: - rule = candidate.rule.model_copy(update={"params": self._expand(candidate.rule.params)}) + rule = candidate.rule.model_copy(update={"params": self.expand(candidate.rule.params)}) runner = self._runner(rule) return await runner(rule), candidate - def _expand(self, params: dict[str, JsonValue]) -> dict[str, JsonValue]: + def expand(self, params: dict[str, JsonValue]) -> dict[str, JsonValue]: """Resolve ``{season}``-style placeholders against the current time.""" context = RuleContext( self._clock(), @@ -677,7 +722,7 @@ async def _on_config_change(self, _: RuntimeConfig) -> None: # --- Runners -------------------------------------------------------------------------- -def _validation_summary(exc: ValidationError) -> str: +def validation_summary(exc: ValidationError) -> str: """Field errors without echoing input values.""" return "; ".join( f"{'.'.join(str(part) for part in err['loc']) or 'params'}: {err['msg']}" @@ -701,7 +746,7 @@ async def run(rule: SourceRule) -> DisplayResult: try: request = ImmichDisplayRequest.model_validate(params) except ValidationError as exc: - raise InvalidRuleError(f"Invalid immich rule: {_validation_summary(exc)}") from None + raise InvalidRuleError(f"Invalid immich rule: {validation_summary(exc)}") from None asset = await provider.fetch(request) return await display.display_asset(asset, fit=request.fit, push=True) diff --git a/tests/test_api_refresh.py b/tests/test_api_refresh.py index 53495af..55dd10a 100644 --- a/tests/test_api_refresh.py +++ b/tests/test_api_refresh.py @@ -166,6 +166,7 @@ def test_status_when_disabled(make_client: ClientFactory) -> None: "last_display_at": None, "consecutive_failures": 0, "hold_until": None, + "smart_mix": {"enabled": False, "entries": 0, "context": None}, "active_rule": None, } diff --git a/tests/test_api_smart_mix.py b/tests/test_api_smart_mix.py new file mode 100644 index 0000000..85c9e13 --- /dev/null +++ b/tests/test_api_smart_mix.py @@ -0,0 +1,232 @@ +"""API tests: smart search, Smart Mix context boost and playlist inspection.""" + +from __future__ import annotations + +from datetime import UTC, datetime, timedelta +from typing import Any +from zoneinfo import ZoneInfo + +from fastapi.testclient import TestClient + +from app.core.context import RuleContext +from tests.conftest import ClientFactory +from tests.immich_fake import FakeImmich +from tests.test_api_immich import KEY, immich_client, servers, show +from tests.test_api_refresh import alice_and_bob, pin, refresh + + +def smart_search(client: TestClient, **body: Any) -> Any: + return client.post("/api/display/smart-search", json=body) + + +def enable_mix(client: TestClient, *entries: dict[str, Any], **extra: Any) -> None: + response = client.put( + "/api/config", + json={"smart_mix": {"enabled": True, "entries": list(entries), **extra}}, + ) + assert response.status_code == 200, response.text + + +def bob_entry(**extra: Any) -> dict[str, Any]: + return {"kind": "immich", "label": "bob", "params": {"persons": ["Bob"]}, **extra} + + +def smart_bodies(fake: FakeImmich) -> list[dict[str, Any]]: + return fake.bodies("/api/search/smart") + + +# --- POST /api/display/smart-search ------------------------------------------------------ +def test_smart_search_displays_a_semantic_match(make_client: ClientFactory) -> None: + fake = alice_and_bob() + fake.smart_results["beach vacation"] = ["a2"] + client = immich_client(make_client) + with servers(fake): + response = smart_search(client, query="beach vacation", persons=["Alice"]) + + assert response.status_code == 200, response.text + assert response.json()["image"]["details"]["asset_id"] == "a2" + body = smart_bodies(fake)[0] + assert body["query"] == "beach vacation" and body["personIds"] == ["p1"] + + +def test_smart_search_is_ephemeral_by_default(make_client: ClientFactory) -> None: + fake = alice_and_bob() + fake.add_asset("b2", people=[("p2", "Bob")], localDateTime="2022-01-01T10:00:00.000Z") + client = immich_client(make_client) + with servers(fake): + assert show(client, persons=["Bob"]).status_code == 200 + assert smart_search(client, query="sunset", persons=["Alice"]).status_code == 200 + replayed = refresh(client) + assert ( + smart_search(client, query="sunset", persons=["Alice"], ephemeral=False).status_code + == 200 + ) + stored = client.get("/api/status").json()["scheduler"]["active_rule"] + + assert replayed.json()["display"]["image"]["title"].startswith("Bob") + assert stored == {"kind": "immich", "source": "last"} + + +def test_smart_search_needs_something_to_search(make_client: ClientFactory) -> None: + client = immich_client(make_client) + response = smart_search(client) + assert response.status_code == 422 and "query" in response.json()["detail"] + + +def test_smart_search_expands_placeholders(make_client: ClientFactory) -> None: + fake = alice_and_bob() + client = immich_client(make_client) + with servers(fake): + assert smart_search(client, query="{season} walk").status_code == 200 + + season = RuleContext(datetime.now(UTC), ZoneInfo("UTC")).season + assert smart_bodies(fake)[0]["query"] == f"{season} walk" + + +def test_smart_search_on_this_day_searches_past_years(make_client: ClientFactory) -> None: + today = datetime.now(UTC).date() + memory = f"{today.year - 2}-{today.month:02d}-{min(today.day, 28):02d}T10:00:00.000Z" + fake = FakeImmich() + fake.add_asset("memory", localDateTime=memory) + fake.add_asset( + "other", localDateTime=f"{today.year - 2}-{(today.month % 12) + 1:02d}-15T10:00:00.000Z" + ) + client = immich_client(make_client) + with servers(fake): + response = smart_search(client, on_this_day=True) + + assert response.status_code == 200, response.text + assert response.json()["image"]["details"]["asset_id"] == "memory" + assert all("takenAfter" in body for body in fake.bodies("/api/search/random")) + + +def test_smart_search_hold_is_reported(make_client: ClientFactory) -> None: + fake = alice_and_bob() + client = immich_client(make_client) + with servers(fake): + assert smart_search(client, query="x", hold_minutes=30).status_code == 200 + assert client.get("/api/status").json()["scheduler"]["hold_until"] is not None + + +# --- /api/smart-mix/context ----------------------------------------------------------------- +def test_context_requires_an_enabled_mix(make_client: ClientFactory) -> None: + client = immich_client(make_client) + response = client.post("/api/smart-mix/context", json={"queries": ["beach"]}) + assert response.status_code == 409 + + +def test_context_boost_steers_the_next_refresh_then_clears(make_client: ClientFactory) -> None: + fake = alice_and_bob() + fake.smart_results["beach"] = ["a1", "a2", "a3"] + client = immich_client(make_client) + enable_mix(client, bob_entry()) + + with servers(fake): + response = client.post( + "/api/smart-mix/context", + json={"queries": ["beach"], "exclusive": True, "label": "beach", "ttl_minutes": 30}, + ) + assert response.status_code == 200, response.text + body = response.json() + assert (body["label"], body["kind"], body["exclusive"], body["effective"]) == ( + "beach", + "immich", + True, + True, + ) + boosted = refresh(client).json() + status = client.get("/api/status").json()["scheduler"]["smart_mix"] + cleared = client.delete("/api/smart-mix/context").json() + normal = refresh(client).json() + + assert (boosted["rule_source"], boosted["entry_label"]) == ("smart_mix", "beach") + assert smart_bodies(fake)[0]["query"] == "beach" + assert status["context"]["label"] == "beach" and status["entries"] == 1 + assert cleared == {"cleared": True} + assert normal["entry_label"] == "bob" + + +def test_expired_context_is_ignored(make_client: ClientFactory) -> None: + client = immich_client(make_client) + enable_mix(client, bob_entry()) + assert ( + client.post( + "/api/smart-mix/context", json={"queries": ["beach"], "ttl_minutes": 1} + ).status_code + == 200 + ) + scheduler = client.app.state.scheduler_service # type: ignore[attr-defined] + scheduler._clock = lambda: datetime.now(UTC) + timedelta(minutes=5) + assert client.get("/api/smart-mix").json()["context"] is None + assert client.delete("/api/smart-mix/context").json() == {"cleared": False} + + +def test_context_validation(make_client: ClientFactory) -> None: + client = immich_client(make_client) + enable_mix(client, bob_entry()) + post = client.post + assert post("/api/smart-mix/context", json={}).status_code == 422 + assert ( + post("/api/smart-mix/context", json={"kind": "tmdb", "params": {"a": 1}}).status_code == 422 + ) + assert ( + post("/api/smart-mix/context", json={"kind": "Bad Kind", "params": {"a": 1}}).status_code + == 422 + ) + assert post("/api/smart-mix/context", json={"params": {"mode": "teleport"}}).status_code == 422 + assert ( + post("/api/smart-mix/context", json={"ttl_minutes": 0, "queries": ["x"]}).status_code == 422 + ) + assert post("/api/smart-mix/context", json={"weight": 0, "queries": ["x"]}).status_code == 422 + + +def test_pinned_rule_wins_over_the_mix(make_client: ClientFactory) -> None: + fake = alice_and_bob() + client = immich_client(make_client) + enable_mix(client, bob_entry()) + pin(client, {"kind": "immich", "params": {"persons": ["Alice"]}}) + with servers(fake): + response = refresh(client) + context = client.post("/api/smart-mix/context", json={"queries": ["x"]}).json() + + assert response.json()["rule_source"] == "pinned" + assert context["effective"] is False + + +# --- GET /api/smart-mix ----------------------------------------------------------------------- +def test_playlist_view(make_client: ClientFactory) -> None: + client = immich_client(make_client) + enable_mix( + client, + bob_entry(weight=3), + {"kind": "immich", "params": {"clip_queries": ["{season} light"], "mode": "search"}}, + {"kind": "immich", "weight": 5, "enabled": False}, + ) + view = client.get("/api/smart-mix").json() + + assert view["enabled"] and view["effective"] and view["supported_kinds"] == ["immich"] + assert [e["probability"] for e in view["entries"]] == [0.75, 0.25, 0.0] + season = RuleContext(datetime.now(UTC), ZoneInfo("UTC")).season + assert view["entries"][1]["resolved_params"]["clip_queries"] == [f"{season} light"] + assert view["entries"][1]["params"]["clip_queries"] == ["{season} light"] + assert view["last_entry_index"] is None and view["context"] is None + + +def test_playlist_view_when_disabled(make_client: ClientFactory) -> None: + view = immich_client(make_client).get("/api/smart-mix").json() + assert view["enabled"] is False and view["effective"] is False and view["entries"] == [] + + +# --- Authentication --------------------------------------------------------------------------- +def test_endpoints_require_the_api_key(make_client: ClientFactory) -> None: + client = immich_client(make_client, app_api_key=KEY) + headers = {"X-API-Key": KEY} + + assert client.get("/api/smart-mix").status_code == 401 # GET is protected too + assert client.post("/api/smart-mix/context", json={"queries": ["x"]}).status_code == 401 + assert client.delete("/api/smart-mix/context").status_code == 401 + assert client.post("/api/display/smart-search", json={"query": "x"}).status_code == 401 + + assert client.get("/api/smart-mix", headers=headers).status_code == 200 + assert client.delete("/api/smart-mix/context", headers=headers).status_code == 200 + assert client.get("/api/status").status_code == 200 # status stays public From 6003c36ad534ed87997b6f8cd48644a7bef511f8 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sun, 15 Nov 2026 14:56:12 +0100 Subject: [PATCH 49/86] docs: document smart mix and Home Assistant examples Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- CLAUDE.md | 2 + README.md | 122 ++++++++++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 120 insertions(+), 4 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 6e6dd58..9d54071 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -54,6 +54,8 @@ Clean, responsive (mobile/desktop) English web interface allowing users to: ### 5. REST API (`GET /docs`) - `POST /api/display/immich`: Select and display an Immich photo (`mode` random|album|favorites|search, `persons` as plain names, `match_mode`, `always_include`, `album_name`/`album_id`, `clip_queries`, `accounts`, `fit`, `push_to_fraimic`, `ignore_history`, `skip_quality_gate`). Photos are vetted by a thumbnail-based quality gate (`quality` settings section) and a burst cooldown before the original is downloaded. +- `POST /api/display/smart-search`: Contextual push (`query`/`queries`, `persons`, `on_this_day`, `taken_after`/`taken_before`, `ephemeral` default true, `hold_minutes`) without Immich IDs. +- `GET /api/smart-mix`, `POST`/`DELETE /api/smart-mix/context`: Inspect the weighted Smart Mix playlist (`smart_mix` settings section; source-agnostic `kind` + `params` entries) and set/clear a temporary boost. Rule precedence for scheduled refreshes and `POST /api/refresh`: pinned `scheduler.source_rule` > Smart Mix > last non-ephemeral manual display. Direct pushes (`ephemeral`, `hold_minutes`) reset the timer without altering the playlist. `/api/smart-mix` is API-key protected for every method. - `GET /api/immich/albums`, `GET /api/immich/people`, `POST /api/immich/people/refresh`: Discovery across the configured Immich accounts (`immich.accounts`; keys are masked and `GET /api/immich/*` is API-key protected when `APP_API_KEY` is set). - `POST /api/display/media`: Search and display an HD poster (`title`, `media_type`, `fallback_url`, `push_to_fraimic`). - `POST /api/fraimic/wakeup`: Webhook signaling frame wake-up to flush any queued upload immediately. diff --git a/README.md b/README.md index 2764bbc..313cbc8 100644 --- a/README.md +++ b/README.md @@ -85,6 +85,9 @@ curl -X POST .../api/display/immich -H 'Content-Type: application/json' -d '{"mo | `fit`, `push_to_fraimic` | Fit override, push to the frame (default true) | | `ignore_history` | Allow photos shown within `anti_repeat_days` or taken close to one | | `skip_quality_gate` | Skip the suitability check (default: skipped in `album` mode, checked otherwise) | +| `taken_after`, `taken_before` | Only photos taken in this range (ISO 8601 with a timezone) | +| `on_this_day` | Memories: `{"window_days": 3, "years_back": 10, "min_years_ago": 1}` around today's date in past years (exclusive with the date range) | +| `ephemeral`, `hold_minutes` | Temporary push: do not remember it as the rule to replay; keep it up at least this long (see [Smart Mix](#smart-mix-and-smart-search)) | Unset filters fall back to the `immich` section of the settings. All modes share one query path, so persons, albums and favorites combine freely. @@ -173,10 +176,12 @@ The frame can update itself without Home Assistant. The scheduler replays the ** rule** every `scheduler.interval_hours` hours (`REFRESH_INTERVAL_HOURS`, default 6, minimum 0.25) once `scheduler.enabled` is on (`SCHEDULER_ENABLED=true`): -- **Active rule.** The last request made through `POST /api/display/immich` (pushed to the +- **Active rule**, in order of precedence: (1) the rule pinned in `scheduler.source_rule`; + (2) the [Smart Mix](#smart-mix-and-smart-search) playlist, when enabled and non-empty; + (3) the last non-ephemeral request made through `POST /api/display/immich` (pushed to the frame; previews with `push_to_fraimic=false` do not count), so showing "Alice and Bob at the beach" once keeps rotating through those photos with the anti-repeat history. - Pin a fixed rule in `scheduler.source_rule` to override it: + Pin a fixed rule in `scheduler.source_rule` to override the others: ```bash curl -X PUT http://localhost:8000/api/config -H 'Content-Type: application/json' -d '{"scheduler": {"enabled": true, "source_rule": @@ -184,7 +189,7 @@ rule** every `scheduler.interval_hours` hours (`REFRESH_INTERVAL_HOURS`, default ``` `params` takes the fields of `POST /api/display/immich` (except `push_to_fraimic` and - `ignore_history`). Only Immich rules can be replayed for now. The last rule is kept in + `ignore_history`, `ephemeral`, `hold_minutes`). Only Immich rules can be replayed for now. The last rule is kept in `./data/scheduler_state.json`, so displaying a photo never rewrites your settings. - **Timer.** Any display (a manual photo, an upload, a refresh) restarts the interval, so a picture chosen by hand stays up for a full interval. A refresh that became due while @@ -202,7 +207,7 @@ rule** every `scheduler.interval_hours` hours (`REFRESH_INTERVAL_HOURS`, default | Endpoint | Purpose | | --- | --- | | `POST /api/refresh` | Replay the active rule now and push the result (ignores quiet hours; 409 when there is nothing to replay or a refresh is running) | -| `GET /api/status` | `scheduler`: `next_run_at`, `in_quiet_hours`, `last_run` (`ok`/`failed`/`skipped` and why), `consecutive_failures`, `active_rule` (`pinned` or `last`) | +| `GET /api/status` | `scheduler`: `next_run_at`, `in_quiet_hours`, `last_run` (`ok`/`failed`/`skipped` and why), `consecutive_failures`, `active_rule` (`pinned`, `smart_mix` or `last`), `hold_until`, `smart_mix` | ```yaml # Home Assistant: a "next photo" button @@ -215,6 +220,115 @@ rest_command: X-API-Key: !secret smart_frame_api_key # only when APP_API_KEY is set ``` +## Smart Mix and Smart Search + +**Smart Mix** is a weighted playlist of source rules for scheduled refreshes, so the frame +shows a varied rotation (family, favorites, "this season", memories...) instead of one +filter. It knows nothing about providers: each entry wraps a rule (`kind` + `params`, the +body of the matching display endpoint), and the runner registered for that `kind` plays it. +Adding a provider later needs no change to the configuration. + +```bash +curl -X PUT http://localhost:8000/api/config -H 'Content-Type: application/json' -d '{ + "scheduler": {"enabled": true, "interval_hours": 3}, + "smart_mix": {"enabled": true, "entries": [ + {"label": "Family", "kind": "immich", "weight": 5, + "params": {"persons": ["Alice", "Bob"], "match_mode": "any"}}, + {"label": "This season", "kind": "immich", "weight": 2, + "params": {"mode": "search", "clip_queries": ["{season} landscape", "{month_name} light"]}}, + {"label": "On this day", "kind": "immich", "weight": 1, + "params": {"on_this_day": {"window_days": 3, "years_back": 10}}} + ]} +}' +``` + +- **Weights** are relative. Each refresh orders the enabled entries by weighted random + sampling and tries them in turn: if one has no candidate (nothing left in the anti-repeat + history, an empty album) or fails, the next one is tried, up to `smart_mix.max_attempts` + (default 3). With `avoid_consecutive` (default) the entry shown last is tried last. +- **Context placeholders.** `{season}`, `{month}`, `{month_name}` and `{year}` in string + params are expanded each time the entry runs (`smart_mix.hemisphere` flips the seasons; + the timezone is `scheduler.timezone`). `on_this_day` searches `window_days` around today's + date in each of the last `years_back` years; `taken_after` / `taken_before` give a fixed + date range. No album IDs are needed. +- **Precedence** for scheduled refreshes and `POST /api/refresh`: the pinned + `scheduler.source_rule`, then the Smart Mix (enabled with at least one enabled entry), + then the last non-ephemeral manual display. Mix refreshes never overwrite that last + display, so turning the mix off restores the previous behavior. +- **Direct pushes always win.** `POST /api/display/immich`, `/upload` and `/smart-search` + display immediately, restart the refresh timer and never touch the playlist or your + settings. Add `"ephemeral": true` so a temporary push (a movie poster, a song) is not + remembered as the rule to replay, and `"hold_minutes": 150` so no scheduled refresh + replaces it before then (`hold_until` in `GET /api/status`). A manual + `POST /api/refresh` ignores the hold. + +**Smart Search** is the same idea for one-off pushes: describe what you want, never an ID. + +```bash +curl -X POST http://localhost:8000/api/display/smart-search -H 'Content-Type: application/json' \ + -d '{"query": "rainy sunday", "persons": ["Alice"], "hold_minutes": 120}' +curl -X POST .../api/display/smart-search -H 'Content-Type: application/json' \ + -d '{"on_this_day": true}' +``` + +`query` / `queries` are CLIP phrases (placeholders allowed), combined freely with `persons`, +`match_mode`, `accounts`, `on_this_day`, `taken_after` / `taken_before`, `fit`, +`push_to_fraimic` and `ignore_history`. Smart-search pushes are ephemeral by default +(`"ephemeral": false` stores one as the rule to replay). + +A **context boost** shapes the *next scheduled refreshes* for a while, without displaying +anything now: it joins the playlist with its own weight (default 3), or replaces it with +`"exclusive": true`, until `ttl_minutes` pass. + +```bash +curl -X POST .../api/smart-mix/context -H 'Content-Type: application/json' \ + -d '{"queries": ["cozy rainy day"], "weight": 5, "ttl_minutes": 240, "label": "rain"}' +curl -X DELETE .../api/smart-mix/context +``` + +For another source, send `kind` and `params` instead of `queries`. Unknown kinds are +rejected: `GET /api/smart-mix` lists the supported ones. + +| Endpoint | Purpose | +| --- | --- | +| `POST /api/display/smart-search` | Contextual search and immediate (ephemeral) push | +| `POST /api/smart-mix/context` | Temporary boost or override of the playlist (409 when the mix is disabled) | +| `DELETE /api/smart-mix/context` | Remove the boost | +| `GET /api/smart-mix` | Playlist with each entry's probability, resolved placeholders, live boost and supported kinds | + +`/api/smart-mix` requires the API key for every method when `APP_API_KEY` is set. +`GET /api/status` reports `scheduler.smart_mix`, `hold_until`, and the entry shown by the +last refresh (`last_run.entry_label`). + +```yaml +# Home Assistant: push a contextual photo on demand, boost the mix while it rains +rest_command: + frame_smart_search: + url: http://smart-frame.lan:8000/api/display/smart-search + method: POST + content_type: application/json + payload: '{"query": "{{ query }}", "hold_minutes": {{ hold | default(120) }}}' + timeout: 60 + headers: + X-API-Key: !secret smart_frame_api_key + frame_rain_boost: + url: http://smart-frame.lan:8000/api/smart-mix/context + method: POST + content_type: application/json + payload: '{"queries": ["cozy rainy day"], "weight": 5, "ttl_minutes": 240, "label": "rain"}' + headers: + X-API-Key: !secret smart_frame_api_key + +automation: + - alias: Frame - rainy day mood + trigger: + - platform: state + entity_id: weather.home + to: rainy + action: + - service: rest_command.frame_rain_boost +``` + ## Development ```bash From 1ae549c4cfc0ff5424e5f86365b2d2e5b2ca3422 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sun, 15 Nov 2026 15:21:28 +0100 Subject: [PATCH 50/86] feat: add typography and no-crop composition templates Bundle the Inter font family (SIL OFL 1.1) and add typography helpers: cached font loading, WCAG contrast-based black/white text selection, word wrapping with ellipsis and auto-shrinking text blocks. Text is drawn without anti-aliasing so glyphs stay a single palette color after dithering. Add poster, album (sleeve/vinyl) and title-card templates that never crop the artwork and adapt to portrait/landscape and both panels. The pipeline gains finalize() (rotate, dither, encode) and render_layout() so templates share the exact .bin encoding path. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- .gitattributes | 2 + app/assets/fonts/Inter-Bold.ttf | Bin 0 -> 420428 bytes app/assets/fonts/Inter-Regular.ttf | Bin 0 -> 411640 bytes app/assets/fonts/OFL.txt | 92 +++++++ app/processor/pipeline.py | 51 +++- app/processor/templates.py | 426 +++++++++++++++++++++++++++++ app/processor/typography.py | 276 +++++++++++++++++++ pyproject.toml | 2 +- tests/test_templates.py | 200 ++++++++++++++ tests/test_typography.py | 145 ++++++++++ 10 files changed, 1188 insertions(+), 6 deletions(-) create mode 100644 app/assets/fonts/Inter-Bold.ttf create mode 100644 app/assets/fonts/Inter-Regular.ttf create mode 100644 app/assets/fonts/OFL.txt create mode 100644 app/processor/templates.py create mode 100644 app/processor/typography.py create mode 100644 tests/test_templates.py create mode 100644 tests/test_typography.py diff --git a/.gitattributes b/.gitattributes index c7ab696..3f20fc1 100644 --- a/.gitattributes +++ b/.gitattributes @@ -8,3 +8,5 @@ *.webp binary *.gif binary *.bin binary +*.ttf binary +*.otf binary diff --git a/app/assets/fonts/Inter-Bold.ttf b/app/assets/fonts/Inter-Bold.ttf new file mode 100644 index 0000000000000000000000000000000000000000..9fb9b751e5b2441054f6eef670da7b3f53a3505a GIT binary patch literal 420428 zcmeFa3%pH58$UklGPBk?$K?=*gpPCFXYYN^kq&X(@0XB}bdw56k|aq;MM)~D@JhP4 zB=tr@Lh|aSNGa*^mM*Wnl5~?Ko%Q=Z&)VDG`<#7lq~71}|KIaj-}S6#o_S{0ta)Z; z&7N5!G$BMafGLtXcj(w@#@Tmw5<;sBMy1ZZ&gs*2#*$ZrkUpVZvb%Gi^V&JrJuZcI zMI|9F?RQR}yhbUtpL|kin+8G4z$>n~Y~=Vv-y=YVgRRZrV7Z zuDTfV-wRFXq6#SdjIE#_#qm#YmubmD(`swefYY^q03X&q0)C?X2K-&`A~e05z5uvL zUj$sDzX9B$Zv(!oZwKzwcLVq6M}dU~eIkWKII!X5#M5hfUnIx!imn_=33^xYhg*@W19az;DeTfIpc( z0S`(%XlY2KM^=`Vfk`q6SY4h1tSM^&PnGq7SuzV4ltEywJOg;9L^@?t*%VkHTLN3l zw!p5kEAVW2Ht-yI4)9#r8+d`d0C%Z z0&cfZHmvup_ksJY!@%FH--KaHdx+5Nt8Bz&@3MCRzq0=e{yuv@=pXGLh2{vS3b3kE zRT$2xP94y7oqE6&Cl#3PAh(@t2c^O}(?LEvXF14cr=^2@cG@^?fbE?2z>ZEwU{|Lr zu!qwFc#eZScg}Ur1@>|J0MB>M2VUeL=bdYvQNRh#t-#xzJArpOxKrnT=V{Y(I1+npW2kDZT!pE+L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ioCq?CbVH4u?@tqwj;K= z^5&SNy@HseeI1n>quj5javb{xD#x+UP&tm>q&7no+oCop(x5gevQ2GLq)BC-L1c%@ zP^3j=D6&gsD6+@>3J}}peo?H={i4{b+%JmV;(k%A!~LSz0r!hyhuklUbwT5&;t4!r zXm}ABuSv9uXpe|a#fCLN$5?9-r80eqQkemlp$sbXIx2r6#(J9}u5m}ARO7BhsrVbf z^9e!ujS{5-pOq*T_$HKnI>z_S3^BgXNtB9zUZPa|3#j?D;QOLPslc~LlnQ(+%6>A& z_iYR@zHgT(75@&2Qt>aL<|hT;cS@8B+>VuP$mL`8T-^qV{{)KEU>*pWOaq?WPI{j4_-*@rs#ZwpOFWMI;znq!O*eHJ% z8JUYC|5L_~WhOG2;N(MNUwRQ+h%ap@{1JlRn#!1j&83qMQ__!5eLgdmz4)c(buEcK u*yiTNh1c`D`A_Gc%|4x7%@=Z$b5FiC_RhBrv)_#sK6o>?lg|V}=Kla5n}5>) literal 0 HcmV?d00001 diff --git a/app/assets/fonts/OFL.txt b/app/assets/fonts/OFL.txt new file mode 100644 index 0000000..9b2ca37 --- /dev/null +++ b/app/assets/fonts/OFL.txt @@ -0,0 +1,92 @@ +Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION AND CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/app/processor/pipeline.py b/app/processor/pipeline.py index 190dbd3..2513eaa 100644 --- a/app/processor/pipeline.py +++ b/app/processor/pipeline.py @@ -10,6 +10,10 @@ degrees counter-clockwise), then dither it (Atkinson or Floyd-Steinberg, tuned metric). 4. Pack the ``.bin``; the preview indices are rotated back to viewing orientation. +Composition templates (``poster``, ``album``, ``title_card``; see +:mod:`app.processor.templates`) replace step 2 via :func:`render_layout`; steps 3-4 are +shared through :func:`finalize`. + Rendering is CPU-bound and synchronous; call it through ``asyncio.to_thread``. """ @@ -40,6 +44,7 @@ ) from app.processor.packing import encode_bin from app.processor.palette import PALETTE_RGB +from app.processor.templates import Canvas, Layout, compose_layout Rotation = Literal[0, 90, 270] PREVIEW_JPEG_QUALITY = 90 @@ -174,11 +179,15 @@ def compose( return paste_centered(background, picture) -def render( - image: Image.Image, options: RenderOptions, regions: Sequence[FocusRegion] = () -) -> RenderResult: - """Compose, dither and encode ``image`` for the configured panel.""" - composed = compose(image.convert("RGB"), options, regions) +def finalize(composed: Image.Image, options: RenderOptions) -> RenderResult: + """Rotate, dither and encode a frame-sized composition (viewing orientation). + + Raises: + ValueError: If ``composed`` does not have the frame size of ``options``. + """ + if composed.size != options.frame_size: + raise ValueError(f"Composition is {composed.size}, expected {options.frame_size}") + composed = composed.convert("RGB") quarter_turns = options.rotation // 90 # Rotate *before* dithering, like the official converter's ``--fit rotate``: error # diffusion scans the panel's native portrait buffer, so the ``.bin`` is byte-identical. @@ -196,6 +205,38 @@ def render( ) +def render( + image: Image.Image, options: RenderOptions, regions: Sequence[FocusRegion] = () +) -> RenderResult: + """Compose, dither and encode ``image`` for the configured panel.""" + return finalize(compose(image.convert("RGB"), options, regions), options) + + +def canvas_for(options: RenderOptions) -> Canvas: + """The template canvas matching ``options``.""" + return Canvas(options.frame_size, options.eink, options.safe_margin_px) + + +def render_layout( + image: Image.Image | None, layout: Layout, options: RenderOptions +) -> RenderResult: + """Compose ``image`` with a template (never cropped), then dither and encode it. + + Raises: + ValueError: If the layout needs artwork and ``image`` is ``None``. + """ + return finalize(compose_layout(image, layout, canvas_for(options)), options) + + +def render_layout_bytes(data: bytes | None, layout: Layout, options: RenderOptions) -> RenderResult: + """Decode untrusted bytes (if any) and :func:`render_layout` them. + + Raises: + InvalidImageError: If ``data`` is not a supported image. + """ + return render_layout(decode_image(data) if data is not None else None, layout, options) + + def render_bytes( data: bytes, options: RenderOptions, regions: Sequence[FocusRegion] = () ) -> RenderResult: diff --git a/app/processor/templates.py b/app/processor/templates.py new file mode 100644 index 0000000..501aca2 --- /dev/null +++ b/app/processor/templates.py @@ -0,0 +1,426 @@ +"""No-crop composition templates: movie posters, album covers and typographic cards. + +Templates turn artwork (and optional text) into a frame-sized composition in *viewing* +orientation. They never crop the artwork: posters and covers are scaled to fit inside +their slot. The result then goes through the regular rotation/dithering/encoding stage +(:func:`app.processor.pipeline.finalize`). + +* ``poster`` - the full poster centered over a blurred, darkened backdrop made from the + poster itself, with a thin light border and a soft drop shadow. +* ``album`` - the full square cover with a typography block (title, artist, album) on a + flat background color sampled from the cover. ``style="vinyl"`` adds a record peeking + out of the sleeve. Portrait frames stack cover and text; landscape frames put the text + on the right. +* ``title_card`` - a clean typographic card used when no artwork could be found. + +Every template adapts to the frame size (portrait or landscape, 13.3" or 31.5" panel) and +keeps ``safe_margin_px`` clear on every side. +""" + +from __future__ import annotations + +import colorsys +from dataclasses import dataclass +from typing import Final, Literal + +from PIL import Image, ImageDraw, ImageEnhance, ImageFilter + +from app.core.config_models import EinkConfig +from app.processor.enhance import enhance +from app.processor.fit import Size, blurred_background, fit_inside +from app.processor.palette import PALETTE_RGB +from app.processor.typography import ( + RGB, + Align, + FittedText, + draw_text, + fit_text, + pick_text_color, +) + +AlbumStyle = Literal["sleeve", "vinyl"] +TemplateName = Literal["poster", "album", "title_card"] + +#: Extra darkening of the poster backdrop (on top of the blur's own darkening). +POSTER_BACKDROP_DARKEN: Final = 0.7 +#: Poster inset as a fraction of the frame's short side. +POSTER_INSET: Final = 0.05 +POSTER_BORDER_COLOR: Final[RGB] = (235, 235, 235) +SHADOW_OPACITY: Final = 150 +#: Fraction of the vinyl disc that sticks out of the sleeve. +VINYL_PEEK: Final = 0.32 +VINYL_BLACK: Final[RGB] = (12, 12, 12) +VINYL_GROOVE: Final[RGB] = (58, 58, 58) +#: Background colors are pulled this much toward the nearest panel color (cleaner dither). +PALETTE_PULL: Final = 0.35 +TITLE_CARD_BACKGROUND: Final[RGB] = (0, 0, 0) +_SUPERSAMPLE: Final = 2 + + +# --- Layouts ---------------------------------------------------------------------------- +@dataclass(frozen=True, slots=True) +class PosterLayout: + """Full poster over a blurred backdrop (movies, TV series).""" + + name: TemplateName = "poster" + + +@dataclass(frozen=True, slots=True) +class AlbumLayout: + """Square cover with a title / artist / album typography block.""" + + title: str + artist: str | None = None + album: str | None = None + style: AlbumStyle = "sleeve" + name: TemplateName = "album" + + +@dataclass(frozen=True, slots=True) +class TitleCardLayout: + """Typographic card (no artwork): the last-resort fallback.""" + + title: str + subtitle: str | None = None + caption: str | None = None + accent: RGB = (255, 0, 0) + name: TemplateName = "title_card" + + +Layout = PosterLayout | AlbumLayout | TitleCardLayout + + +@dataclass(frozen=True, slots=True) +class Canvas: + """Frame geometry and enhancement settings shared by every template.""" + + size: Size + eink: EinkConfig + safe_margin_px: int = 0 + + @property + def short_side(self) -> int: + """The frame's shorter dimension.""" + return min(self.size) + + @property + def portrait(self) -> bool: + """Whether the frame is taller than wide.""" + return self.size[1] >= self.size[0] + + def pad(self, fraction: float) -> int: + """A padding of ``fraction`` of the short side, never inside the safe margin.""" + return max(self.safe_margin_px, round(self.short_side * fraction)) + + +# --- Color helpers ---------------------------------------------------------------------- +def _nearest_palette(color: RGB) -> RGB: + return min(PALETTE_RGB, key=lambda p: sum((a - b) ** 2 for a, b in zip(color, p, strict=True))) + + +def _blend(a: RGB, b: RGB, amount: float) -> RGB: + r, g, bl = (round(x + (y - x) * amount) for x, y in zip(a, b, strict=True)) + return r, g, bl + + +def dominant_color(image: Image.Image) -> RGB: + """The most frequent clearly colored tone of ``image`` (else its most frequent tone).""" + small = image.convert("RGB").resize((64, 64), Image.Resampling.BILINEAR) + quantized = small.quantize(colors=6, method=Image.Quantize.MEDIANCUT) + palette = quantized.getpalette() or [] + counts = sorted(quantized.getcolors() or [], reverse=True) + total = sum(count for count, _ in counts) or 1 + colors: list[tuple[int, RGB]] = [] + for count, pixel in counts: + index = int(pixel) # type: ignore[call-overload] + rgb = (palette[index * 3], palette[index * 3 + 1], palette[index * 3 + 2]) + colors.append((count, rgb)) + if not colors: + return (0, 0, 0) + for count, rgb in colors: + _, lightness, saturation = colorsys.rgb_to_hls(*(c / 255 for c in rgb)) + if count / total >= 0.08 and saturation >= 0.3 and 0.12 <= lightness <= 0.88: + return rgb + return colors[0][1] + + +def background_from(image: Image.Image) -> RGB: + """A flat background color matching ``image``, pushed away from mid-grey. + + The lightness is moved to a clearly dark or clearly light value so black or white text + reads well on it, then nudged toward the nearest panel color so the flat area dithers + with little noise. + """ + hue, lightness, saturation = colorsys.rgb_to_hls(*(c / 255 for c in dominant_color(image))) + lightness = min(lightness, 0.22) if lightness < 0.55 else max(lightness, 0.84) + saturation = min(saturation, 0.75) + r, g, b = colorsys.hls_to_rgb(hue, lightness, saturation) + color: RGB = (round(r * 255), round(g * 255), round(b * 255)) + return _blend(color, _nearest_palette(color), PALETTE_PULL) + + +def accent_from(image: Image.Image) -> RGB: + """A saturated accent color taken from ``image`` (vinyl label).""" + hue, lightness, saturation = colorsys.rgb_to_hls(*(c / 255 for c in dominant_color(image))) + r, g, b = colorsys.hls_to_rgb(hue, min(max(lightness, 0.35), 0.6), max(saturation, 0.55)) + return round(r * 255), round(g * 255), round(b * 255) + + +# --- Drawing helpers -------------------------------------------------------------------- +def _drop_shadow(canvas: Image.Image, box: tuple[int, int, int, int], offset: int) -> None: + """Darken a soft, offset rectangle under ``box`` (in place).""" + mask = Image.new("L", canvas.size, 0) + x0, y0, x1, y1 = box + ImageDraw.Draw(mask).rectangle( + (x0 + offset, y0 + offset, x1 + offset, y1 + offset), fill=SHADOW_OPACITY + ) + mask = mask.filter(ImageFilter.GaussianBlur(max(1, round(offset * 1.5)))) + canvas.paste((0, 0, 0), (0, 0), mask) + + +def _paste_framed( + canvas: Image.Image, picture: Image.Image, origin: tuple[int, int], *, border: int +) -> None: + """Paste ``picture`` at ``origin`` with a shadow and an optional light border.""" + x, y = origin + box = (x, y, x + picture.width - 1, y + picture.height - 1) + _drop_shadow(canvas, box, max(3, round(min(canvas.size) * 0.01))) + if border > 0: + ImageDraw.Draw(canvas).rectangle( + (x - border, y - border, box[2] + border, box[3] + border), fill=POSTER_BORDER_COLOR + ) + canvas.paste(picture, (x, y)) + + +def _square_cover(image: Image.Image, side: int, background: RGB) -> Image.Image: + """``image`` fitted (uncropped) into a ``side`` square, padded with ``background``.""" + fitted = fit_inside(image, (side, side)) + if fitted.size == (side, side): + return fitted + square = Image.new("RGB", (side, side), background) + square.paste(fitted, ((side - fitted.width) // 2, (side - fitted.height) // 2)) + return square + + +def _vinyl_disc(diameter: int, label: RGB) -> Image.Image: + """An anti-aliased RGBA record (supersampled, then downscaled).""" + big = diameter * _SUPERSAMPLE + disc = Image.new("RGBA", (big, big), (0, 0, 0, 0)) + draw = ImageDraw.Draw(disc) + draw.ellipse((0, 0, big - 1, big - 1), fill=(*VINYL_BLACK, 255)) + radius = big / 2 + groove_width = max(1, round(big * 0.002)) + fraction = 0.92 + while fraction > 0.42: + inset = radius * (1 - fraction) + draw.ellipse( + (inset, inset, big - 1 - inset, big - 1 - inset), + outline=(*VINYL_GROOVE, 255), + width=groove_width, + ) + fraction -= 0.07 + label_inset = radius * (1 - 0.34) + draw.ellipse( + (label_inset, label_inset, big - 1 - label_inset, big - 1 - label_inset), + fill=(*label, 255), + ) + hole_inset = radius * (1 - 0.035) + draw.ellipse( + (hole_inset, hole_inset, big - 1 - hole_inset, big - 1 - hole_inset), + fill=(*VINYL_BLACK, 255), + ) + return disc.resize((diameter, diameter), Image.Resampling.LANCZOS) + + +@dataclass(frozen=True, slots=True) +class _TextBlock: + """Fitted lines of a template, top to bottom, with the gap before each one.""" + + parts: tuple[tuple[FittedText, int], ...] + + @property + def height(self) -> int: + return sum(fitted.height + gap for fitted, gap in self.parts if fitted.lines) + + def draw( + self, image: Image.Image, *, x: int, y: int, width: int, fill: RGB, align: Align + ) -> None: + draw = ImageDraw.Draw(image) + cursor = y + for fitted, gap in self.parts: + if not fitted.lines: + continue + cursor += gap + cursor = draw_text(draw, fitted, x=x, y=cursor, width=width, fill=fill, align=align) + + +def _album_text(layout: AlbumLayout, width: int, unit: int, scale: float) -> _TextBlock: + """Title (bold, up to 2 lines), artist and album; sizes relative to ``unit``.""" + + def size(fraction: float) -> int: + return max(8, round(unit * fraction * scale)) + + title = fit_text( + layout.title, + weight="bold", + max_width=width, + max_lines=2, + max_size=size(0.072), + min_size=size(0.042), + ) + artist = fit_text( + layout.artist or "", + weight="regular", + max_width=width, + max_lines=1, + max_size=size(0.05), + min_size=size(0.034), + ) + album = fit_text( + layout.album or "", + weight="regular", + max_width=width, + max_lines=1, + max_size=size(0.038), + min_size=size(0.028), + ) + return _TextBlock(((title, 0), (artist, size(0.02)), (album, size(0.014)))) + + +def _fit_album_text(layout: AlbumLayout, width: int, height: int, unit: int) -> _TextBlock: + """The album text block, scaled down until it fits ``height``.""" + scale = 1.0 + block = _album_text(layout, width, unit, scale) + while block.height > height and scale > 0.5: + scale *= 0.9 + block = _album_text(layout, width, unit, scale) + return block + + +# --- Templates -------------------------------------------------------------------------- +def compose_poster(image: Image.Image, canvas: Canvas) -> Image.Image: + """The full poster centered over a blurred, darkened backdrop of itself.""" + width, height = canvas.size + backdrop = blurred_background(image, canvas.size) + backdrop = ImageEnhance.Brightness(backdrop).enhance(POSTER_BACKDROP_DARKEN) + backdrop = enhance(backdrop, canvas.eink, edge_filters=False) + inset = canvas.pad(POSTER_INSET) + poster = enhance(fit_inside(image, (width - 2 * inset, height - 2 * inset)), canvas.eink) + border = max(2, round(canvas.short_side * 0.003)) + origin = ((width - poster.width) // 2, (height - poster.height) // 2) + _paste_framed(backdrop, poster, origin, border=border) + return backdrop + + +def compose_album(image: Image.Image, layout: AlbumLayout, canvas: Canvas) -> Image.Image: + """Square cover (sleeve or vinyl) with the track's typography block.""" + width, height = canvas.size + background = background_from(image) + result = Image.new("RGB", canvas.size, background) + text_color = pick_text_color(background) + pad = canvas.pad(0.06) + gap = round(canvas.short_side * 0.045) + vinyl = layout.style == "vinyl" + group_factor = 1 + VINYL_PEEK if vinyl else 1.0 + + if canvas.portrait: + min_text = round(height * 0.2) + cover = min(round((width - 2 * pad) / group_factor), height - 2 * pad - gap - min_text) + if not vinyl: + cover = min(cover, round(width * 0.82)) + text_width = width - 2 * pad + text_height = height - 2 * pad - cover - gap + block = _fit_album_text(layout, text_width, text_height, canvas.short_side) + group_height = cover + gap + block.height + top = pad + max(0, (height - 2 * pad - group_height) // 2) + left = (width - round(cover * group_factor)) // 2 + text_box = (pad, top + cover + gap) + align: Align = "center" + else: + text_min = round(width * 0.3) + cover = min(height - 2 * pad, round((width - 2 * pad - gap - text_min) / group_factor)) + left = pad + top = (height - cover) // 2 + text_x = left + round(cover * group_factor) + gap + text_width = width - pad - text_x + block = _fit_album_text(layout, text_width, height - 2 * pad, canvas.short_side) + text_box = (text_x, (height - block.height) // 2) + align = "left" + + sleeve = enhance(_square_cover(image, cover, background), canvas.eink) + if vinyl: + disc = _vinyl_disc(cover - 2 * max(2, round(cover * 0.02)), accent_from(image)) + disc_x = left + round(cover * VINYL_PEEK) + disc_y = top + (cover - disc.height) // 2 + result.paste(disc, (disc_x, disc_y), disc) + _paste_framed(result, sleeve, (left, top), border=0) + block.draw(result, x=text_box[0], y=text_box[1], width=text_width, fill=text_color, align=align) + return result + + +def compose_title_card(layout: TitleCardLayout, canvas: Canvas) -> Image.Image: + """A centered title, an accent rule, then subtitle and caption, on black.""" + width, height = canvas.size + result = Image.new("RGB", canvas.size, TITLE_CARD_BACKGROUND) + fill = pick_text_color(TITLE_CARD_BACKGROUND) + pad = canvas.pad(0.09) + text_width = width - 2 * pad + unit = canvas.short_side + title = fit_text( + layout.title, + weight="bold", + max_width=text_width, + max_lines=4, + max_size=round(unit * 0.1), + min_size=round(unit * 0.05), + ) + subtitle = fit_text( + layout.subtitle or "", + weight="regular", + max_width=text_width, + max_lines=2, + max_size=round(unit * 0.05), + min_size=round(unit * 0.034), + ) + caption = fit_text( + layout.caption or "", + weight="regular", + max_width=text_width, + max_lines=2, + max_size=round(unit * 0.036), + min_size=round(unit * 0.026), + ) + rule_height = max(4, round(unit * 0.008)) + rule_gap = round(unit * 0.045) + below = _TextBlock(((subtitle, 0), (caption, round(unit * 0.02)))) + total = title.height + rule_gap * 2 + rule_height + below.height + top = max(pad, (height - total) // 2) + draw = ImageDraw.Draw(result) + cursor = draw_text(draw, title, x=pad, y=top, width=text_width, fill=fill, align="center") + cursor += rule_gap + rule_width = round(text_width * 0.22) + rule_x = (width - rule_width) // 2 + rule = (rule_x, cursor, rule_x + rule_width - 1, cursor + rule_height - 1) + draw.rectangle(rule, fill=layout.accent) + cursor += rule_height + rule_gap + below.draw(result, x=pad, y=cursor, width=text_width, fill=fill, align="center") + return result + + +def compose_layout(image: Image.Image | None, layout: Layout, canvas: Canvas) -> Image.Image: + """Compose ``layout`` for ``canvas`` (viewing orientation, RGB, frame-sized). + + Raises: + ValueError: If the layout needs artwork and ``image`` is ``None``. + """ + if isinstance(layout, TitleCardLayout): + composed = compose_title_card(layout, canvas) + elif image is None: + raise ValueError(f"The {layout.name} template needs an image") + elif isinstance(layout, PosterLayout): + composed = compose_poster(image.convert("RGB"), canvas) + else: + composed = compose_album(image.convert("RGB"), layout, canvas) + if composed.size != canvas.size: # pragma: no cover - defensive + raise RuntimeError(f"Template produced {composed.size}, expected {canvas.size}") + return composed diff --git a/app/processor/typography.py b/app/processor/typography.py new file mode 100644 index 0000000..9ce6259 --- /dev/null +++ b/app/processor/typography.py @@ -0,0 +1,276 @@ +"""Typography for composition templates: bundled fonts, wrapping, fitting and contrast. + +The Inter font family (SIL Open Font License 1.1, see ``app/assets/fonts/OFL.txt``) is +bundled with the package so text never falls back to Pillow's tiny bitmap font. + +Text is always drawn in pure palette black or white: those are exact Spectra 6 colors, +so glyphs survive dithering without colored fringes. :func:`pick_text_color` chooses the +one with the higher WCAG contrast against the background it is drawn on. +""" + +from __future__ import annotations + +import io +from dataclasses import dataclass +from functools import lru_cache +from importlib import resources +from typing import Final, Literal + +import numpy as np +from PIL import Image, ImageDraw, ImageFont + +FontWeight = Literal["regular", "bold"] +RGB = tuple[int, int, int] +Align = Literal["left", "center"] + +FONT_FILES: Final[dict[FontWeight, str]] = { + "regular": "Inter-Regular.ttf", + "bold": "Inter-Bold.ttf", +} +BLACK: Final[RGB] = (0, 0, 0) +WHITE: Final[RGB] = (255, 255, 255) +ELLIPSIS: Final = "\u2026" +#: Characters stripped before an ellipsis so lines never end with "word,…". +_TRAILING_PUNCTUATION: Final = " ,;:-\u2013\u2014/|" +#: Font size step when shrinking text to fit (fraction of the current size). +_SHRINK_STEP: Final = 0.92 +DEFAULT_LINE_SPACING: Final = 1.18 + + +# --- Fonts ------------------------------------------------------------------------------ +@lru_cache(maxsize=len(FONT_FILES)) +def font_bytes(weight: FontWeight) -> bytes: + """Raw TTF data of a bundled font weight (read once from the package).""" + resource = resources.files("app").joinpath("assets", "fonts", FONT_FILES[weight]) + return resource.read_bytes() + + +@lru_cache(maxsize=128) +def load_font(weight: FontWeight, size: int) -> ImageFont.FreeTypeFont: + """The bundled Inter font at ``size`` pixels (cached per weight and size). + + Raises: + ValueError: If ``size`` is not positive. + """ + if size <= 0: + raise ValueError("Font size must be positive") + return ImageFont.truetype(io.BytesIO(font_bytes(weight)), size) + + +def line_height(font: ImageFont.FreeTypeFont, spacing: float = DEFAULT_LINE_SPACING) -> int: + """Distance between two baselines for ``font``.""" + ascent, descent = font.getmetrics() + return round((ascent + descent) * spacing) + + +# --- Contrast --------------------------------------------------------------------------- +def _linearize(channel: np.ndarray) -> np.ndarray: + srgb = channel / 255.0 + return np.where(srgb <= 0.04045, srgb / 12.92, ((srgb + 0.055) / 1.055) ** 2.4) + + +def relative_luminance(color: RGB) -> float: + """WCAG 2.x relative luminance of an sRGB color (``0`` black .. ``1`` white).""" + r, g, b = (_linearize(np.array(float(c))) for c in color) + return float(0.2126 * r + 0.7152 * g + 0.0722 * b) + + +def contrast_ratio(luminance_a: float, luminance_b: float) -> float: + """WCAG contrast ratio between two relative luminances (``1`` .. ``21``).""" + light, dark = max(luminance_a, luminance_b), min(luminance_a, luminance_b) + return (light + 0.05) / (dark + 0.05) + + +def mean_luminance(region: Image.Image) -> float: + """Average relative luminance of the pixels of ``region`` (any mode).""" + pixels = np.asarray(region.convert("RGB"), dtype=np.float64) + linear = _linearize(pixels) + luminance = 0.2126 * linear[..., 0] + 0.7152 * linear[..., 1] + 0.0722 * linear[..., 2] + return float(luminance.mean()) + + +def pick_text_color(background: Image.Image | RGB) -> RGB: + """Black or white, whichever contrasts more with ``background``. + + Args: + background: The area the text is drawn on (sampled pixel by pixel), or a flat color. + """ + if isinstance(background, Image.Image): + luminance = mean_luminance(background) + else: + luminance = relative_luminance(background) + on_black = contrast_ratio(luminance, 0.0) + on_white = contrast_ratio(luminance, 1.0) + return BLACK if on_black >= on_white else WHITE + + +# --- Wrapping --------------------------------------------------------------------------- +def _fits(text: str, font: ImageFont.FreeTypeFont, max_width: int) -> bool: + return font.getlength(text) <= max_width + + +def ellipsize( + text: str, font: ImageFont.FreeTypeFont, max_width: int, *, force: bool = False +) -> str: + """``text`` truncated with an ellipsis so it fits ``max_width``. + + Args: + text: Text to shorten. + font: Font used to measure. + max_width: Available width in pixels. + force: Always end with an ellipsis (the text is known to continue); otherwise text + that fits is returned unchanged. + """ + text = text.strip() + if force: + forced = text.rstrip(_TRAILING_PUNCTUATION) + ELLIPSIS + if _fits(forced, font, max_width): + return forced + elif _fits(text, font, max_width): + return text + cut = text + while cut: + cut = cut[:-1] + candidate = cut.rstrip(_TRAILING_PUNCTUATION) + ELLIPSIS + if _fits(candidate, font, max_width): + return candidate + return ELLIPSIS if _fits(ELLIPSIS, font, max_width) else "" + + +def _split_long_word(word: str, font: ImageFont.FreeTypeFont, max_width: int) -> list[str]: + """Hard-break a word wider than ``max_width`` into pieces that each fit.""" + pieces: list[str] = [] + rest = word + while rest and not _fits(rest, font, max_width): + cut = len(rest) - 1 + while cut > 1 and not _fits(rest[:cut], font, max_width): + cut -= 1 + pieces.append(rest[:cut]) + rest = rest[cut:] + if rest: + pieces.append(rest) + return pieces + + +def wrap_lines(text: str, font: ImageFont.FreeTypeFont, max_width: int) -> list[str]: + """Greedy word wrap of ``text`` into lines no wider than ``max_width`` (no limit).""" + lines: list[str] = [] + current = "" + for word in text.split(): + candidate = f"{current} {word}" if current else word + if _fits(candidate, font, max_width): + current = candidate + continue + if current: + lines.append(current) + pieces = _split_long_word(word, font, max_width) + lines.extend(pieces[:-1]) + current = pieces[-1] if pieces else "" + if current: + lines.append(current) + return lines + + +def wrap_text( + text: str, font: ImageFont.FreeTypeFont, max_width: int, max_lines: int +) -> tuple[list[str], bool]: + """Wrap ``text`` into at most ``max_lines`` lines, ellipsizing the last one if needed. + + Returns: + ``(lines, truncated)`` where ``truncated`` tells whether text was cut. + """ + if max_lines < 1: + raise ValueError("max_lines must be at least 1") + lines = wrap_lines(text, font, max_width) + if len(lines) <= max_lines: + return lines, False + kept = lines[:max_lines] + kept[-1] = ellipsize(kept[-1], font, max_width, force=True) + return kept, True + + +# --- Fitting & drawing ------------------------------------------------------------------ +@dataclass(frozen=True, slots=True) +class FittedText: + """Wrapped lines and the font they fit with.""" + + lines: tuple[str, ...] + font: ImageFont.FreeTypeFont + size: int + truncated: bool + spacing: float = DEFAULT_LINE_SPACING + + @property + def line_height(self) -> int: + """Baseline-to-baseline distance.""" + return line_height(self.font, self.spacing) + + @property + def height(self) -> int: + """Total block height (last line without trailing spacing).""" + if not self.lines: + return 0 + ascent, descent = self.font.getmetrics() + return self.line_height * (len(self.lines) - 1) + ascent + descent + + @property + def width(self) -> int: + """Width of the widest line.""" + return max((round(self.font.getlength(line)) for line in self.lines), default=0) + + +def fit_text( + text: str, + *, + weight: FontWeight, + max_width: int, + max_lines: int, + max_size: int, + min_size: int, + spacing: float = DEFAULT_LINE_SPACING, +) -> FittedText: + """Largest font size in ``[min_size, max_size]`` at which ``text`` fits without cutting. + + If even ``min_size`` needs more than ``max_lines`` lines, the text is ellipsized at + ``min_size``. + """ + if min_size > max_size: + raise ValueError("min_size must not exceed max_size") + text = " ".join(text.split()) + size = max_size + while True: + font = load_font(weight, size) + lines, truncated = wrap_text(text, font, max_width, max_lines) if text else ([], False) + if not truncated or size <= min_size: + return FittedText(tuple(lines), font, size, truncated, spacing) + size = max(min_size, int(size * _SHRINK_STEP)) + + +def draw_text( + draw: ImageDraw.ImageDraw, + fitted: FittedText, + *, + x: int, + y: int, + width: int, + fill: RGB, + align: Align = "left", +) -> int: + """Draw ``fitted`` with its top-left at ``(x, y)`` inside a box ``width`` wide. + + Text is rendered without anti-aliasing: grey edge pixels would be dithered into + colored fringes (yellow next to white glyphs on dark backgrounds), whereas aliased + glyphs stay a single exact palette color and look crisp at panel resolution. + + Returns: + The y coordinate just below the block. + """ + draw.fontmode = "1" + baseline_step = fitted.line_height + for index, line in enumerate(fitted.lines): + line_x = x + if align == "center": + line_x = x + (width - round(fitted.font.getlength(line))) // 2 + position = (line_x, y + index * baseline_step) + draw.text(position, line, font=fitted.font, fill=fill, anchor="la") + return y + fitted.height diff --git a/pyproject.toml b/pyproject.toml index 1db39b8..40e7db8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -51,7 +51,7 @@ Issues = "https://github.com/ant1fr/Smart-Frame-Engine/issues" include = ["app*"] [tool.setuptools.package-data] -app = ["py.typed", "templates/*.html"] +app = ["py.typed", "templates/*.html", "assets/fonts/*.ttf", "assets/fonts/*.txt"] # --- Ruff ----------------------------------------------------------------------- [tool.ruff] diff --git a/tests/test_templates.py b/tests/test_templates.py new file mode 100644 index 0000000..58b6739 --- /dev/null +++ b/tests/test_templates.py @@ -0,0 +1,200 @@ +from __future__ import annotations + +import io +from typing import Any + +import numpy as np +import numpy.typing as npt +import pytest +from PIL import Image + +from app.core.config_models import EinkConfig, RuntimeConfig +from app.processor.pipeline import ( + RenderOptions, + finalize, + render_layout, + render_layout_bytes, +) +from app.processor.templates import ( + VINYL_BLACK, + AlbumLayout, + Canvas, + PosterLayout, + TitleCardLayout, + background_from, + compose_layout, + dominant_color, +) +from app.processor.typography import WHITE + +NEUTRAL = EinkConfig(brightness=1.0, contrast=1.0, saturation=1.0, edge_filters=False) +MAGENTA = (255, 0, 255) +CYAN = (0, 255, 255) +FRAMES = [(1200, 1600), (1600, 1200), (1440, 2560), (2560, 1440)] + + +def canvas(size: tuple[int, int], margin: int = 0) -> Canvas: + return Canvas(size, NEUTRAL, margin) + + +def mask_bbox(image: Image.Image, color: tuple[int, int, int]) -> tuple[int, int, int, int]: + """Bounding box (x0, y0, x1, y1 exclusive) of the pixels exactly equal to ``color``.""" + pixels: npt.NDArray[np.uint8] = np.asarray(image) + ys, xs = np.nonzero(np.all(pixels == np.array(color, np.uint8), axis=-1)) + assert xs.size, f"no {color} pixel found" + return int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1 + + +def options(**sections: Any) -> RenderOptions: + return RenderOptions.from_config(RuntimeConfig.model_validate(sections), fit="contain") + + +@pytest.mark.parametrize("size", FRAMES) +@pytest.mark.parametrize( + "layout", + [ + PosterLayout(), + AlbumLayout(title="Song", artist="Artist", album="Album"), + AlbumLayout(title="Song", artist="Artist", album="Album", style="vinyl"), + TitleCardLayout(title="Title", subtitle="2001", caption="Caption"), + ], +) +def test_every_template_fills_the_frame(size: tuple[int, int], layout: Any) -> None: + art = Image.new("RGB", (500, 750), (40, 90, 160)) + composed = compose_layout(art, layout, canvas(size)) + assert composed.size == size + assert composed.mode == "RGB" + + +@pytest.mark.parametrize("size", FRAMES) +def test_poster_is_never_cropped(size: tuple[int, int]) -> None: + poster = Image.new("RGB", (400, 600), MAGENTA) + composed = compose_layout(poster, PosterLayout(), canvas(size)) + x0, y0, x1, y1 = mask_bbox(composed, MAGENTA) + width, height = x1 - x0, y1 - y0 + assert abs(width / height - 400 / 600) < 0.01 + inset = round(min(size) * 0.05) + assert x0 >= inset and y0 >= inset + assert x1 <= size[0] - inset and y1 <= size[1] - inset + # Fills its slot along the limiting axis (fit, not shrink). + assert width == size[0] - 2 * inset or height == size[1] - 2 * inset + + +def test_poster_has_a_light_border_and_a_darker_backdrop() -> None: + poster = Image.new("RGB", (400, 600), MAGENTA) + composed = compose_layout(poster, PosterLayout(), canvas((1200, 1600))) + x0, y0, _, _ = mask_bbox(composed, MAGENTA) + border = composed.getpixel((x0 - 1, y0 + 50)) + assert border == (235, 235, 235) + corner = composed.getpixel((5, 5)) + assert isinstance(corner, tuple) + assert corner[0] < 255 * 0.6 # blurred and darkened + + +def test_poster_respects_a_larger_safe_margin() -> None: + poster = Image.new("RGB", (400, 600), MAGENTA) + composed = compose_layout(poster, PosterLayout(), canvas((1200, 1600), margin=150)) + x0, y0, x1, y1 = mask_bbox(composed, MAGENTA) + assert min(x0, y0) >= 150 + assert x1 <= 1050 and y1 <= 1450 + + +@pytest.mark.parametrize("size", FRAMES) +@pytest.mark.parametrize("style", ["sleeve", "vinyl"]) +def test_album_cover_is_square_and_uncropped(size: tuple[int, int], style: str) -> None: + cover = Image.new("RGB", (800, 600), CYAN) # not square: must be padded, not cropped + layout = AlbumLayout(title="Title", artist="Artist", album="Album", style=style) # type: ignore[arg-type] + composed = compose_layout(cover, layout, canvas(size)) + x0, y0, x1, y1 = mask_bbox(composed, CYAN) + assert abs((x1 - x0) / (y1 - y0) - 800 / 600) < 0.01 + assert x0 > 0 and y0 > 0 and x1 < size[0] and y1 < size[1] + + +@pytest.mark.parametrize("size", [(1200, 1600), (1600, 1200)]) +def test_vinyl_record_peeks_out_of_the_sleeve(size: tuple[int, int]) -> None: + cover = Image.new("RGB", (600, 600), CYAN) + sleeve = compose_layout(cover, AlbumLayout(title="T", style="sleeve"), canvas(size)) + vinyl = compose_layout(cover, AlbumLayout(title="T", style="vinyl"), canvas(size)) + _, _, sleeve_right, _ = mask_bbox(vinyl, CYAN) + disc = np.all(np.asarray(vinyl) == np.array(VINYL_BLACK, np.uint8), axis=-1) + assert disc[:, sleeve_right:].any() + assert not np.all(np.asarray(sleeve) == np.array(VINYL_BLACK, np.uint8), axis=-1).any() + + +def test_album_text_is_white_on_a_dark_cover_and_black_on_a_light_one() -> None: + dark = compose_layout( + Image.new("RGB", (600, 600), (30, 20, 60)), + AlbumLayout(title="Night Drive", artist="Someone"), + canvas((1200, 1600)), + ) + text_area = dark.crop((0, 1150, 1200, 1600)) + assert WHITE in {color for _, color in text_area.getcolors(maxcolors=100_000) or []} + light = compose_layout( + Image.new("RGB", (600, 600), (250, 240, 200)), + AlbumLayout(title="Morning", artist="Someone"), + canvas((1200, 1600)), + ) + text_area = light.crop((0, 1150, 1200, 1600)) + assert (0, 0, 0) in {color for _, color in text_area.getcolors(maxcolors=100_000) or []} + + +def test_background_color_comes_from_the_cover_and_avoids_mid_grey() -> None: + cover = Image.new("RGB", (100, 100), (200, 30, 40)) + assert dominant_color(cover) == (200, 30, 40) + red, green, blue = background_from(cover) + assert red > green and red > blue # same hue family + luminance = 0.2126 * red + 0.7152 * green + 0.0722 * blue + assert luminance < 90 or luminance > 200 + + +def test_long_album_text_stays_inside_the_frame() -> None: + layout = AlbumLayout( + title="An extremely long track title " * 6, + artist="A band with an incredibly long name " * 3, + album="Deluxe remastered anniversary edition " * 3, + ) + composed = compose_layout(Image.new("RGB", (600, 600), CYAN), layout, canvas((1600, 1200))) + assert composed.size == (1600, 1200) + + +def test_poster_and_album_need_artwork_but_the_title_card_does_not() -> None: + with pytest.raises(ValueError, match="needs an image"): + compose_layout(None, PosterLayout(), canvas((1200, 1600))) + with pytest.raises(ValueError, match="needs an image"): + compose_layout(None, AlbumLayout(title="x"), canvas((1200, 1600))) + card = compose_layout(None, TitleCardLayout(title="No poster"), canvas((1200, 1600))) + assert card.getpixel((10, 10)) == (0, 0, 0) + + +def test_title_card_draws_the_accent_rule() -> None: + card = compose_layout( + None, TitleCardLayout(title="Movie", accent=(0, 0, 255)), canvas((1200, 1600)) + ) + x0, _, x1, _ = mask_bbox(card, (0, 0, 255)) + assert abs((x0 + x1) / 2 - 600) <= 1 + + +@pytest.mark.parametrize( + ("panel", "orientation", "size"), + [("133", "portrait", 960_000), ("133", "landscape", 960_000), ("315", "portrait", 2_304_000)], +) +def test_render_layout_encodes_a_bin_for_the_panel(panel: str, orientation: str, size: int) -> None: + opts = options(fraimic={"panel": panel}, display={"orientation": orientation}) + result = render_layout(Image.new("RGB", (500, 750), (90, 30, 30)), PosterLayout(), opts) + assert len(result.bin) == size + assert result.composed.size == opts.frame_size + + +def test_render_layout_bytes_decodes_untrusted_data() -> None: + buffer = io.BytesIO() + Image.new("RGB", (300, 300), CYAN).save(buffer, format="PNG") + opts = options() + result = render_layout_bytes(buffer.getvalue(), AlbumLayout(title="x"), opts) + assert len(result.bin) == 960_000 + card = render_layout_bytes(None, TitleCardLayout(title="x"), opts) + assert len(card.bin) == 960_000 + + +def test_finalize_rejects_a_composition_of_the_wrong_size() -> None: + with pytest.raises(ValueError, match="expected"): + finalize(Image.new("RGB", (100, 100)), options()) diff --git a/tests/test_typography.py b/tests/test_typography.py new file mode 100644 index 0000000..e2a2dd6 --- /dev/null +++ b/tests/test_typography.py @@ -0,0 +1,145 @@ +from __future__ import annotations + +import pytest +from PIL import Image, ImageDraw + +from app.processor.typography import ( + BLACK, + ELLIPSIS, + WHITE, + contrast_ratio, + draw_text, + ellipsize, + fit_text, + font_bytes, + load_font, + pick_text_color, + relative_luminance, + wrap_lines, + wrap_text, +) + + +def test_bundled_fonts_load_with_their_family_and_style() -> None: + assert font_bytes("regular")[:4] == b"\x00\x01\x00\x00" + assert load_font("regular", 32).getname() == ("Inter", "Regular") + assert load_font("bold", 32).getname() == ("Inter", "Bold") + assert load_font("bold", 32) is load_font("bold", 32) # cached + + +def test_font_size_must_be_positive() -> None: + with pytest.raises(ValueError, match="positive"): + load_font("regular", 0) + + +def test_relative_luminance_and_contrast_follow_wcag() -> None: + assert relative_luminance(BLACK) == pytest.approx(0.0) + assert relative_luminance(WHITE) == pytest.approx(1.0) + assert contrast_ratio(1.0, 0.0) == pytest.approx(21.0) + + +@pytest.mark.parametrize( + ("background", "expected"), + [ + ((10, 10, 10), WHITE), + ((0, 0, 255), WHITE), # panel blue is dark + ((255, 0, 0), BLACK), # panel red reads better with black (WCAG) + ((255, 255, 0), BLACK), + ((240, 240, 230), BLACK), + ((60, 25, 10), WHITE), + ], +) +def test_pick_text_color_on_flat_colors( + background: tuple[int, int, int], expected: tuple[int, int, int] +) -> None: + assert pick_text_color(background) == expected + + +def test_pick_text_color_samples_the_region_under_the_text() -> None: + mostly_dark = Image.new("RGB", (100, 40), (20, 20, 20)) + ImageDraw.Draw(mostly_dark).rectangle((0, 0, 9, 39), fill=(255, 255, 255)) + assert pick_text_color(mostly_dark) == WHITE + mostly_light = Image.new("RGB", (100, 40), (250, 250, 250)) + ImageDraw.Draw(mostly_light).rectangle((0, 0, 9, 39), fill=(0, 0, 0)) + assert pick_text_color(mostly_light) == BLACK + + +def test_wrap_lines_respects_the_width() -> None: + font = load_font("regular", 40) + text = "The quick brown fox jumps over the lazy dog again and again" + lines = wrap_lines(text, font, 400) + assert len(lines) > 1 + assert all(font.getlength(line) <= 400 for line in lines) + assert " ".join(lines) == text + + +def test_wrap_lines_hard_breaks_words_wider_than_the_box() -> None: + font = load_font("bold", 40) + word = "Supercalifragilisticexpialidocious" + lines = wrap_lines(f"A {word}", font, 200) + assert all(font.getlength(line) <= 200 for line in lines) + assert "".join(lines[1:]) == word + + +def test_wrap_text_ellipsizes_the_last_allowed_line() -> None: + font = load_font("regular", 40) + text = " ".join(["word"] * 40) + lines, truncated = wrap_text(text, font, 300, 2) + assert truncated + assert len(lines) == 2 + assert lines[-1].endswith(ELLIPSIS) + assert all(font.getlength(line) <= 300 for line in lines) + + +def test_wrap_text_keeps_short_text_intact() -> None: + font = load_font("regular", 40) + assert wrap_text("Kind of Blue", font, 600, 1) == (["Kind of Blue"], False) + assert wrap_text("", font, 600, 1) == ([], False) + with pytest.raises(ValueError): + wrap_text("x", font, 600, 0) + + +def test_ellipsize_drops_trailing_punctuation_before_the_ellipsis() -> None: + font = load_font("regular", 40) + result = ellipsize("Hello, wonderful world of eInk displays", font, 160) + assert result.endswith(ELLIPSIS) + assert not result[:-1].endswith((",", " ")) + assert font.getlength(result) <= 160 + assert ellipsize("Hi", font, 160) == "Hi" + assert ellipsize("Hi", font, 160, force=True) == f"Hi{ELLIPSIS}" + + +def test_fit_text_shrinks_before_truncating() -> None: + text = "A rather long title that does not fit at the largest size" + fitted = fit_text(text, weight="bold", max_width=700, max_lines=2, max_size=90, min_size=30) + assert not fitted.truncated + assert 30 <= fitted.size < 90 + assert len(fitted.lines) <= 2 + assert fitted.width <= 700 + + +def test_fit_text_truncates_at_the_minimum_size() -> None: + fitted = fit_text( + "word " * 200, weight="regular", max_width=300, max_lines=1, max_size=60, min_size=40 + ) + assert fitted.truncated + assert fitted.size == 40 + assert fitted.lines[0].endswith(ELLIPSIS) + + +def test_fit_text_validates_its_size_range() -> None: + with pytest.raises(ValueError): + fit_text("x", weight="regular", max_width=100, max_lines=1, max_size=10, min_size=20) + + +def test_draw_text_renders_aliased_single_color_glyphs() -> None: + image = Image.new("RGB", (600, 200), BLACK) + fitted = fit_text( + "Crisp text", weight="bold", max_width=560, max_lines=1, max_size=80, min_size=40 + ) + bottom = draw_text( + ImageDraw.Draw(image), fitted, x=20, y=20, width=560, fill=WHITE, align="center" + ) + assert bottom == 20 + fitted.height + colors = {color for _, color in image.getcolors(maxcolors=1024) or []} + assert colors == {BLACK, WHITE} # no anti-aliased greys that would dither to color From 1a71c5402768ddef0b8f020528cc70e30f3ea977 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sun, 15 Nov 2026 15:25:38 +0100 Subject: [PATCH 51/86] feat: add expiry and cancellation to the delivery queue Queued images can now be ephemeral and carry expires_at. An expired image is dropped before any delivery attempt (flush, wakeup, worker tick), is hidden from queue inspection, and bounds the worker sleep so it is purged on time; a drop handler hook lets the application restore the previous image. cancel_ephemeral() drops a queued ephemeral image on demand and extend_pending() moves the expiry of matching content. The last successful delivery is persisted to /data/last_delivery.json and frame_content_differs() (which also accounts for an upload in progress) tells whether the frame may need a re-upload. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- app/api/routes/fraimic.py | 2 +- app/core/settings.py | 5 + app/main.py | 4 +- app/services/delivery.py | 221 +++++++++++++++++++++++++++++++++++--- tests/test_delivery.py | 174 ++++++++++++++++++++++++++++++ 5 files changed, 391 insertions(+), 15 deletions(-) diff --git a/app/api/routes/fraimic.py b/app/api/routes/fraimic.py index daa651b..bb4c31d 100644 --- a/app/api/routes/fraimic.py +++ b/app/api/routes/fraimic.py @@ -30,7 +30,7 @@ class WakeupAccepted(BaseModel): def _outcome_response(outcome: DeliveryOutcome) -> JSONResponse: - status_code = 200 if outcome.status in {"delivered", "nothing_pending"} else 202 + status_code = 200 if outcome.status in {"delivered", "nothing_pending", "dropped"} else 202 return JSONResponse(outcome.model_dump(mode="json"), status_code=status_code) diff --git a/app/core/settings.py b/app/core/settings.py index 2f6ec60..e1c4bbf 100644 --- a/app/core/settings.py +++ b/app/core/settings.py @@ -175,6 +175,11 @@ def queue_dir(self) -> Path: """Directory holding the upload waiting for the frame (``pending.bin``).""" return self.data_dir / "queue" + @property + def last_delivery_path(self) -> Path: + """Location of the last successful frame delivery (what the frame shows).""" + return self.data_dir / "last_delivery.json" + @property def scheduler_state_path(self) -> Path: """Location of the scheduler state (replayable rule, timer, last run).""" diff --git a/app/main.py b/app/main.py index 0b030c2..41a9b38 100644 --- a/app/main.py +++ b/app/main.py @@ -93,7 +93,9 @@ async def _on_config_change(_: RuntimeConfig) -> None: current_store = CurrentImageStore(settings.cache_dir) current_store.load() - delivery = DeliveryService(settings.queue_dir, config_store) + delivery = DeliveryService( + settings.queue_dir, config_store, last_delivery_path=settings.last_delivery_path + ) delivery.load() display = DisplayService(config_store, current_store, delivery, history_store) url_policy = URLPolicy.from_entries( diff --git a/app/services/delivery.py b/app/services/delivery.py index e85c57d..d394ec1 100644 --- a/app/services/delivery.py +++ b/app/services/delivery.py @@ -11,6 +11,16 @@ Only the newest image is kept: submitting a new image replaces any pending one. The queue survives restarts. Uploads are serialized, so a wakeup racing with the worker never pushes the same image twice. + +Ephemeral images (a song cover, a movie poster) may carry ``expires_at``. An expired +image is never uploaded: it is dropped before any delivery attempt, hidden from queue +inspection, and the worker wakes up at the expiry time to purge it. The drop handler +(set by the application, see :class:`app.services.ephemeral.EphemeralService`) then +restores the previous non-ephemeral image. :meth:`DeliveryService.cancel_ephemeral` +drops a queued ephemeral image on demand (playback stopped). + +The last successful delivery is persisted so the application knows what the frame shows +after a restart (no needless re-upload to a sleeping frame). """ from __future__ import annotations @@ -19,7 +29,7 @@ import contextlib import hashlib import logging -from collections.abc import Callable, Coroutine +from collections.abc import Awaitable, Callable, Coroutine from datetime import UTC, datetime, timedelta from pathlib import Path from typing import Any, Final, Literal @@ -48,6 +58,7 @@ WORKER_ERROR_PAUSE_S: Final = 5.0 DeliveryReason = Literal["submit", "force", "wakeup", "worker"] +DropReason = Literal["expired", "cancelled"] Clock = Callable[[], datetime] ClientFactory = Callable[[FraimicConfig], FraimicClient] @@ -78,6 +89,19 @@ class PendingUpload(BaseModel): last_attempt_at: AwareDatetime | None = None last_error: str | None = None next_attempt_at: AwareDatetime | None = None + ephemeral: bool = Field( + default=False, description="Temporary image (now playing, poster): can be cancelled" + ) + expires_at: AwareDatetime | None = Field( + default=None, description="Dropped instead of delivered after this time" + ) + content_key: str | None = Field( + default=None, description="Identity of the displayed content (deduplication)" + ) + + def expired(self, now: datetime) -> bool: + """Whether the image must no longer be delivered.""" + return self.expires_at is not None and self.expires_at <= now class LastDelivery(BaseModel): @@ -100,10 +124,15 @@ class FrameTelemetry(BaseModel): info: FrameInfo | None = None +DropHandler = Callable[[PendingUpload, DropReason], Awaitable[None]] + + class DeliveryOutcome(BaseModel): """Result of a submit, push or flush.""" - status: Literal["delivered", "queued", "nothing_pending"] + status: Literal["delivered", "queued", "nothing_pending", "dropped"] = Field( + description="dropped = the queued image had expired and was discarded" + ) reason: DeliveryReason sha256: str | None = None error: str | None = None @@ -129,9 +158,21 @@ def __init__( *, client_factory: ClientFactory = FraimicClient.from_config, clock: Clock = _utcnow, + last_delivery_path: Path | None = None, ) -> None: + """Create the service (call :meth:`load` then :meth:`start`). + + Args: + queue_dir: Directory of ``pending.bin`` / ``pending.json``. + config_store: Runtime configuration (the ``fraimic`` section). + client_factory: Builds the frame client (tests inject a fake transport). + clock: Returns the current aware time. + last_delivery_path: Where the last successful delivery is persisted + (``None`` keeps it in memory only). + """ self._bin_path = queue_dir / PENDING_BIN self._meta_path = queue_dir / PENDING_META + self._last_delivery_path = last_delivery_path self._config_store = config_store self._client_factory = client_factory self._clock = clock @@ -141,7 +182,9 @@ def __init__( self._wake = asyncio.Event() self._signalled = False # an explicit wake-up (vs. a mere reschedule) self._task: asyncio.Task[None] | None = None - self._background: set[asyncio.Task[DeliveryOutcome]] = set() + self._background: set[asyncio.Task[Any]] = set() + self._drop_handler: DropHandler | None = None + self._inflight: PendingUpload | None = None self._client: FraimicClient | None = None self._client_config: FraimicConfig | None = None @@ -166,8 +209,13 @@ def load(self) -> PendingUpload | None: else: logger.info("Restored pending upload %s from %s", pending.sha256[:12], pending.source) self._pending = pending + self._last_delivery = self._load_last_delivery() return pending + def set_drop_handler(self, handler: DropHandler | None) -> None: + """Coroutine called (in the background) after an expired image was dropped.""" + self._drop_handler = handler + async def start(self) -> None: """Start the background worker and follow configuration changes.""" self._config_store.add_listener(self._on_config_change) @@ -191,8 +239,32 @@ async def stop(self) -> None: # --- Read access ------------------------------------------------------------------- @property def pending(self) -> PendingUpload | None: - """The image waiting for the frame, if any.""" - return self._pending + """The image waiting for the frame, if any (an expired image is never returned). + + Seeing an expired image wakes the worker so it is purged right away. + """ + pending = self._pending + if pending is not None and pending.expired(self._clock()): + self._signal() + return None + return pending + + @property + def last_delivery(self) -> LastDelivery | None: + """The most recent successful upload (persisted across restarts).""" + return self._last_delivery + + def frame_content_differs(self, sha256: str) -> bool: + """Whether the frame may show something other than the image ``sha256``. + + An upload in progress counts as what the frame shows; an unknown frame state + (nothing ever delivered) counts as different. + """ + inflight = self._inflight + if inflight is not None: + return inflight.sha256 != sha256 + last = self._last_delivery + return last is None or last.sha256 != sha256 @property def telemetry(self) -> FrameTelemetry: @@ -203,7 +275,7 @@ def snapshot(self) -> DeliverySnapshot: """Current delivery state (no network access).""" return DeliverySnapshot( power_mode=self._config.fraimic.power_mode, - pending=self._pending, + pending=self.pending, last_delivery=self._last_delivery, telemetry=self._telemetry, ) @@ -216,6 +288,9 @@ async def submit( source: str | None = None, title: str | None = None, immediate: bool | None = None, + ephemeral: bool = False, + expires_at: datetime | None = None, + content_key: str | None = None, ) -> DeliveryOutcome: """Queue ``data`` for the frame, replacing any pending image. @@ -225,6 +300,9 @@ async def submit( title: Optional human-readable title. immediate: Attempt the upload now. ``None`` follows the power mode (``continuous`` = now, ``deepsleep`` = queue for the worker). + ephemeral: Temporary image that :meth:`cancel_ephemeral` may drop. + expires_at: Drop the image instead of delivering it after this time. + content_key: Identity of the displayed content (deduplication). Raises: ValueError: If ``data`` does not match the configured panel's size. @@ -240,6 +318,9 @@ async def submit( created_at=self._clock(), source=source, title=title, + ephemeral=ephemeral, + expires_at=expires_at, + content_key=content_key, ) async with self._state_lock: await asyncio.to_thread(self._write_pending, data, pending) @@ -253,18 +334,29 @@ async def submit( return DeliveryOutcome(status="queued", reason="submit", sha256=pending.sha256) async def flush(self, reason: DeliveryReason = "wakeup") -> DeliveryOutcome: - """Try to deliver the pending image now (no-op when nothing is pending).""" + """Try to deliver the pending image now (no-op when nothing is pending). + + An expired image is dropped instead (status ``dropped``) and the drop handler + runs in the background. + """ async with self._upload_lock: async with self._state_lock: + expired = await self._purge_expired_locked() pending = self._pending data = await asyncio.to_thread(self._read_pending, pending) if pending else None if pending is not None and data is None: await asyncio.to_thread(remove_quietly, self._bin_path, self._meta_path) self._pending = None + if expired is not None: + self._dispatch_drop(expired, "expired") + return DeliveryOutcome( + status="dropped", reason=reason, sha256=expired.sha256, error="Image expired" + ) if pending is None or data is None: return DeliveryOutcome(status="nothing_pending", reason=reason) client = await self._get_client() + self._inflight = pending try: await self._probe(client) result = await client.upload_bin(data, expected_size=pending.size) @@ -273,6 +365,8 @@ async def flush(self, reason: DeliveryReason = "wakeup") -> DeliveryOutcome: return DeliveryOutcome( status="queued", reason=reason, sha256=pending.sha256, error=str(exc) ) + finally: + self._inflight = None now = self._clock() self._telemetry = self._telemetry.model_copy( @@ -285,6 +379,7 @@ async def flush(self, reason: DeliveryReason = "wakeup") -> DeliveryOutcome: bytes=result.bytes_sent, reason=reason, ) + await self._save_last_delivery() async with self._state_lock: if self._pending is not None and self._pending.sha256 == pending.sha256: await asyncio.to_thread(remove_quietly, self._bin_path, self._meta_path) @@ -334,6 +429,42 @@ async def refresh_info(self) -> FrameInfo: ) return info + async def cancel_ephemeral(self) -> PendingUpload | None: + """Drop the pending image if it is ephemeral (e.g. playback stopped). + + The drop handler is **not** called: the caller decides what to show instead. + + Returns: + The dropped image, or ``None`` when nothing ephemeral was waiting. + """ + async with self._state_lock: + pending = self._pending + if pending is None or not pending.ephemeral: + return None + await asyncio.to_thread(remove_quietly, self._bin_path, self._meta_path) + self._pending = None + logger.info("Cancelled queued ephemeral image %s", pending.sha256[:12]) + self._reschedule() + return pending + + async def extend_pending(self, content_key: str, expires_at: datetime | None) -> bool: + """Move the expiry of the pending image if it shows ``content_key``. + + Returns: + Whether a matching pending image was updated. + """ + async with self._state_lock: + pending = self._pending + if pending is None or pending.content_key != content_key: + return False + updated = pending.model_copy(update={"expires_at": expires_at}) + self._pending = updated + await asyncio.to_thread( + atomic_write_json, self._meta_path, updated.model_dump(mode="json") + ) + self._reschedule() + return True + def wake(self) -> None: """Wake the worker so it re-evaluates immediately.""" self._signal() @@ -349,15 +480,23 @@ def _reschedule(self) -> None: # --- Worker --------------------------------------------------------------------------- def next_wait(self) -> float | None: - """Seconds the worker sleeps before its next check (``None`` = until woken).""" + """Seconds the worker sleeps before its next check (``None`` = until woken). + + A pending image with ``expires_at`` bounds the wait so it is purged on time. + """ config = self._config.fraimic pending = self._pending if pending is not None: + now = self._clock() if config.power_mode == "deepsleep": - return float(config.poll_interval_s) - if pending.next_attempt_at is None: - return 0.0 - return max(0.0, (pending.next_attempt_at - self._clock()).total_seconds()) + wait = float(config.poll_interval_s) + elif pending.next_attempt_at is None: + wait = 0.0 + else: + wait = max(0.0, (pending.next_attempt_at - now).total_seconds()) + if pending.expires_at is not None: + wait = min(wait, max(0.0, (pending.expires_at - now).total_seconds())) + return wait if config.power_mode == "continuous" and config.base_url: return TELEMETRY_INTERVAL_S return None @@ -386,6 +525,11 @@ async def _run(self) -> None: await asyncio.sleep(WORKER_ERROR_PAUSE_S) async def _tick(self, woken: bool) -> None: + async with self._state_lock: + expired = await self._purge_expired_locked() + if expired is not None: + self._dispatch_drop(expired, "expired") + return config = self._config.fraimic pending = self._pending if pending is not None: @@ -468,11 +612,62 @@ async def _refresh_quietly(self) -> DeliveryOutcome: await self.refresh_info() return DeliveryOutcome(status="nothing_pending", reason="wakeup") - def _spawn(self, coro: Coroutine[Any, Any, DeliveryOutcome]) -> None: + def _spawn(self, coro: Coroutine[Any, Any, Any]) -> None: task = asyncio.create_task(coro) self._background.add(task) task.add_done_callback(self._background.discard) + async def _purge_expired_locked(self) -> PendingUpload | None: + """Drop the pending image if it expired (caller holds ``_state_lock``).""" + pending = self._pending + if pending is None or not pending.expired(self._clock()): + return None + await asyncio.to_thread(remove_quietly, self._bin_path, self._meta_path) + self._pending = None + logger.info( + "Dropped expired image %s (%s) instead of delivering it", + pending.sha256[:12], + pending.title or pending.source or "untitled", + ) + return pending + + def _dispatch_drop(self, pending: PendingUpload, reason: DropReason) -> None: + handler = self._drop_handler + if handler is not None: + self._spawn(self._run_drop_handler(handler, pending, reason)) + + @staticmethod + async def _run_drop_handler( + handler: DropHandler, pending: PendingUpload, reason: DropReason + ) -> None: + try: + await handler(pending, reason) + except asyncio.CancelledError: + raise + except Exception: + logger.exception("Handling the dropped image %s failed", pending.sha256[:12]) + + def _load_last_delivery(self) -> LastDelivery | None: + if self._last_delivery_path is None: + return None + raw = read_json(self._last_delivery_path, lambda: None) + if raw is None: + return None + try: + return LastDelivery.model_validate(raw) + except ValidationError: + logger.warning("Ignoring invalid %s", self._last_delivery_path) + return None + + async def _save_last_delivery(self) -> None: + path, last = self._last_delivery_path, self._last_delivery + if path is None or last is None: + return + try: + await asyncio.to_thread(atomic_write_json, path, last.model_dump(mode="json")) + except OSError: + logger.exception("Could not persist the last delivery to %s", path) + async def _on_config_change(self, config: RuntimeConfig) -> None: pending = self._pending if pending is not None and pending.panel != config.fraimic.panel: diff --git a/tests/test_delivery.py b/tests/test_delivery.py index 31f22fa..586bba9 100644 --- a/tests/test_delivery.py +++ b/tests/test_delivery.py @@ -393,3 +393,177 @@ async def test_refresh_info_updates_telemetry(make_service: ServiceFactory) -> N def test_next_wait_when_idle(make_service: ServiceFactory) -> None: assert make_service("continuous").next_wait() == 300.0 assert make_service("deepsleep").next_wait() is None + + +# --- ephemeral expiry & cancellation ---------------------------------------------------------- +class DropRecorder: + def __init__(self) -> None: + self.calls: list[tuple[str, str]] = [] + + async def __call__(self, pending: Any, reason: str) -> None: + self.calls.append((pending.sha256, reason)) + + +@respx.mock +async def test_expired_pending_is_dropped_instead_of_delivered( + make_service: ServiceFactory, tmp_path: Path +) -> None: + clock = FakeClock() + respx.get(INFO_URL).respond(json=INFO) + upload = respx.post(IMAGE_URL).respond(200) + service = make_service("deepsleep", clock=clock) + recorder = DropRecorder() + service.set_drop_handler(recorder) + await service.submit( + BIN_A, source="music", ephemeral=True, expires_at=clock.now + timedelta(minutes=3) + ) + assert service.pending is not None and service.pending.ephemeral + + clock.advance(181) # the song ended while the frame was asleep + outcome = await service.wakeup(wait=True) + + assert outcome is not None and outcome.status == "dropped" + assert outcome.sha256 == hashlib.sha256(BIN_A).hexdigest() + assert not upload.called + assert service.pending is None + assert queue_files(tmp_path) == set() + await eventually(lambda: recorder.calls == [(hashlib.sha256(BIN_A).hexdigest(), "expired")]) + + +async def test_queue_inspection_hides_expired_images(make_service: ServiceFactory) -> None: + clock = FakeClock() + service = make_service("deepsleep", clock=clock) + await service.submit(BIN_A, ephemeral=True, expires_at=clock.now + timedelta(seconds=60)) + assert service.snapshot().pending is not None + clock.advance(61) + assert service.pending is None + assert service.snapshot().pending is None + + +async def test_worker_purges_on_expiry_without_a_wakeup(make_service: ServiceFactory) -> None: + service = make_service("deepsleep", poll_interval_s=3600) + recorder = DropRecorder() + service.set_drop_handler(recorder) + await service.start() + expires = datetime.now(UTC) + timedelta(seconds=0.2) + await service.submit(BIN_A, ephemeral=True, expires_at=expires) + + await eventually(lambda: bool(recorder.calls)) + assert recorder.calls[0][1] == "expired" + assert service._pending is None + + +async def test_next_wait_is_bounded_by_the_expiry(make_service: ServiceFactory) -> None: + clock = FakeClock() + service = make_service("deepsleep", clock=clock, poll_interval_s=600) + await service.submit(BIN_A, ephemeral=True, expires_at=clock.now + timedelta(seconds=90)) + assert service.next_wait() == pytest.approx(90.0) + clock.advance(100) + assert service.next_wait() == 0.0 + + +async def test_restored_expired_pending_is_purged_by_the_worker(tmp_path: Path) -> None: + clock = FakeClock() + store = make_config_store(tmp_path, "deepsleep") + first = DeliveryService(tmp_path / "queue", store, clock=clock) + first.load() + await first.submit(BIN_A, ephemeral=True, expires_at=clock.now + timedelta(minutes=1)) + + clock.advance(120) # the app was down past the expiry + restarted = DeliveryService(tmp_path / "queue", store, clock=clock) + assert restarted.load() is not None + recorder = DropRecorder() + restarted.set_drop_handler(recorder) + assert restarted.next_wait() == 0.0 + await restarted.start() + try: + await eventually(lambda: bool(recorder.calls)) + finally: + await restarted.stop() + assert queue_files(tmp_path) == set() + + +async def test_cancel_ephemeral_only_drops_ephemeral_images( + make_service: ServiceFactory, tmp_path: Path +) -> None: + service = make_service("deepsleep") + recorder = DropRecorder() + service.set_drop_handler(recorder) + + await service.submit(BIN_A, source="immich") + assert await service.cancel_ephemeral() is None + assert service.pending is not None + + await service.submit(BIN_B, source="tmdb", ephemeral=True) + dropped = await service.cancel_ephemeral() + assert dropped is not None and dropped.source == "tmdb" + assert service.pending is None + assert queue_files(tmp_path) == set() + assert recorder.calls == [] # the caller decides what to show instead + + +async def test_extend_pending_moves_the_expiry_of_matching_content( + make_service: ServiceFactory, tmp_path: Path +) -> None: + clock = FakeClock() + service = make_service("deepsleep", clock=clock) + await service.submit( + BIN_A, ephemeral=True, expires_at=clock.now + timedelta(minutes=1), content_key="song-1" + ) + later = clock.now + timedelta(minutes=5) + assert not await service.extend_pending("song-2", later) + assert await service.extend_pending("song-1", later) + assert service.pending is not None and service.pending.expires_at == later + + restarted = DeliveryService(tmp_path / "queue", service._config_store, clock=clock) + restored = restarted.load() + assert restored is not None and restored.expires_at == later + + +@respx.mock +async def test_last_delivery_is_persisted_and_restored(tmp_path: Path) -> None: + respx.get(INFO_URL).respond(json=INFO) + respx.post(IMAGE_URL).respond(200) + store = make_config_store(tmp_path, "continuous") + path = tmp_path / "last_delivery.json" + first = DeliveryService(tmp_path / "queue", store, last_delivery_path=path) + first.load() + await first.submit(BIN_A) + await first.stop() + assert path.is_file() + + restarted = DeliveryService(tmp_path / "queue", store, last_delivery_path=path) + restarted.load() + sha_a = hashlib.sha256(BIN_A).hexdigest() + assert restarted.last_delivery is not None and restarted.last_delivery.sha256 == sha_a + assert not restarted.frame_content_differs(sha_a) + assert restarted.frame_content_differs(hashlib.sha256(BIN_B).hexdigest()) + + path.write_text("{not json", encoding="utf-8") + broken = DeliveryService(tmp_path / "queue", store, last_delivery_path=path) + broken.load() + assert broken.last_delivery is None + assert broken.frame_content_differs(sha_a) # unknown frame state + + +@respx.mock +async def test_frame_content_counts_an_upload_in_progress(make_service: ServiceFactory) -> None: + respx.get(INFO_URL).respond(json=INFO) + started, release = asyncio.Event(), asyncio.Event() + + async def slow_upload(request: httpx.Request) -> httpx.Response: + started.set() + await release.wait() + return httpx.Response(200) + + respx.post(IMAGE_URL).mock(side_effect=slow_upload) + service = make_service("deepsleep") + sha_a, sha_b = hashlib.sha256(BIN_A).hexdigest(), hashlib.sha256(BIN_B).hexdigest() + await service.submit(BIN_A) + flush = asyncio.create_task(service.flush("wakeup")) + await started.wait() + assert not service.frame_content_differs(sha_a) + assert service.frame_content_differs(sha_b) + release.set() + assert (await flush).status == "delivered" + assert not service.frame_content_differs(sha_a) From 810c399e0b45f2219cca8b5df9d4bf3158055baa Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sun, 15 Nov 2026 15:33:12 +0100 Subject: [PATCH 52/86] feat: add base and preview image slots The cache now holds three slots: current (what the frame shows), base (the last pushed non-ephemeral image, restored after an ephemeral one) and preview (the latest render). Renders with push_to_fraimic=false only update the preview, served at /api/preview.jpg and /api/preview_dithered.png, so templates can be inspected without touching current.* or the frame. POST /api/fraimic/push?from_preview=true promotes the preview and sends it. DisplayService gains template rendering (display_layout), ephemeral and expiry metadata, revert_to_base() (re-sends the base only when the frame may not show it), expiry extension and display listeners. Existing data seeds the base slot on startup. BREAKING CHANGE: push_to_fraimic=false no longer replaces current.*. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- app/api/routes/display.py | 6 +- app/api/routes/fraimic.py | 16 +- app/api/routes/images.py | 32 +++- app/api/routes/smart_mix.py | 4 +- app/core/auth.py | 12 +- app/providers/base.py | 7 + app/providers/immich/models.py | 4 +- app/services/current_image.py | 258 +++++++++++++++++++++++++----- app/services/display.py | 278 +++++++++++++++++++++++++++++---- tests/test_api_immich.py | 2 +- tests/test_api_phase2.py | 30 +++- tests/test_current_image.py | 123 +++++++++++++++ 12 files changed, 687 insertions(+), 85 deletions(-) diff --git a/app/api/routes/display.py b/app/api/routes/display.py index fb3fb9d..2623399 100644 --- a/app/api/routes/display.py +++ b/app/api/routes/display.py @@ -48,7 +48,11 @@ async def display_upload( file: Annotated[UploadFile, File(description="Image file (max MAX_UPLOAD_MB)")], fit: Annotated[FitMode | None, Form(description="Override the default fit mode")] = None, push_to_fraimic: Annotated[ - bool, Form(description="Send the result to the frame (or queue it in deepsleep mode)") + bool, + Form( + description="Send the result to the frame (or queue it in deepsleep mode); " + "false only renders a preview (/api/preview.jpg)" + ), ] = True, ephemeral: Annotated[ bool, Form(description="Temporary push (accepted for symmetry; uploads are never replayed)") diff --git a/app/api/routes/fraimic.py b/app/api/routes/fraimic.py index bb4c31d..d81a221 100644 --- a/app/api/routes/fraimic.py +++ b/app/api/routes/fraimic.py @@ -46,14 +46,26 @@ def _outcome_response(outcome: DeliveryOutcome) -> JSONResponse: responses={**_OUTCOME_RESPONSES, 409: {"description": "No current image to push"}}, summary="Force push the current image to the frame", ) -async def force_push(display: DisplayServiceDep) -> JSONResponse: +async def force_push( + display: DisplayServiceDep, + from_preview: Annotated[ + bool, + Query( + description="First make the latest preview (a push_to_fraimic=false render) the " + "current image" + ), + ] = False, +) -> JSONResponse: """Send ``current.bin`` now, whatever the power mode. + With ``?from_preview=true`` the latest preview is promoted first, so a template can be + rendered with ``push_to_fraimic=false``, inspected at ``/api/preview.jpg``, then sent. + Returns ``200`` when delivered and ``202`` when the frame could not be reached; the image then stays queued and is retried automatically. """ try: - outcome = await display.push_current() + outcome = await display.push_current(from_preview=from_preview) except NoCurrentImageError as exc: raise HTTPException(status_code=409, detail=str(exc)) from exc return _outcome_response(outcome) diff --git a/app/api/routes/images.py b/app/api/routes/images.py index c99e618..dc8799d 100644 --- a/app/api/routes/images.py +++ b/app/api/routes/images.py @@ -1,4 +1,8 @@ -"""Current image files (Home Assistant Generic Camera, UI preview, Fraimic pull). +"""Image files (Home Assistant Generic Camera, UI preview, Fraimic pull). + +* ``/api/current.*`` - what the frame shows (or will show once a sleeping frame wakes up). +* ``/api/preview.*`` - the most recent render, including ``push_to_fraimic=false`` renders + used to inspect a template without touching the frame. Readable without an API key unless ``PUBLIC_IMAGE_ENDPOINTS=false`` (enforced by the auth middleware). Responses carry an ``ETag`` derived from the ``.bin`` hash and @@ -90,3 +94,29 @@ async def current_bin(request: Request, store: CurrentImageStoreDep) -> Response "application/octet-stream", filename=filename, ) + + +@router.head("/preview.jpg", include_in_schema=False) +@router.get( + "/preview.jpg", + responses=_responses("image/jpeg"), + summary="Most recent render (enhanced, before dithering), pushed or not", +) +async def preview_jpeg(request: Request, store: CurrentImageStoreDep) -> Response: + """The latest composition as JPEG, including ``push_to_fraimic=false`` renders.""" + meta = store.preview_meta + path = store.paths("preview").jpeg + return _serve(request, path, meta.sha256 if meta else None, "pjpg", "image/jpeg") + + +@router.head("/preview_dithered.png", include_in_schema=False) +@router.get( + "/preview_dithered.png", + responses=_responses("image/png"), + summary="Most recent render as the panel would show it (6-color simulation)", +) +async def preview_dithered(request: Request, store: CurrentImageStoreDep) -> Response: + """Exact 6-color dithered preview of the latest render, in viewing orientation.""" + meta = store.preview_meta + path = store.paths("preview").dithered + return _serve(request, path, meta.sha256 if meta else None, "ppng", "image/png") diff --git a/app/api/routes/smart_mix.py b/app/api/routes/smart_mix.py index 10d8e46..d174523 100644 --- a/app/api/routes/smart_mix.py +++ b/app/api/routes/smart_mix.py @@ -60,7 +60,9 @@ class SmartSearchRequest(BaseModel): taken_after: AwareDatetime | None = None taken_before: AwareDatetime | None = None fit: FitMode | None = None - push_to_fraimic: bool = True + push_to_fraimic: bool = Field( + default=True, description="Send to the frame; false only renders a preview" + ) ephemeral: bool = Field( default=True, description="Temporary push: not stored as the rule replayed by POST /api/refresh", diff --git a/app/core/auth.py b/app/core/auth.py index 5c1b312..fc984c6 100644 --- a/app/core/auth.py +++ b/app/core/auth.py @@ -5,8 +5,8 @@ * ``POST``/``PUT``/``PATCH``/``DELETE`` on any route require the key. * ``/api/config`` and ``/api/immich`` (family member names, albums) and everything below them require the key for every method. -* ``/api/current.jpg``, ``/api/current.bin`` and ``/api/current_dithered.png`` require - the key only when +* ``/api/current.jpg``, ``/api/current.bin``, ``/api/current_dithered.png``, + ``/api/preview.jpg`` and ``/api/preview_dithered.png`` require the key only when ``PUBLIC_IMAGE_ENDPOINTS=false``. * Everything else (UI, ``/docs``, ``/openapi.json``, ``/api/health``, ``GET /api/status``) stays public so the UI can load and prompt for the key. @@ -31,7 +31,13 @@ MUTATING_METHODS: Final = frozenset({"POST", "PUT", "PATCH", "DELETE"}) PROTECTED_PREFIXES: Final = ("/api/config", "/api/immich", "/api/smart-mix") IMAGE_ENDPOINTS: Final = frozenset( - {"/api/current.jpg", "/api/current.bin", "/api/current_dithered.png"} + { + "/api/current.jpg", + "/api/current.bin", + "/api/current_dithered.png", + "/api/preview.jpg", + "/api/preview_dithered.png", + } ) #: OpenAPI-only security scheme so ``/docs`` offers an "Authorize" button. Enforcement diff --git a/app/providers/base.py b/app/providers/base.py index 5a581cf..a6b53d6 100644 --- a/app/providers/base.py +++ b/app/providers/base.py @@ -20,6 +20,7 @@ from app.core.config_models import FitMode from app.processor.fit import FocusRegion +from app.processor.templates import Layout class ProviderError(Exception): @@ -62,6 +63,10 @@ class ImageAsset: means "use the configured default". regions: Regions of interest (faces) in normalized coordinates, most relevant first. taken_at: When the picture was taken, if known (burst cooldown in the history). + layout: Composition template (poster, album cover, title card) used instead of a + fit mode; ``data`` may then be empty for templates that need no artwork. + track_history: Record the display in the anti-repeat history (photos); posters + and album covers are shown on demand and are not tracked. """ data: bytes = field(repr=False) @@ -72,6 +77,8 @@ class ImageAsset: recommended_fit: FitMode | None = None regions: tuple[FocusRegion, ...] = () taken_at: datetime | None = None + layout: Layout | None = None + track_history: bool = True RequestT = TypeVar("RequestT", contravariant=True) diff --git a/app/providers/immich/models.py b/app/providers/immich/models.py index 5eb0909..b27cf1c 100644 --- a/app/providers/immich/models.py +++ b/app/providers/immich/models.py @@ -173,7 +173,9 @@ class ImmichDisplayRequest(BaseModel): ) fit: FitMode | None = Field(default=None, description="Override the default fit mode") push_to_fraimic: bool = Field( - default=True, description="Send the result to the frame (or queue it in deepsleep mode)" + default=True, + description="Send the result to the frame (or queue it in deepsleep mode); " + "false only renders a preview (/api/preview.jpg)", ) ignore_history: bool = Field( default=False, diff --git a/app/services/current_image.py b/app/services/current_image.py index c1b1220..a54c421 100644 --- a/app/services/current_image.py +++ b/app/services/current_image.py @@ -1,12 +1,16 @@ -"""Persistence of the most recently rendered image in ``/data/cache``. +"""Persistence of rendered images in ``/data/cache``, in three slots. -Files: +* ``current`` - what the frame shows (or is about to show once a sleeping frame wakes up): + ``current.bin`` (pushed to the frame), ``current.jpg`` (Home Assistant, UI), + ``current_dithered.png`` (exact 6-color simulation) and ``current.json`` (metadata). +* ``base`` - the most recent **pushed, non-ephemeral** image (``base.*``). When an + ephemeral image (now playing, movie poster) expires or is cancelled, ``base`` is copied + back to ``current`` and re-sent to the frame if needed. +* ``preview`` - the most recent render of any kind (``preview.*``), including renders made + with ``push_to_fraimic=false``, which never touch ``current``. -* ``current.bin`` - the panel frame buffer pushed to the Fraimic frame. -* ``current.jpg`` - the enhanced composition before dithering (Home Assistant, UI). -* ``current_dithered.png`` - exact 6-color simulation of what the panel shows. -* ``current.json`` - metadata, written **last** as the commit marker. It records the - SHA-256 of ``current.bin``, so a set interrupted mid-write is detected and ignored. +In each slot the ``.json`` metadata is written **last** as the commit marker. It records +the SHA-256 of the slot's ``.bin``, so a set interrupted mid-write is detected and ignored. """ from __future__ import annotations @@ -14,9 +18,10 @@ import hashlib import logging import threading +from dataclasses import dataclass from datetime import UTC, datetime from pathlib import Path -from typing import Final +from typing import Final, Literal from pydantic import AwareDatetime, BaseModel, ConfigDict, Field, JsonValue, ValidationError @@ -27,6 +32,9 @@ logger = logging.getLogger(__name__) +SlotName = Literal["current", "base", "preview"] +SLOTS: Final[tuple[SlotName, ...]] = ("current", "base", "preview") + BIN_NAME: Final = "current.bin" JPEG_NAME: Final = "current.jpg" DITHERED_NAME: Final = "current_dithered.png" @@ -34,7 +42,7 @@ class CurrentImageMeta(BaseModel): - """Metadata of the current image (served by ``GET /api/status``).""" + """Metadata of a rendered image (served by ``GET /api/status``).""" model_config = ConfigDict(frozen=True) @@ -50,49 +58,125 @@ class CurrentImageMeta(BaseModel): dither: DitherAlgorithm frame_size: tuple[int, int] = Field(description="Composition size (width, height)") processed_at: AwareDatetime - sha256: str = Field(description="SHA-256 of current.bin") + sha256: str = Field(description="SHA-256 of the .bin") bin_size: int + template: str | None = Field( + default=None, description="Composition template (poster, album, title_card), if any" + ) + pushed: bool = Field(default=True, description="Whether the image was sent to the frame") + ephemeral: bool = Field( + default=False, description="Temporary image: the previous one comes back afterwards" + ) + expires_at: AwareDatetime | None = Field( + default=None, description="When an ephemeral image is replaced by the previous one" + ) + content_key: str | None = Field( + default=None, description="Identity of the displayed content (deduplication)" + ) + + def expired(self, now: datetime) -> bool: + """Whether this ephemeral image is past its expiry.""" + return self.ephemeral and self.expires_at is not None and self.expires_at <= now + + +@dataclass(frozen=True, slots=True) +class SlotPaths: + """Files of one slot.""" + + bin: Path + jpeg: Path + dithered: Path + meta: Path + + def all(self) -> tuple[Path, Path, Path, Path]: + """Every file of the slot, metadata last.""" + return self.bin, self.jpeg, self.dithered, self.meta + + +def slots_for(*, push: bool, ephemeral: bool) -> tuple[SlotName, ...]: + """Slots a render is written to. + + * pushed, non-ephemeral: ``current`` + ``base`` + ``preview``; + * pushed, ephemeral: ``current`` + ``preview``; + * not pushed: ``preview`` only. + """ + if not push: + return ("preview",) + if ephemeral: + return ("current", "preview") + return ("current", "base", "preview") class CurrentImageStore: - """Reads and atomically writes the current image set.""" + """Reads and atomically writes the image slots.""" def __init__(self, cache_dir: Path) -> None: self._dir = cache_dir self._lock = threading.Lock() - self._meta: CurrentImageMeta | None = None + self._metas: dict[SlotName, CurrentImageMeta | None] = dict.fromkeys(SLOTS) + + # --- Paths ---------------------------------------------------------------------------- + def paths(self, slot: SlotName) -> SlotPaths: + """Files of ``slot``.""" + return SlotPaths( + bin=self._dir / f"{slot}.bin", + jpeg=self._dir / f"{slot}.jpg", + dithered=self._dir / f"{slot}_dithered.png", + meta=self._dir / f"{slot}.json", + ) @property def bin_path(self) -> Path: """Location of ``current.bin``.""" - return self._dir / BIN_NAME + return self.paths("current").bin @property def jpeg_path(self) -> Path: """Location of ``current.jpg``.""" - return self._dir / JPEG_NAME + return self.paths("current").jpeg @property def dithered_path(self) -> Path: """Location of ``current_dithered.png``.""" - return self._dir / DITHERED_NAME + return self.paths("current").dithered @property def meta_path(self) -> Path: """Location of ``current.json``.""" - return self._dir / META_NAME + return self.paths("current").meta + # --- Metadata ------------------------------------------------------------------------- @property def meta(self) -> CurrentImageMeta | None: """Metadata of the current image, or ``None`` when nothing was rendered yet.""" - return self._meta + return self._metas["current"] + + @property + def base_meta(self) -> CurrentImageMeta | None: + """Metadata of the last pushed non-ephemeral image, if any.""" + return self._metas["base"] + + @property + def preview_meta(self) -> CurrentImageMeta | None: + """Metadata of the most recent render (pushed or not), if any.""" + return self._metas["preview"] + + def slot_meta(self, slot: SlotName) -> CurrentImageMeta | None: + """Metadata of ``slot``.""" + return self._metas[slot] def load(self) -> CurrentImageMeta | None: - """Load and verify the stored set (call once at startup).""" + """Load and verify every slot (call once at startup); returns the current one.""" with self._lock: - self._meta = self._load_verified() - return self._meta + for slot in SLOTS: + self._metas[slot] = self._load_verified(slot) + current = self._metas["current"] + if self._metas["base"] is None and current is not None and not current.ephemeral: + # Data written before the base slot existed: the current image is the base. + self._copy_slot("current", "base", current) + return current + # --- Writes --------------------------------------------------------------------------- def save( self, result: RenderResult, @@ -100,8 +184,16 @@ def save( source: str, title: str | None = None, details: dict[str, JsonValue] | None = None, + push: bool = True, + ephemeral: bool = False, + expires_at: datetime | None = None, + content_key: str | None = None, + template: str | None = None, ) -> CurrentImageMeta: - """Persist a render result as the current image (blocking; use a thread).""" + """Persist a render result into the slots chosen by :func:`slots_for`. + + Blocking; call it through a thread. + """ options = result.options meta = CurrentImageMeta( source=source, @@ -116,54 +208,144 @@ def save( processed_at=datetime.now(UTC), sha256=result.sha256, bin_size=len(result.bin), + template=template, + pushed=push, + ephemeral=ephemeral, + expires_at=expires_at, + content_key=content_key, ) jpeg = result.preview_jpeg() dithered = result.dithered_png() + slots = slots_for(push=push, ephemeral=ephemeral) with self._lock: - atomic_write_bytes(self.bin_path, result.bin) - atomic_write_bytes(self.jpeg_path, jpeg) - atomic_write_bytes(self.dithered_path, dithered) - atomic_write_json(self.meta_path, meta.model_dump(mode="json")) - self._meta = meta + for slot in slots: + self._write_slot(slot, result.bin, jpeg, dithered, meta) logger.info( - "Saved current image from %s (%s, %d bytes, sha256 %s)", + "Saved image from %s (%s, %d bytes, sha256 %s) to %s", source, title or "untitled", meta.bin_size, meta.sha256[:12], + "+".join(slots), ) return meta - def read_bin(self) -> tuple[bytes, CurrentImageMeta] | None: - """Return ``current.bin`` and its metadata if both are present and consistent.""" + def restore_base(self) -> CurrentImageMeta | None: + """Copy the ``base`` slot over ``current`` (blocking; call it through a thread). + + Returns: + The restored metadata, or ``None`` when there is no valid base image. + """ + with self._lock: + base = self._metas["base"] + if base is None: + return None + if not self._copy_slot("base", "current", base): + self._metas["base"] = None + return None + logger.info("Restored the previous image (%s, %s)", base.source, base.title or "untitled") + return base + + def promote_preview(self) -> CurrentImageMeta | None: + """Make the preview the current image (and the base, unless it is ephemeral). + + Blocking; call it through a thread. + + Returns: + The promoted metadata, or ``None`` when there is no valid preview. + """ with self._lock: - meta = self._meta + preview = self._metas["preview"] + if preview is None: + return None + promoted = preview.model_copy(update={"pushed": True}) + targets: tuple[SlotName, ...] = ( + ("current",) if promoted.ephemeral else ("current", "base") + ) + for target in targets: + if not self._copy_slot("preview", target, promoted): + return None + atomic_write_json(self.paths("preview").meta, promoted.model_dump(mode="json")) + self._metas["preview"] = promoted + logger.info("Promoted the preview (%s) to the current image", promoted.title or "untitled") + return promoted + + def extend_expiry( + self, content_key: str, expires_at: datetime | None + ) -> CurrentImageMeta | None: + """Move the expiry of the current image if it shows ``content_key``. + + Returns: + The updated metadata, or ``None`` when the current image is something else. + """ + with self._lock: + meta = self._metas["current"] + if meta is None or not meta.ephemeral or meta.content_key != content_key: + return None + updated = meta.model_copy(update={"expires_at": expires_at}) + atomic_write_json(self.paths("current").meta, updated.model_dump(mode="json")) + self._metas["current"] = updated + return updated + + # --- Reads ---------------------------------------------------------------------------- + def read_bin(self, slot: SlotName = "current") -> tuple[bytes, CurrentImageMeta] | None: + """Return the ``.bin`` of ``slot`` and its metadata if both are present and consistent.""" + with self._lock: + meta = self._metas[slot] if meta is None: return None try: - data = self.bin_path.read_bytes() + data = self.paths(slot).bin.read_bytes() except FileNotFoundError: return None if hashlib.sha256(data).hexdigest() != meta.sha256: - logger.warning("current.bin does not match current.json; ignoring it") + logger.warning("%s.bin does not match %s.json; ignoring it", slot, slot) return None return data, meta - def _load_verified(self) -> CurrentImageMeta | None: - raw = read_json(self.meta_path, lambda: None) + # --- Internals ------------------------------------------------------------------------ + def _copy_slot(self, source: SlotName, target: SlotName, meta: CurrentImageMeta) -> bool: + """Copy the files of ``source`` to ``target`` (caller holds the lock).""" + paths = self.paths(source) + try: + data = paths.bin.read_bytes() + jpeg = paths.jpeg.read_bytes() + dithered = paths.dithered.read_bytes() + except FileNotFoundError: + logger.warning("The %s image files are missing; cannot copy them", source) + return False + if hashlib.sha256(data).hexdigest() != meta.sha256: + logger.warning("%s.bin does not match %s.json; cannot copy it", source, source) + return False + self._write_slot(target, data, jpeg, dithered, meta) + return True + + def _write_slot( + self, slot: SlotName, data: bytes, jpeg: bytes, dithered: bytes, meta: CurrentImageMeta + ) -> None: + paths = self.paths(slot) + atomic_write_bytes(paths.bin, data) + atomic_write_bytes(paths.jpeg, jpeg) + atomic_write_bytes(paths.dithered, dithered) + atomic_write_json(paths.meta, meta.model_dump(mode="json")) + self._metas[slot] = meta + + def _load_verified(self, slot: SlotName) -> CurrentImageMeta | None: + paths = self.paths(slot) + raw = read_json(paths.meta, lambda: None) if raw is None: return None try: meta = CurrentImageMeta.model_validate(raw) except ValidationError: - logger.warning("Ignoring invalid %s", self.meta_path) + logger.warning("Ignoring invalid %s", paths.meta) return None try: - data = self.bin_path.read_bytes() + data = paths.bin.read_bytes() except FileNotFoundError: - logger.warning("%s is missing; no current image", self.bin_path) + logger.warning("%s is missing; no %s image", paths.bin, slot) return None if len(data) != meta.bin_size or hashlib.sha256(data).hexdigest() != meta.sha256: - logger.warning("current.bin does not match current.json; no current image") + logger.warning("%s.bin does not match %s.json; no %s image", slot, slot, slot) return None return meta diff --git a/app/services/display.py b/app/services/display.py index 75c0721..2eb3884 100644 --- a/app/services/display.py +++ b/app/services/display.py @@ -1,14 +1,22 @@ -"""Display orchestration: render an image, store it as current, deliver it to the frame. +"""Display orchestration: render an image, store it, deliver it to the frame. -Every image source (uploads now; Immich, TMDB and URLs in later milestones) goes -through :meth:`DisplayService.display_bytes`, which serializes rendering so that only -one image is processed at a time (bounded memory, consistent ``current.*`` files). +Every image source goes through :class:`DisplayService`, which serializes rendering so +that only one image is processed at a time (bounded memory, consistent slot files). + +* A **pushed** render becomes the current image and is handed to the delivery service. + Unless it is ephemeral, it also becomes the *base* image restored after an ephemeral + image (now playing, movie poster) expires or is cancelled. +* A render with ``push=False`` only updates the *preview* slot: what Home Assistant and + the frame see (``current.*``) is left untouched. """ from __future__ import annotations import asyncio -from collections.abc import Sequence +import logging +from collections.abc import Callable, Sequence +from dataclasses import dataclass +from datetime import datetime from pydantic import BaseModel, Field, JsonValue @@ -16,11 +24,21 @@ from app.core.config_store import ConfigStore from app.core.history_store import HistoryStore from app.processor.fit import FocusRegion -from app.processor.pipeline import RenderOptions, render_bytes +from app.processor.pipeline import ( + RenderOptions, + RenderResult, + render_bytes, + render_layout_bytes, +) +from app.processor.templates import Layout from app.providers.base import ImageAsset from app.services.current_image import CurrentImageMeta, CurrentImageStore from app.services.delivery import DeliveryOutcome, DeliveryService +logger = logging.getLogger(__name__) + +DisplayListener = Callable[[CurrentImageMeta], None] + class NoCurrentImageError(LookupError): """There is no usable current image to push.""" @@ -33,6 +51,35 @@ class DisplayResult(BaseModel): delivery: DeliveryOutcome | None = Field( default=None, description="Frame delivery outcome (null when push was disabled)" ) + deduplicated: bool = Field( + default=False, + description="The same content was already displayed: only its expiry was extended", + ) + + +@dataclass(frozen=True, slots=True) +class DisplayMeta: + """Descriptive metadata and delivery intent of one display.""" + + source: str + title: str | None = None + details: dict[str, JsonValue] | None = None + push: bool = True + ephemeral: bool = False + expires_at: datetime | None = None + content_key: str | None = None + + +class RevertOutcome(BaseModel): + """What restoring the previous (base) image did.""" + + reverted: bool = Field(description="current.* now shows the previous image again") + has_base: bool = Field(description="Whether a previous non-ephemeral image exists") + pushed_base: bool = Field( + default=False, description="The previous image was re-sent (or queued) for the frame" + ) + delivery: DeliveryOutcome | None = None + image: CurrentImageMeta | None = None class DisplayService: @@ -50,7 +97,13 @@ def __init__( self._delivery = delivery self._history = history self._render_lock = asyncio.Lock() + self._listeners: list[DisplayListener] = [] + + def add_listener(self, listener: DisplayListener) -> None: + """Call ``listener`` after every change of the current image (display or revert).""" + self._listeners.append(listener) + # --- Rendering ------------------------------------------------------------------------ async def display_bytes( self, data: bytes, @@ -61,53 +114,201 @@ async def display_bytes( fit: FitMode | None = None, regions: Sequence[FocusRegion] = (), push: bool = True, + ephemeral: bool = False, + expires_at: datetime | None = None, + content_key: str | None = None, ) -> DisplayResult: - """Render ``data``, make it the current image and optionally push it. + """Render ``data`` with a fit mode, store it and optionally push it. Raises: InvalidImageError: If ``data`` is not a supported image. """ - async with self._render_lock: - options = RenderOptions.from_config(self._config_store.config, fit=fit) - result = await asyncio.to_thread(render_bytes, data, options, tuple(regions)) - meta = await asyncio.to_thread( - self._current.save, result, source=source, title=title, details=details - ) - delivery = ( - await self._delivery.submit(result.bin, source=source, title=title) if push else None + options = RenderOptions.from_config(self._config_store.config, fit=fit) + focus = tuple(regions) + return await self._display( + lambda: render_bytes(data, options, focus), + DisplayMeta(source, title, details, push, ephemeral, expires_at, content_key), + template=None, + ) + + async def display_layout( + self, data: bytes | None, layout: Layout, meta: DisplayMeta + ) -> DisplayResult: + """Render ``data`` (or nothing, for a title card) with a composition template. + + Templates never crop and always use the ``official`` eInk profile (posters and + album art are graphic designs, not photos). + + Raises: + InvalidImageError: If ``data`` is not a supported image. + """ + options = RenderOptions.from_config( + self._config_store.config, fit="contain", eink_profile="official" + ) + return await self._display( + lambda: render_layout_bytes(data, layout, options), meta, template=layout.name ) - return DisplayResult(image=meta, delivery=delivery) async def display_asset( - self, asset: ImageAsset, *, fit: FitMode | None = None, push: bool = True + self, + asset: ImageAsset, + *, + fit: FitMode | None = None, + push: bool = True, + ephemeral: bool = False, + expires_at: datetime | None = None, + content_key: str | None = None, ) -> DisplayResult: """Display a provider asset and record it in the anti-repeat history. - The fit mode is the explicit ``fit``, else the asset's recommended one, else the - configured default. The history entry is written only after rendering succeeded. + Assets with a :attr:`ImageAsset.layout` use that template; others use the explicit + ``fit``, else the asset's recommended one, else the configured default. The history + entry is written only after rendering succeeded (and only for tracked assets). Raises: InvalidImageError: If the asset's bytes are not a supported image. """ - result = await self.display_bytes( - asset.data, - source=asset.source, - title=asset.title, - details=asset.details, - fit=fit or asset.recommended_fit, - regions=asset.regions, - push=push, + meta = DisplayMeta( + asset.source, asset.title, asset.details, push, ephemeral, expires_at, content_key ) - await self._history.record(asset.history_key, asset.source, taken_at=asset.taken_at) + if asset.layout is not None: + result = await self.display_layout(asset.data or None, asset.layout, meta) + else: + result = await self.display_bytes( + asset.data, + source=asset.source, + title=asset.title, + details=asset.details, + fit=fit or asset.recommended_fit, + regions=asset.regions, + push=push, + ephemeral=ephemeral, + expires_at=expires_at, + content_key=content_key, + ) + if asset.track_history: + await self._history.record(asset.history_key, asset.source, taken_at=asset.taken_at) return result - async def push_current(self) -> DeliveryOutcome: + async def _display( + self, + renderer: Callable[[], RenderResult], + meta: DisplayMeta, + *, + template: str | None, + ) -> DisplayResult: + async with self._render_lock: + result = await asyncio.to_thread(renderer) + stored = await asyncio.to_thread( + self._current.save, + result, + source=meta.source, + title=meta.title, + details=meta.details, + push=meta.push, + ephemeral=meta.ephemeral, + expires_at=meta.expires_at if meta.ephemeral else None, + content_key=meta.content_key, + template=template, + ) + delivery: DeliveryOutcome | None = None + if meta.push: + delivery = await self._delivery.submit( + result.bin, + source=meta.source, + title=meta.title, + ephemeral=meta.ephemeral, + expires_at=meta.expires_at if meta.ephemeral else None, + content_key=meta.content_key, + ) + self._notify(stored) + return DisplayResult(image=stored, delivery=delivery) + + # --- Ephemeral support ---------------------------------------------------------------- + async def extend_expiry( + self, content_key: str, expires_at: datetime | None + ) -> CurrentImageMeta | None: + """Keep the current ephemeral image up longer if it shows ``content_key``. + + The queued upload (if any) is updated too; nothing is rendered or re-sent. + + Returns: + The updated metadata, or ``None`` when the current image is something else. + """ + async with self._render_lock: + updated = await asyncio.to_thread(self._current.extend_expiry, content_key, expires_at) + if updated is None: + return None + await self._delivery.extend_pending(content_key, expires_at) + self._notify(updated) + return updated + + async def revert_to_base(self, *, only_if_current: str | None = None) -> RevertOutcome: + """Show the previous non-ephemeral image again. + + ``current.*`` is restored from ``base.*``; the base ``.bin`` is (re)submitted only + when the frame may not be showing it already (see + :meth:`DeliveryService.frame_content_differs`), so a deep-sleeping frame is not + woken up for nothing. + + Args: + only_if_current: Revert only while the current image still has this SHA-256 + (an expiry must not undo a newer display). + """ + async with self._render_lock: + current = self._current.meta + base = self._current.base_meta + if only_if_current is not None and ( + current is None or current.sha256 != only_if_current + ): + return RevertOutcome(reverted=False, has_base=base is not None, image=current) + if base is None: + return RevertOutcome(reverted=False, has_base=False, image=current) + restored = await asyncio.to_thread(self._current.restore_base) + loaded = await asyncio.to_thread(self._current.read_bin, "base") + if restored is None or loaded is None: + return RevertOutcome(reverted=False, has_base=False, image=self._current.meta) + data, meta = loaded + delivery: DeliveryOutcome | None = None + panel_ok = meta.panel == self._config_store.config.fraimic.panel + if panel_ok and self._delivery.frame_content_differs(meta.sha256): + delivery = await self._delivery.submit(data, source=meta.source, title=meta.title) + elif not panel_ok: + logger.warning("The previous image was rendered for panel %s; not re-sent", meta.panel) + self._notify(restored) + return RevertOutcome( + reverted=True, + has_base=True, + pushed_base=delivery is not None, + delivery=delivery, + image=restored, + ) + + async def push_current(self, *, from_preview: bool = False) -> DeliveryOutcome: """Send the current image to the frame now, whatever the power mode. + Args: + from_preview: First make the latest preview (e.g. a ``push_to_fraimic=false`` + render) the current image, then send it. + Raises: - NoCurrentImageError: If nothing was rendered yet, or the current image was - rendered for a different panel than the one configured now. + NoCurrentImageError: If nothing was rendered yet, or the image was rendered for + a different panel than the one configured now. """ + if from_preview: + preview = self._current.preview_meta + if preview is None: + raise NoCurrentImageError("No preview has been rendered yet") + if preview.panel != self._config_store.config.fraimic.panel: + raise NoCurrentImageError( + f"The preview was rendered for panel {preview.panel}; render it again " + f"for panel {self._config_store.config.fraimic.panel} first" + ) + async with self._render_lock: + promoted = await asyncio.to_thread(self._current.promote_preview) + if promoted is None: + raise NoCurrentImageError("The preview files are missing or damaged") + self._notify(promoted) loaded = await asyncio.to_thread(self._current.read_bin) if loaded is None: raise NoCurrentImageError("No image has been rendered yet") @@ -118,5 +319,18 @@ async def push_current(self) -> DeliveryOutcome: f"for panel {self._config_store.config.fraimic.panel} first" ) return await self._delivery.submit( - data, source=meta.source, title=meta.title, immediate=True + data, + source=meta.source, + title=meta.title, + immediate=True, + ephemeral=meta.ephemeral, + expires_at=meta.expires_at, + content_key=meta.content_key, ) + + def _notify(self, meta: CurrentImageMeta) -> None: + for listener in self._listeners: + try: + listener(meta) + except Exception: + logger.exception("Display listener failed") diff --git a/tests/test_api_immich.py b/tests/test_api_immich.py index dca2531..7e8b221 100644 --- a/tests/test_api_immich.py +++ b/tests/test_api_immich.py @@ -114,7 +114,7 @@ def test_display_uses_face_regions_for_the_crop(make_client: ClientFactory) -> N client = immich_client(make_client) with servers(fake, frame=False): assert show(client, persons=["Alice"], push_to_fraimic=False).status_code == 200 - current = np.asarray(Image.open(io.BytesIO(client.get("/api/current.jpg").content))) + current = np.asarray(Image.open(io.BytesIO(client.get("/api/preview.jpg").content))) red = (current[..., 0] > 200) & (current[..., 1] < 80) & (current[..., 2] < 80) assert red.sum() > 1000 # the face is inside the 1200x1600 crop diff --git a/tests/test_api_phase2.py b/tests/test_api_phase2.py index 3de885c..7a87fd5 100644 --- a/tests/test_api_phase2.py +++ b/tests/test_api_phase2.py @@ -124,7 +124,8 @@ def test_upload_landscape_uses_rotated_frame(frame_client: Callable[..., TestCli body = upload(client, push=False).json() assert body["image"]["frame_size"] == [1600, 1200] assert body["image"]["rotation"] == 90 - jpeg = Image.open(io.BytesIO(client.get("/api/current.jpg").content)) + assert client.get("/api/current.jpg").status_code == 404 # not pushed: preview only + jpeg = Image.open(io.BytesIO(client.get("/api/preview.jpg").content)) assert jpeg.size == (1600, 1200) @@ -223,7 +224,8 @@ def test_force_push(frame_client: Callable[..., TestClient]) -> None: assert client.post("/api/fraimic/push").status_code == 409 upload(client, push=False) - response = client.post("/api/fraimic/push") + assert client.post("/api/fraimic/push").status_code == 409 # only a preview exists + response = client.post("/api/fraimic/push", params={"from_preview": "true"}) assert response.status_code == 200 assert response.json()["status"] == "delivered" assert response.json()["reason"] == "force" @@ -235,7 +237,7 @@ def test_force_push_with_unreachable_frame_queues(frame_client: Callable[..., Te respx.get(INFO_URL).mock(side_effect=httpx.ConnectError("down")) client = frame_client() upload(client, push=False) - response = client.post("/api/fraimic/push") + response = client.post("/api/fraimic/push", params={"from_preview": "true"}) assert response.status_code == 202 assert response.json()["status"] == "queued" assert client.get("/api/status").json()["delivery"]["pending"] is True @@ -246,7 +248,7 @@ def test_force_push_refuses_image_for_other_panel(frame_client: Callable[..., Te client = frame_client() upload(client, push=False) assert client.put("/api/config", json={"fraimic": {"panel": "315"}}).status_code == 200 - response = client.post("/api/fraimic/push") + response = client.post("/api/fraimic/push", params={"from_preview": "true"}) assert response.status_code == 409 assert "panel 133" in response.json()["detail"] @@ -287,7 +289,8 @@ def test_new_mutating_routes_require_api_key(make_client: ClientFactory) -> None assert client.get("/api/current_dithered.png").status_code == 401 assert client.get("/api/fraimic/info").status_code == 200 assert upload(client, push=False, **{"X-API-Key": KEY}).status_code == 200 - assert client.get("/api/current.bin", params={"api_key": KEY}).status_code == 200 + assert client.get("/api/preview.jpg").status_code == 401 + assert client.get("/api/preview.jpg", params={"api_key": KEY}).status_code == 200 def test_status_before_any_image(make_client: ClientFactory) -> None: @@ -321,3 +324,20 @@ def test_upload_accepts_heic(frame_client: Callable[..., TestClient]) -> None: response = upload(client, push=False, data=buffer.getvalue()) assert response.status_code == 200, response.text assert response.json()["image"]["bin_size"] == 960_000 + + +def test_preview_endpoints_serve_the_latest_render(make_client: ClientFactory) -> None: + client = make_client() + assert client.get("/api/preview.jpg").status_code == 404 + assert client.get("/api/preview_dithered.png").status_code == 404 + body = upload(client, push=False).json() + assert body["delivery"] is None + assert body["image"]["pushed"] is False + jpeg = client.get("/api/preview.jpg") + assert jpeg.status_code == 200 and jpeg.headers["content-type"] == "image/jpeg" + etag = jpeg.headers["etag"] + assert client.get("/api/preview.jpg", headers={"If-None-Match": etag}).status_code == 304 + png = client.get("/api/preview_dithered.png") + assert png.status_code == 200 and png.content[:8] == b"\x89PNG\r\n\x1a\n" + assert client.head("/api/preview.jpg").status_code == 200 + assert client.get("/api/status").json()["current_image"] is None diff --git a/tests/test_current_image.py b/tests/test_current_image.py index 6f28ed5..028f4b7 100644 --- a/tests/test_current_image.py +++ b/tests/test_current_image.py @@ -1,6 +1,7 @@ from __future__ import annotations import json +from datetime import UTC, datetime, timedelta from pathlib import Path import pytest @@ -54,3 +55,125 @@ def test_missing_or_invalid_meta(tmp_path: Path, result: RenderResult) -> None: store.meta_path.write_text('{"source": 1}', encoding="utf-8") assert CurrentImageStore(tmp_path).load() is None + + +# --- slots --------------------------------------------------------------------------------- +@pytest.fixture(scope="module") +def other() -> RenderResult: + options = RenderOptions.from_config(RuntimeConfig()) + return render(Image.new("RGB", (300, 400), (200, 40, 40)), options) + + +def slot_shas(store: CurrentImageStore) -> dict[str, str | None]: + return { + slot: (meta.sha256 if (meta := store.slot_meta(slot)) else None) + for slot in ("current", "base", "preview") + } + + +@pytest.mark.parametrize( + ("push", "ephemeral", "slots"), + [ + (True, False, {"current", "base", "preview"}), + (True, True, {"current", "preview"}), + (False, False, {"preview"}), + (False, True, {"preview"}), + ], +) +def test_slot_policy( + tmp_path: Path, result: RenderResult, push: bool, ephemeral: bool, slots: set[str] +) -> None: + store = CurrentImageStore(tmp_path) + store.save(result, source="x", push=push, ephemeral=ephemeral) + written = {slot for slot, sha in slot_shas(store).items() if sha == result.sha256} + assert written == slots + for slot in ("current", "base", "preview"): + assert store.paths(slot).meta.exists() == (slot in slots) # type: ignore[arg-type] + + +def test_preview_render_leaves_the_current_image_alone( + tmp_path: Path, result: RenderResult, other: RenderResult +) -> None: + store = CurrentImageStore(tmp_path) + store.save(result, source="immich") + store.save(other, source="tmdb", push=False) + assert store.meta is not None and store.meta.sha256 == result.sha256 + assert store.preview_meta is not None and store.preview_meta.sha256 == other.sha256 + assert store.preview_meta.pushed is False + + +def test_restore_base_brings_back_the_previous_image( + tmp_path: Path, result: RenderResult, other: RenderResult +) -> None: + store = CurrentImageStore(tmp_path) + assert store.restore_base() is None + store.save(result, source="immich", title="Beach") + store.save(other, source="music", ephemeral=True, content_key="song") + assert store.meta is not None and store.meta.ephemeral + assert store.base_meta is not None and store.base_meta.sha256 == result.sha256 + + restored = store.restore_base() + assert restored is not None and restored.title == "Beach" + assert store.meta == restored + assert store.bin_path.read_bytes() == result.bin + reloaded = CurrentImageStore(tmp_path) + assert reloaded.load() == restored + + +def test_restore_base_refuses_a_damaged_base(tmp_path: Path, result: RenderResult) -> None: + store = CurrentImageStore(tmp_path) + store.save(result, source="immich") + store.paths("base").bin.write_bytes(b"\x00" * 960_000) + assert store.restore_base() is None + assert store.base_meta is None + + +def test_legacy_current_image_seeds_the_base_slot(tmp_path: Path, result: RenderResult) -> None: + store = CurrentImageStore(tmp_path) + store.save(result, source="upload") + for slot in ("base", "preview"): + for path in store.paths(slot).all(): # type: ignore[arg-type] + path.unlink() + reloaded = CurrentImageStore(tmp_path) + reloaded.load() + assert reloaded.base_meta is not None and reloaded.base_meta.sha256 == result.sha256 + assert reloaded.paths("base").bin.read_bytes() == result.bin + + +def test_an_ephemeral_current_image_does_not_seed_the_base( + tmp_path: Path, result: RenderResult +) -> None: + store = CurrentImageStore(tmp_path) + store.save(result, source="music", ephemeral=True) + assert CurrentImageStore(tmp_path).load() is not None + assert not store.paths("base").meta.exists() + + +def test_extend_expiry_only_touches_matching_ephemeral_content( + tmp_path: Path, result: RenderResult +) -> None: + store = CurrentImageStore(tmp_path) + start = datetime(2026, 11, 15, 12, 0, tzinfo=UTC) + store.save(result, source="music", ephemeral=True, expires_at=start, content_key="a") + assert store.extend_expiry("b", start + timedelta(minutes=5)) is None + updated = store.extend_expiry("a", start + timedelta(minutes=5)) + assert updated is not None and updated.expires_at == start + timedelta(minutes=5) + assert CurrentImageStore(tmp_path).load() == updated + assert updated.expired(start + timedelta(minutes=6)) + assert not updated.expired(start + timedelta(minutes=4)) + + +def test_promote_preview(tmp_path: Path, result: RenderResult, other: RenderResult) -> None: + store = CurrentImageStore(tmp_path) + assert store.promote_preview() is None + store.save(result, source="immich") + store.save(other, source="tmdb", push=False) + promoted = store.promote_preview() + assert promoted is not None and promoted.pushed + assert store.meta == promoted and store.base_meta == promoted + assert store.bin_path.read_bytes() == other.bin + + store.save(result, source="music", push=False, ephemeral=True) + ephemeral = store.promote_preview() + assert ephemeral is not None and store.meta == ephemeral + assert store.base_meta == promoted # an ephemeral preview never becomes the base From ceeca7bfafa44757cd0192d232e4670426bfdca5 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sun, 15 Nov 2026 15:41:03 +0100 Subject: [PATCH 53/86] feat: revert expired ephemeral images and add queue endpoints EphemeralService ends ephemeral images (now playing, posters) on expiry or cancellation: a timer sleeps until the current image's expires_at, the delivery drop handler covers images that expired while queued for a sleeping frame, and DELETE /api/queue/ephemeral cancels on demand. The previous non-ephemeral image is restored and re-sent only if the frame may not show it; the scheduler hold is lifted, and a background refresh replays the active rule when no previous image exists. GET /api/queue exposes the pending upload, the last delivery and the ephemeral state, which /api/status now includes too. Ephemeral Immich, smart-search and upload pushes no longer become the restorable image. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- app/api/deps.py | 7 + app/api/routes/display.py | 7 +- app/api/routes/immich.py | 4 +- app/api/routes/queue.py | 61 +++++++ app/api/routes/system.py | 7 + app/main.py | 13 ++ app/providers/immich/models.py | 3 +- app/services/display.py | 13 +- app/services/ephemeral.py | 260 ++++++++++++++++++++++++++++++ app/services/scheduler.py | 40 ++++- tests/test_api_queue.py | 97 +++++++++++ tests/test_ephemeral_service.py | 277 ++++++++++++++++++++++++++++++++ tests/test_scheduler_service.py | 42 +++++ 13 files changed, 825 insertions(+), 6 deletions(-) create mode 100644 app/api/routes/queue.py create mode 100644 app/services/ephemeral.py create mode 100644 tests/test_api_queue.py create mode 100644 tests/test_ephemeral_service.py diff --git a/app/api/deps.py b/app/api/deps.py index c408989..4357b48 100644 --- a/app/api/deps.py +++ b/app/api/deps.py @@ -13,6 +13,7 @@ from app.services.current_image import CurrentImageStore from app.services.delivery import DeliveryService from app.services.display import DisplayService +from app.services.ephemeral import EphemeralService from app.services.scheduler import SchedulerService @@ -56,6 +57,11 @@ def get_scheduler_service(request: Request) -> SchedulerService: return cast(SchedulerService, request.app.state.scheduler_service) +def get_ephemeral_service(request: Request) -> EphemeralService: + """Lifetime manager of ephemeral images (expiry, cancellation, revert).""" + return cast(EphemeralService, request.app.state.ephemeral_service) + + def get_people_directory(request: Request) -> PeopleDirectory: """Cache of the people known to each Immich account.""" return cast(PeopleDirectory, request.app.state.people_directory) @@ -70,3 +76,4 @@ def get_people_directory(request: Request) -> PeopleDirectory: ImmichProviderDep = Annotated[ImmichProvider, Depends(get_immich_provider)] PeopleDirectoryDep = Annotated[PeopleDirectory, Depends(get_people_directory)] SchedulerDep = Annotated[SchedulerService, Depends(get_scheduler_service)] +EphemeralServiceDep = Annotated[EphemeralService, Depends(get_ephemeral_service)] diff --git a/app/api/routes/display.py b/app/api/routes/display.py index 2623399..6d50cc0 100644 --- a/app/api/routes/display.py +++ b/app/api/routes/display.py @@ -55,7 +55,11 @@ async def display_upload( ), ] = True, ephemeral: Annotated[ - bool, Form(description="Temporary push (accepted for symmetry; uploads are never replayed)") + bool, + Form( + description="Temporary push: the previous image comes back after " + "DELETE /api/queue/ephemeral (uploads are never replayed)" + ), ] = False, hold_minutes: Annotated[ int | None, @@ -86,6 +90,7 @@ async def display_upload( details={"filename": title, "bytes": len(data)}, fit=fit, push=push_to_fraimic, + ephemeral=ephemeral, ) except InvalidImageError as exc: raise HTTPException(status_code=415, detail=str(exc)) from exc diff --git a/app/api/routes/immich.py b/app/api/routes/immich.py index 49b9ce5..b14d523 100644 --- a/app/api/routes/immich.py +++ b/app/api/routes/immich.py @@ -77,7 +77,9 @@ async def show_immich( except ProviderError as exc: raise provider_http_error(exc) from exc try: - result = await display.display_asset(asset, fit=request.fit, push=request.push_to_fraimic) + result = await display.display_asset( + asset, fit=request.fit, push=request.push_to_fraimic, ephemeral=request.ephemeral + ) except InvalidImageError as exc: raise HTTPException( status_code=502, detail="Immich returned an image that cannot be decoded" diff --git a/app/api/routes/queue.py b/app/api/routes/queue.py new file mode 100644 index 0000000..3eda9ff --- /dev/null +++ b/app/api/routes/queue.py @@ -0,0 +1,61 @@ +"""Upload queue inspection and ephemeral image cancellation (Home Assistant friendly). + +* ``GET /api/queue`` - what waits for the frame (an expired image is never listed), the + last delivery and the ephemeral image currently shown or queued. +* ``DELETE /api/queue/ephemeral`` - playback stopped: drop the queued ephemeral image and + bring the previous image back right away (idempotent; always ``200``). +""" + +from __future__ import annotations + +from fastapi import APIRouter, Security +from pydantic import BaseModel, Field + +from app.api.deps import DeliveryServiceDep, EphemeralServiceDep +from app.core.auth import api_key_scheme +from app.core.config_models import PowerMode +from app.services.delivery import LastDelivery, PendingUpload +from app.services.ephemeral import CancelOutcome, EphemeralView + +router = APIRouter(prefix="/api/queue", tags=["queue"]) + + +class QueueView(BaseModel): + """The upload queue and the ephemeral image state.""" + + power_mode: PowerMode + pending: PendingUpload | None = Field( + description="The image waiting for the frame (expired images are dropped, not listed)" + ) + last_delivery: LastDelivery | None + ephemeral: EphemeralView + + +@router.get("", response_model=QueueView, summary="Inspect the upload queue") +async def get_queue(delivery: DeliveryServiceDep, ephemeral: EphemeralServiceDep) -> QueueView: + """The pending upload, the last delivery and the current ephemeral image.""" + snapshot = delivery.snapshot() + return QueueView( + power_mode=snapshot.power_mode, + pending=snapshot.pending, + last_delivery=snapshot.last_delivery, + ephemeral=ephemeral.view(), + ) + + +@router.delete( + "/ephemeral", + response_model=CancelOutcome, + dependencies=[Security(api_key_scheme)], + summary="Cancel the ephemeral image (playback stopped)", +) +async def cancel_ephemeral(ephemeral: EphemeralServiceDep) -> CancelOutcome: + """Drop a queued movie poster or album cover and restore the previous image. + + Call it when playback pauses or stops. The previous non-ephemeral image becomes the + current image again; it is re-sent only if the frame may not be showing it (a sleeping + frame that never received the cover is not woken up). Without a previous image, a + background refresh replays the active rule. Calling it when nothing is ephemeral is a + harmless no-op (``cancelled: false``). + """ + return await ephemeral.cancel() diff --git a/app/api/routes/system.py b/app/api/routes/system.py index b5c68d7..eea0d60 100644 --- a/app/api/routes/system.py +++ b/app/api/routes/system.py @@ -13,11 +13,13 @@ ConfigStoreDep, CurrentImageStoreDep, DeliveryServiceDep, + EphemeralServiceDep, SchedulerDep, SettingsDep, ) from app.services.current_image import CurrentImageMeta from app.services.delivery import FrameTelemetry, LastDelivery, PendingUpload +from app.services.ephemeral import EphemeralView from app.services.scheduler import SchedulerSnapshot router = APIRouter(prefix="/api", tags=["system"]) @@ -70,6 +72,9 @@ class StatusResponse(BaseModel): default=None, description="Metadata of the current image (null before the first one)" ) scheduler: SchedulerSnapshot = Field(description="Autonomous refresh: timer and last run") + ephemeral: EphemeralView = Field( + description="Temporary image (now playing, poster) shown or queued, and its expiry" + ) services: ServiceConfigured @@ -87,6 +92,7 @@ async def status( current: CurrentImageStoreDep, delivery: DeliveryServiceDep, scheduler: SchedulerDep, + ephemeral: EphemeralServiceDep, ) -> StatusResponse: """Overall system status, queue state and current image (no secrets, no network).""" config = store.config @@ -113,6 +119,7 @@ async def status( ), current_image=current.meta, scheduler=scheduler.snapshot(), + ephemeral=ephemeral.view(), services=ServiceConfigured( immich=bool(config.immich.accounts), tmdb=bool(config.tmdb.api_key.get_secret_value()), diff --git a/app/main.py b/app/main.py index 41a9b38..79e8535 100644 --- a/app/main.py +++ b/app/main.py @@ -24,6 +24,7 @@ from app.api.routes import fraimic as fraimic_routes from app.api.routes import images as image_routes from app.api.routes import immich as immich_routes +from app.api.routes import queue as queue_routes from app.api.routes import refresh as refresh_routes from app.api.routes import smart_mix as smart_mix_routes from app.api.routes import system as system_routes @@ -40,6 +41,7 @@ from app.services.current_image import CurrentImageStore from app.services.delivery import DeliveryService from app.services.display import DisplayService +from app.services.ephemeral import EphemeralService from app.services.scheduler import SchedulerService, immich_runner logger = logging.getLogger(__name__) @@ -117,6 +119,13 @@ async def _on_config_change(_: RuntimeConfig) -> None: has_pending=lambda: delivery.pending is not None, ) scheduler.load() + ephemeral = EphemeralService( + current_store, + display, + delivery, + clear_hold=scheduler.clear_hold, + refresh=lambda: scheduler.run_in_background("revert"), + ) app.state.config_store = config_store app.state.history_store = history_store @@ -126,7 +135,9 @@ async def _on_config_change(_: RuntimeConfig) -> None: app.state.people_directory = people app.state.immich_provider = immich app.state.scheduler_service = scheduler + app.state.ephemeral_service = ephemeral + await ephemeral.start() # before the delivery worker can drop an expired image await delivery.start() await scheduler.start() config = config_store.config @@ -146,6 +157,7 @@ async def _on_config_change(_: RuntimeConfig) -> None: yield finally: await scheduler.stop() + await ephemeral.stop() await delivery.stop() logger.info("Smart Frame Engine stopped") @@ -200,6 +212,7 @@ async def _validation_handler(_: Request, exc: RequestValidationError) -> JSONRe app.include_router(smart_mix_routes.display_router) app.include_router(smart_mix_routes.router) app.include_router(fraimic_routes.router) + app.include_router(queue_routes.router) @app.get("/", include_in_schema=False) async def index(request: Request) -> RedirectResponse: diff --git a/app/providers/immich/models.py b/app/providers/immich/models.py index b27cf1c..5c7581b 100644 --- a/app/providers/immich/models.py +++ b/app/providers/immich/models.py @@ -195,7 +195,8 @@ class ImmichDisplayRequest(BaseModel): ephemeral: bool = Field( default=False, description="Temporary push: do not make this request the rule replayed by " - "POST /api/refresh when nothing is pinned", + "POST /api/refresh when nothing is pinned, nor the image restored after " + "DELETE /api/queue/ephemeral", ) hold_minutes: int | None = Field( default=None, diff --git a/app/services/display.py b/app/services/display.py index 2eb3884..ec19687 100644 --- a/app/services/display.py +++ b/app/services/display.py @@ -75,6 +75,9 @@ class RevertOutcome(BaseModel): reverted: bool = Field(description="current.* now shows the previous image again") has_base: bool = Field(description="Whether a previous non-ephemeral image exists") + stale: bool = Field( + default=False, description="Nothing done: a newer image replaced the expected one" + ) pushed_base: bool = Field( default=False, description="The previous image was re-sent (or queued) for the frame" ) @@ -261,7 +264,9 @@ async def revert_to_base(self, *, only_if_current: str | None = None) -> RevertO if only_if_current is not None and ( current is None or current.sha256 != only_if_current ): - return RevertOutcome(reverted=False, has_base=base is not None, image=current) + return RevertOutcome( + reverted=False, has_base=base is not None, stale=True, image=current + ) if base is None: return RevertOutcome(reverted=False, has_base=False, image=current) restored = await asyncio.to_thread(self._current.restore_base) @@ -272,7 +277,11 @@ async def revert_to_base(self, *, only_if_current: str | None = None) -> RevertO delivery: DeliveryOutcome | None = None panel_ok = meta.panel == self._config_store.config.fraimic.panel if panel_ok and self._delivery.frame_content_differs(meta.sha256): - delivery = await self._delivery.submit(data, source=meta.source, title=meta.title) + # Queue and wake the worker rather than uploading inline: callers (a Home + # Assistant webhook) must not wait for a full upload. + delivery = await self._delivery.submit( + data, source=meta.source, title=meta.title, immediate=False + ) elif not panel_ok: logger.warning("The previous image was rendered for panel %s; not re-sent", meta.panel) self._notify(restored) diff --git a/app/services/ephemeral.py b/app/services/ephemeral.py new file mode 100644 index 0000000..842e3cd --- /dev/null +++ b/app/services/ephemeral.py @@ -0,0 +1,260 @@ +"""Lifetime of ephemeral images (now playing, movie posters). + +An ephemeral image is pushed for a while and must not outlive what it illustrates: once +the song or the movie is over, the previous non-ephemeral image (the *base*) comes back. + +:class:`EphemeralService` handles both ways an ephemeral image ends: + +* **Expiry** - a timer sleeps until the ``expires_at`` of the current ephemeral image. The + delivery service also drops an expired image that is still queued for a sleeping frame + and calls :meth:`EphemeralService.handle_dropped`. +* **Cancellation** - ``DELETE /api/queue/ephemeral`` (e.g. Home Assistant on pause/stop) + drops the queued image and reverts immediately. + +Reverting restores ``current.*`` from ``base.*``, re-sends the base image only when the +frame may not be showing it already (a sleeping frame that never received the ephemeral +image is left alone), and lifts the scheduler hold that protected the ephemeral image. +When there is no base image yet, a background refresh replays the active rule instead. +""" + +from __future__ import annotations + +import asyncio +import contextlib +import logging +from collections.abc import Awaitable, Callable +from datetime import UTC, datetime +from typing import Final, Literal + +from pydantic import AwareDatetime, BaseModel, Field + +from app.services.current_image import CurrentImageMeta, CurrentImageStore +from app.services.delivery import DeliveryOutcome, DeliveryService, DropReason, PendingUpload +from app.services.display import DisplayService, RevertOutcome + +logger = logging.getLogger(__name__) + +EndReason = Literal["expired", "cancelled"] +Clock = Callable[[], datetime] +HoldClearer = Callable[[], Awaitable[None]] +Refresher = Callable[[], bool] + +#: The timer never sleeps longer than this, so clock jumps (suspend, NTP) are caught up. +MAX_TIMER_SLEEP_S: Final = 300.0 +TIMER_ERROR_PAUSE_S: Final = 5.0 + + +def _utcnow() -> datetime: + return datetime.now(UTC) + + +class EphemeralView(BaseModel): + """The ephemeral image currently shown or queued (``GET /api/queue``, ``/api/status``).""" + + active: bool = Field(description="Whether the current image is ephemeral") + source: str | None = None + title: str | None = None + template: str | None = None + expires_at: AwareDatetime | None = Field( + default=None, description="When the previous image comes back (null = until replaced)" + ) + pending: bool = Field(description="Whether an ephemeral image waits for a sleeping frame") + has_base: bool = Field(description="Whether a previous image exists to come back to") + + +class CancelOutcome(BaseModel): + """Result of ``DELETE /api/queue/ephemeral``.""" + + cancelled: bool = Field(description="An ephemeral image was queued or shown") + dropped_pending: bool = Field(description="A queued ephemeral upload was discarded") + reverted: bool = Field(description="The previous image is the current image again") + pushed_base: bool = Field(description="The previous image was re-sent (or queued)") + refreshing: bool = Field( + description="No previous image existed: a background refresh was started instead" + ) + delivery: DeliveryOutcome | None = None + image: CurrentImageMeta | None = Field(default=None, description="The current image now") + + +class EphemeralService: + """Ends ephemeral images on expiry or cancellation and restores the previous image.""" + + def __init__( + self, + current: CurrentImageStore, + display: DisplayService, + delivery: DeliveryService, + *, + clear_hold: HoldClearer | None = None, + refresh: Refresher | None = None, + clock: Clock = _utcnow, + ) -> None: + """Create the service (call :meth:`start`). + + Args: + current: The image slots. + display: Performs the revert (restore + conditional re-send). + delivery: The upload queue (cancellation, expired-image drops). + clear_hold: Lifts the scheduler hold that protected the ephemeral image. + refresh: Starts a background refresh when there is no previous image; returns + whether one was started. + clock: Returns the current aware time. + """ + self._current = current + self._display = display + self._delivery = delivery + self._clear_hold = clear_hold + self._refresh = refresh + self._clock = clock + self._lock = asyncio.Lock() + self._wake = asyncio.Event() + self._task: asyncio.Task[None] | None = None + self._ended: str | None = None # SHA-256 of the last ephemeral image ended + + # --- Lifecycle ------------------------------------------------------------------------ + async def start(self) -> None: + """Hook into the display and delivery services and start the expiry timer. + + Call it before :meth:`DeliveryService.start` so an expired image restored from + disk is reverted as soon as the delivery worker drops it. + """ + self._display.add_listener(self._on_display) + self._delivery.set_drop_handler(self.handle_dropped) + if self._task is None: + self._task = asyncio.create_task(self._run(), name="ephemeral-expiry-timer") + + async def stop(self) -> None: + """Stop the expiry timer.""" + task, self._task = self._task, None + self._delivery.set_drop_handler(None) + if task is not None: + task.cancel() + with contextlib.suppress(asyncio.CancelledError): + await task + + def rearm(self) -> None: + """Recompute the next expiry (call after the current image changed).""" + self._wake.set() + + # --- Read access ---------------------------------------------------------------------- + def next_expiry(self) -> datetime | None: + """When the current ephemeral image expires (``None`` when nothing will).""" + meta = self._current.meta + if meta is None or not meta.ephemeral or meta.expires_at is None: + return None + if meta.sha256 == self._ended: + return None # already ended (e.g. nothing to revert to) + return meta.expires_at + + def view(self) -> EphemeralView: + """The ephemeral image currently shown or queued.""" + meta = self._current.meta + pending = self._delivery.pending + active = meta is not None and meta.ephemeral + return EphemeralView( + active=active, + source=meta.source if active and meta else None, + title=meta.title if active and meta else None, + template=meta.template if active and meta else None, + expires_at=meta.expires_at if active and meta else None, + pending=pending is not None and pending.ephemeral, + has_base=self._current.base_meta is not None, + ) + + # --- Operations ----------------------------------------------------------------------- + async def cancel(self) -> CancelOutcome: + """End the ephemeral image now: drop it from the queue and restore the previous one.""" + async with self._lock: + dropped = await self._delivery.cancel_ephemeral() + meta = self._current.meta + if meta is None or not meta.ephemeral: + return CancelOutcome( + cancelled=dropped is not None, + dropped_pending=dropped is not None, + reverted=False, + pushed_base=False, + refreshing=False, + image=meta, + ) + revert, refreshing = await self._end_locked(meta, "cancelled") + self.rearm() + return CancelOutcome( + cancelled=True, + dropped_pending=dropped is not None, + reverted=revert.reverted, + pushed_base=revert.pushed_base, + refreshing=refreshing, + delivery=revert.delivery, + image=revert.image, + ) + + async def expire_if_due(self) -> RevertOutcome | None: + """Revert the current ephemeral image if its expiry has passed. + + Returns: + What the revert did, or ``None`` when nothing was due. + """ + async with self._lock: + meta = self._current.meta + if meta is None or meta.sha256 == self._ended or not meta.expired(self._clock()): + return None + revert, _ = await self._end_locked(meta, "expired") + self.rearm() + return revert + + async def handle_dropped(self, pending: PendingUpload, reason: DropReason) -> None: + """Delivery drop handler: an expired image was discarded before reaching the frame.""" + async with self._lock: + meta = self._current.meta + if meta is None or meta.sha256 != pending.sha256 or meta.sha256 == self._ended: + return # a newer image is current: nothing to undo + await self._end_locked(meta, reason) + self.rearm() + + # --- Internals ------------------------------------------------------------------------ + async def _end_locked( + self, meta: CurrentImageMeta, reason: EndReason + ) -> tuple[RevertOutcome, bool]: + """Restore the previous image (caller holds ``_lock``).""" + revert = await self._display.revert_to_base(only_if_current=meta.sha256) + if revert.stale: + return revert, False + self._ended = meta.sha256 + if self._clear_hold is not None: + await self._clear_hold() + refreshing = False + if not revert.reverted and self._refresh is not None: + refreshing = self._refresh() + logger.info( + "Ephemeral image %r %s: %s", + meta.title or meta.source, + reason, + "previous image restored" + if revert.reverted + else ("refreshing" if refreshing else "no previous image to restore"), + ) + return revert, refreshing + + def _on_display(self, meta: CurrentImageMeta) -> None: + if meta.sha256 != self._ended: + self._ended = None + self.rearm() + + def _timeout(self) -> float: + expiry = self.next_expiry() + if expiry is None: + return MAX_TIMER_SLEEP_S + return min(MAX_TIMER_SLEEP_S, max(0.0, (expiry - self._clock()).total_seconds())) + + async def _run(self) -> None: + while True: + with contextlib.suppress(TimeoutError): + await asyncio.wait_for(self._wake.wait(), self._timeout()) + self._wake.clear() + try: + await self.expire_if_due() + except asyncio.CancelledError: + raise + except Exception: + logger.exception("Ending an expired ephemeral image failed") + await asyncio.sleep(TIMER_ERROR_PAUSE_S) diff --git a/app/services/scheduler.py b/app/services/scheduler.py index 7d1ae1e..0d036ec 100644 --- a/app/services/scheduler.py +++ b/app/services/scheduler.py @@ -29,6 +29,7 @@ from __future__ import annotations import asyncio +import contextlib import logging from collections.abc import Awaitable, Callable, Mapping from dataclasses import dataclass @@ -58,7 +59,7 @@ DEFAULT_MIN_DELAY_S: Final = 30.0 _MAX_BACKOFF_EXPONENT: Final = 16 -RefreshReason = Literal["scheduled", "manual"] +RefreshReason = Literal["scheduled", "manual", "revert"] RunStatus = Literal["ok", "failed", "skipped"] RuleSource = Literal["pinned", "smart_mix", "last"] Clock = Callable[[], datetime] @@ -272,6 +273,7 @@ def __init__( self._scheduler: AsyncIOScheduler | None = None self._next_run_at: datetime | None = None self._listening = False + self._background: set[asyncio.Task[None]] = set() # --- Lifecycle ---------------------------------------------------------------------- def load(self) -> SchedulerState: @@ -300,6 +302,12 @@ async def start(self) -> None: async def stop(self) -> None: """Stop the timer (a refresh in progress is cancelled).""" + for task in list(self._background): + task.cancel() + for task in list(self._background): + with contextlib.suppress(asyncio.CancelledError): + await task + self._background.clear() scheduler, self._scheduler = self._scheduler, None if scheduler is not None and scheduler.running: scheduler.shutdown(wait=False) @@ -512,6 +520,36 @@ async def record_manual( await self._save(**update) self._arm() + async def clear_hold(self) -> None: + """Lift the protection of a pushed image (e.g. an ephemeral image was reverted).""" + if self._state.hold_until is None: + return + await self._save(hold_until=None) + self._arm() + + def run_in_background(self, reason: RefreshReason = "revert") -> bool: + """Start :meth:`run` without waiting; failures are logged, never raised. + + Returns: + Whether a refresh was started (``False`` while one is already running). + """ + if self._lock.locked(): + return False + task = asyncio.create_task(self._run_quietly(reason), name=f"refresh-{reason}") + self._background.add(task) + task.add_done_callback(self._background.discard) + return True + + async def _run_quietly(self, reason: RefreshReason) -> None: + try: + await self.run(reason) + except asyncio.CancelledError: + raise + except (RefreshError, ProviderError, InvalidImageError) as exc: + logger.info("Background refresh (%s) did not run: %s", reason, _safe_detail(exc)) + except Exception: + logger.exception("Background refresh (%s) failed", reason) + async def set_context(self, context: MixContext | None) -> None: """Set (or clear with ``None``) the temporary Smart Mix boost.""" await self._save(context=context) diff --git a/tests/test_api_queue.py b/tests/test_api_queue.py new file mode 100644 index 0000000..0170343 --- /dev/null +++ b/tests/test_api_queue.py @@ -0,0 +1,97 @@ +from __future__ import annotations + +import io + +import numpy as np +from fastapi.testclient import TestClient +from PIL import Image + +from tests.conftest import ClientFactory + +KEY = "queue-key" + + +def jpeg(color: tuple[int, int, int]) -> bytes: + buffer = io.BytesIO() + pixels = np.full((480, 640, 3), color, dtype=np.uint8) + Image.fromarray(pixels).save(buffer, format="JPEG") + return buffer.getvalue() + + +def upload( + client: TestClient, color: tuple[int, int, int], *, ephemeral: bool, **headers: str +) -> dict[str, object]: + response = client.post( + "/api/display/upload", + files={"file": ("photo.jpg", jpeg(color), "image/jpeg")}, + data={"ephemeral": "true" if ephemeral else "false"}, + headers=headers, + ) + assert response.status_code == 200, response.text + body: dict[str, object] = response.json() + return body + + +def deepsleep_client(make_client: ClientFactory, **overrides: object) -> TestClient: + return make_client(fraimic_host="frame.test", fraimic_power_mode="deepsleep", **overrides) + + +def test_queue_is_empty_at_first(make_client: ClientFactory) -> None: + body = deepsleep_client(make_client).get("/api/queue").json() + assert body["power_mode"] == "deepsleep" + assert body["pending"] is None + assert body["last_delivery"] is None + assert body["ephemeral"] == { + "active": False, + "source": None, + "title": None, + "template": None, + "expires_at": None, + "pending": False, + "has_base": False, + } + + +def test_cancel_reverts_an_ephemeral_upload_to_the_previous_image( + make_client: ClientFactory, +) -> None: + client = deepsleep_client(make_client) + base = upload(client, (30, 90, 160), ephemeral=False) + upload(client, (200, 40, 40), ephemeral=True) + + queue = client.get("/api/queue").json() + assert queue["ephemeral"]["active"] and queue["ephemeral"]["pending"] + assert queue["pending"]["ephemeral"] is True + status = client.get("/api/status").json() + assert status["ephemeral"]["active"] is True + + outcome = client.delete("/api/queue/ephemeral") + assert outcome.status_code == 200 + body = outcome.json() + assert body["cancelled"] and body["dropped_pending"] and body["reverted"] + assert body["pushed_base"] # the sleeping frame never received anything yet + assert body["image"]["sha256"] == base["image"]["sha256"] # type: ignore[index] + + queue = client.get("/api/queue").json() + assert not queue["ephemeral"]["active"] + assert queue["pending"]["sha256"] == base["image"]["sha256"] # type: ignore[index] + assert queue["pending"]["ephemeral"] is False + current = client.get("/api/status").json()["current_image"] + assert current["sha256"] == base["image"]["sha256"] # type: ignore[index] + + +def test_cancel_is_a_harmless_no_op(make_client: ClientFactory) -> None: + client = deepsleep_client(make_client) + upload(client, (30, 90, 160), ephemeral=False) + body = client.delete("/api/queue/ephemeral").json() + assert body["cancelled"] is False + assert body["reverted"] is False + assert client.get("/api/queue").json()["pending"] is not None # untouched + + +def test_cancel_requires_the_api_key(make_client: ClientFactory) -> None: + client = deepsleep_client(make_client, app_api_key=KEY) + assert client.get("/api/queue").status_code == 200 + assert client.delete("/api/queue/ephemeral").status_code == 401 + response = client.delete("/api/queue/ephemeral", headers={"X-API-Key": KEY}) + assert response.status_code == 200 diff --git a/tests/test_ephemeral_service.py b/tests/test_ephemeral_service.py new file mode 100644 index 0000000..1a75058 --- /dev/null +++ b/tests/test_ephemeral_service.py @@ -0,0 +1,277 @@ +from __future__ import annotations + +import asyncio +import io +from collections.abc import AsyncIterator, Callable +from dataclasses import dataclass, field +from datetime import UTC, datetime, timedelta +from pathlib import Path +from typing import Any + +import pytest +import respx +from PIL import Image + +from app.core.config_store import ConfigStore +from app.core.history_store import HistoryStore +from app.services.current_image import CurrentImageStore +from app.services.delivery import DeliveryService +from app.services.display import DisplayService +from app.services.ephemeral import EphemeralService + +BASE = "http://frame.test" +INFO_URL = f"{BASE}/api/info" +IMAGE_URL = f"{BASE}/api/image" +INFO = {"battery": {"percent": 80}} + + +class FakeClock: + def __init__(self) -> None: + self.now = datetime(2026, 11, 15, 20, 0, tzinfo=UTC) + + def __call__(self) -> datetime: + return self.now + + def advance(self, seconds: float) -> None: + self.now += timedelta(seconds=seconds) + + +def png(color: tuple[int, int, int]) -> bytes: + buffer = io.BytesIO() + Image.new("RGB", (240, 320), color).save(buffer, format="PNG") + return buffer.getvalue() + + +@dataclass +class Env: + clock: FakeClock + current: CurrentImageStore + delivery: DeliveryService + display: DisplayService + ephemeral: EphemeralService + holds_cleared: list[bool] = field(default_factory=list) + refreshes: list[bool] = field(default_factory=list) + + async def show(self, color: tuple[int, int, int], **kwargs: Any) -> str: + result = await self.display.display_bytes(png(color), source="test", **kwargs) + return result.image.sha256 + + +EnvFactory = Callable[..., Env] + + +@pytest.fixture +async def make_env(tmp_path: Path) -> AsyncIterator[EnvFactory]: + created: list[Env] = [] + + def _make(power_mode: str = "deepsleep", *, real_clock: bool = False) -> Env: + clock = FakeClock() + config = ConfigStore( + tmp_path / "config.json", + {"fraimic": {"host": "frame.test", "power_mode": power_mode}}, + ) + config.load() + history = HistoryStore(tmp_path / "history.json") + history.load() + current = CurrentImageStore(tmp_path / "cache") + current.load() + clock_kwargs: dict[str, Any] = {} if real_clock else {"clock": clock} + delivery = DeliveryService( + tmp_path / "queue", + config, + last_delivery_path=tmp_path / "last_delivery.json", + **clock_kwargs, + ) + delivery.load() + display = DisplayService(config, current, delivery, history) + env = Env(clock, current, delivery, display, None) # type: ignore[arg-type] + + async def clear_hold() -> None: + env.holds_cleared.append(True) + + def refresh() -> bool: + env.refreshes.append(True) + return True + + env.ephemeral = EphemeralService( + current, display, delivery, clear_hold=clear_hold, refresh=refresh, **clock_kwargs + ) + created.append(env) + return env + + yield _make + for env in created: + await env.ephemeral.stop() + await env.delivery.stop() + + +async def eventually(condition: Callable[[], bool], timeout: float = 5.0) -> None: + deadline = asyncio.get_running_loop().time() + timeout + while not condition(): + if asyncio.get_running_loop().time() > deadline: + raise AssertionError("condition not met in time") + await asyncio.sleep(0.02) + + +@respx.mock +async def test_expired_queued_cover_is_dropped_and_frame_is_left_alone( + make_env: EnvFactory, +) -> None: + """Deep sleep: the song ended before the frame woke up; it still shows the photo.""" + respx.get(INFO_URL).respond(json=INFO) + upload = respx.post(IMAGE_URL).respond(200) + env = make_env("deepsleep") + await env.ephemeral.start() + base = await env.show((30, 90, 160)) + assert (await env.delivery.wakeup(wait=True)).status == "delivered" # type: ignore[union-attr] + + cover = await env.show( + (200, 40, 40), ephemeral=True, expires_at=env.clock.now + timedelta(minutes=3) + ) + assert env.current.meta is not None and env.current.meta.sha256 == cover + assert env.ephemeral.view().pending + + env.clock.advance(200) + outcome = await env.delivery.wakeup(wait=True) + assert outcome is not None and outcome.status == "dropped" + await eventually(lambda: bool(env.holds_cleared)) # the revert ran to completion + assert env.current.meta is not None and env.current.meta.sha256 == base + + assert upload.call_count == 1 # only the photo: the frame was never woken for nothing + assert env.delivery.pending is None + assert env.holds_cleared == [True] + assert env.refreshes == [] + assert not env.ephemeral.view().active + + +@respx.mock +async def test_expiry_of_a_delivered_cover_resends_the_previous_image( + make_env: EnvFactory, +) -> None: + respx.get(INFO_URL).respond(json=INFO) + upload = respx.post(IMAGE_URL).respond(200) + env = make_env("continuous") + base = await env.show((30, 90, 160)) + cover = await env.show( + (200, 40, 40), ephemeral=True, expires_at=env.clock.now + timedelta(minutes=3) + ) + assert upload.call_count == 2 + assert env.delivery.last_delivery is not None + assert env.delivery.last_delivery.sha256 == cover + + assert await env.ephemeral.expire_if_due() is None # not yet + env.clock.advance(181) + revert = await env.ephemeral.expire_if_due() + + assert revert is not None and revert.reverted and revert.pushed_base + assert env.current.meta is not None and env.current.meta.sha256 == base + pending = env.delivery.pending + assert pending is not None and pending.sha256 == base and not pending.ephemeral + assert await env.ephemeral.expire_if_due() is None # nothing left to end + + +async def test_expiry_without_a_previous_image_starts_a_refresh(make_env: EnvFactory) -> None: + env = make_env("deepsleep") + await env.show((200, 40, 40), ephemeral=True, expires_at=env.clock.now + timedelta(minutes=1)) + env.clock.advance(61) + + revert = await env.ephemeral.expire_if_due() + assert revert is not None and not revert.reverted and not revert.has_base + assert env.refreshes == [True] + assert env.holds_cleared == [True] + # Ended once: the timer does not spin on the still-current expired image. + assert env.ephemeral.next_expiry() is None + assert await env.ephemeral.expire_if_due() is None + assert env.refreshes == [True] + + +async def test_a_newer_display_is_never_undone_by_an_old_expiry(make_env: EnvFactory) -> None: + env = make_env("deepsleep") + await env.show((30, 90, 160)) + await env.show((200, 40, 40), ephemeral=True, expires_at=env.clock.now + timedelta(minutes=1)) + old_pending = env.delivery.pending + assert old_pending is not None + newest = await env.show((20, 160, 60)) # a scheduled refresh replaced the cover + + env.clock.advance(120) + assert await env.ephemeral.expire_if_due() is None + await env.ephemeral.handle_dropped(old_pending, "expired") + assert env.current.meta is not None and env.current.meta.sha256 == newest + assert env.holds_cleared == [] + + +async def test_cancel_drops_the_queued_cover_and_reverts(make_env: EnvFactory) -> None: + env = make_env("deepsleep") + base = await env.show((30, 90, 160)) + await env.show((200, 40, 40), ephemeral=True, expires_at=env.clock.now + timedelta(hours=2)) + + outcome = await env.ephemeral.cancel() + + assert outcome.cancelled and outcome.dropped_pending and outcome.reverted + assert outcome.image is not None and outcome.image.sha256 == base + # The frame never received anything: the previous image is queued for it. + assert outcome.pushed_base + pending = env.delivery.pending + assert pending is not None and pending.sha256 == base + assert env.holds_cleared == [True] + + again = await env.ephemeral.cancel() + assert not again.cancelled and not again.reverted and not again.dropped_pending + + +async def test_cancel_without_a_previous_image_refreshes(make_env: EnvFactory) -> None: + env = make_env("deepsleep") + await env.show((200, 40, 40), ephemeral=True) + outcome = await env.ephemeral.cancel() + assert outcome.cancelled and outcome.dropped_pending + assert not outcome.reverted and outcome.refreshing + assert env.refreshes == [True] + + +async def test_view_describes_the_ephemeral_image(make_env: EnvFactory) -> None: + env = make_env("deepsleep") + view = env.ephemeral.view() + assert not view.active and not view.pending and not view.has_base + await env.show((30, 90, 160)) + expires = env.clock.now + timedelta(minutes=5) + await env.display.display_bytes( + png((200, 40, 40)), source="music", title="So What", ephemeral=True, expires_at=expires + ) + view = env.ephemeral.view() + assert view.active and view.pending and view.has_base + assert view.source == "music" and view.title == "So What" and view.expires_at == expires + assert env.ephemeral.next_expiry() == expires + + +async def test_timer_reverts_on_expiry(make_env: EnvFactory) -> None: + env = make_env("deepsleep", real_clock=True) + await env.ephemeral.start() + base = await env.show((30, 90, 160)) + await env.show( + (200, 40, 40), + ephemeral=True, + expires_at=datetime.now(UTC) + timedelta(seconds=0.3), + ) + await eventually(lambda: bool(env.holds_cleared)) + assert env.holds_cleared == [True] + assert env.current.meta is not None and env.current.meta.sha256 == base + + +async def test_expired_cover_restored_from_disk_is_reverted_at_startup( + make_env: EnvFactory, +) -> None: + first = make_env("deepsleep", real_clock=True) + base = await first.show((30, 90, 160)) + await first.show( + (200, 40, 40), ephemeral=True, expires_at=datetime.now(UTC) + timedelta(seconds=0.1) + ) + await asyncio.sleep(0.2) # the app was down while the cover expired + + restarted = make_env("deepsleep", real_clock=True) + assert restarted.current.meta is not None and restarted.current.meta.ephemeral + await restarted.ephemeral.start() + await restarted.delivery.start() + await eventually(lambda: bool(restarted.holds_cleared)) + assert restarted.current.meta is not None and restarted.current.meta.sha256 == base + pending = restarted.delivery.pending + assert pending is not None and pending.sha256 == base diff --git a/tests/test_scheduler_service.py b/tests/test_scheduler_service.py index 3a1706c..4a54bf9 100644 --- a/tests/test_scheduler_service.py +++ b/tests/test_scheduler_service.py @@ -432,3 +432,45 @@ async def test_immich_runner_rejects_invalid_params() -> None: message = str(excinfo.value) assert "mode" in message and "extra" in message assert "bogus-mode" not in message + + +# --- ephemeral support ------------------------------------------------------------------------- +async def test_clear_hold_lifts_the_protection_of_a_pushed_image(harness: HarnessFactory) -> None: + h = harness(interval_hours=1) + service = h.service() + await service.record_manual(ALICE, ephemeral=True, hold_minutes=180) + assert service.state.hold_until == h.clock.now + timedelta(minutes=180) + held_until = service.compute_next_run() + assert held_until is not None and held_until >= h.clock.now + timedelta(minutes=180) + + await service.clear_hold() + assert service.state.hold_until is None + assert json.loads(h.state_path.read_text(encoding="utf-8"))["hold_until"] is None + released = service.compute_next_run() + assert released is not None and released < held_until + await service.clear_hold() # idempotent + + +async def test_run_in_background_replays_the_rule_and_swallows_errors( + harness: HarnessFactory, +) -> None: + h = harness() + service = h.service() + assert service.run_in_background("revert") # nothing to replay: logged, not raised + await asyncio.sleep(0.05) + assert service.state.last_run is None + + await service.record_manual(ALICE) + assert service.run_in_background("revert") + await asyncio.sleep(0.05) + assert h.runner.calls == [ALICE] + assert service.state.last_run is not None + assert service.state.last_run.reason == "revert" + assert service.state.last_run.status == "ok" + + h.runner.gate = asyncio.Event() + assert service.run_in_background("revert") + await asyncio.sleep(0.01) + assert not service.run_in_background("revert") # one at a time + h.runner.gate.set() + await asyncio.sleep(0.05) From 18cf860e4d6863e39f9a4afe79882da3e19780f0 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sun, 15 Nov 2026 15:47:24 +0100 Subject: [PATCH 54/86] feat: add TMDB provider with regional poster ranking Add a TMDB provider that searches movies and series (movie, tv or multi, with year and an optional TV season), ranks posters by exact language and region, then same language, textless, English and anything else (ties broken by rating), and downloads the best one at tmdb.image_size. Posters use the poster template so they are never cropped. PosterResolver adds a two-tier fallback: the Home Assistant picture (fallback_base64 or fallback_url), then /data/assets/tmdb_fallback.png or a typographic title card. A shared ImageFetcher downloads external images with per-hop SSRF validation of redirects, a size limit and image verification, and never puts URLs (which may embed Home Assistant tokens) in error messages; httpx request lines are now only logged in DEBUG mode. tmdb.language now defaults to fr-FR and tmdb.image_size to w780; new settings: ephemeral_ttl_minutes, hold_minutes, fallback_title_card. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- app/clients/http_images.py | 165 +++++++++++++++++++ app/core/config_models.py | 29 +++- app/core/logging_config.py | 10 +- app/core/settings.py | 5 + app/main.py | 7 +- app/providers/tmdb/__init__.py | 18 ++ app/providers/tmdb/client.py | 152 +++++++++++++++++ app/providers/tmdb/models.py | 114 +++++++++++++ app/providers/tmdb/provider.py | 276 +++++++++++++++++++++++++++++++ app/providers/tmdb/ranking.py | 93 +++++++++++ tests/test_config_store.py | 4 +- tests/test_http_images.py | 134 +++++++++++++++ tests/test_tmdb_provider.py | 291 +++++++++++++++++++++++++++++++++ tests/test_tmdb_ranking.py | 120 ++++++++++++++ 14 files changed, 1408 insertions(+), 10 deletions(-) create mode 100644 app/clients/http_images.py create mode 100644 app/providers/tmdb/__init__.py create mode 100644 app/providers/tmdb/client.py create mode 100644 app/providers/tmdb/models.py create mode 100644 app/providers/tmdb/provider.py create mode 100644 app/providers/tmdb/ranking.py create mode 100644 tests/test_http_images.py create mode 100644 tests/test_tmdb_provider.py create mode 100644 tests/test_tmdb_ranking.py diff --git a/app/clients/http_images.py b/app/clients/http_images.py new file mode 100644 index 0000000..b95c56c --- /dev/null +++ b/app/clients/http_images.py @@ -0,0 +1,165 @@ +"""SSRF-aware download of images from external URLs (posters, album covers, HA pictures). + +Every URL - including each redirect target - is checked with +:func:`app.core.security.validate_external_url` before it is contacted, redirects are +followed manually (at most :data:`MAX_REDIRECTS` hops), the body is read with a hard size +limit and the bytes must be a real, supported image. Error messages never contain the URL +(Home Assistant picture URLs embed access tokens), only its host. +""" + +from __future__ import annotations + +import base64 +import binascii +import logging +from typing import Final +from urllib.parse import urljoin, urlsplit + +import httpx + +from app import __version__ +from app.core.security import ( + InvalidImageError, + PayloadTooLargeError, + UnsafeURLError, + URLPolicy, + read_limited, + validate_external_url, + verify_image_bytes, +) +from app.providers.base import ProviderUnavailableError + +logger = logging.getLogger(__name__) + +MAX_REDIRECTS: Final = 5 +CONNECT_TIMEOUT_S: Final = 5.0 +READ_TIMEOUT_S: Final = 20.0 +REDIRECT_STATUSES: Final = frozenset({301, 302, 303, 307, 308}) +#: Generic client identification (no personal data); MusicBrainz requires a meaningful one. +USER_AGENT: Final = ( + f"SmartFrameEngine/{__version__} (+https://github.com/ant1fr/Smart-Frame-Engine)" +) + + +class ImageFetchError(ProviderUnavailableError): + """The image could not be downloaded (unsafe URL, HTTP error, not an image...).""" + + +def describe_host(url: str) -> str: + """The host of ``url`` for log and error messages (never the path or query).""" + try: + return urlsplit(url).hostname or "unknown host" + except ValueError: + return "invalid URL" + + +class ImageFetcher: + """Downloads images from untrusted URLs under an outbound URL policy.""" + + def __init__( + self, + policy: URLPolicy, + max_bytes: int, + *, + transport: httpx.AsyncBaseTransport | None = None, + ) -> None: + """Create the fetcher. + + Args: + policy: Outbound URL policy (``BLOCK_PRIVATE_URLS`` / ``URL_ALLOWLIST``). + max_bytes: Maximum accepted body size. + transport: Optional transport (tests). + """ + self._policy = policy + self._max_bytes = max_bytes + self._http = httpx.AsyncClient( + timeout=httpx.Timeout(READ_TIMEOUT_S, connect=CONNECT_TIMEOUT_S), + follow_redirects=False, + headers={"User-Agent": USER_AGENT, "Accept": "image/*"}, + transport=transport, + ) + + @property + def max_bytes(self) -> int: + """The size limit applied to downloads.""" + return self._max_bytes + + async def aclose(self) -> None: + """Close the connection pool.""" + await self._http.aclose() + + async def fetch(self, url: str) -> bytes: + """Download ``url`` and return verified image bytes. + + Raises: + ImageFetchError: The URL is unsafe, the server failed, the body is too large or + it is not a supported image. + """ + host = describe_host(url) + try: + current = await validate_external_url(url, self._policy) + except UnsafeURLError as exc: + raise ImageFetchError(f"Refusing to fetch an image from {host}: {exc}") from None + for _ in range(MAX_REDIRECTS + 1): + host = describe_host(current) + try: + async with self._http.stream("GET", current) as response: + if response.status_code in REDIRECT_STATUSES: + location = response.headers.get("location") + if not location: + raise ImageFetchError(f"{host} answered a redirect without a target") + current = await validate_external_url( + urljoin(current, location), self._policy + ) + continue + if response.status_code != 200: + raise ImageFetchError( + f"{host} answered HTTP {response.status_code} for the image" + ) + declared = response.headers.get("content-length") + data = await read_limited( + response.aiter_bytes(), + self._max_bytes, + declared_length=int(declared) if declared and declared.isdigit() else None, + ) + except UnsafeURLError as exc: + raise ImageFetchError(f"Refusing to follow a redirect from {host}: {exc}") from None + except PayloadTooLargeError as exc: + raise ImageFetchError(f"The image from {host} is too large ({exc})") from None + except httpx.TimeoutException: + raise ImageFetchError(f"{host} did not respond in time", timeout=True) from None + except httpx.HTTPError as exc: + raise ImageFetchError( + f"Cannot download the image from {host} ({type(exc).__name__})" + ) from None + try: + verify_image_bytes(data) + except InvalidImageError as exc: + raise ImageFetchError(f"{host} did not return a usable image ({exc})") from None + return data + raise ImageFetchError(f"Too many redirects while fetching the image from {host}") + + +def decode_base64_image(value: str, max_bytes: int) -> bytes: + """Decode a base64 image (optionally a ``data:image/...;base64,`` URI) and verify it. + + Raises: + PayloadTooLargeError: The decoded image would exceed ``max_bytes``. + InvalidImageError: The value is not valid base64 or not a supported image. + """ + payload = value.strip() + if payload.startswith("data:"): + header, _, payload = payload.partition(",") + if ";base64" not in header: + raise InvalidImageError("Only base64 data URIs are supported") + payload = "".join(payload.split()) + if len(payload) // 4 * 3 > max_bytes + 3: + raise PayloadTooLargeError(max_bytes) + try: + data = base64.b64decode(payload, validate=True) + except (binascii.Error, ValueError) as exc: + raise InvalidImageError("Invalid base64 image data") from exc + if len(data) > max_bytes: + raise PayloadTooLargeError(max_bytes) + verify_image_bytes(data) + return data diff --git a/app/core/config_models.py b/app/core/config_models.py index c6c6780..7fdbcbb 100644 --- a/app/core/config_models.py +++ b/app/core/config_models.py @@ -199,12 +199,33 @@ def _clean_aliases( class TmdbConfig(_Section): """TMDB (The Movie Database) settings for HD movie and TV posters.""" - api_key: SecretStr = Field(default=SecretStr(""), description="TMDB API key (v3)") + api_key: SecretStr = Field( + default=SecretStr(""), description="TMDB API key (v3) or read access token (v4)" + ) language: str = Field( - default="en-US", description="Preferred poster/metadata language, e.g. fr-FR or en-US" + default="fr-FR", + description="Preferred poster/metadata language and region, e.g. fr-FR or en-US " + "(regional posters first, then same language, textless, English)", + ) + image_size: Literal["w780", "w1280", "original"] = Field( + default="w780", + description='Poster resolution to download (original is sharper on the 31.5" panel)', + ) + ephemeral_ttl_minutes: int = Field( + default=180, + ge=1, + le=1440, + description="How long an ephemeral poster stays before the previous image returns", ) - image_size: Literal["w1280", "original"] = Field( - default="original", description="Poster resolution to download" + hold_minutes: int | None = Field( + default=None, + ge=1, + le=10080, + description="Protect a pushed poster from scheduled refreshes for this long", + ) + fallback_title_card: bool = Field( + default=True, + description="Render a title card when no poster can be found (else answer 404)", ) @field_validator("language") diff --git a/app/core/logging_config.py b/app/core/logging_config.py index 7e148d7..7a9a436 100644 --- a/app/core/logging_config.py +++ b/app/core/logging_config.py @@ -73,10 +73,14 @@ def setup_logging(level: str = "INFO") -> None: stream_handler.setFormatter(logging.Formatter(LOG_FORMAT)) root.addHandler(stream_handler) + quiet = logging.DEBUG if root.level <= logging.DEBUG else logging.WARNING # APScheduler logs every job execution at INFO; the scheduler service logs its own. - logging.getLogger("apscheduler").setLevel( - logging.DEBUG if root.level <= logging.DEBUG else logging.WARNING - ) + logging.getLogger("apscheduler").setLevel(quiet) + # httpx logs every request URL at INFO. URLs supplied by Home Assistant (artwork, + # fallback posters) may embed short-lived access tokens that are not known secrets, so + # request lines are only logged in DEBUG mode. + for name in ("httpx", "httpcore"): + logging.getLogger(name).setLevel(quiet) handlers: list[logging.Handler] = list(root.handlers) for name in _UVICORN_LOGGERS: diff --git a/app/core/settings.py b/app/core/settings.py index e1c4bbf..96d6b87 100644 --- a/app/core/settings.py +++ b/app/core/settings.py @@ -170,6 +170,11 @@ def cache_dir(self) -> Path: """Directory holding the current rendered image (``current.jpg``, ``current.bin``).""" return self.data_dir / "cache" + @property + def assets_dir(self) -> Path: + """User-provided assets, e.g. ``tmdb_fallback.png`` (global poster fallback).""" + return self.data_dir / "assets" + @property def queue_dir(self) -> Path: """Directory holding the upload waiting for the frame (``pending.bin``).""" diff --git a/app/main.py b/app/main.py index 79e8535..86fe329 100644 --- a/app/main.py +++ b/app/main.py @@ -56,7 +56,12 @@ def _prepare_data_dir(settings: EnvSettings) -> None: - for directory in (settings.data_dir, settings.cache_dir, settings.queue_dir): + for directory in ( + settings.data_dir, + settings.cache_dir, + settings.queue_dir, + settings.assets_dir, + ): try: directory.mkdir(parents=True, exist_ok=True) except OSError as exc: diff --git a/app/providers/tmdb/__init__.py b/app/providers/tmdb/__init__.py new file mode 100644 index 0000000..9185ff5 --- /dev/null +++ b/app/providers/tmdb/__init__.py @@ -0,0 +1,18 @@ +"""TMDB (The Movie Database) movie and TV poster provider.""" + +from app.providers.tmdb.client import TmdbClient +from app.providers.tmdb.models import TmdbImage, TmdbMediaType, TmdbRequest +from app.providers.tmdb.provider import PosterResolver, TmdbProvider +from app.providers.tmdb.ranking import parse_language, pick_result, rank_posters + +__all__ = [ + "PosterResolver", + "TmdbClient", + "TmdbImage", + "TmdbMediaType", + "TmdbProvider", + "TmdbRequest", + "parse_language", + "pick_result", + "rank_posters", +] diff --git a/app/providers/tmdb/client.py b/app/providers/tmdb/client.py new file mode 100644 index 0000000..001e7cb --- /dev/null +++ b/app/providers/tmdb/client.py @@ -0,0 +1,152 @@ +"""Minimal async TMDB (v3 API) client: search and poster listings.""" + +from __future__ import annotations + +import logging +from typing import Any, Final, Self + +import httpx + +from app.clients.http_images import USER_AGENT +from app.providers.base import ProviderUnavailableError +from app.providers.tmdb.models import ResultMediaType, SearchResult, TmdbImage, TmdbMediaType + +logger = logging.getLogger(__name__) + +API_BASE: Final = "https://api.themoviedb.org/3" +IMAGE_BASE: Final = "https://image.tmdb.org/t/p" +CONNECT_TIMEOUT_S: Final = 5.0 +READ_TIMEOUT_S: Final = 15.0 + + +def is_bearer_token(api_key: str) -> bool: + """Whether ``api_key`` is a v4 read access token (a JWT) rather than a v3 key.""" + return api_key.startswith("eyJ") and api_key.count(".") == 2 + + +def image_url(file_path: str, size: str) -> str: + """Full image URL of a poster ``file_path`` at ``size`` (``w780``, ``original``...).""" + return f"{IMAGE_BASE}/{size}{file_path}" + + +class TmdbClient: + """One TMDB session. Use as ``async with`` (closes the connection pool).""" + + def __init__( + self, + api_key: str, + *, + base_url: str = API_BASE, + transport: httpx.AsyncBaseTransport | None = None, + ) -> None: + headers = {"Accept": "application/json", "User-Agent": USER_AGENT} + params: dict[str, str] = {} + if is_bearer_token(api_key): + headers["Authorization"] = f"Bearer {api_key}" + else: + params["api_key"] = api_key + self._http = httpx.AsyncClient( + base_url=base_url, + headers=headers, + params=params, + timeout=httpx.Timeout(READ_TIMEOUT_S, connect=CONNECT_TIMEOUT_S), + follow_redirects=False, + transport=transport, + ) + + async def __aenter__(self) -> Self: + return self + + async def __aexit__(self, *_: object) -> None: + await self._http.aclose() + + async def _get(self, path: str, params: dict[str, Any]) -> dict[str, Any] | None: + """GET a JSON object; ``None`` on 404. + + Raises: + ProviderUnavailableError: Network error, timeout, rejected key or bad payload. + """ + try: + response = await self._http.get( + path, params={k: v for k, v in params.items() if v is not None} + ) + except httpx.TimeoutException: + raise ProviderUnavailableError("TMDB did not respond in time", timeout=True) from None + except httpx.HTTPError as exc: + raise ProviderUnavailableError( + f"Cannot connect to TMDB ({type(exc).__name__})" + ) from None + if response.status_code == 404: + return None + if response.status_code in {401, 403}: + raise ProviderUnavailableError("TMDB rejected the API key") + if response.status_code == 429: + raise ProviderUnavailableError("TMDB rate limit reached; try again shortly") + if response.status_code != 200: + raise ProviderUnavailableError(f"TMDB answered HTTP {response.status_code}") + try: + payload = response.json() + except ValueError: + raise ProviderUnavailableError("TMDB returned invalid JSON") from None + if not isinstance(payload, dict): + raise ProviderUnavailableError("TMDB returned an unexpected payload") + return payload + + async def search( + self, query: str, media_type: TmdbMediaType, *, year: int | None, language: str + ) -> list[SearchResult]: + """Movies and/or series matching ``query``, most relevant first.""" + params: dict[str, Any] = {"query": query, "language": language, "include_adult": "false"} + if media_type == "movie": + params["year"] = year + elif media_type == "tv": + params["first_air_date_year"] = year + payload = await self._get(f"/search/{media_type}", params) or {} + results: list[SearchResult] = [] + for raw in payload.get("results") or []: + if not isinstance(raw, dict): + continue + kind = raw.get("media_type", media_type) + if kind not in {"movie", "tv"}: + continue # people in a multi search + parsed = self._parse_result(raw, kind) + if parsed is not None: + results.append(parsed) + return results + + @staticmethod + def _parse_result(raw: dict[str, Any], kind: ResultMediaType) -> SearchResult | None: + title = raw.get("title") if kind == "movie" else raw.get("name") + if not isinstance(title, str) or not isinstance(raw.get("id"), int): + return None + return SearchResult.model_validate( + { + "id": raw["id"], + "media_type": kind, + "title": title, + "original_title": raw.get("original_title" if kind == "movie" else "original_name"), + "release_date": raw.get("release_date" if kind == "movie" else "first_air_date"), + "poster_path": raw.get("poster_path"), + "popularity": raw.get("popularity") or 0.0, + } + ) + + async def posters( + self, + media_type: ResultMediaType, + tmdb_id: int, + *, + include_languages: str, + season: int | None = None, + ) -> list[TmdbImage]: + """Posters of a movie or series (or of one season), unranked.""" + if season is not None: + path = f"/tv/{tmdb_id}/season/{season}/images" + else: + path = f"/{media_type}/{tmdb_id}/images" + payload = await self._get(path, {"include_image_language": include_languages}) or {} + posters: list[TmdbImage] = [] + for raw in payload.get("posters") or []: + if isinstance(raw, dict) and isinstance(raw.get("file_path"), str): + posters.append(TmdbImage.model_validate(raw)) + return posters diff --git a/app/providers/tmdb/models.py b/app/providers/tmdb/models.py new file mode 100644 index 0000000..160869e --- /dev/null +++ b/app/providers/tmdb/models.py @@ -0,0 +1,114 @@ +"""TMDB API payloads and the poster request.""" + +from __future__ import annotations + +import re +from datetime import date +from typing import Final, Literal + +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator + +TmdbMediaType = Literal["movie", "tv", "multi"] +ResultMediaType = Literal["movie", "tv"] + +_LANGUAGE_RE: Final = re.compile(r"^[a-z]{2}(-[A-Z]{2})?$") + + +def validate_language(value: str | None) -> str | None: + """Accept ``fr``, ``fr-FR``... (``None`` = use the configured language).""" + if value is None: + return None + value = value.strip() + if not _LANGUAGE_RE.match(value): + raise ValueError("must look like 'fr-FR', 'en-US' or 'fr'") + return value + + +class TmdbRequest(BaseModel): + """What to look up on TMDB.""" + + model_config = ConfigDict(extra="forbid", populate_by_name=True) + + query: str = Field(min_length=1, max_length=200, description="Movie or series title") + media_type: TmdbMediaType = Field( + default="multi", description="movie, tv, or multi (both; 'auto' is accepted)" + ) + year: int | None = Field(default=None, ge=1870, le=2200, description="Release year") + season: int | None = Field( + default=None, ge=0, le=100, description="TV only: prefer this season's poster" + ) + language: str | None = Field( + default=None, description="Overrides tmdb.language for this request, e.g. fr-CA" + ) + + @field_validator("query") + @classmethod + def _strip_query(cls, value: str) -> str: + value = " ".join(value.split()) + if not value: + raise ValueError("must not be blank") + return value + + @field_validator("media_type", mode="before") + @classmethod + def _auto_is_multi(cls, value: object) -> object: + return "multi" if value == "auto" else value + + @field_validator("language") + @classmethod + def _check_language(cls, value: str | None) -> str | None: + return validate_language(value) + + @model_validator(mode="after") + def _season_needs_tv(self) -> TmdbRequest: + if self.season is not None and self.media_type == "movie": + raise ValueError("season only applies to media_type 'tv' (or 'multi')") + return self + + +class SearchResult(BaseModel): + """One movie or series from a TMDB search.""" + + model_config = ConfigDict(extra="ignore") + + id: int + media_type: ResultMediaType + title: str + original_title: str | None = None + release_date: str | None = None + poster_path: str | None = None + popularity: float = 0.0 + + @property + def year(self) -> int | None: + """Release (or first air) year, if known.""" + if not self.release_date: + return None + try: + return date.fromisoformat(self.release_date[:10]).year + except ValueError: + return None + + +class TmdbImage(BaseModel): + """One poster of a movie, series or season. + + ``iso_3166_1`` (region) is optional: older payloads only carry the language. + """ + + model_config = ConfigDict(extra="ignore") + + file_path: str + iso_639_1: str | None = None + iso_3166_1: str | None = None + vote_average: float = 0.0 + vote_count: int = 0 + width: int = 0 + height: int = 0 + + @field_validator("iso_639_1", "iso_3166_1", mode="before") + @classmethod + def _blank_is_none(cls, value: object) -> object: + if isinstance(value, str) and not value.strip(): + return None + return value diff --git a/app/providers/tmdb/provider.py b/app/providers/tmdb/provider.py new file mode 100644 index 0000000..0c02a70 --- /dev/null +++ b/app/providers/tmdb/provider.py @@ -0,0 +1,276 @@ +"""TMDB poster provider and its two-tier fallback chain. + +:class:`TmdbProvider` finds the movie or series, ranks its posters by regional preference +(:mod:`app.providers.tmdb.ranking`) and downloads the best one. Posters are rendered with +the ``poster`` template, so they are never cropped. + +:class:`PosterResolver` adds the fallbacks used when TMDB has no match or fails: + +1. the per-request fallback from Home Assistant (``fallback_base64``, then + ``fallback_url`` - typically the ``media_player`` entity picture); +2. the global fallback ``/data/assets/tmdb_fallback.png`` when present, else a clean + typographic title card. +""" + +from __future__ import annotations + +import asyncio +import logging +from collections.abc import Callable +from dataclasses import replace +from pathlib import Path +from typing import Final, Literal + +from pydantic import JsonValue + +from app.clients.http_images import ImageFetcher, ImageFetchError, decode_base64_image +from app.core.config_store import ConfigStore +from app.core.security import InvalidImageError, PayloadTooLargeError, verify_image_bytes +from app.processor.templates import PosterLayout, TitleCardLayout +from app.providers.base import ( + BaseImageProvider, + ImageAsset, + NoCandidateError, + ProviderError, + ProviderNotConfiguredError, + ProviderUnavailableError, +) +from app.providers.tmdb.client import TmdbClient, image_url +from app.providers.tmdb.models import SearchResult, TmdbImage, TmdbRequest +from app.providers.tmdb.ranking import fold, parse_language, pick_result, rank_posters + +logger = logging.getLogger(__name__) + +SOURCE: Final = "tmdb" +GLOBAL_FALLBACK_NAME: Final = "tmdb_fallback.png" +#: Ranked posters tried before giving up on downloads. +MAX_DOWNLOAD_ATTEMPTS: Final = 3 +TITLE_CARD_ACCENT: Final = (255, 0, 0) + +FallbackTier = Literal["request", "global", "title_card"] +ClientFactory = Callable[[str], TmdbClient] + + +def _display_title(result: SearchResult, season: int | None) -> str: + title = result.title + if season is not None: + return f"{title} · Season {season}" + return f"{title} ({result.year})" if result.year else title + + +class TmdbProvider(BaseImageProvider[TmdbRequest]): + """Movie and TV posters from The Movie Database.""" + + name = SOURCE + + def __init__( + self, + config_store: ConfigStore, + fetcher: ImageFetcher, + *, + client_factory: ClientFactory = TmdbClient, + ) -> None: + self._config_store = config_store + self._fetcher = fetcher + self._client_factory = client_factory + + @property + def configured(self) -> bool: + """Whether a TMDB key is set.""" + return bool(self._config_store.config.tmdb.api_key.get_secret_value().strip()) + + async def fetch(self, request: TmdbRequest) -> ImageAsset: + """Find the title and download its best poster. + + Raises: + ProviderNotConfiguredError: No TMDB key. + NoCandidateError: No match, or the match has no poster. + ProviderUnavailableError: TMDB or its image CDN failed. + """ + config = self._config_store.config.tmdb + api_key = config.api_key.get_secret_value().strip() + if not api_key: + raise ProviderNotConfiguredError( + "TMDB is not configured: set TMDB_API_KEY or tmdb.api_key" + ) + language = request.language or config.language + lang, region = parse_language(language) + include = ",".join(dict.fromkeys([lang, "en", "null"])) + async with self._client_factory(api_key) as client: + results = await client.search( + request.query, request.media_type, year=request.year, language=language + ) + chosen = pick_result(results, request.query, request.year) + if chosen is None: + raise NoCandidateError(f"TMDB has no movie or series matching {request.query!r}") + season = request.season if chosen.media_type == "tv" else None + posters: list[TmdbImage] = [] + if season is not None: + posters = await client.posters( + "tv", chosen.id, include_languages=include, season=season + ) + if not posters: + season = None # no season artwork: use the series posters + if not posters: + posters = await client.posters( + chosen.media_type, chosen.id, include_languages=include + ) + ranked = rank_posters(posters, lang, region) + candidates = [poster.file_path for poster in ranked[:MAX_DOWNLOAD_ATTEMPTS]] + if chosen.poster_path and chosen.poster_path not in candidates: + candidates.append(chosen.poster_path) # the default poster as a last resort + if not candidates: + raise NoCandidateError(f"TMDB has no poster for {chosen.title!r}") + + data, path = await self._download(candidates, config.image_size) + poster = next((p for p in ranked if p.file_path == path), None) + details: dict[str, JsonValue] = { + "title": chosen.title, + "original_title": chosen.original_title, + "year": chosen.year, + "media_type": chosen.media_type, + "tmdb_id": chosen.id, + "season": season, + "language": language, + "poster_language": poster.iso_639_1 if poster else None, + "poster_region": poster.iso_3166_1 if poster else None, + } + return ImageAsset( + data=data, + source=SOURCE, + history_key=f"tmdb:{chosen.media_type}:{chosen.id}", + title=_display_title(chosen, season), + details={key: value for key, value in details.items() if value is not None}, + recommended_fit="contain", + layout=PosterLayout(), + track_history=False, + ) + + async def _download(self, paths: list[str], size: str) -> tuple[bytes, str]: + failure: ImageFetchError | None = None + for path in paths: + try: + return await self._fetcher.fetch(image_url(path, size)), path + except ImageFetchError as exc: + logger.info("TMDB poster download failed, trying the next one: %s", exc) + failure = exc + raise ProviderUnavailableError( + f"Could not download a poster from TMDB ({failure})", + timeout=bool(failure and failure.timeout), + ) + + +class PosterResolver: + """TMDB poster with the per-request and global fallbacks.""" + + def __init__( + self, + provider: TmdbProvider, + fetcher: ImageFetcher, + config_store: ConfigStore, + assets_dir: Path, + ) -> None: + self._provider = provider + self._fetcher = fetcher + self._config_store = config_store + self._assets_dir = assets_dir + + @property + def global_fallback_path(self) -> Path: + """Location of the optional global fallback poster.""" + return self._assets_dir / GLOBAL_FALLBACK_NAME + + async def resolve( + self, + request: TmdbRequest, + *, + fallback_url: str | None = None, + fallback_base64: str | None = None, + ) -> ImageAsset: + """The TMDB poster, else a fallback (see the module docstring). + + Raises: + ProviderError: TMDB failed, no fallback worked and ``tmdb.fallback_title_card`` + is disabled. + """ + try: + return await self._provider.fetch(request) + except ProviderError as exc: + failure = exc + logger.info("TMDB poster unavailable for %r: %s", request.query, exc) + + reason = str(failure) + asset = await self._request_fallback(request, fallback_url, fallback_base64, reason) + if asset is None: + asset = await self._global_fallback(request, reason) + if asset is None and self._config_store.config.tmdb.fallback_title_card: + asset = self._title_card(request, reason) + if asset is None: + raise failure + return asset + + async def _request_fallback( + self, + request: TmdbRequest, + url: str | None, + encoded: str | None, + reason: str, + ) -> ImageAsset | None: + if encoded: + try: + data = decode_base64_image(encoded, self._fetcher.max_bytes) + return self._asset(data, request, "request", reason) + except (InvalidImageError, PayloadTooLargeError) as exc: + logger.info("Ignoring the fallback_base64 poster: %s", exc) + if url: + try: + data = await self._fetcher.fetch(url) + return self._asset(data, request, "request", reason) + except ImageFetchError as exc: + logger.info("Ignoring the fallback_url poster: %s", exc) + return None + + async def _global_fallback(self, request: TmdbRequest, reason: str) -> ImageAsset | None: + path = self.global_fallback_path + try: + data = await asyncio.to_thread(path.read_bytes) + except FileNotFoundError: + return None + except OSError as exc: + logger.warning("Cannot read %s: %s", path, exc) + return None + try: + if len(data) > self._fetcher.max_bytes: + raise PayloadTooLargeError(self._fetcher.max_bytes) + verify_image_bytes(data) + except (InvalidImageError, PayloadTooLargeError) as exc: + logger.warning("Ignoring %s: %s", path, exc) + return None + return self._asset(data, request, "global", reason) + + def _title_card(self, request: TmdbRequest, reason: str) -> ImageAsset: + parts = [] + if request.year: + parts.append(str(request.year)) + if request.season is not None: + parts.append(f"Season {request.season}") + layout = TitleCardLayout( + title=request.query, + subtitle=" · ".join(parts) or None, + accent=TITLE_CARD_ACCENT, + ) + asset = self._asset(b"", request, "title_card", reason) + return replace(asset, layout=layout) + + @staticmethod + def _asset(data: bytes, request: TmdbRequest, tier: FallbackTier, reason: str) -> ImageAsset: + return ImageAsset( + data=data, + source=SOURCE, + history_key=f"tmdb-fallback:{fold(request.query)}", + title=request.query, + details={"title": request.query, "fallback": tier, "fallback_reason": reason}, + recommended_fit="contain", + layout=PosterLayout(), + track_history=False, + ) diff --git a/app/providers/tmdb/ranking.py b/app/providers/tmdb/ranking.py new file mode 100644 index 0000000..8d2be0e --- /dev/null +++ b/app/providers/tmdb/ranking.py @@ -0,0 +1,93 @@ +"""Regional poster ranking and search-result selection. + +TMDB tags each poster with a language (``iso_639_1``) and, for regional variants, a +country (``iso_3166_1``): a French poster for France (``fr``/``FR``) differs from the +Québec one (``fr``/``CA``). For ``language="fr-FR"`` posters are ranked: + +1. exact language **and** region (``fr`` + ``FR``); +2. same language, any or no region (``fr`` + ``CA``, ``fr`` + none); +3. textless artwork (no language); +4. English; +5. anything else. + +Within a tier, the best rated poster wins: ``(vote_average, vote_count)`` descending. +""" + +from __future__ import annotations + +import re +import unicodedata +from collections.abc import Sequence +from typing import Final + +from app.providers.tmdb.models import SearchResult, TmdbImage + +FALLBACK_LANGUAGE: Final = "en" +#: Search results considered when looking for an exact title match. +EXACT_MATCH_WINDOW: Final = 5 +_NON_WORD: Final = re.compile(r"[^\w]+") + + +def parse_language(language: str) -> tuple[str, str | None]: + """Split ``"fr-FR"`` into ``("fr", "FR")`` (``"fr"`` gives ``("fr", None)``).""" + lang, _, region = language.partition("-") + return lang.lower(), (region.upper() or None) + + +def poster_tier(image: TmdbImage, lang: str, region: str | None) -> int: + """The priority tier of ``image`` (0 = best).""" + image_lang = image.iso_639_1.lower() if image.iso_639_1 else None + image_region = image.iso_3166_1.upper() if image.iso_3166_1 else None + if image_lang == lang: + return 0 if region is not None and image_region == region else 1 + if image_lang is None: + return 2 + if image_lang == FALLBACK_LANGUAGE: + return 3 + return 4 + + +def rank_posters(images: Sequence[TmdbImage], lang: str, region: str | None) -> list[TmdbImage]: + """Posters ordered by regional preference, then rating (stable for ties).""" + return sorted( + images, + key=lambda image: ( + poster_tier(image, lang, region), + -image.vote_average, + -image.vote_count, + ), + ) + + +def fold(text: str) -> str: + """Accent-, case- and punctuation-insensitive form of a title.""" + decomposed = unicodedata.normalize("NFKD", text) + stripped = "".join(char for char in decomposed if not unicodedata.combining(char)) + return " ".join(_NON_WORD.sub(" ", stripped.casefold()).split()) + + +def pick_result( + results: Sequence[SearchResult], query: str, year: int | None +) -> SearchResult | None: + """The search result that best matches ``query``. + + Among the first :data:`EXACT_MATCH_WINDOW` results (TMDB orders by relevance), an + exact folded title match (translated or original title) wins, preferring the requested + year; otherwise the first result is used. + """ + if not results: + return None + wanted = fold(query) + window = results[:EXACT_MATCH_WINDOW] + exact = [ + result + for result in window + if wanted in {fold(result.title), fold(result.original_title or "")} + ] + if year is not None: + dated = [result for result in exact if result.year == year] + if dated: + return dated[0] + if exact: + return exact[0] + return results[0] diff --git a/tests/test_config_store.py b/tests/test_config_store.py index aa4368c..f74f55c 100644 --- a/tests/test_config_store.py +++ b/tests/test_config_store.py @@ -100,10 +100,10 @@ async def test_unknown_paths_rejected(config_path: Path, patch: dict[str, object async def test_reset_section_and_all(config_path: Path) -> None: store = make_store(config_path) await store.update( - {"eink": {"contrast": 1.5, "saturation": 1.0}, "tmdb": {"language": "fr-FR"}} + {"eink": {"contrast": 1.5, "saturation": 1.0}, "tmdb": {"language": "de-DE"}} ) await store.reset(["eink"]) - assert store.overrides == {"tmdb": {"language": "fr-FR"}} + assert store.overrides == {"tmdb": {"language": "de-DE"}} await store.reset() assert store.overrides == {} assert store.config == RuntimeConfig() diff --git a/tests/test_http_images.py b/tests/test_http_images.py new file mode 100644 index 0000000..315604c --- /dev/null +++ b/tests/test_http_images.py @@ -0,0 +1,134 @@ +from __future__ import annotations + +import base64 +import io +from collections.abc import AsyncIterator + +import httpx +import pytest +import respx +from PIL import Image + +from app.clients.http_images import ( + USER_AGENT, + ImageFetcher, + ImageFetchError, + decode_base64_image, + describe_host, +) +from app.core.security import InvalidImageError, PayloadTooLargeError, URLPolicy + + +def png_bytes(size: tuple[int, int] = (40, 30)) -> bytes: + buffer = io.BytesIO() + Image.new("RGB", size, (10, 120, 200)).save(buffer, format="PNG") + return buffer.getvalue() + + +@pytest.fixture +async def fetcher() -> AsyncIterator[ImageFetcher]: + instance = ImageFetcher(URLPolicy(), 1_000_000) + yield instance + await instance.aclose() + + +@respx.mock +async def test_fetch_returns_verified_image_bytes(fetcher: ImageFetcher) -> None: + route = respx.get("https://cdn.test/poster.png").respond(200, content=png_bytes()) + assert await fetcher.fetch("https://cdn.test/poster.png") == png_bytes() + assert route.calls.last.request.headers["user-agent"] == USER_AGENT + + +@respx.mock +async def test_fetch_follows_redirects(fetcher: ImageFetcher) -> None: + respx.get("https://coverartarchive.test/release/1/front").respond( + 307, headers={"location": "https://archive.test/img/front.png"} + ) + respx.get("https://archive.test/img/front.png").respond(200, content=png_bytes()) + assert await fetcher.fetch("https://coverartarchive.test/release/1/front") == png_bytes() + + +@respx.mock +async def test_fetch_resolves_relative_redirects(fetcher: ImageFetcher) -> None: + respx.get("https://cdn.test/a/old.png").respond(302, headers={"location": "../new.png"}) + respx.get("https://cdn.test/new.png").respond(200, content=png_bytes()) + assert await fetcher.fetch("https://cdn.test/a/old.png") == png_bytes() + + +@respx.mock +async def test_redirect_to_a_blocked_address_is_refused() -> None: + fetcher = ImageFetcher(URLPolicy(block_private=True), 1_000_000) + respx.get("http://93.184.216.34/poster.png").respond( + 302, headers={"location": "http://127.0.0.1:8123/api/secret.png"} + ) + internal = respx.get("http://127.0.0.1:8123/api/secret.png").respond(200, content=png_bytes()) + try: + with pytest.raises(ImageFetchError, match="Refusing to follow a redirect"): + await fetcher.fetch("http://93.184.216.34/poster.png") + finally: + await fetcher.aclose() + assert not internal.called + + +async def test_blocked_and_malformed_urls_are_refused() -> None: + fetcher = ImageFetcher(URLPolicy(block_private=True), 1_000_000) + try: + with pytest.raises(ImageFetchError, match="Refusing"): + await fetcher.fetch("http://192.168.1.10/a.png") + with pytest.raises(ImageFetchError, match="Refusing"): + await fetcher.fetch("ftp://cdn.test/a.png") + finally: + await fetcher.aclose() + + +@respx.mock +async def test_too_many_redirects(fetcher: ImageFetcher) -> None: + respx.get("https://loop.test/a").respond(302, headers={"location": "https://loop.test/a"}) + with pytest.raises(ImageFetchError, match="Too many redirects"): + await fetcher.fetch("https://loop.test/a") + + +@respx.mock +async def test_errors_never_leak_the_url_query(fetcher: ImageFetcher) -> None: + respx.get(url__startswith="http://ha.test:8123/api/media_player_proxy").respond(404) + with pytest.raises(ImageFetchError) as caught: + await fetcher.fetch("http://ha.test:8123/api/media_player_proxy/m?token=SECRET123") + assert "SECRET123" not in str(caught.value) + assert "ha.test" in str(caught.value) + + +@respx.mock +async def test_http_errors_timeouts_and_non_images(fetcher: ImageFetcher) -> None: + respx.get("https://cdn.test/500").respond(500) + respx.get("https://cdn.test/slow").mock(side_effect=httpx.ReadTimeout("slow")) + respx.get("https://cdn.test/text").respond(200, content=b"nope") + respx.get("https://cdn.test/big").respond(200, content=b"x" * 2_000_000) + with pytest.raises(ImageFetchError, match="HTTP 500"): + await fetcher.fetch("https://cdn.test/500") + with pytest.raises(ImageFetchError) as timeout: + await fetcher.fetch("https://cdn.test/slow") + assert timeout.value.timeout + with pytest.raises(ImageFetchError, match="usable image"): + await fetcher.fetch("https://cdn.test/text") + with pytest.raises(ImageFetchError, match="too large"): + await fetcher.fetch("https://cdn.test/big") + + +def test_decode_base64_image() -> None: + raw = png_bytes() + encoded = base64.b64encode(raw).decode() + assert decode_base64_image(encoded, 1_000_000) == raw + assert decode_base64_image(f"data:image/png;base64,{encoded}", 1_000_000) == raw + with pytest.raises(InvalidImageError): + decode_base64_image("not base64!!", 1_000_000) + with pytest.raises(InvalidImageError): + decode_base64_image(base64.b64encode(b"plain text").decode(), 1_000_000) + with pytest.raises(PayloadTooLargeError): + decode_base64_image(encoded, 10) + with pytest.raises(InvalidImageError): + decode_base64_image("data:image/png,raw", 1_000_000) + + +def test_describe_host() -> None: + assert describe_host("https://image.tmdb.org/t/p/w780/a.jpg?x=1") == "image.tmdb.org" + assert describe_host("nonsense") == "unknown host" diff --git a/tests/test_tmdb_provider.py b/tests/test_tmdb_provider.py new file mode 100644 index 0000000..f80497b --- /dev/null +++ b/tests/test_tmdb_provider.py @@ -0,0 +1,291 @@ +from __future__ import annotations + +import base64 +import io +from collections.abc import AsyncIterator +from pathlib import Path +from typing import Any + +import httpx +import pytest +import respx +from PIL import Image + +from app.clients.http_images import ImageFetcher +from app.core.config_store import ConfigStore +from app.core.security import URLPolicy +from app.processor.templates import PosterLayout, TitleCardLayout +from app.providers.base import ( + NoCandidateError, + ProviderNotConfiguredError, + ProviderUnavailableError, +) +from app.providers.tmdb import PosterResolver, TmdbProvider, TmdbRequest + +API = "https://api.themoviedb.org/3" +IMG = "https://image.tmdb.org/t/p" +V3_KEY = "0123456789abcdef0123456789abcdef" +V4_TOKEN = "eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJ4In0.c2lnbmF0dXJl" + + +def png_bytes(color: tuple[int, int, int] = (200, 30, 40)) -> bytes: + buffer = io.BytesIO() + Image.new("RGB", (40, 60), color).save(buffer, format="PNG") + return buffer.getvalue() + + +def config_store(tmp_path: Path, **tmdb: Any) -> ConfigStore: + seed = {"tmdb": {"api_key": V3_KEY, "language": "fr-FR", **tmdb}} + store = ConfigStore(tmp_path / "config.json", seed) + store.load() + return store + + +class Setup: + def __init__(self, tmp_path: Path, **tmdb: Any) -> None: + self.store = config_store(tmp_path, **tmdb) + self.fetcher = ImageFetcher(URLPolicy(), 5_000_000) + self.provider = TmdbProvider(self.store, self.fetcher) + self.assets = tmp_path / "assets" + self.assets.mkdir() + self.resolver = PosterResolver(self.provider, self.fetcher, self.store, self.assets) + + +@pytest.fixture +async def setup(tmp_path: Path) -> AsyncIterator[Setup]: + instance = Setup(tmp_path) + yield instance + await instance.fetcher.aclose() + + +AMELIE_SEARCH = { + "results": [ + { + "id": 194, + "title": "Le Fabuleux Destin d'Amélie Poulain", + "original_title": "Le Fabuleux Destin d'Amélie Poulain", + "release_date": "2001-04-25", + "poster_path": "/default.jpg", + "popularity": 50.0, + } + ] +} +AMELIE_POSTERS = { + "posters": [ + {"file_path": "/en.jpg", "iso_639_1": "en", "vote_average": 9.0, "vote_count": 50}, + {"file_path": "/fr_ca.jpg", "iso_639_1": "fr", "iso_3166_1": "CA", "vote_average": 6.0}, + {"file_path": "/fr_fr.jpg", "iso_639_1": "fr", "iso_3166_1": "FR", "vote_average": 5.0}, + {"file_path": "/textless.jpg", "iso_639_1": None, "vote_average": 8.0}, + ] +} + + +@respx.mock +async def test_fetch_downloads_the_best_regional_poster(setup: Setup) -> None: + search = respx.get(f"{API}/search/movie").respond(json=AMELIE_SEARCH) + images = respx.get(f"{API}/movie/194/images").respond(json=AMELIE_POSTERS) + download = respx.get(f"{IMG}/w780/fr_fr.jpg").respond(content=png_bytes()) + + asset = await setup.provider.fetch(TmdbRequest(query="amelie", media_type="movie", year=2001)) + + assert asset.data == png_bytes() + assert download.called + assert asset.layout == PosterLayout() + assert asset.recommended_fit == "contain" + assert not asset.track_history + assert asset.title == "Le Fabuleux Destin d'Amélie Poulain (2001)" + assert asset.details["poster_region"] == "FR" + assert asset.details["tmdb_id"] == 194 + params = search.calls.last.request.url.params + assert params["language"] == "fr-FR" + assert params["year"] == "2001" + assert params["api_key"] == V3_KEY + assert images.calls.last.request.url.params["include_image_language"] == "fr,en,null" + + +@respx.mock +async def test_v4_tokens_use_a_bearer_header(tmp_path: Path) -> None: + setup = Setup(tmp_path, api_key=V4_TOKEN) + search = respx.get(f"{API}/search/multi").respond(json={"results": []}) + try: + with pytest.raises(NoCandidateError): + await setup.provider.fetch(TmdbRequest(query="Nothing")) + finally: + await setup.fetcher.aclose() + request = search.calls.last.request + assert request.headers["authorization"] == f"Bearer {V4_TOKEN}" + assert "api_key" not in request.url.params + + +@respx.mock +async def test_multi_search_skips_people_and_prefers_an_exact_title(setup: Setup) -> None: + respx.get(f"{API}/search/multi").respond( + json={ + "results": [ + {"id": 1, "media_type": "person", "name": "Breaking Bad"}, + {"id": 2, "media_type": "movie", "title": "Breaking Bad Movie"}, + {"id": 1396, "media_type": "tv", "name": "Breaking Bad", "first_air_date": "2008"}, + ] + } + ) + respx.get(f"{API}/tv/1396/images").respond( + json={"posters": [{"file_path": "/bb.jpg", "iso_639_1": "en"}]} + ) + respx.get(f"{IMG}/w780/bb.jpg").respond(content=png_bytes()) + asset = await setup.provider.fetch(TmdbRequest(query="breaking bad", language="en-US")) + assert asset.details["media_type"] == "tv" + assert asset.details["tmdb_id"] == 1396 + + +@respx.mock +async def test_season_posters_with_fallback_to_the_series(setup: Setup) -> None: + respx.get(f"{API}/search/tv").respond( + json={"results": [{"id": 1399, "name": "Game of Thrones", "poster_path": "/series.jpg"}]} + ) + season = respx.get(f"{API}/tv/1399/season/3/images").respond( + json={"posters": [{"file_path": "/s3.jpg", "iso_639_1": "fr"}]} + ) + respx.get(f"{IMG}/w780/s3.jpg").respond(content=png_bytes()) + asset = await setup.provider.fetch( + TmdbRequest(query="Game of Thrones", media_type="tv", season=3) + ) + assert season.called + assert asset.details["season"] == 3 + assert asset.title == "Game of Thrones · Season 3" + + respx.get(f"{API}/tv/1399/season/9/images").respond(404) + respx.get(f"{API}/tv/1399/images").respond(json={"posters": []}) + respx.get(f"{IMG}/w780/series.jpg").respond(content=png_bytes()) + fallback = await setup.provider.fetch( + TmdbRequest(query="Game of Thrones", media_type="tv", season=9) + ) + assert "season" not in fallback.details # the series' default poster was used + + +@respx.mock +async def test_a_failed_download_tries_the_next_ranked_poster(setup: Setup) -> None: + respx.get(f"{API}/search/movie").respond(json=AMELIE_SEARCH) + respx.get(f"{API}/movie/194/images").respond(json=AMELIE_POSTERS) + respx.get(f"{IMG}/w780/fr_fr.jpg").respond(404) + respx.get(f"{IMG}/w780/fr_ca.jpg").respond(content=png_bytes()) + asset = await setup.provider.fetch(TmdbRequest(query="Amélie", media_type="movie")) + assert asset.details["poster_region"] == "CA" + + +@respx.mock +async def test_configured_image_size_is_used(tmp_path: Path) -> None: + setup = Setup(tmp_path, image_size="original") + respx.get(f"{API}/search/movie").respond(json=AMELIE_SEARCH) + respx.get(f"{API}/movie/194/images").respond(json=AMELIE_POSTERS) + route = respx.get(f"{IMG}/original/fr_fr.jpg").respond(content=png_bytes()) + try: + await setup.provider.fetch(TmdbRequest(query="Amélie", media_type="movie")) + finally: + await setup.fetcher.aclose() + assert route.called + + +async def test_missing_key_is_reported(tmp_path: Path) -> None: + setup = Setup(tmp_path, api_key="") + try: + assert not setup.provider.configured + with pytest.raises(ProviderNotConfiguredError): + await setup.provider.fetch(TmdbRequest(query="x")) + finally: + await setup.fetcher.aclose() + + +@respx.mock +async def test_upstream_errors_are_reported(setup: Setup) -> None: + route = respx.get(f"{API}/search/multi").respond(401) + with pytest.raises(ProviderUnavailableError, match="rejected the API key"): + await setup.provider.fetch(TmdbRequest(query="x")) + route.mock(side_effect=httpx.ConnectTimeout("slow")) + with pytest.raises(ProviderUnavailableError) as timeout: + await setup.provider.fetch(TmdbRequest(query="x")) + assert timeout.value.timeout + + +# --- fallbacks ------------------------------------------------------------------------------ +@respx.mock +async def test_resolver_returns_the_tmdb_poster_when_found(setup: Setup) -> None: + respx.get(f"{API}/search/movie").respond(json=AMELIE_SEARCH) + respx.get(f"{API}/movie/194/images").respond(json=AMELIE_POSTERS) + respx.get(f"{IMG}/w780/fr_fr.jpg").respond(content=png_bytes()) + asset = await setup.resolver.resolve( + TmdbRequest(query="Amélie", media_type="movie"), fallback_url="https://ha.test/pic.png" + ) + assert "fallback" not in asset.details + + +@respx.mock +async def test_resolver_uses_the_home_assistant_picture_first(setup: Setup) -> None: + respx.get(f"{API}/search/multi").respond(json={"results": []}) + ha = respx.get("https://ha.test/api/media_player_proxy/tv").respond( + content=png_bytes((1, 2, 3)) + ) + asset = await setup.resolver.resolve( + TmdbRequest(query="Home video"), + fallback_url="https://ha.test/api/media_player_proxy/tv?token=abc", + ) + assert ha.called + assert asset.data == png_bytes((1, 2, 3)) + assert asset.details["fallback"] == "request" + assert asset.layout == PosterLayout() + + +@respx.mock +async def test_resolver_prefers_base64_over_the_url(setup: Setup) -> None: + respx.get(f"{API}/search/multi").respond(500) + url = respx.get("https://ha.test/pic.png").respond(content=png_bytes()) + encoded = base64.b64encode(png_bytes((9, 9, 9))).decode() + asset = await setup.resolver.resolve( + TmdbRequest(query="x"), fallback_url="https://ha.test/pic.png", fallback_base64=encoded + ) + assert asset.data == png_bytes((9, 9, 9)) + assert not url.called + assert "TMDB answered HTTP 500" in str(asset.details["fallback_reason"]) + + +@respx.mock +async def test_resolver_falls_back_to_the_global_poster_then_a_title_card(setup: Setup) -> None: + respx.get(f"{API}/search/multi").respond(json={"results": []}) + respx.get("https://ha.test/broken.png").respond(404) + request = TmdbRequest(query="Unknown Film", year=1999) + + card = await setup.resolver.resolve(request, fallback_url="https://ha.test/broken.png") + assert card.details["fallback"] == "title_card" + assert isinstance(card.layout, TitleCardLayout) + assert card.layout.title == "Unknown Film" + assert card.layout.subtitle == "1999" + assert card.data == b"" + + setup.resolver.global_fallback_path.write_bytes(png_bytes((5, 5, 5))) + glob = await setup.resolver.resolve(request, fallback_url="https://ha.test/broken.png") + assert glob.details["fallback"] == "global" + assert glob.data == png_bytes((5, 5, 5)) + + setup.resolver.global_fallback_path.write_bytes(b"not an image") + assert (await setup.resolver.resolve(request)).details["fallback"] == "title_card" + + +@respx.mock +async def test_resolver_without_title_card_raises_the_tmdb_error(tmp_path: Path) -> None: + setup = Setup(tmp_path, fallback_title_card=False) + respx.get(f"{API}/search/multi").respond(json={"results": []}) + try: + with pytest.raises(NoCandidateError): + await setup.resolver.resolve(TmdbRequest(query="x")) + finally: + await setup.fetcher.aclose() + + +async def test_resolver_works_without_a_tmdb_key(tmp_path: Path) -> None: + setup = Setup(tmp_path, api_key="") + try: + asset = await setup.resolver.resolve(TmdbRequest(query="Offline", season=2)) + finally: + await setup.fetcher.aclose() + assert isinstance(asset.layout, TitleCardLayout) + assert asset.layout.subtitle == "Season 2" + assert "not configured" in str(asset.details["fallback_reason"]) diff --git a/tests/test_tmdb_ranking.py b/tests/test_tmdb_ranking.py new file mode 100644 index 0000000..d1aedb5 --- /dev/null +++ b/tests/test_tmdb_ranking.py @@ -0,0 +1,120 @@ +from __future__ import annotations + +import pytest + +from app.providers.tmdb.models import SearchResult, TmdbImage, TmdbRequest +from app.providers.tmdb.ranking import fold, parse_language, pick_result, poster_tier, rank_posters + + +def poster( + name: str, + lang: str | None, + region: str | None = None, + votes: float = 5.0, + count: int = 10, +) -> TmdbImage: + return TmdbImage( + file_path=f"/{name}.jpg", + iso_639_1=lang, + iso_3166_1=region, + vote_average=votes, + vote_count=count, + ) + + +def names(images: list[TmdbImage]) -> list[str]: + return [image.file_path.strip("/").removesuffix(".jpg") for image in images] + + +@pytest.mark.parametrize( + ("language", "expected"), + [("fr-FR", ("fr", "FR")), ("en-US", ("en", "US")), ("fr", ("fr", None))], +) +def test_parse_language(language: str, expected: tuple[str, str | None]) -> None: + assert parse_language(language) == expected + + +def test_posters_follow_the_exact_regional_priority() -> None: + images = [ + poster("german", "de", "DE", votes=9.9), + poster("english", "en", "US", votes=9.0), + poster("textless", None, votes=8.0), + poster("quebec", "fr", "CA", votes=7.0), + poster("france", "fr", "FR", votes=1.0), + poster("french_any", "fr", None, votes=7.5), + ] + ranked = rank_posters(images, "fr", "FR") + assert names(ranked) == ["france", "french_any", "quebec", "textless", "english", "german"] + assert [poster_tier(image, "fr", "FR") for image in ranked] == [0, 1, 1, 2, 3, 4] + + +def test_ties_within_a_tier_use_rating_then_vote_count() -> None: + images = [ + poster("low", "fr", "FR", votes=5.1, count=100), + poster("high", "fr", "FR", votes=5.6, count=2), + poster("high_more_votes", "fr", "FR", votes=5.6, count=40), + ] + assert names(rank_posters(images, "fr", "FR")) == ["high_more_votes", "high", "low"] + + +def test_missing_region_data_degrades_to_language_ranking() -> None: + images = [poster("en", "en"), poster("fr", "fr"), poster("none", None)] + assert names(rank_posters(images, "fr", "FR")) == ["fr", "none", "en"] + # Without a requested region, every French poster shares the first tier. + assert poster_tier(poster("fr_ca", "fr", "CA"), "fr", None) == 1 + + +def test_english_request_still_prefers_its_region() -> None: + images = [poster("gb", "en", "GB", votes=9.0), poster("us", "en", "US", votes=1.0)] + assert names(rank_posters(images, "en", "US")) == ["us", "gb"] + + +def test_fold_ignores_accents_case_and_punctuation() -> None: + assert fold("Amélie") == fold("AMELIE") == "amelie" + assert fold("Le Fabuleux Destin d'Amélie Poulain") == "le fabuleux destin d amelie poulain" + + +def result( + tmdb_id: int, title: str, date: str | None = None, original: str | None = None +) -> SearchResult: + return SearchResult( + id=tmdb_id, media_type="movie", title=title, original_title=original, release_date=date + ) + + +def test_pick_result_prefers_an_exact_title_and_the_requested_year() -> None: + results = [ + result(1, "Dune: Part Two", "2024-02-27"), + result(2, "Dune", "1984-12-14"), + result(3, "Dune", "2021-09-15"), + ] + assert pick_result(results, "dune", 2021) == results[2] + assert pick_result(results, "Dune", None) == results[1] + assert pick_result(results, "Something else", None) == results[0] + assert pick_result([], "Dune", None) is None + + +def test_pick_result_matches_the_original_title() -> None: + results = [ + result(1, "Spirited Away (dub)"), + result(2, "Le Voyage de Chihiro", original="千と千尋の神隠し"), + ] + assert pick_result(results, "千と千尋の神隠し", None) == results[1] + + +def test_search_result_year() -> None: + assert result(1, "x", "2001-04-25").year == 2001 + assert result(1, "x", "").year is None + assert result(1, "x", "garbage").year is None + + +def test_request_validation() -> None: + assert TmdbRequest(query=" Amélie ").query == "Amélie" + assert TmdbRequest(query="x", media_type="auto").media_type == "multi" # type: ignore[arg-type] + assert TmdbRequest(query="x", language="fr-CA").language == "fr-CA" + with pytest.raises(ValueError): + TmdbRequest(query="x", media_type="movie", season=2) + with pytest.raises(ValueError): + TmdbRequest(query="x", language="french") + with pytest.raises(ValueError): + TmdbRequest(query=" ") From 4a0ac32f07b777bc3c0d545b6920831f4f69335b Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sun, 15 Nov 2026 15:52:53 +0100 Subject: [PATCH 55/86] feat: add TMDB display endpoint and scheduler runner POST /api/display/tmdb finds a movie or series and shows its best poster with the poster template. Pushes are ephemeral by default: they expire after tmdb.ephemeral_ttl_minutes (or ttl_minutes), can be cancelled with DELETE /api/queue/ephemeral, honour tmdb.hold_minutes, and are not replayed. Non-ephemeral pushes become the rule replayed by POST /api/refresh. POST /api/display/media is kept as a deprecated alias accepting title and media_type auto. The tmdb runner makes kind "tmdb" valid in Smart Mix entries and context boosts (replayed as regular images). ttl_minutes, ttl_seconds and fallback_base64 are never stored in replayed rules. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- app/api/deps.py | 7 ++ app/api/routes/refresh.py | 2 +- app/api/routes/smart_mix.py | 13 ++- app/api/routes/tmdb.py | 106 +++++++++++++++++++++ app/main.py | 17 +++- app/providers/tmdb/models.py | 66 ++++++++++++- app/services/scheduler.py | 42 ++++++++- tests/test_api_smart_mix.py | 2 +- tests/test_api_tmdb.py | 175 +++++++++++++++++++++++++++++++++++ 9 files changed, 422 insertions(+), 8 deletions(-) create mode 100644 app/api/routes/tmdb.py create mode 100644 tests/test_api_tmdb.py diff --git a/app/api/deps.py b/app/api/deps.py index 4357b48..60c5629 100644 --- a/app/api/deps.py +++ b/app/api/deps.py @@ -10,6 +10,7 @@ from app.core.history_store import HistoryStore from app.core.settings import EnvSettings from app.providers.immich import ImmichProvider, PeopleDirectory +from app.providers.tmdb import PosterResolver from app.services.current_image import CurrentImageStore from app.services.delivery import DeliveryService from app.services.display import DisplayService @@ -52,6 +53,11 @@ def get_immich_provider(request: Request) -> ImmichProvider: return cast(ImmichProvider, request.app.state.immich_provider) +def get_poster_resolver(request: Request) -> PosterResolver: + """TMDB posters with the Home Assistant and global fallbacks.""" + return cast(PosterResolver, request.app.state.poster_resolver) + + def get_scheduler_service(request: Request) -> SchedulerService: """The autonomous refresh scheduler.""" return cast(SchedulerService, request.app.state.scheduler_service) @@ -77,3 +83,4 @@ def get_people_directory(request: Request) -> PeopleDirectory: PeopleDirectoryDep = Annotated[PeopleDirectory, Depends(get_people_directory)] SchedulerDep = Annotated[SchedulerService, Depends(get_scheduler_service)] EphemeralServiceDep = Annotated[EphemeralService, Depends(get_ephemeral_service)] +PosterResolverDep = Annotated[PosterResolver, Depends(get_poster_resolver)] diff --git a/app/api/routes/refresh.py b/app/api/routes/refresh.py index 3e5dc7a..e0589e9 100644 --- a/app/api/routes/refresh.py +++ b/app/api/routes/refresh.py @@ -22,7 +22,7 @@ class RefreshResult(BaseModel): """Outcome of a manual refresh.""" reason: Literal["manual"] = "manual" - rule_kind: str = Field(description="Source of the replayed rule (immich, media, url)") + rule_kind: str = Field(description="Source of the replayed rule (immich, tmdb)") rule_source: RuleSource = Field( description="pinned = scheduler.source_rule; smart_mix = the weighted playlist; " "last = the last manual display request" diff --git a/app/api/routes/smart_mix.py b/app/api/routes/smart_mix.py index d174523..81780cb 100644 --- a/app/api/routes/smart_mix.py +++ b/app/api/routes/smart_mix.py @@ -26,6 +26,7 @@ from app.core.auth import api_key_scheme from app.core.config_models import FitMode, SourceKind, SourceRule from app.providers.immich.models import ImmichDisplayRequest, MatchMode, OnThisDay +from app.providers.tmdb.models import TmdbDisplayRequest from app.services.display import DisplayResult from app.services.scheduler import ContextView, validation_summary from app.services.smart_mix import DEFAULT_CONTEXT_WEIGHT, MixContext @@ -155,6 +156,13 @@ class ContextResponse(ContextView): ) +#: Request models validating the params of a boosted rule, per source kind. +_RULE_MODELS: dict[str, type[BaseModel]] = { + "immich": ImmichDisplayRequest, + "tmdb": TmdbDisplayRequest, +} + + def _rule_from(body: ContextRequest) -> SourceRule: params: dict[str, JsonValue] = dict(body.params) shorthand = bool(body.queries or body.persons or body.on_this_day) @@ -171,9 +179,10 @@ def _rule_from(body: ContextRequest) -> SourceRule: params["on_this_day"] = {} if not params: raise HTTPException(status_code=422, detail="Give params or queries for the boost") - if body.kind == "immich": + model = _RULE_MODELS.get(body.kind) + if model is not None: try: - ImmichDisplayRequest.model_validate(params) + model.model_validate(params) except ValidationError as exc: raise HTTPException(status_code=422, detail=validation_summary(exc)) from exc return SourceRule(kind=body.kind, params=params) diff --git a/app/api/routes/tmdb.py b/app/api/routes/tmdb.py new file mode 100644 index 0000000..23b2596 --- /dev/null +++ b/app/api/routes/tmdb.py @@ -0,0 +1,106 @@ +"""TMDB poster display (movie / TV playback from Home Assistant).""" + +from __future__ import annotations + +from datetime import timedelta +from typing import Any + +from fastapi import APIRouter, HTTPException, Security + +from app.api.deps import ConfigStoreDep, DisplayServiceDep, PosterResolverDep, SchedulerDep +from app.api.errors import PROVIDER_ERROR_RESPONSES, provider_http_error +from app.core.auth import api_key_scheme +from app.core.config_store import ConfigStore +from app.core.security import InvalidImageError +from app.providers.base import ProviderError +from app.providers.tmdb import PosterResolver +from app.providers.tmdb.models import TmdbDisplayRequest +from app.services.display import DisplayResult, DisplayService +from app.services.scheduler import SchedulerService, tmdb_rule + +display_router = APIRouter( + prefix="/api/display", tags=["display"], dependencies=[Security(api_key_scheme)] +) + +_ERRORS: dict[int | str, dict[str, Any]] = { + **PROVIDER_ERROR_RESPONSES, + 404: {"description": "No poster found and tmdb.fallback_title_card is disabled"}, + 409: {"description": "TMDB is not configured and tmdb.fallback_title_card is disabled"}, +} + + +@display_router.post( + "/tmdb", + response_model=DisplayResult, + responses=_ERRORS, + summary="Display a movie or TV series poster", +) +async def display_tmdb( + body: TmdbDisplayRequest, + resolver: PosterResolverDep, + display: DisplayServiceDep, + scheduler: SchedulerDep, + config: ConfigStoreDep, +) -> DisplayResult: + """Find the title on TMDB and show its best poster, uncropped, over a blurred backdrop. + + Posters are ranked for ``language`` (default ``tmdb.language``): exact language and + region first (``fr``/``FR``), then the same language, textless artwork, English, and + anything else. When TMDB has no match or fails, ``fallback_base64`` / ``fallback_url`` + (e.g. the Home Assistant ``media_player`` picture) is used, then + ``/data/assets/tmdb_fallback.png``, then a typographic title card. + + By default the poster is **ephemeral**: after ``ttl_minutes`` (default + ``tmdb.ephemeral_ttl_minutes``) or ``DELETE /api/queue/ephemeral`` the previous image comes + back, and a deep-sleeping frame that wakes up later never receives an expired poster. + """ + return await show_tmdb(body, resolver, display, scheduler, config) + + +@display_router.post( + "/media", + response_model=DisplayResult, + responses=_ERRORS, + summary="Display a poster (alias of /api/display/tmdb)", + deprecated=True, +) +async def display_media( + body: TmdbDisplayRequest, + resolver: PosterResolverDep, + display: DisplayServiceDep, + scheduler: SchedulerDep, + config: ConfigStoreDep, +) -> DisplayResult: + """Same as ``POST /api/display/tmdb`` (``title`` and ``media_type: auto`` accepted).""" + return await show_tmdb(body, resolver, display, scheduler, config) + + +async def show_tmdb( + body: TmdbDisplayRequest, + resolver: PosterResolver, + display: DisplayService, + scheduler: SchedulerService, + config: ConfigStore, +) -> DisplayResult: + """Resolve, render and (when pushed) record one TMDB display request.""" + settings = config.config.tmdb + try: + asset = await resolver.resolve( + body.search(), fallback_url=body.fallback_url, fallback_base64=body.fallback_base64 + ) + except ProviderError as exc: + raise provider_http_error(exc) from exc + ttl = body.ttl_minutes or settings.ephemeral_ttl_minutes + expires_at = scheduler.now() + timedelta(minutes=ttl) if body.ephemeral else None + try: + result = await display.display_asset( + asset, push=body.push_to_fraimic, ephemeral=body.ephemeral, expires_at=expires_at + ) + except InvalidImageError as exc: + raise HTTPException( + status_code=502, detail="The poster could not be decoded as an image" + ) from exc + if body.push_to_fraimic: + hold = body.hold_minutes if body.hold_minutes is not None else settings.hold_minutes + await scheduler.record_manual(tmdb_rule(body), ephemeral=body.ephemeral, hold_minutes=hold) + return result diff --git a/app/main.py b/app/main.py index 86fe329..899eccc 100644 --- a/app/main.py +++ b/app/main.py @@ -28,6 +28,8 @@ from app.api.routes import refresh as refresh_routes from app.api.routes import smart_mix as smart_mix_routes from app.api.routes import system as system_routes +from app.api.routes import tmdb as tmdb_routes +from app.clients.http_images import ImageFetcher from app.core.auth import APIKeyMiddleware from app.core.config_models import RuntimeConfig from app.core.config_store import ConfigStore @@ -38,11 +40,12 @@ from app.core.security import URLPolicy from app.core.settings import EnvSettings, get_env_settings from app.providers.immich import ImmichGateway, ImmichProvider, PeopleDirectory +from app.providers.tmdb import PosterResolver, TmdbProvider from app.services.current_image import CurrentImageStore from app.services.delivery import DeliveryService from app.services.display import DisplayService from app.services.ephemeral import EphemeralService -from app.services.scheduler import SchedulerService, immich_runner +from app.services.scheduler import SchedulerService, immich_runner, tmdb_runner logger = logging.getLogger(__name__) @@ -117,10 +120,16 @@ async def _on_config_change(_: RuntimeConfig) -> None: history_store, max_bytes=settings.max_upload_bytes, ) + image_fetcher = ImageFetcher(url_policy, settings.max_upload_bytes) + tmdb = TmdbProvider(config_store, image_fetcher) + poster_resolver = PosterResolver(tmdb, image_fetcher, config_store, settings.assets_dir) scheduler = SchedulerService( settings.scheduler_state_path, config_store, - {"immich": immich_runner(immich, display)}, + { + "immich": immich_runner(immich, display), + "tmdb": tmdb_runner(poster_resolver, display), + }, has_pending=lambda: delivery.pending is not None, ) scheduler.load() @@ -141,6 +150,8 @@ async def _on_config_change(_: RuntimeConfig) -> None: app.state.immich_provider = immich app.state.scheduler_service = scheduler app.state.ephemeral_service = ephemeral + app.state.image_fetcher = image_fetcher + app.state.poster_resolver = poster_resolver await ephemeral.start() # before the delivery worker can drop an expired image await delivery.start() @@ -164,6 +175,7 @@ async def _on_config_change(_: RuntimeConfig) -> None: await scheduler.stop() await ephemeral.stop() await delivery.stop() + await image_fetcher.aclose() logger.info("Smart Frame Engine stopped") app = FastAPI( @@ -212,6 +224,7 @@ async def _validation_handler(_: Request, exc: RequestValidationError) -> JSONRe app.include_router(image_routes.router) app.include_router(display_routes.router) app.include_router(immich_routes.display_router) + app.include_router(tmdb_routes.display_router) app.include_router(immich_routes.router) app.include_router(refresh_routes.router) app.include_router(smart_mix_routes.display_router) diff --git a/app/providers/tmdb/models.py b/app/providers/tmdb/models.py index 160869e..af3465c 100644 --- a/app/providers/tmdb/models.py +++ b/app/providers/tmdb/models.py @@ -6,7 +6,14 @@ from datetime import date from typing import Final, Literal -from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator +from pydantic import ( + AliasChoices, + BaseModel, + ConfigDict, + Field, + field_validator, + model_validator, +) TmdbMediaType = Literal["movie", "tv", "multi"] ResultMediaType = Literal["movie", "tv"] @@ -112,3 +119,60 @@ def _blank_is_none(cls, value: object) -> object: if isinstance(value, str) and not value.strip(): return None return value + + +MAX_FALLBACK_URL_LENGTH: Final = 4096 +#: Upper bound of a base64 fallback picture (the decoded size is checked separately). +MAX_FALLBACK_BASE64_LENGTH: Final = 40_000_000 + + +class TmdbDisplayRequest(TmdbRequest): + """Body of ``POST /api/display/tmdb`` (and of replayable ``tmdb`` rules).""" + + query: str = Field( + min_length=1, + max_length=200, + validation_alias=AliasChoices("query", "title"), + description="Movie or series title ('title' is accepted as an alias)", + ) + fallback_url: str | None = Field( + default=None, + max_length=MAX_FALLBACK_URL_LENGTH, + description="Picture used when TMDB has no match, e.g. the absolute URL of the Home " + "Assistant media_player entity_picture", + ) + fallback_base64: str | None = Field( + default=None, + max_length=MAX_FALLBACK_BASE64_LENGTH, + description="Same as fallback_url, as base64 (or a data: URI); tried first", + ) + push_to_fraimic: bool = Field( + default=True, description="Send to the frame; false only renders a preview" + ) + ephemeral: bool = Field( + default=True, + description="Temporary poster: the previous image comes back after ttl_minutes or " + "DELETE /api/queue/ephemeral, and the request is not replayed by POST /api/refresh", + ) + ttl_minutes: int | None = Field( + default=None, + ge=1, + le=1440, + description="Ephemeral lifetime (default tmdb.ephemeral_ttl_minutes)", + ) + hold_minutes: int | None = Field( + default=None, + ge=1, + le=10080, + description="Protect the poster from scheduled refreshes (default tmdb.hold_minutes)", + ) + + def search(self) -> TmdbRequest: + """The TMDB lookup part of the request.""" + return TmdbRequest( + query=self.query, + media_type=self.media_type, + year=self.year, + season=self.season, + language=self.language, + ) diff --git a/app/services/scheduler.py b/app/services/scheduler.py index 0d036ec..f5395a3 100644 --- a/app/services/scheduler.py +++ b/app/services/scheduler.py @@ -49,6 +49,8 @@ from app.core.security import InvalidImageError from app.providers.base import ProviderError from app.providers.immich import ImmichDisplayRequest, ImmichProvider +from app.providers.tmdb import PosterResolver +from app.providers.tmdb.models import TmdbDisplayRequest from app.services.display import DisplayResult, DisplayService from app.services.schedule import QuietWindow, in_quiet, next_run_at from app.services.smart_mix import MixCandidate, MixContext, SmartMixResolver @@ -67,7 +69,15 @@ #: Request fields that describe one action rather than the selection; never replayed. NON_REPLAYED_FIELDS: Final = frozenset( - {"push_to_fraimic", "ignore_history", "ephemeral", "hold_minutes"} + { + "push_to_fraimic", + "ignore_history", + "ephemeral", + "hold_minutes", + "ttl_minutes", + "ttl_seconds", + "fallback_base64", + } ) @@ -789,3 +799,33 @@ async def run(rule: SourceRule) -> DisplayResult: return await display.display_asset(asset, fit=request.fit, push=True) return run + + +def tmdb_rule(request: TmdbDisplayRequest) -> SourceRule: + """The replayable rule of a TMDB display request (only the fields it set). + + ``fallback_base64`` is never stored (it can be megabytes of picture data). + """ + params = request.model_dump(mode="json", exclude_unset=True, exclude=set(NON_REPLAYED_FIELDS)) + return SourceRule(kind="tmdb", params=params) + + +def tmdb_runner(resolver: PosterResolver, display: DisplayService) -> RuleRunner: + """Replay ``tmdb`` rules: show the poster again as a regular (non-ephemeral) image. + + A Smart Mix entry such as ``{"kind": "tmdb", "params": {"query": "Amélie"}}`` thus puts a + favourite poster into the rotation like any photo. + """ + + async def run(rule: SourceRule) -> DisplayResult: + params = { + key: value for key, value in rule.params.items() if key not in NON_REPLAYED_FIELDS + } + try: + request = TmdbDisplayRequest.model_validate(params) + except ValidationError as exc: + raise InvalidRuleError(f"Invalid tmdb rule: {validation_summary(exc)}") from None + asset = await resolver.resolve(request.search(), fallback_url=request.fallback_url) + return await display.display_asset(asset, push=True) + + return run diff --git a/tests/test_api_smart_mix.py b/tests/test_api_smart_mix.py index 85c9e13..91bfeb5 100644 --- a/tests/test_api_smart_mix.py +++ b/tests/test_api_smart_mix.py @@ -204,7 +204,7 @@ def test_playlist_view(make_client: ClientFactory) -> None: ) view = client.get("/api/smart-mix").json() - assert view["enabled"] and view["effective"] and view["supported_kinds"] == ["immich"] + assert view["enabled"] and view["effective"] and view["supported_kinds"] == ["immich", "tmdb"] assert [e["probability"] for e in view["entries"]] == [0.75, 0.25, 0.0] season = RuleContext(datetime.now(UTC), ZoneInfo("UTC")).season assert view["entries"][1]["resolved_params"]["clip_queries"] == [f"{season} light"] diff --git a/tests/test_api_tmdb.py b/tests/test_api_tmdb.py new file mode 100644 index 0000000..3469f2b --- /dev/null +++ b/tests/test_api_tmdb.py @@ -0,0 +1,175 @@ +from __future__ import annotations + +import io +from datetime import UTC, datetime, timedelta +from typing import Any + +import httpx +import respx +from fastapi.testclient import TestClient +from PIL import Image + +from tests.conftest import ClientFactory + +API = "https://api.themoviedb.org/3" +IMG = "https://image.tmdb.org/t/p" +KEY = "0123456789abcdef0123456789abcdef" + + +def png_bytes(color: tuple[int, int, int] = (180, 40, 40)) -> bytes: + buffer = io.BytesIO() + Image.new("RGB", (200, 300), color).save(buffer, format="PNG") + return buffer.getvalue() + + +def mock_amelie() -> None: + # The deep-sleeping frame never answers (the worker probes it after a push). + respx.get("http://frame.test/api/info").mock(side_effect=httpx.ConnectTimeout("asleep")) + respx.get(f"{API}/search/movie").respond( + json={"results": [{"id": 194, "title": "Amélie", "release_date": "2001-04-25"}]} + ) + respx.get(f"{API}/movie/194/images").respond( + json={"posters": [{"file_path": "/fr.jpg", "iso_639_1": "fr", "iso_3166_1": "FR"}]} + ) + respx.get(f"{IMG}/w780/fr.jpg").respond(content=png_bytes()) + + +def tmdb_client(make_client: ClientFactory, **overrides: Any) -> TestClient: + overrides.setdefault("tmdb_api_key", KEY) + return make_client(fraimic_host="frame.test", fraimic_power_mode="deepsleep", **overrides) + + +def show(client: TestClient, **body: Any) -> Any: + body.setdefault("query", "Amélie") + body.setdefault("media_type", "movie") + response = client.post("/api/display/tmdb", json=body) + assert response.status_code == 200, response.text + return response.json() + + +@respx.mock +def test_ephemeral_poster_push(make_client: ClientFactory) -> None: + mock_amelie() + client = tmdb_client(make_client) + before = datetime.now(UTC) + body = show(client) + + image = body["image"] + assert image["template"] == "poster" + assert image["source"] == "tmdb" + assert image["ephemeral"] is True + expires = datetime.fromisoformat(image["expires_at"]) + assert before + timedelta(minutes=179) < expires < datetime.now(UTC) + timedelta(minutes=181) + assert body["delivery"]["status"] == "queued" + + queue = client.get("/api/queue").json() + assert queue["pending"]["ephemeral"] is True + assert queue["ephemeral"]["active"] and queue["ephemeral"]["template"] == "poster" + status = client.get("/api/status").json() + assert status["scheduler"]["active_rule"] is None # an ephemeral push is not replayed + + +@respx.mock +def test_ttl_and_hold_overrides(make_client: ClientFactory) -> None: + mock_amelie() + client = tmdb_client(make_client) + assert client.put("/api/config", json={"tmdb": {"hold_minutes": 30}}).status_code == 200 + body = show(client, ttl_minutes=5) + expires = datetime.fromisoformat(body["image"]["expires_at"]) + assert expires < datetime.now(UTC) + timedelta(minutes=6) + hold = client.get("/api/status").json()["scheduler"]["hold_until"] + assert hold is not None + + +@respx.mock +def test_non_ephemeral_poster_becomes_the_replayed_rule(make_client: ClientFactory) -> None: + mock_amelie() + client = tmdb_client(make_client) + body = show(client, ephemeral=False, fallback_base64="aGVsbG8=") + assert body["image"]["ephemeral"] is False + assert body["image"]["expires_at"] is None + status = client.get("/api/status").json() + assert status["scheduler"]["active_rule"] == {"kind": "tmdb", "source": "last"} + + refreshed = client.post("/api/refresh") + assert refreshed.status_code == 200, refreshed.text + assert refreshed.json()["rule_kind"] == "tmdb" + assert refreshed.json()["rule_source"] == "last" + state = client.app.state.scheduler_service.state # type: ignore[attr-defined] + assert state.last_rule.params == {"query": "Amélie", "media_type": "movie"} + + +@respx.mock +def test_push_false_renders_a_preview_only(make_client: ClientFactory) -> None: + mock_amelie() + client = tmdb_client(make_client) + body = show(client, push_to_fraimic=False) + assert body["delivery"] is None + assert client.get("/api/current.jpg").status_code == 404 + preview = client.get("/api/preview.jpg") + assert preview.status_code == 200 + assert Image.open(io.BytesIO(preview.content)).size == (1200, 1600) + assert client.get("/api/queue").json()["pending"] is None + + +def test_title_card_when_tmdb_is_not_configured(make_client: ClientFactory) -> None: + client = tmdb_client(make_client, tmdb_api_key="") + body = show(client, query="Some Home Movie", year=1999) + assert body["image"]["template"] == "title_card" + assert body["image"]["details"]["fallback"] == "title_card" + + +def test_errors_without_any_fallback(make_client: ClientFactory) -> None: + client = tmdb_client(make_client, tmdb_api_key="") + assert ( + client.put("/api/config", json={"tmdb": {"fallback_title_card": False}}).status_code == 200 + ) + response = client.post("/api/display/tmdb", json={"query": "x"}) + assert response.status_code == 409 + invalid = {"query": "x", "season": 1, "media_type": "movie"} + assert client.post("/api/display/tmdb", json=invalid).status_code == 422 + + +@respx.mock +def test_media_alias_accepts_title_and_auto(make_client: ClientFactory) -> None: + respx.get(f"{API}/search/multi").respond( + json={"results": [{"id": 194, "media_type": "movie", "title": "Amélie"}]} + ) + respx.get(f"{API}/movie/194/images").respond(json={"posters": [{"file_path": "/fr.jpg"}]}) + respx.get(f"{IMG}/w780/fr.jpg").respond(content=png_bytes()) + client = tmdb_client(make_client) + response = client.post( + "/api/display/media", + json={"title": "Amélie", "media_type": "auto", "push_to_fraimic": False}, + ) + assert response.status_code == 200, response.text + assert response.json()["image"]["details"]["tmdb_id"] == 194 + + +@respx.mock +def test_smart_mix_entries_can_replay_posters(make_client: ClientFactory) -> None: + mock_amelie() + client = tmdb_client(make_client) + entry = {"kind": "tmdb", "params": {"query": "Amélie", "media_type": "movie"}, "label": "Film"} + response = client.put("/api/config", json={"smart_mix": {"enabled": True, "entries": [entry]}}) + assert response.status_code == 200 + refreshed = client.post("/api/refresh") + assert refreshed.status_code == 200, refreshed.text + body = refreshed.json() + assert body["rule_kind"] == "tmdb" + assert body["rule_source"] == "smart_mix" + assert body["entry_label"] == "Film" + current = client.get("/api/status").json()["current_image"] + assert current["template"] == "poster" and current["ephemeral"] is False + + +def test_smart_mix_context_validates_tmdb_params(make_client: ClientFactory) -> None: + client = tmdb_client(make_client) + assert client.put("/api/config", json={"smart_mix": {"enabled": True}}).status_code == 200 + bad = client.post("/api/smart-mix/context", json={"kind": "tmdb", "params": {"a": 1}}) + assert bad.status_code == 422 + good = client.post( + "/api/smart-mix/context", json={"kind": "tmdb", "params": {"query": "Amélie"}} + ) + assert good.status_code == 200, good.text + assert good.json()["kind"] == "tmdb" From 7881f80a97614fd8abab78a84666635ab77eaee0 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sun, 15 Nov 2026 15:57:15 +0100 Subject: [PATCH 56/86] feat: add Deezer and MusicBrainz artwork lookup ArtworkResolver finds high-resolution album covers without any API key: the Deezer public search (album, else track; cover_xl 1000x1000), then a MusicBrainz release-group or recording search with the matching Cover Art Archive front-1200 image (redirects are followed through the SSRF-checked fetcher). MusicBrainz calls are rate-limited to one per second with a descriptive User-Agent, Deezer quota errors fall through, and lookups (including misses, but never transient failures) are cached in an in-memory LRU. Add the music configuration section and a shared fold() text helper. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- app/core/config_models.py | 33 +++ app/core/text.py | 20 ++ app/providers/music/__init__.py | 10 + app/providers/music/artwork.py | 353 ++++++++++++++++++++++++++++++++ app/providers/tmdb/provider.py | 3 +- app/providers/tmdb/ranking.py | 11 +- tests/test_api.py | 1 + tests/test_music_artwork.py | 247 ++++++++++++++++++++++ tests/test_tmdb_ranking.py | 3 +- 9 files changed, 669 insertions(+), 12 deletions(-) create mode 100644 app/core/text.py create mode 100644 app/providers/music/__init__.py create mode 100644 app/providers/music/artwork.py create mode 100644 tests/test_music_artwork.py diff --git a/app/core/config_models.py b/app/core/config_models.py index 7fdbcbb..ac94f34 100644 --- a/app/core/config_models.py +++ b/app/core/config_models.py @@ -237,6 +237,38 @@ def _validate_language(cls, value: str) -> str: return value +class MusicConfig(_Section): + """Now-playing album covers (POST /api/display/now-playing).""" + + enrich_artwork: bool = Field( + default=True, + description="Look up a high-resolution cover (Deezer, then MusicBrainz / Cover Art " + "Archive) when none is provided or it cannot be downloaded", + ) + default_style: Literal["sleeve", "vinyl"] = Field( + default="sleeve", description="Album template style: sleeve, or vinyl (a record peeks out)" + ) + default_ttl_minutes: int = Field( + default=10, + ge=1, + le=1440, + description="Cover lifetime when the request gives no duration or ttl", + ) + ttl_grace_seconds: int = Field( + default=30, + ge=0, + le=3600, + description="Added to the remaining track time so the cover outlives short gaps", + ) + deezer_enabled: bool = Field(default=True, description="Search covers on Deezer (no key)") + musicbrainz_enabled: bool = Field( + default=True, description="Fall back to MusicBrainz / Cover Art Archive" + ) + lookup_cache_size: int = Field( + default=256, ge=0, le=10_000, description="Cover lookups remembered in memory (0 = off)" + ) + + class FraimicConfig(_Section): """Fraimic frame connection, panel model and power management.""" @@ -545,6 +577,7 @@ class RuntimeConfig(BaseModel): immich: ImmichConfig = Field(default_factory=ImmichConfig) tmdb: TmdbConfig = Field(default_factory=TmdbConfig) + music: MusicConfig = Field(default_factory=MusicConfig) fraimic: FraimicConfig = Field(default_factory=FraimicConfig) display: DisplayConfig = Field(default_factory=DisplayConfig) eink: EinkConfig = Field(default_factory=EinkConfig) diff --git a/app/core/text.py b/app/core/text.py new file mode 100644 index 0000000..f3d86c4 --- /dev/null +++ b/app/core/text.py @@ -0,0 +1,20 @@ +"""Text normalization shared by providers (title and artist matching).""" + +from __future__ import annotations + +import re +import unicodedata +from typing import Final + +_NON_WORD: Final = re.compile(r"[^\w]+") + + +def fold(text: str) -> str: + """Accent-, case- and punctuation-insensitive form of a title or name. + + ``"Le Fabuleux Destin d'Amélie"`` and ``"le fabuleux destin d amelie"`` fold to the same + value, so do ``"AC/DC"`` and ``"ac dc"``. + """ + decomposed = unicodedata.normalize("NFKD", text) + stripped = "".join(char for char in decomposed if not unicodedata.combining(char)) + return " ".join(_NON_WORD.sub(" ", stripped.casefold()).split()) diff --git a/app/providers/music/__init__.py b/app/providers/music/__init__.py new file mode 100644 index 0000000..b63d3c8 --- /dev/null +++ b/app/providers/music/__init__.py @@ -0,0 +1,10 @@ +"""Music now-playing support: album cover lookup (Deezer, MusicBrainz / Cover Art Archive).""" + +from app.providers.music.artwork import ( + Artwork, + ArtworkMatch, + ArtworkResolver, + MinIntervalLimiter, +) + +__all__ = ["Artwork", "ArtworkMatch", "ArtworkResolver", "MinIntervalLimiter"] diff --git a/app/providers/music/artwork.py b/app/providers/music/artwork.py new file mode 100644 index 0000000..f3ed7b2 --- /dev/null +++ b/app/providers/music/artwork.py @@ -0,0 +1,353 @@ +"""High-resolution album cover lookup for now-playing displays (no API key needed). + +1. **Deezer** public search API: ``/search/album`` (artist + album) or ``/search`` (artist + + track) and the ``cover_xl`` picture (1000x1000). +2. **MusicBrainz** release-group search (rate-limited to one request per second as their + policy requires, with a descriptive User-Agent) and the matching **Cover Art Archive** + front cover (``front-1200``; the archive answers with a redirect to its storage). + +Lookups are cached in memory (including "no cover" answers, but never transient errors), +so Home Assistant attribute updates do not hammer the services. The resolver never +raises: a failed lookup returns ``None`` and the caller renders a typographic card. +""" + +from __future__ import annotations + +import asyncio +import logging +import time +from collections import OrderedDict +from collections.abc import Awaitable, Callable +from dataclasses import dataclass +from typing import Any, Final, Literal + +import httpx + +from app.clients.http_images import USER_AGENT, ImageFetcher, ImageFetchError +from app.core.config_store import ConfigStore +from app.core.text import fold + +logger = logging.getLogger(__name__) + +DEEZER_API: Final = "https://api.deezer.com" +MUSICBRAINZ_API: Final = "https://musicbrainz.org/ws/2" +COVER_ART_ARCHIVE: Final = "https://coverartarchive.org" +MUSICBRAINZ_INTERVAL_S: Final = 1.0 +CONNECT_TIMEOUT_S: Final = 5.0 +READ_TIMEOUT_S: Final = 10.0 +SEARCH_LIMIT: Final = 10 +#: Minimum MusicBrainz search score (0-100) to accept a release group. +MIN_MUSICBRAINZ_SCORE: Final = 80 +_LUCENE_SPECIAL: Final = '+-&|!(){}[]^"~*?:\\/' + +ArtworkSource = Literal["deezer", "musicbrainz"] + + +class ArtworkLookupError(Exception): + """A transient lookup failure (network, rate limit): the answer must not be cached.""" + + +@dataclass(frozen=True, slots=True) +class ArtworkMatch: + """A cover found for a track or album.""" + + url: str + source: ArtworkSource + album: str | None = None + artist: str | None = None + + +@dataclass(frozen=True, slots=True) +class Artwork: + """Downloaded cover bytes and where they came from.""" + + data: bytes + match: ArtworkMatch + + +def lucene_quote(value: str) -> str: + """``value`` as a quoted Lucene phrase with special characters escaped.""" + escaped = "".join(f"\\{char}" if char in _LUCENE_SPECIAL else char for char in value) + return f'"{escaped}"' + + +def _same(a: str | None, b: str | None) -> bool: + return bool(a) and bool(b) and fold(a or "") == fold(b or "") + + +def _artist_matches(wanted: str, candidate: str | None) -> bool: + """Exact folded match, or one name containing the other ("Queen" / "Queen + Bowie").""" + if not candidate: + return False + a, b = fold(wanted), fold(candidate) + return bool(a) and bool(b) and (a == b or a in b or b in a) + + +class MinIntervalLimiter: + """Allows one call per ``interval_s`` seconds (shared by concurrent callers).""" + + def __init__( + self, + interval_s: float, + *, + clock: Callable[[], float] = time.monotonic, + sleep: Callable[[float], Awaitable[None]] = asyncio.sleep, + ) -> None: + self._interval = interval_s + self._clock = clock + self._sleep = sleep + self._lock = asyncio.Lock() + self._last: float | None = None + + async def wait(self) -> None: + """Wait until the next call is allowed.""" + async with self._lock: + if self._last is not None: + delay = self._last + self._interval - self._clock() + if delay > 0: + await self._sleep(delay) + self._last = self._clock() + + +class ArtworkResolver: + """Finds and downloads album covers from Deezer, then MusicBrainz / Cover Art Archive.""" + + def __init__( + self, + config_store: ConfigStore, + fetcher: ImageFetcher, + *, + transport: httpx.AsyncBaseTransport | None = None, + limiter: MinIntervalLimiter | None = None, + ) -> None: + self._config_store = config_store + self._fetcher = fetcher + self._http = httpx.AsyncClient( + headers={"User-Agent": USER_AGENT, "Accept": "application/json"}, + timeout=httpx.Timeout(READ_TIMEOUT_S, connect=CONNECT_TIMEOUT_S), + follow_redirects=False, + transport=transport, + ) + self._limiter = limiter or MinIntervalLimiter(MUSICBRAINZ_INTERVAL_S) + self._cache: OrderedDict[tuple[str, str, str], ArtworkMatch | None] = OrderedDict() + + async def aclose(self) -> None: + """Close the connection pool.""" + await self._http.aclose() + + # --- Public API ----------------------------------------------------------------------- + async def find(self, *, title: str, artist: str, album: str | None) -> Artwork | None: + """Download the best cover for a track (``None`` when nothing usable was found).""" + match = await self.lookup(title=title, artist=artist, album=album) + if match is None: + return None + try: + data = await self._fetcher.fetch(match.url) + except ImageFetchError as exc: + logger.info("Cover download from %s failed: %s", match.source, exc) + return None + return Artwork(data, match) + + async def lookup(self, *, title: str, artist: str, album: str | None) -> ArtworkMatch | None: + """The cover URL for a track, from the cache or the services.""" + key = (fold(artist), fold(album or ""), fold(title)) + size = self._config_store.config.music.lookup_cache_size + if size and key in self._cache: + self._cache.move_to_end(key) + return self._cache[key] + try: + match = await self._search(title=title, artist=artist, album=album) + except ArtworkLookupError as exc: + logger.info("Cover lookup failed (not cached): %s", exc) + return None + if size: + self._cache[key] = match + while len(self._cache) > size: + self._cache.popitem(last=False) + return match + + # --- Search --------------------------------------------------------------------------- + async def _search(self, *, title: str, artist: str, album: str | None) -> ArtworkMatch | None: + config = self._config_store.config.music + transient = False + if config.deezer_enabled: + try: + match = await self._deezer(title=title, artist=artist, album=album) + if match is not None: + return match + except ArtworkLookupError as exc: + logger.info("Deezer cover lookup failed: %s", exc) + transient = True + if config.musicbrainz_enabled: + try: + match = await self._musicbrainz(title=title, artist=artist, album=album) + if match is not None: + return match + except ArtworkLookupError as exc: + logger.info("MusicBrainz cover lookup failed: %s", exc) + transient = True + if transient: + raise ArtworkLookupError("no cover found and a service failed") + return None + + async def _get_json(self, url: str, params: dict[str, Any], service: str) -> dict[str, Any]: + try: + response = await self._http.get(url, params=params) + except httpx.HTTPError as exc: + raise ArtworkLookupError(f"{service} unreachable ({type(exc).__name__})") from None + if response.status_code in {429, 503}: + raise ArtworkLookupError(f"{service} rate limit (HTTP {response.status_code})") + if response.status_code != 200: + raise ArtworkLookupError(f"{service} answered HTTP {response.status_code}") + try: + payload = response.json() + except ValueError: + raise ArtworkLookupError(f"{service} returned invalid JSON") from None + if not isinstance(payload, dict): + raise ArtworkLookupError(f"{service} returned an unexpected payload") + return payload + + async def _deezer(self, *, title: str, artist: str, album: str | None) -> ArtworkMatch | None: + if album: + payload = await self._get_json( + f"{DEEZER_API}/search/album", + {"q": f'artist:"{artist}" album:"{album}"', "limit": SEARCH_LIMIT}, + "Deezer", + ) + self._check_deezer_error(payload) + match = self._pick_deezer_album(payload.get("data"), artist, album) + if match is not None: + return match + payload = await self._get_json( + f"{DEEZER_API}/search", + {"q": f'artist:"{artist}" track:"{title}"', "limit": SEARCH_LIMIT}, + "Deezer", + ) + self._check_deezer_error(payload) + return self._pick_deezer_track(payload.get("data"), artist, album) + + @staticmethod + def _check_deezer_error(payload: dict[str, Any]) -> None: + error = payload.get("error") + if isinstance(error, dict): + # Deezer reports quota errors (code 4) with HTTP 200. + raise ArtworkLookupError(f"Deezer error {error.get('code')}: {error.get('message')}") + + @staticmethod + def _pick_deezer_album(data: object, artist: str, album: str) -> ArtworkMatch | None: + if not isinstance(data, list): + return None + candidates = [ + item + for item in data + if isinstance(item, dict) + and isinstance(item.get("cover_xl"), str) + and _artist_matches(artist, (item.get("artist") or {}).get("name")) + ] + candidates.sort(key=lambda item: not _same(item.get("title"), album)) + if not candidates: + return None + best = candidates[0] + return ArtworkMatch( + url=best["cover_xl"], + source="deezer", + album=best.get("title"), + artist=(best.get("artist") or {}).get("name"), + ) + + @staticmethod + def _pick_deezer_track(data: object, artist: str, album: str | None) -> ArtworkMatch | None: + if not isinstance(data, list): + return None + candidates = [] + for item in data: + if not isinstance(item, dict): + continue + item_album = item.get("album") or {} + if not isinstance(item_album.get("cover_xl"), str): + continue + if not _artist_matches(artist, (item.get("artist") or {}).get("name")): + continue + candidates.append(item) + if album: + candidates.sort( + key=lambda item: not _same((item.get("album") or {}).get("title"), album) + ) + if not candidates: + return None + best = candidates[0] + return ArtworkMatch( + url=best["album"]["cover_xl"], + source="deezer", + album=best["album"].get("title"), + artist=(best.get("artist") or {}).get("name"), + ) + + async def _musicbrainz( + self, *, title: str, artist: str, album: str | None + ) -> ArtworkMatch | None: + if album: + query = f"releasegroup:{lucene_quote(album)} AND artist:{lucene_quote(artist)}" + await self._limiter.wait() + payload = await self._get_json( + f"{MUSICBRAINZ_API}/release-group/", + {"query": query, "fmt": "json", "limit": 5}, + "MusicBrainz", + ) + group = self._pick_release_group(payload.get("release-groups"), artist) + else: + query = f"recording:{lucene_quote(title)} AND artist:{lucene_quote(artist)}" + await self._limiter.wait() + payload = await self._get_json( + f"{MUSICBRAINZ_API}/recording/", + {"query": query, "fmt": "json", "limit": 5}, + "MusicBrainz", + ) + group = self._group_from_recordings(payload.get("recordings"), artist) + if group is None: + return None + group_id, group_title = group + return ArtworkMatch( + url=f"{COVER_ART_ARCHIVE}/release-group/{group_id}/front-1200", + source="musicbrainz", + album=group_title, + artist=artist, + ) + + @staticmethod + def _credited(item: dict[str, Any], artist: str) -> bool: + credits = item.get("artist-credit") or [] + names = [c.get("name") for c in credits if isinstance(c, dict)] + return any(_artist_matches(artist, name) for name in names) + + @classmethod + def _pick_release_group(cls, groups: object, artist: str) -> tuple[str, str | None] | None: + if not isinstance(groups, list): + return None + for group in groups: + if not isinstance(group, dict) or not isinstance(group.get("id"), str): + continue + if int(group.get("score") or 0) < MIN_MUSICBRAINZ_SCORE: + continue + if cls._credited(group, artist): + return group["id"], group.get("title") + return None + + @classmethod + def _group_from_recordings( + cls, recordings: object, artist: str + ) -> tuple[str, str | None] | None: + if not isinstance(recordings, list): + return None + for recording in recordings: + if not isinstance(recording, dict): + continue + if int(recording.get("score") or 0) < MIN_MUSICBRAINZ_SCORE: + continue + if not cls._credited(recording, artist): + continue + for release in recording.get("releases") or []: + group = release.get("release-group") if isinstance(release, dict) else None + if isinstance(group, dict) and isinstance(group.get("id"), str): + return group["id"], group.get("title") or release.get("title") + return None diff --git a/app/providers/tmdb/provider.py b/app/providers/tmdb/provider.py index 0c02a70..f1ec67b 100644 --- a/app/providers/tmdb/provider.py +++ b/app/providers/tmdb/provider.py @@ -26,6 +26,7 @@ from app.clients.http_images import ImageFetcher, ImageFetchError, decode_base64_image from app.core.config_store import ConfigStore from app.core.security import InvalidImageError, PayloadTooLargeError, verify_image_bytes +from app.core.text import fold from app.processor.templates import PosterLayout, TitleCardLayout from app.providers.base import ( BaseImageProvider, @@ -37,7 +38,7 @@ ) from app.providers.tmdb.client import TmdbClient, image_url from app.providers.tmdb.models import SearchResult, TmdbImage, TmdbRequest -from app.providers.tmdb.ranking import fold, parse_language, pick_result, rank_posters +from app.providers.tmdb.ranking import parse_language, pick_result, rank_posters logger = logging.getLogger(__name__) diff --git a/app/providers/tmdb/ranking.py b/app/providers/tmdb/ranking.py index 8d2be0e..c969904 100644 --- a/app/providers/tmdb/ranking.py +++ b/app/providers/tmdb/ranking.py @@ -15,17 +15,15 @@ from __future__ import annotations -import re -import unicodedata from collections.abc import Sequence from typing import Final +from app.core.text import fold from app.providers.tmdb.models import SearchResult, TmdbImage FALLBACK_LANGUAGE: Final = "en" #: Search results considered when looking for an exact title match. EXACT_MATCH_WINDOW: Final = 5 -_NON_WORD: Final = re.compile(r"[^\w]+") def parse_language(language: str) -> tuple[str, str | None]: @@ -59,13 +57,6 @@ def rank_posters(images: Sequence[TmdbImage], lang: str, region: str | None) -> ) -def fold(text: str) -> str: - """Accent-, case- and punctuation-insensitive form of a title.""" - decomposed = unicodedata.normalize("NFKD", text) - stripped = "".join(char for char in decomposed if not unicodedata.combining(char)) - return " ".join(_NON_WORD.sub(" ", stripped.casefold()).split()) - - def pick_result( results: Sequence[SearchResult], query: str, year: int | None ) -> SearchResult | None: diff --git a/tests/test_api.py b/tests/test_api.py index a1d8ad9..996db90 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -96,6 +96,7 @@ def test_config_schema(make_client: ClientFactory) -> None: assert set(schema["properties"]) == { "immich", "tmdb", + "music", "fraimic", "display", "eink", diff --git a/tests/test_music_artwork.py b/tests/test_music_artwork.py new file mode 100644 index 0000000..9aa21b9 --- /dev/null +++ b/tests/test_music_artwork.py @@ -0,0 +1,247 @@ +from __future__ import annotations + +import io +from collections.abc import AsyncIterator +from pathlib import Path +from typing import Any + +import httpx +import pytest +import respx +from PIL import Image + +from app.clients.http_images import USER_AGENT, ImageFetcher +from app.core.config_store import ConfigStore +from app.core.security import URLPolicy +from app.providers.music import ArtworkResolver, MinIntervalLimiter +from app.providers.music.artwork import lucene_quote + +DEEZER = "https://api.deezer.com" +MB = "https://musicbrainz.org/ws/2" +CAA = "https://coverartarchive.org" + + +def png_bytes(color: tuple[int, int, int] = (10, 20, 200)) -> bytes: + buffer = io.BytesIO() + Image.new("RGB", (50, 50), color).save(buffer, format="PNG") + return buffer.getvalue() + + +class NoWait(MinIntervalLimiter): + def __init__(self) -> None: + self.sleeps: list[float] = [] + clock = iter(float(i) * 0.1 for i in range(1000)) + + async def fake_sleep(seconds: float) -> None: + self.sleeps.append(seconds) + + super().__init__(1.0, clock=lambda: next(clock), sleep=fake_sleep) + + +class Setup: + def __init__(self, tmp_path: Path, **music: Any) -> None: + self.store = ConfigStore(tmp_path / "config.json", {"music": music}) + self.store.load() + self.fetcher = ImageFetcher(URLPolicy(), 5_000_000) + self.limiter = NoWait() + self.resolver = ArtworkResolver(self.store, self.fetcher, limiter=self.limiter) + + async def close(self) -> None: + await self.resolver.aclose() + await self.fetcher.aclose() + + +@pytest.fixture +async def setup(tmp_path: Path) -> AsyncIterator[Setup]: + instance = Setup(tmp_path) + yield instance + await instance.close() + + +def deezer_album(title: str, artist: str, cover: str) -> dict[str, Any]: + return {"title": title, "artist": {"name": artist}, "cover_xl": cover} + + +@respx.mock +async def test_deezer_album_search_finds_the_xl_cover(setup: Setup) -> None: + search = respx.get(f"{DEEZER}/search/album").respond( + json={ + "data": [ + deezer_album("Kind of Blue (Legacy)", "Miles Davis", "https://cdn.test/legacy.jpg"), + deezer_album("Kind of Blue", "Miles Davis", "https://cdn.test/kob.jpg"), + deezer_album("Kind of Blue", "Tribute Band", "https://cdn.test/fake.jpg"), + ] + } + ) + respx.get("https://cdn.test/kob.jpg").respond(content=png_bytes()) + + artwork = await setup.resolver.find(title="So What", artist="Miles Davis", album="Kind of Blue") + + assert artwork is not None + assert artwork.data == png_bytes() + assert artwork.match.source == "deezer" + assert artwork.match.album == "Kind of Blue" + request = search.calls.last.request + assert request.url.params["q"] == 'artist:"Miles Davis" album:"Kind of Blue"' + assert request.headers["user-agent"] == USER_AGENT + + +@respx.mock +async def test_deezer_track_search_when_the_album_is_unknown(setup: Setup) -> None: + album_search = respx.get(f"{DEEZER}/search/album") + respx.get(f"{DEEZER}/search").respond( + json={ + "data": [ + { + "title": "Bohemian Rhapsody", + "artist": {"name": "Queen"}, + "album": { + "title": "A Night at the Opera", + "cover_xl": "https://cdn.test/q.jpg", + }, + } + ] + } + ) + respx.get("https://cdn.test/q.jpg").respond(content=png_bytes()) + artwork = await setup.resolver.find(title="Bohemian Rhapsody", artist="Queen", album=None) + assert artwork is not None and artwork.match.album == "A Night at the Opera" + assert not album_search.called + + +@respx.mock +async def test_musicbrainz_and_cover_art_archive_fallback(setup: Setup) -> None: + respx.get(f"{DEEZER}/search/album").respond(json={"data": []}) + respx.get(f"{DEEZER}/search").respond(json={"data": []}) + mb = respx.get(f"{MB}/release-group/").respond( + json={ + "release-groups": [ + { + "id": "low-score", + "score": 40, + "title": "Obscure", + "artist-credit": [{"name": "Indie Band"}], + }, + { + "id": "rg-1", + "score": 100, + "title": "Obscure", + "artist-credit": [{"name": "Indie Band"}], + }, + ] + } + ) + respx.get(f"{CAA}/release-group/rg-1/front-1200").respond( + 307, headers={"location": "https://archive.test/rg-1/front.jpg"} + ) + respx.get("https://archive.test/rg-1/front.jpg").respond(content=png_bytes((1, 1, 1))) + + artwork = await setup.resolver.find(title="Track", artist="Indie Band", album="Obscure") + + assert artwork is not None + assert artwork.match.source == "musicbrainz" + assert artwork.data == png_bytes((1, 1, 1)) + params = mb.calls.last.request.url.params + assert params["query"] == 'releasegroup:"Obscure" AND artist:"Indie Band"' + assert params["fmt"] == "json" + + +@respx.mock +async def test_musicbrainz_recording_search_without_an_album(setup: Setup) -> None: + respx.get(f"{DEEZER}/search").respond(json={"data": []}) + respx.get(f"{MB}/recording/").respond( + json={ + "recordings": [ + { + "score": 95, + "artist-credit": [{"name": "Indie Band"}], + "releases": [{"title": "Single", "release-group": {"id": "rg-9"}}], + } + ] + } + ) + match = await setup.resolver.lookup(title="Track", artist="Indie Band", album=None) + assert match is not None + assert match.url == f"{CAA}/release-group/rg-9/front-1200" + assert match.album == "Single" + + +@respx.mock +async def test_nothing_found_returns_none_and_is_cached(setup: Setup) -> None: + deezer = respx.get(f"{DEEZER}/search/album").respond(json={"data": []}) + respx.get(f"{DEEZER}/search").respond(json={"data": []}) + mb = respx.get(f"{MB}/release-group/").respond(json={"release-groups": []}) + assert await setup.resolver.find(title="x", artist="Nobody", album="Nothing") is None + assert await setup.resolver.find(title="x", artist="nobody", album="NOTHING") is None + assert deezer.call_count == 1 and mb.call_count == 1 + + +@respx.mock +async def test_matches_are_cached(setup: Setup) -> None: + search = respx.get(f"{DEEZER}/search/album").respond( + json={"data": [deezer_album("Album", "Artist", "https://cdn.test/a.jpg")]} + ) + download = respx.get("https://cdn.test/a.jpg").respond(content=png_bytes()) + for _ in range(3): + assert await setup.resolver.find(title="Song", artist="Artist", album="Album") is not None + assert search.call_count == 1 + assert download.call_count == 3 # the URL is cached, not the image + + +@respx.mock +async def test_transient_errors_are_not_cached(setup: Setup) -> None: + route = respx.get(f"{DEEZER}/search/album").mock(side_effect=httpx.ConnectError("down")) + respx.get(f"{MB}/release-group/").respond(503) + assert await setup.resolver.lookup(title="s", artist="A", album="B") is None + + route.mock( + return_value=httpx.Response( + 200, json={"data": [deezer_album("B", "A", "https://cdn.test/b.jpg")]} + ) + ) + match = await setup.resolver.lookup(title="s", artist="A", album="B") + assert match is not None and match.url == "https://cdn.test/b.jpg" + + +@respx.mock +async def test_deezer_quota_errors_fall_through_to_musicbrainz(setup: Setup) -> None: + respx.get(f"{DEEZER}/search/album").respond( + json={"error": {"type": "Exception", "message": "Quota limit exceeded", "code": 4}} + ) + respx.get(f"{MB}/release-group/").respond( + json={"release-groups": [{"id": "g", "score": 100, "artist-credit": [{"name": "A"}]}]} + ) + match = await setup.resolver.lookup(title="s", artist="A", album="B") + assert match is not None and match.source == "musicbrainz" + + +@respx.mock +async def test_sources_can_be_disabled(tmp_path: Path) -> None: + setup = Setup(tmp_path, deezer_enabled=False, musicbrainz_enabled=False) + deezer = respx.get(f"{DEEZER}/search/album") + try: + assert await setup.resolver.lookup(title="s", artist="A", album="B") is None + finally: + await setup.close() + assert not deezer.called + + +@respx.mock +async def test_a_failed_cover_download_returns_none(setup: Setup) -> None: + respx.get(f"{DEEZER}/search/album").respond( + json={"data": [deezer_album("B", "A", "https://cdn.test/missing.jpg")]} + ) + respx.get("https://cdn.test/missing.jpg").respond(404) + assert await setup.resolver.find(title="s", artist="A", album="B") is None + + +async def test_rate_limiter_spaces_out_calls() -> None: + limiter = NoWait() + await limiter.wait() # t=0.0: first call is free + await limiter.wait() # t=0.1: waits 0.9 s (the clock advances 0.1 per reading) + assert limiter.sleeps and limiter.sleeps[0] == pytest.approx(0.9) + + +def test_lucene_quote_escapes_special_characters() -> None: + assert lucene_quote('AC/DC "Live"') == '"AC\\/DC \\"Live\\""' + assert lucene_quote("Sigur Rós") == '"Sigur Rós"' diff --git a/tests/test_tmdb_ranking.py b/tests/test_tmdb_ranking.py index d1aedb5..21296a2 100644 --- a/tests/test_tmdb_ranking.py +++ b/tests/test_tmdb_ranking.py @@ -2,8 +2,9 @@ import pytest +from app.core.text import fold from app.providers.tmdb.models import SearchResult, TmdbImage, TmdbRequest -from app.providers.tmdb.ranking import fold, parse_language, pick_result, poster_tier, rank_posters +from app.providers.tmdb.ranking import parse_language, pick_result, poster_tier, rank_posters def poster( From ee68c5071b528bd6539b74cc45e3c2c2fb352611 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sun, 15 Nov 2026 16:06:59 +0100 Subject: [PATCH 57/86] feat: add now-playing display endpoint POST /api/display/now-playing renders the album cover of the track that is playing with the album template (sleeve or vinyl) and the title, artist and album underneath. The cover comes from artwork_base64 or artwork_url, else (enrich_artwork) from Deezer, then MusicBrainz / Cover Art Archive, else a typographic card. Covers are ephemeral by default and expire when the track should end (duration - position + music.ttl_grace_seconds, or ttl_seconds, or music.default_ttl_minutes). A request for the track already displayed is deduplicated: only its expiry (and the queued upload's) moves, nothing is rendered or sent again, so Home Assistant can call it on every attribute change without waking a battery frame. fold() now transliterates ligatures (ae, oe, o, ss...) for matching. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- app/api/deps.py | 7 ++ app/api/routes/now_playing.py | 50 ++++++++ app/core/text.py | 20 +++- app/main.py | 10 ++ app/providers/music/models.py | 84 +++++++++++++ app/services/now_playing.py | 168 ++++++++++++++++++++++++++ tests/test_api_now_playing.py | 217 ++++++++++++++++++++++++++++++++++ tests/test_tmdb_ranking.py | 7 ++ 8 files changed, 560 insertions(+), 3 deletions(-) create mode 100644 app/api/routes/now_playing.py create mode 100644 app/providers/music/models.py create mode 100644 app/services/now_playing.py create mode 100644 tests/test_api_now_playing.py diff --git a/app/api/deps.py b/app/api/deps.py index 60c5629..d0132a7 100644 --- a/app/api/deps.py +++ b/app/api/deps.py @@ -15,6 +15,7 @@ from app.services.delivery import DeliveryService from app.services.display import DisplayService from app.services.ephemeral import EphemeralService +from app.services.now_playing import NowPlayingService from app.services.scheduler import SchedulerService @@ -68,6 +69,11 @@ def get_ephemeral_service(request: Request) -> EphemeralService: return cast(EphemeralService, request.app.state.ephemeral_service) +def get_now_playing_service(request: Request) -> NowPlayingService: + """Now-playing album covers.""" + return cast(NowPlayingService, request.app.state.now_playing_service) + + def get_people_directory(request: Request) -> PeopleDirectory: """Cache of the people known to each Immich account.""" return cast(PeopleDirectory, request.app.state.people_directory) @@ -84,3 +90,4 @@ def get_people_directory(request: Request) -> PeopleDirectory: SchedulerDep = Annotated[SchedulerService, Depends(get_scheduler_service)] EphemeralServiceDep = Annotated[EphemeralService, Depends(get_ephemeral_service)] PosterResolverDep = Annotated[PosterResolver, Depends(get_poster_resolver)] +NowPlayingServiceDep = Annotated[NowPlayingService, Depends(get_now_playing_service)] diff --git a/app/api/routes/now_playing.py b/app/api/routes/now_playing.py new file mode 100644 index 0000000..ef94d22 --- /dev/null +++ b/app/api/routes/now_playing.py @@ -0,0 +1,50 @@ +"""Now-playing album covers (music playback from Home Assistant).""" + +from __future__ import annotations + +from fastapi import APIRouter, HTTPException, Security + +from app.api.deps import NowPlayingServiceDep, SchedulerDep +from app.core.auth import api_key_scheme +from app.core.security import InvalidImageError +from app.providers.music.models import NowPlayingRequest +from app.services.display import DisplayResult + +display_router = APIRouter( + prefix="/api/display", tags=["display"], dependencies=[Security(api_key_scheme)] +) + + +@display_router.post( + "/now-playing", + response_model=DisplayResult, + responses={502: {"description": "The cover could not be decoded as an image"}}, + summary="Display the album cover of the track that is playing", +) +async def display_now_playing( + body: NowPlayingRequest, now_playing: NowPlayingServiceDep, scheduler: SchedulerDep +) -> DisplayResult: + """Show the full, uncropped cover with the title, artist and album underneath. + + The cover is ``artwork_base64`` / ``artwork_url`` when usable; otherwise (with + ``enrich_artwork``) a 1000x1000 cover is looked up on Deezer, then MusicBrainz / Cover + Art Archive; otherwise a typographic card is shown. + + The cover is **ephemeral** by default. It expires when the track should be over + (``duration_seconds - position_seconds`` plus ``music.ttl_grace_seconds``, or + ``ttl_seconds``, or ``music.default_ttl_minutes``) and on + ``DELETE /api/queue/ephemeral``; the previous image then comes back. Sending the track + that is already displayed only moves its expiry (``deduplicated: true``), so Home + Assistant can call this on every attribute change. + """ + try: + result = await now_playing.show(body) + except InvalidImageError as exc: + raise HTTPException( + status_code=502, detail="The cover could not be decoded as an image" + ) from exc + if body.push_to_fraimic and not result.deduplicated: + await scheduler.record_manual( + None, ephemeral=body.ephemeral, hold_minutes=body.hold_minutes + ) + return result diff --git a/app/core/text.py b/app/core/text.py index f3d86c4..a8bffd4 100644 --- a/app/core/text.py +++ b/app/core/text.py @@ -7,14 +7,28 @@ from typing import Final _NON_WORD: Final = re.compile(r"[^\w]+") +#: Letters that Unicode decomposition does not split into base letters. +_TRANSLITERATIONS: Final = str.maketrans( + { + "æ": "ae", + "œ": "oe", + "ø": "o", + "đ": "d", + "ð": "d", + "ł": "l", + "þ": "th", + "\u0131": "i", # dotless i + } +) def fold(text: str) -> str: """Accent-, case- and punctuation-insensitive form of a title or name. ``"Le Fabuleux Destin d'Amélie"`` and ``"le fabuleux destin d amelie"`` fold to the same - value, so do ``"AC/DC"`` and ``"ac dc"``. + value, so do ``"AC/DC"`` and ``"ac dc"``, or ``"Ágætis byrjun"`` and ``"agaetis byrjun"``. """ - decomposed = unicodedata.normalize("NFKD", text) + lowered = text.casefold().translate(_TRANSLITERATIONS) + decomposed = unicodedata.normalize("NFKD", lowered) stripped = "".join(char for char in decomposed if not unicodedata.combining(char)) - return " ".join(_NON_WORD.sub(" ", stripped.casefold()).split()) + return " ".join(_NON_WORD.sub(" ", stripped).split()) diff --git a/app/main.py b/app/main.py index 899eccc..3b1f2ee 100644 --- a/app/main.py +++ b/app/main.py @@ -24,6 +24,7 @@ from app.api.routes import fraimic as fraimic_routes from app.api.routes import images as image_routes from app.api.routes import immich as immich_routes +from app.api.routes import now_playing as now_playing_routes from app.api.routes import queue as queue_routes from app.api.routes import refresh as refresh_routes from app.api.routes import smart_mix as smart_mix_routes @@ -40,11 +41,13 @@ from app.core.security import URLPolicy from app.core.settings import EnvSettings, get_env_settings from app.providers.immich import ImmichGateway, ImmichProvider, PeopleDirectory +from app.providers.music import ArtworkResolver from app.providers.tmdb import PosterResolver, TmdbProvider from app.services.current_image import CurrentImageStore from app.services.delivery import DeliveryService from app.services.display import DisplayService from app.services.ephemeral import EphemeralService +from app.services.now_playing import NowPlayingService from app.services.scheduler import SchedulerService, immich_runner, tmdb_runner logger = logging.getLogger(__name__) @@ -123,6 +126,10 @@ async def _on_config_change(_: RuntimeConfig) -> None: image_fetcher = ImageFetcher(url_policy, settings.max_upload_bytes) tmdb = TmdbProvider(config_store, image_fetcher) poster_resolver = PosterResolver(tmdb, image_fetcher, config_store, settings.assets_dir) + artwork = ArtworkResolver(config_store, image_fetcher) + now_playing = NowPlayingService( + config_store, display, current_store, image_fetcher, artwork + ) scheduler = SchedulerService( settings.scheduler_state_path, config_store, @@ -152,6 +159,7 @@ async def _on_config_change(_: RuntimeConfig) -> None: app.state.ephemeral_service = ephemeral app.state.image_fetcher = image_fetcher app.state.poster_resolver = poster_resolver + app.state.now_playing_service = now_playing await ephemeral.start() # before the delivery worker can drop an expired image await delivery.start() @@ -175,6 +183,7 @@ async def _on_config_change(_: RuntimeConfig) -> None: await scheduler.stop() await ephemeral.stop() await delivery.stop() + await artwork.aclose() await image_fetcher.aclose() logger.info("Smart Frame Engine stopped") @@ -225,6 +234,7 @@ async def _validation_handler(_: Request, exc: RequestValidationError) -> JSONRe app.include_router(display_routes.router) app.include_router(immich_routes.display_router) app.include_router(tmdb_routes.display_router) + app.include_router(now_playing_routes.display_router) app.include_router(immich_routes.router) app.include_router(refresh_routes.router) app.include_router(smart_mix_routes.display_router) diff --git a/app/providers/music/models.py b/app/providers/music/models.py new file mode 100644 index 0000000..d0e5931 --- /dev/null +++ b/app/providers/music/models.py @@ -0,0 +1,84 @@ +"""Now-playing request (Home Assistant ``media_player`` attributes).""" + +from __future__ import annotations + +from typing import Final, Literal + +from pydantic import BaseModel, ConfigDict, Field, field_validator + +AlbumStyleName = Literal["sleeve", "vinyl"] + +MAX_ARTWORK_URL_LENGTH: Final = 4096 +#: Upper bound of a base64 cover (the decoded size is checked separately). +MAX_ARTWORK_BASE64_LENGTH: Final = 40_000_000 + + +class NowPlayingRequest(BaseModel): + """Body of ``POST /api/display/now-playing``.""" + + model_config = ConfigDict(extra="forbid") + + title: str = Field(min_length=1, max_length=300, description="Track title (media_title)") + artist: str = Field(min_length=1, max_length=300, description="Artist (media_artist)") + album: str | None = Field( + default=None, max_length=300, description="Album name (media_album_name)" + ) + artwork_url: str | None = Field( + default=None, + max_length=MAX_ARTWORK_URL_LENGTH, + description="Cover URL, e.g. the absolute URL of the media_player entity_picture", + ) + artwork_base64: str | None = Field( + default=None, + max_length=MAX_ARTWORK_BASE64_LENGTH, + description="Cover as base64 (or a data: URI); tried before artwork_url", + ) + enrich_artwork: bool = Field( + default=True, + description="When no usable cover was provided, look one up on Deezer, then " + "MusicBrainz / Cover Art Archive", + ) + style: AlbumStyleName | None = Field( + default=None, description="sleeve or vinyl (default music.default_style)" + ) + duration_seconds: float | None = Field( + default=None, ge=0, le=86_400, description="Track length (media_duration)" + ) + position_seconds: float | None = Field( + default=None, ge=0, le=86_400, description="Playback position (media_position)" + ) + ttl_seconds: int | None = Field( + default=None, + ge=10, + le=86_400, + description="Explicit cover lifetime (overrides the duration-based one)", + ) + hold_minutes: int | None = Field( + default=None, + ge=1, + le=10_080, + description="Protect the cover from scheduled refreshes for this long", + ) + push_to_fraimic: bool = Field( + default=True, description="Send to the frame; false only renders a preview" + ) + ephemeral: bool = Field( + default=True, + description="Temporary cover: the previous image comes back when it expires or on " + "DELETE /api/queue/ephemeral", + ) + + @field_validator("title", "artist", "album") + @classmethod + def _clean(cls, value: str | None) -> str | None: + if value is None: + return None + cleaned = " ".join(value.split()) + return cleaned or None + + @field_validator("title", "artist") + @classmethod + def _required(cls, value: str | None) -> str: + if not value: + raise ValueError("must not be blank") + return value diff --git a/app/services/now_playing.py b/app/services/now_playing.py new file mode 100644 index 0000000..536940c --- /dev/null +++ b/app/services/now_playing.py @@ -0,0 +1,168 @@ +"""Now-playing album covers (Home Assistant music playback). + +A request describes the track that is playing. The cover comes from, in order: + +1. ``artwork_base64`` / ``artwork_url`` sent by Home Assistant; +2. when missing or unusable (and enrichment is enabled), a high-resolution cover looked up + on Deezer, then MusicBrainz / Cover Art Archive; +3. otherwise a clean typographic card (title, artist, album). + +The cover is rendered with the ``album`` template and is ephemeral by default: it expires +when the track should be over (``duration - position`` plus a grace period), so a frame +waking up later shows the previous image again instead of a stale song. + +Home Assistant fires automations on every attribute change (position updates, volume...). +A request for the track that is already displayed is **deduplicated**: only its expiry is +moved, nothing is rendered or sent again (no needless wake-up of a battery frame). +""" + +from __future__ import annotations + +import hashlib +import logging +from collections.abc import Callable +from datetime import UTC, datetime, timedelta +from typing import Final, Literal + +from pydantic import JsonValue + +from app.clients.http_images import ImageFetcher, ImageFetchError, decode_base64_image +from app.core.config_models import MusicConfig +from app.core.config_store import ConfigStore +from app.core.security import InvalidImageError, PayloadTooLargeError +from app.core.text import fold +from app.processor.templates import AlbumLayout, Layout, TitleCardLayout +from app.providers.music.artwork import ArtworkResolver +from app.providers.music.models import NowPlayingRequest +from app.services.current_image import CurrentImageStore +from app.services.display import DisplayMeta, DisplayResult, DisplayService + +logger = logging.getLogger(__name__) + +SOURCE: Final = "music" +TITLE_CARD_ACCENT: Final = (0, 0, 255) + +ArtworkOrigin = Literal["provided", "deezer", "musicbrainz", "none"] +Clock = Callable[[], datetime] + + +def _utcnow() -> datetime: + return datetime.now(UTC) + + +def content_key(request: NowPlayingRequest, style: str) -> str: + """Identity of the displayed cover (same track, album and style = same picture).""" + parts = [fold(request.title), fold(request.artist), fold(request.album or ""), style] + return "music:" + hashlib.sha256("\x1f".join(parts).encode("utf-8")).hexdigest()[:32] + + +def cover_ttl(request: NowPlayingRequest, config: MusicConfig) -> timedelta: + """How long the cover stays: explicit ttl, else remaining track time, else the default.""" + if request.ttl_seconds is not None: + return timedelta(seconds=request.ttl_seconds) + if request.duration_seconds: + remaining = request.duration_seconds - (request.position_seconds or 0.0) + if remaining > 0: + return timedelta(seconds=remaining + config.ttl_grace_seconds) + return timedelta(minutes=config.default_ttl_minutes) + + +class NowPlayingService: + """Renders and pushes now-playing covers.""" + + def __init__( + self, + config_store: ConfigStore, + display: DisplayService, + current: CurrentImageStore, + fetcher: ImageFetcher, + artwork: ArtworkResolver, + *, + clock: Clock = _utcnow, + ) -> None: + self._config_store = config_store + self._display = display + self._current = current + self._fetcher = fetcher + self._artwork = artwork + self._clock = clock + + async def show(self, request: NowPlayingRequest) -> DisplayResult: + """Display (or refresh the expiry of) the cover of the track that is playing. + + Raises: + InvalidImageError: The cover could not be rendered. + """ + config = self._config_store.config.music + style = request.style or config.default_style + key = content_key(request, style) + now = self._clock() + expires_at = now + cover_ttl(request, config) if request.ephemeral else None + + if request.push_to_fraimic and request.ephemeral: + current = self._current.meta + if ( + current is not None + and current.ephemeral + and current.content_key == key + and not current.expired(now) + ): + updated = await self._display.extend_expiry(key, expires_at) + if updated is not None: + logger.debug("Now playing %r is already displayed; expiry moved", request.title) + return DisplayResult(image=updated, delivery=None, deduplicated=True) + + data, origin = await self._cover(request, config) + layout: Layout + if data is not None: + layout = AlbumLayout( + title=request.title, artist=request.artist, album=request.album, style=style + ) + else: + layout = TitleCardLayout( + title=request.title, + subtitle=request.artist, + caption=request.album, + accent=TITLE_CARD_ACCENT, + ) + details: dict[str, JsonValue] = { + "title": request.title, + "artist": request.artist, + "album": request.album, + "style": style, + "artwork": origin, + "duration_seconds": request.duration_seconds, + } + meta = DisplayMeta( + source=SOURCE, + title=f"{request.title} — {request.artist}", + details={k: v for k, v in details.items() if v is not None}, + push=request.push_to_fraimic, + ephemeral=request.ephemeral, + expires_at=expires_at, + content_key=key, + ) + return await self._display.display_layout(data, layout, meta) + + async def _cover( + self, request: NowPlayingRequest, config: MusicConfig + ) -> tuple[bytes | None, ArtworkOrigin]: + if request.artwork_base64: + try: + return decode_base64_image(request.artwork_base64, self._fetcher.max_bytes), ( + "provided" + ) + except (InvalidImageError, PayloadTooLargeError) as exc: + logger.info("Ignoring artwork_base64: %s", exc) + if request.artwork_url: + try: + return await self._fetcher.fetch(request.artwork_url), "provided" + except ImageFetchError as exc: + logger.info("Ignoring artwork_url: %s", exc) + if request.enrich_artwork and config.enrich_artwork: + artwork = await self._artwork.find( + title=request.title, artist=request.artist, album=request.album + ) + if artwork is not None: + return artwork.data, artwork.match.source + return None, "none" diff --git a/tests/test_api_now_playing.py b/tests/test_api_now_playing.py new file mode 100644 index 0000000..910ac91 --- /dev/null +++ b/tests/test_api_now_playing.py @@ -0,0 +1,217 @@ +from __future__ import annotations + +import base64 +import io +from datetime import UTC, datetime, timedelta +from typing import Any + +import httpx +import pytest +import respx +from fastapi.testclient import TestClient +from PIL import Image + +from app.core.config_models import MusicConfig +from app.providers.music.models import NowPlayingRequest +from app.services.now_playing import content_key, cover_ttl +from tests.conftest import ClientFactory + +DEEZER = "https://api.deezer.com" +MB = "https://musicbrainz.org/ws/2" + + +def png_bytes(color: tuple[int, int, int] = (20, 40, 160), size: int = 300) -> bytes: + buffer = io.BytesIO() + Image.new("RGB", (size, size), color).save(buffer, format="PNG") + return buffer.getvalue() + + +def frame_asleep() -> None: + respx.get("http://frame.test/api/info").mock(side_effect=httpx.ConnectTimeout("asleep")) + + +def music_client(make_client: ClientFactory) -> TestClient: + return make_client(fraimic_host="frame.test", fraimic_power_mode="deepsleep") + + +def play(client: TestClient, **body: Any) -> Any: + body.setdefault("title", "So What") + body.setdefault("artist", "Miles Davis") + response = client.post("/api/display/now-playing", json=body) + assert response.status_code == 200, response.text + return response.json() + + +@respx.mock +def test_provided_artwork_is_rendered_with_the_album_template(make_client: ClientFactory) -> None: + frame_asleep() + cover = respx.get("http://ha.test:8123/api/media_player_proxy/m").respond(content=png_bytes()) + deezer = respx.get(url__startswith=DEEZER) + client = music_client(make_client) + before = datetime.now(UTC) + + body = play( + client, + album="Kind of Blue", + artwork_url="http://ha.test:8123/api/media_player_proxy/m?token=abc", + duration_seconds=545, + position_seconds=45, + ) + + assert cover.called and not deezer.called + image = body["image"] + assert image["template"] == "album" + assert image["source"] == "music" + assert image["title"] == "So What — Miles Davis" + assert image["details"]["artwork"] == "provided" + assert image["ephemeral"] is True + expires = datetime.fromisoformat(image["expires_at"]) + # 500 s left in the track + 30 s grace + assert before + timedelta(seconds=525) < expires < datetime.now(UTC) + timedelta(seconds=535) + assert body["delivery"]["status"] == "queued" + assert client.get("/api/queue").json()["pending"]["ephemeral"] is True + + +@respx.mock +def test_broken_artwork_url_is_enriched_from_deezer(make_client: ClientFactory) -> None: + frame_asleep() + respx.get("https://ha.test/broken.jpg").respond(404) + respx.get(f"{DEEZER}/search/album").respond( + json={ + "data": [ + { + "title": "Kind of Blue", + "artist": {"name": "Miles Davis"}, + "cover_xl": "https://cdn.test/kob.jpg", + } + ] + } + ) + respx.get("https://cdn.test/kob.jpg").respond(content=png_bytes((200, 30, 30), 1000)) + body = play( + music_client(make_client), + album="Kind of Blue", + artwork_url="https://ha.test/broken.jpg", + style="vinyl", + ) + assert body["image"]["details"]["artwork"] == "deezer" + assert body["image"]["details"]["style"] == "vinyl" + + +@respx.mock +def test_base64_artwork_is_used_first(make_client: ClientFactory) -> None: + frame_asleep() + url = respx.get("https://ha.test/cover.jpg").respond(content=png_bytes()) + encoded = base64.b64encode(png_bytes((5, 5, 5))).decode() + body = play( + music_client(make_client), + artwork_base64=encoded, + artwork_url="https://ha.test/cover.jpg", + ) + assert body["image"]["details"]["artwork"] == "provided" + assert not url.called + + +@respx.mock +def test_title_card_when_no_cover_can_be_found(make_client: ClientFactory) -> None: + frame_asleep() + respx.get(f"{DEEZER}/search").respond(json={"data": []}) + respx.get(f"{MB}/recording/").respond(json={"recordings": []}) + body = play(music_client(make_client), title="Unreleased Demo", artist="Garage Band") + assert body["image"]["template"] == "title_card" + assert body["image"]["details"]["artwork"] == "none" + + +@respx.mock +def test_enrichment_can_be_disabled(make_client: ClientFactory) -> None: + frame_asleep() + deezer = respx.get(url__startswith=DEEZER) + body = play(music_client(make_client), enrich_artwork=False) + assert body["image"]["template"] == "title_card" + assert not deezer.called + + +@respx.mock +def test_same_track_is_deduplicated_and_only_extends_the_expiry( + make_client: ClientFactory, +) -> None: + frame_asleep() + respx.get("https://ha.test/c.jpg").respond(content=png_bytes()) + client = music_client(make_client) + first = play(client, album="Kind of Blue", artwork_url="https://ha.test/c.jpg", ttl_seconds=60) + pending_sha = client.get("/api/queue").json()["pending"]["sha256"] + + again = play(client, album="kind of blue", artwork_url="https://ha.test/c.jpg", ttl_seconds=600) + + assert again["deduplicated"] is True + assert again["delivery"] is None + assert again["image"]["sha256"] == first["image"]["sha256"] + first_expiry = datetime.fromisoformat(first["image"]["expires_at"]) + new_expiry = datetime.fromisoformat(again["image"]["expires_at"]) + assert new_expiry - first_expiry > timedelta(seconds=500) + queue = client.get("/api/queue").json() + assert queue["pending"]["sha256"] == pending_sha + assert datetime.fromisoformat(queue["pending"]["expires_at"]) == new_expiry + + other = play(client, title="Freddie Freeloader", album="Kind of Blue", enrich_artwork=False) + assert other["deduplicated"] is False + + +@respx.mock +def test_push_false_renders_a_preview(make_client: ClientFactory) -> None: + respx.get("https://ha.test/c.jpg").respond(content=png_bytes()) + client = music_client(make_client) + body = play(client, artwork_url="https://ha.test/c.jpg", push_to_fraimic=False) + assert body["delivery"] is None and body["deduplicated"] is False + assert client.get("/api/current.jpg").status_code == 404 + assert client.get("/api/preview.jpg").status_code == 200 + + +@respx.mock +def test_cancel_reverts_to_the_previous_image(make_client: ClientFactory) -> None: + frame_asleep() + respx.get("https://ha.test/c.jpg").respond(content=png_bytes()) + client = music_client(make_client) + client.post( + "/api/display/upload", + files={"file": ("photo.png", png_bytes((90, 160, 60)), "image/png")}, + ) + base = client.get("/api/status").json()["current_image"]["sha256"] + play(client, artwork_url="https://ha.test/c.jpg") + outcome = client.delete("/api/queue/ephemeral").json() + assert outcome["reverted"] is True + assert client.get("/api/status").json()["current_image"]["sha256"] == base + + +def test_request_validation(make_client: ClientFactory) -> None: + client = music_client(make_client) + post = client.post + assert post("/api/display/now-playing", json={"title": "x"}).status_code == 422 + assert post("/api/display/now-playing", json={"title": " ", "artist": "a"}).status_code == 422 + assert ( + post( + "/api/display/now-playing", json={"title": "x", "artist": "a", "style": "cassette"} + ).status_code + == 422 + ) + + +@pytest.mark.parametrize( + ("fields", "expected"), + [ + ({"ttl_seconds": 90, "duration_seconds": 300}, timedelta(seconds=90)), + ({"duration_seconds": 200, "position_seconds": 50}, timedelta(seconds=180)), + ({"duration_seconds": 200, "position_seconds": 250}, timedelta(minutes=10)), + ({}, timedelta(minutes=10)), + ], +) +def test_cover_ttl(fields: dict[str, Any], expected: timedelta) -> None: + request = NowPlayingRequest(title="t", artist="a", **fields) + assert cover_ttl(request, MusicConfig()) == expected + + +def test_content_key_ignores_case_accents_but_not_style() -> None: + a = NowPlayingRequest(title="Café", artist="Sigur Rós", album="Ágætis byrjun") + b = NowPlayingRequest(title="cafe", artist="SIGUR ROS", album="agaetis byrjun") + assert content_key(a, "sleeve") == content_key(b, "sleeve") + assert content_key(a, "sleeve") != content_key(a, "vinyl") diff --git a/tests/test_tmdb_ranking.py b/tests/test_tmdb_ranking.py index 21296a2..20a992d 100644 --- a/tests/test_tmdb_ranking.py +++ b/tests/test_tmdb_ranking.py @@ -119,3 +119,10 @@ def test_request_validation() -> None: TmdbRequest(query="x", language="french") with pytest.raises(ValueError): TmdbRequest(query=" ") + + +def test_fold_transliterates_ligatures() -> None: + assert fold("Ágætis byrjun") == "agaetis byrjun" + assert fold("Œuvre") == "oeuvre" + assert fold("Straße") == "strasse" + assert fold("Søren") == "soren" From 22655d26634265566f5a53342cc015aa57222f65 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sun, 15 Nov 2026 16:12:54 +0100 Subject: [PATCH 58/86] fix: prefer studio album covers in MusicBrainz recording lookups A hit song exists as dozens of equally scored MusicBrainz recordings (live albums, compilations, DJ mixes, videos), so taking the first release returned covers such as a video compilation. Fetch 25 recordings and pick the release group by type: albums first, then singles and EPs, and releases without secondary types (compilation, live...) before others. Found during a live run ("Around the World" now resolves to Homework). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- app/providers/music/artwork.py | 36 ++++++++++++++++++++--- tests/test_music_artwork.py | 52 ++++++++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+), 4 deletions(-) diff --git a/app/providers/music/artwork.py b/app/providers/music/artwork.py index f3ed7b2..bc835f6 100644 --- a/app/providers/music/artwork.py +++ b/app/providers/music/artwork.py @@ -38,6 +38,11 @@ SEARCH_LIMIT: Final = 10 #: Minimum MusicBrainz search score (0-100) to accept a release group. MIN_MUSICBRAINZ_SCORE: Final = 80 +#: Recordings fetched per search: a hit song exists as dozens of equally scored recordings +#: (live, compilations, DJ mixes); the studio album often is not among the first five. +RECORDING_SEARCH_LIMIT: Final = 25 +#: Preferred release-group primary types for a recording's cover (best first). +PRIMARY_TYPE_RANK: Final[dict[str, int]] = {"album": 0, "single": 1, "ep": 1} _LUCENE_SPECIAL: Final = '+-&|!(){}[]^"~*?:\\/' ArtworkSource = Literal["deezer", "musicbrainz"] @@ -300,7 +305,7 @@ async def _musicbrainz( await self._limiter.wait() payload = await self._get_json( f"{MUSICBRAINZ_API}/recording/", - {"query": query, "fmt": "json", "limit": 5}, + {"query": query, "fmt": "json", "limit": RECORDING_SEARCH_LIMIT}, "MusicBrainz", ) group = self._group_from_recordings(payload.get("recordings"), artist) @@ -333,12 +338,26 @@ def _pick_release_group(cls, groups: object, artist: str) -> tuple[str, str | No return group["id"], group.get("title") return None + @staticmethod + def _release_group_rank(group: dict[str, Any]) -> int: + """Lower is better: studio albums, then singles/EPs, then anything else. + + A recording appears on many releases (compilations, live albums, videos); the + original album cover is the one people recognize. + """ + primary = str(group.get("primary-type") or "").casefold() + secondary = group.get("secondary-types") or [] + rank = PRIMARY_TYPE_RANK.get(primary, len(PRIMARY_TYPE_RANK)) + return rank * 2 + (1 if secondary else 0) + @classmethod def _group_from_recordings( cls, recordings: object, artist: str ) -> tuple[str, str | None] | None: if not isinstance(recordings, list): return None + best: tuple[int, int, str, str | None] | None = None + order = 0 for recording in recordings: if not isinstance(recording, dict): continue @@ -348,6 +367,15 @@ def _group_from_recordings( continue for release in recording.get("releases") or []: group = release.get("release-group") if isinstance(release, dict) else None - if isinstance(group, dict) and isinstance(group.get("id"), str): - return group["id"], group.get("title") or release.get("title") - return None + if not isinstance(group, dict) or not isinstance(group.get("id"), str): + continue + candidate = ( + cls._release_group_rank(group), + order, + group["id"], + group.get("title") or release.get("title"), + ) + order += 1 + if best is None or candidate[:2] < best[:2]: + best = candidate + return (best[2], best[3]) if best is not None else None diff --git a/tests/test_music_artwork.py b/tests/test_music_artwork.py index 9aa21b9..e543836 100644 --- a/tests/test_music_artwork.py +++ b/tests/test_music_artwork.py @@ -166,6 +166,58 @@ async def test_musicbrainz_recording_search_without_an_album(setup: Setup) -> No assert match.album == "Single" +@respx.mock +async def test_recording_search_prefers_the_studio_album_over_videos_and_compilations( + setup: Setup, +) -> None: + respx.get(f"{DEEZER}/search").respond(json={"data": []}) + respx.get(f"{MB}/recording/").respond( + json={ + "recordings": [ + { + "score": 100, + "artist-credit": [{"name": "Daft Punk"}], + "releases": [ + { + "release-group": { + "id": "video", + "title": "D.A.F.T.", + "primary-type": "Other", + } + }, + { + "release-group": { + "id": "best-of", + "title": "Musique", + "primary-type": "Album", + "secondary-types": ["Compilation"], + } + }, + { + "release-group": { + "id": "single", + "title": "Around the World", + "primary-type": "Single", + } + }, + { + "release-group": { + "id": "homework", + "title": "Homework", + "primary-type": "Album", + } + }, + ], + } + ] + } + ) + match = await setup.resolver.lookup(title="Around the World", artist="Daft Punk", album=None) + assert match is not None + assert match.album == "Homework" + assert match.url.endswith("/release-group/homework/front-1200") + + @respx.mock async def test_nothing_found_returns_none_and_is_cached(setup: Setup) -> None: deezer = respx.get(f"{DEEZER}/search/album").respond(json={"data": []}) From 9b018962f799f6421d667df63c9c2ef589199d70 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sun, 15 Nov 2026 16:14:43 +0100 Subject: [PATCH 59/86] docs: document ephemeral queue, templates, TMDB and now-playing Document the composition templates and bundled Inter font, the preview and base image slots (including the push_to_fraimic=false behaviour change), TMDB posters with regional ranking and fallbacks, now-playing covers with Deezer / MusicBrainz enrichment and deduplication, and the ephemeral image lifecycle with GET /api/queue and DELETE /api/queue/ephemeral. Add Home Assistant rest_command and automation examples for music and TV playback, TMDB/Inter/Deezer/ MusicBrainz credits, and update .env.example and CLAUDE.md. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- .env.example | 13 ++- CLAUDE.md | 7 +- README.md | 238 +++++++++++++++++++++++++++++++++++++++++++++++++-- 3 files changed, 245 insertions(+), 13 deletions(-) diff --git a/.env.example b/.env.example index 9e5196a..3dac48c 100644 --- a/.env.example +++ b/.env.example @@ -20,12 +20,13 @@ PGID=1000 # When set, all POST/PUT/DELETE routes and /api/config require the # `X-API-Key` header (or `?api_key=`). Generate one with: openssl rand -hex 32 APP_API_KEY= -# Keep /api/current.jpg and /api/current.bin readable without a key +# Keep /api/current.jpg, /api/current.bin and /api/preview.jpg readable without a key # (needed by Home Assistant Generic Camera). Set to false to require ?api_key=. PUBLIC_IMAGE_ENDPOINTS=true # Max size of uploaded/downloaded images, in MB. MAX_UPLOAD_MB=20 -# Reject external image URLs resolving to private/loopback/link-local addresses. +# Reject external image URLs (posters, album covers, Home Assistant pictures) resolving to +# private/loopback/link-local addresses; every redirect target is checked too. BLOCK_PRIVATE_URLS=false # Comma-separated hosts or CIDRs allowed even when BLOCK_PRIVATE_URLS=true, # e.g. homeassistant.local,192.168.1.0/24 @@ -53,9 +54,13 @@ IMMICH_URL=http://immich.local:2283 IMMICH_API_KEY= # --- TMDB movie & TV posters (runtime default) ------------------------------- +# A v3 API key or a v4 read access token (https://www.themoviedb.org/settings/api). +# Without it, POST /api/display/tmdb falls back to the Home Assistant picture, to +# /data/assets/tmdb_fallback.png, then to a title card. TMDB_API_KEY= -# Locale such as en-US or fr-FR. -TMDB_LANGUAGE=en-US +# Poster language and region, e.g. fr-FR or en-US: regional posters are preferred, then +# the same language, textless artwork and English. +TMDB_LANGUAGE=fr-FR # --- Fraimic frame (runtime default) ----------------------------------------- # Hostname, IP or base URL of the frame (see fraimic.local/info for its IP). diff --git a/CLAUDE.md b/CLAUDE.md index 9d54071..ad10ea0 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -34,7 +34,7 @@ Implement two providers initially: - `contain`: Full image display with adaptive padding or blurred background (ideal for movie/TV posters). - **eInk Optimization:** Configurable contrast, saturation, and sharpness adjustments. - **Fraimic Binary Encoding:** Implement the exact `.bin` binary format and error-diffusion dithering (Atkinson by default, as in the official converter, or Floyd-Steinberg) with the official tuned color metric on the official Fraimic color palette, strictly following the reference documentation and official converter code located in `/fraimic-docs` (specifically `/fraimic-docs/fraimic_bin_converter`). -- **Cache:** Save the latest processed image in `/data/cache/`: `current.jpg` (clean composition for the web UI and Home Assistant), `current_dithered.png` (exact 6-color preview), `current.bin` (for Fraimic) and `current.json` (metadata, written last). The deep-sleep upload queue lives in `/data/queue/` (`pending.bin` + `pending.json`). +- **Cache:** Save the latest processed image in `/data/cache/`: `current.jpg` (clean composition for the web UI and Home Assistant), `current_dithered.png` (exact 6-color preview), `current.bin` (for Fraimic) and `current.json` (metadata, written last); `base.*` keeps the last pushed non-ephemeral image (restored when an ephemeral one expires or is cancelled) and `preview.*` the latest render (`push_to_fraimic=false` only writes the preview). The deep-sleep upload queue lives in `/data/queue/` (`pending.bin` + `pending.json`); the last delivery is persisted in `/data/last_delivery.json`. ### 3. Fraimic Communication & Power Management (`clients/fraimic.py`) Support two configurable power modes via the UI and `.env` (`FRAIMIC_POWER_MODE`): @@ -57,7 +57,10 @@ Clean, responsive (mobile/desktop) English web interface allowing users to: - `POST /api/display/smart-search`: Contextual push (`query`/`queries`, `persons`, `on_this_day`, `taken_after`/`taken_before`, `ephemeral` default true, `hold_minutes`) without Immich IDs. - `GET /api/smart-mix`, `POST`/`DELETE /api/smart-mix/context`: Inspect the weighted Smart Mix playlist (`smart_mix` settings section; source-agnostic `kind` + `params` entries) and set/clear a temporary boost. Rule precedence for scheduled refreshes and `POST /api/refresh`: pinned `scheduler.source_rule` > Smart Mix > last non-ephemeral manual display. Direct pushes (`ephemeral`, `hold_minutes`) reset the timer without altering the playlist. `/api/smart-mix` is API-key protected for every method. - `GET /api/immich/albums`, `GET /api/immich/people`, `POST /api/immich/people/refresh`: Discovery across the configured Immich accounts (`immich.accounts`; keys are masked and `GET /api/immich/*` is API-key protected when `APP_API_KEY` is set). -- `POST /api/display/media`: Search and display an HD poster (`title`, `media_type`, `fallback_url`, `push_to_fraimic`). +- `POST /api/display/tmdb`: Search and display an HD movie/TV poster with the no-crop `poster` template (`query`/`title`, `media_type` movie|tv|multi, `year`, `season`, `language`, `fallback_url`/`fallback_base64`, `push_to_fraimic`, `ephemeral` default true, `ttl_minutes`, `hold_minutes`). Regional poster ranking (`tmdb.language`), fallbacks: HA picture -> `/data/assets/tmdb_fallback.png` -> title card. `POST /api/display/media` is a deprecated alias. `tmdb` is a replayable runner kind. +- `POST /api/display/now-playing`: Album cover with the `album` template (`title`, `artist`, `album`, `artwork_url`/`artwork_base64`, `enrich_artwork` via Deezer then MusicBrainz/Cover Art Archive, `style` sleeve|vinyl, `duration_seconds`/`position_seconds`/`ttl_seconds`, `hold_minutes`, `push_to_fraimic`). Ephemeral by default; the same track is deduplicated (expiry extended only). +- `GET /api/queue` & `DELETE /api/queue/ephemeral`: Inspect the upload queue and cancel the ephemeral image. Ephemeral images carry `expires_at`; on expiry/cancel the last pushed non-ephemeral image (`/data/cache/base.*`) is restored and re-sent only if the frame may not show it. +- `GET /api/preview.jpg` & `GET /api/preview_dithered.png`: Latest render; `push_to_fraimic=false` only updates the preview (`POST /api/fraimic/push?from_preview=true` sends it). - `POST /api/fraimic/wakeup`: Webhook signaling frame wake-up to flush any queued upload immediately. - `POST /api/refresh`: Re-run the currently active source rule. - `GET /api/current.jpg` & `GET /api/current.bin`: Serve generated files (compatible with Home Assistant *Generic Camera*). diff --git a/README.md b/README.md index 313cbc8..c5dd2f9 100644 --- a/README.md +++ b/README.md @@ -6,8 +6,9 @@ and pushes them to a [Fraimic](https://fraimic.com) picture frame. Home Assistan friendly, runs standalone in Docker. > **Status:** early development (`v0.x`). The core service, the eInk pipeline, frame -> delivery (continuous and deep-sleep), the Immich provider and the autonomous scheduler -> are in place; more providers and the web UI are being added milestone by milestone. +> delivery (continuous and deep-sleep), the Immich provider, TMDB posters, now-playing +> album covers, ephemeral images and the autonomous scheduler are in place; the web UI is +> being added milestone by milestone. ## Quickstart @@ -54,7 +55,33 @@ Generated files (`./data/cache/`): | `current.jpg` | `GET /api/current.jpg` | Enhanced composition, before dithering (HA Generic Camera) | | `current_dithered.png` | `GET /api/current_dithered.png` | Exact 6-color preview of the panel | | `current.bin` | `GET /api/current.bin` | Frame buffer sent to the frame (960,000 / 2,304,000 bytes) | - +| `preview.jpg`, `preview_dithered.png` | `GET /api/preview.jpg`, `GET /api/preview_dithered.png` | The latest render, including `push_to_fraimic=false` ones | +| `base.*` | - | The last pushed non-ephemeral image, restored after an [ephemeral image](#ephemeral-images-and-the-queue) | + +`current.*` always matches what the frame shows (or will show once a sleeping frame wakes +up). A render with `push_to_fraimic=false` only updates `preview.*`, so a template can be +inspected without touching the frame or Home Assistant's camera; +`POST /api/fraimic/push?from_preview=true` then sends it. (Before this release, +`push_to_fraimic=false` replaced `current.*`.) + +### Composition templates + +Posters and album covers are never cropped. Instead of a fit mode they use a template that +lays the artwork out for the frame (portrait or landscape, 13.3" or 31.5"), always with the +`official` eInk profile: + +- **`poster`** - the full poster centered over a blurred, darkened backdrop made from the + poster itself, with a thin light border and a soft shadow. +- **`album`** - the full square cover (non-square art is padded, not cropped) with the title, + artist and album underneath (portrait) or beside it (landscape), on a flat background + color sampled from the cover. `style: "vinyl"` slides a record out of the sleeve. +- **`title_card`** - a clean typographic card, used when no artwork can be found. + +Text uses the bundled [Inter](https://rsms.me/inter/) font (never Pillow's bitmap +default), wraps and shrinks to fit, ends with an ellipsis when it really is too long, and is +drawn in pure black or white, whichever contrasts more with the background. It is rendered +without anti-aliasing, so glyphs stay a single panel color after dithering instead of +picking up colored fringes. ## Immich Photos come from one or several [Immich](https://immich.app) accounts. Pinned against @@ -164,8 +191,8 @@ The frame is driven through its local REST API (`GET /api/info`, `POST /api/imag | Endpoint | Purpose | | --- | --- | -| `POST /api/display/upload` | Upload an image (multipart `file`, optional `fit`, `push_to_fraimic`) | -| `POST /api/fraimic/push` | Force push the current image now (200 delivered, 202 queued) | +| `POST /api/display/upload` | Upload an image (multipart `file`, optional `fit`, `push_to_fraimic`, `ephemeral`, `hold_minutes`) | +| `POST /api/fraimic/push` | Force push the current image now (200 delivered, 202 queued); `?from_preview=true` sends the latest preview | | `POST /api/fraimic/wakeup` | Frame is awake: flush the queue (202, or `?wait=true` for the outcome) | | `GET /api/fraimic/info` | Last known battery / Wi-Fi / firmware (`?refresh=true` queries the frame) | | `GET /api/status` | Frame telemetry, queue state, current image metadata and scheduler state | @@ -189,8 +216,9 @@ rule** every `scheduler.interval_hours` hours (`REFRESH_INTERVAL_HOURS`, default ``` `params` takes the fields of `POST /api/display/immich` (except `push_to_fraimic` and - `ignore_history`, `ephemeral`, `hold_minutes`). Only Immich rules can be replayed for now. The last rule is kept in - `./data/scheduler_state.json`, so displaying a photo never rewrites your settings. + `ignore_history`, `ephemeral`, `hold_minutes`), or of `POST /api/display/tmdb` for + `"kind": "tmdb"` rules. The last rule is kept in `./data/scheduler_state.json`, so + displaying a photo never rewrites your settings. - **Timer.** Any display (a manual photo, an upload, a refresh) restarts the interval, so a picture chosen by hand stays up for a full interval. A refresh that became due while the app was down runs about 30 s after startup. @@ -329,6 +357,194 @@ automation: - service: rest_command.frame_rain_boost ``` +## Movie and TV posters (TMDB) + +`POST /api/display/tmdb` finds a movie or series on [TMDB](https://www.themoviedb.org) +(`TMDB_API_KEY`: a v3 API key or a v4 read access token) and shows its best poster with the +`poster` template. + +```bash +curl -X POST http://localhost:8000/api/display/tmdb -H 'Content-Type: application/json' \ + -d '{"query": "Le Fabuleux Destin d'"'"'Amélie Poulain", "media_type": "movie", "year": 2001}' +curl -X POST .../api/display/tmdb -H 'Content-Type: application/json' \ + -d '{"query": "The Office", "media_type": "tv", "season": 3, "language": "en-US"}' +``` + +| Request field | Meaning | +| --- | --- | +| `query` (or `title`) | Movie or series title | +| `media_type` | `movie`, `tv` or `multi` (both, default; `auto` is accepted) | +| `year`, `season` | Release year; TV season whose poster is preferred (falls back to the series poster) | +| `language` | Overrides `tmdb.language` (default `fr-FR`), e.g. `fr-CA` | +| `fallback_url`, `fallback_base64` | Picture used when TMDB has nothing, e.g. the Home Assistant `entity_picture` (base64 is tried first) | +| `ephemeral`, `ttl_minutes`, `hold_minutes` | Temporary by default: the previous image returns after `ttl_minutes` (default `tmdb.ephemeral_ttl_minutes`, 180) | +| `push_to_fraimic` | `false` only renders a preview | + +**Regional posters.** TMDB tags posters with a language and, for regional variants, a +country (`fr`/`FR` for France, `fr`/`CA` for Québec). For `fr-FR`, posters are ranked: +exact language and region, then the same language (any or no region), then textless +artwork, then English, then anything else; ties go to the best rated +(`vote_average`, then `vote_count`). Posters are downloaded at `tmdb.image_size` +(`w780` by default; `original` is sharper on the 31.5" panel). + +**Fallbacks.** When TMDB is not configured, has no match or fails: `fallback_base64` / +`fallback_url`, then `./data/assets/tmdb_fallback.png` if you provide one, then a title card +(set `tmdb.fallback_title_card: false` to get the TMDB error instead). `details.fallback` +tells which one was used. + +A non-ephemeral poster (`"ephemeral": false`) becomes the rule replayed by +`POST /api/refresh`, and `"kind": "tmdb"` entries can join the [Smart Mix](#smart-mix-and-smart-search) +(`{"kind": "tmdb", "params": {"query": "Amélie", "media_type": "movie"}, "weight": 1}`). +`POST /api/display/media` is a deprecated alias. + +## Now playing (music) + +`POST /api/display/now-playing` shows the cover of the track that is playing with the +`album` template. + +```bash +curl -X POST http://localhost:8000/api/display/now-playing -H 'Content-Type: application/json' \ + -d '{"title": "So What", "artist": "Miles Davis", "album": "Kind of Blue", + "duration_seconds": 545, "position_seconds": 12, "style": "vinyl"}' +``` + +| Request field | Meaning | +| --- | --- | +| `title`, `artist`, `album` | Track details (`media_title`, `media_artist`, `media_album_name` in Home Assistant) | +| `artwork_url`, `artwork_base64` | Cover provided by the player (base64 is tried first) | +| `enrich_artwork` | When no usable cover was provided, look one up (default true; also `music.enrich_artwork`) | +| `style` | `sleeve` or `vinyl` (default `music.default_style`) | +| `duration_seconds`, `position_seconds`, `ttl_seconds` | When the cover expires (see below) | +| `ephemeral`, `hold_minutes`, `push_to_fraimic` | As for posters | + +**Cover lookup.** No API key is needed: the +[Deezer](https://developers.deezer.com/api) public search (1000x1000 `cover_xl`), then +[MusicBrainz](https://musicbrainz.org) and the [Cover Art Archive](https://coverartarchive.org) +(studio albums are preferred over compilations, live albums and videos; requests are +rate-limited to one per second as MusicBrainz asks). Lookups are cached in memory +(`music.lookup_cache_size`). Without any cover, a typographic card is shown. Disable a +service with `music.deezer_enabled` / `music.musicbrainz_enabled`. + +**Lifetime.** The cover expires when the track should be over: `duration_seconds - +position_seconds + music.ttl_grace_seconds` (30), or `ttl_seconds`, or +`music.default_ttl_minutes` (10). Sending the track that is already displayed only moves +its expiry (`"deduplicated": true` in the response): nothing is rendered or sent again, so +the Home Assistant automation can fire on every attribute change without waking a +battery-powered frame. + +## Ephemeral images and the queue + +A push with `"ephemeral": true` (the default for posters, covers and smart searches) is +temporary: it never becomes the image to come back to, nor the rule replayed by +`POST /api/refresh`. + +- **Expiry.** Posters and covers carry an `expires_at`. When it passes, the previous + non-ephemeral image becomes the current image again. It is re-sent only if the frame may + not be showing it: a deep-sleeping frame that never received the cover is left alone, + and an expired image is dropped from the queue instead of being uploaded when the frame + wakes up. +- **Cancellation.** `DELETE /api/queue/ephemeral` (e.g. playback paused or stopped) drops + a queued ephemeral image and restores the previous one immediately. It is idempotent + (`"cancelled": false` when nothing was ephemeral). +- **No previous image yet?** A refresh of the active rule runs in the background instead. +- Ending an ephemeral image also lifts its `hold_minutes` protection; it does not restart + the refresh timer. + +| Endpoint | Purpose | +| --- | --- | +| `GET /api/queue` | The upload waiting for the frame (expired images are never listed), the last delivery, and the ephemeral image shown or queued with its `expires_at` | +| `DELETE /api/queue/ephemeral` | Cancel the ephemeral image now: `cancelled`, `dropped_pending`, `reverted`, `pushed_base`, `refreshing` | + +`GET /api/status` includes the same `ephemeral` block. The last successful delivery is kept +in `./data/last_delivery.json`, so what the frame shows is still known after a restart. + +## Home Assistant: TV and music + +The app must be able to reach Home Assistant to download `entity_picture` (add its host +to `URL_ALLOWLIST` when `BLOCK_PRIVATE_URLS=true`). Replace `media_player.living_room` and +`http://homeassistant.lan:8123` with yours. Picture URLs embed short-lived access tokens; +the app never writes them to its logs. + +```yaml +rest_command: + frame_now_playing: + url: http://smart-frame.lan:8000/api/display/now-playing + method: POST + content_type: "application/json; charset=utf-8" + timeout: 30 + headers: + X-API-Key: !secret smart_frame_api_key # only when APP_API_KEY is set + payload: >- + {% set p = 'media_player.living_room' %} + {% set pic = state_attr(p, 'entity_picture') %} + {{ { + "title": state_attr(p, 'media_title'), + "artist": state_attr(p, 'media_artist') or 'Unknown artist', + "album": state_attr(p, 'media_album_name'), + "artwork_url": ('http://homeassistant.lan:8123' ~ pic) if pic else none, + "duration_seconds": state_attr(p, 'media_duration'), + "position_seconds": state_attr(p, 'media_position') + } | to_json }} + frame_tv_poster: + url: http://smart-frame.lan:8000/api/display/tmdb + method: POST + content_type: "application/json; charset=utf-8" + timeout: 30 + headers: + X-API-Key: !secret smart_frame_api_key + payload: >- + {% set p = 'media_player.living_room' %} + {% set pic = state_attr(p, 'entity_picture') %} + {% set series = state_attr(p, 'media_series_title') %} + {{ { + "query": series or state_attr(p, 'media_title'), + "media_type": 'tv' if series else 'movie', + "season": state_attr(p, 'media_season') if series else none, + "fallback_url": ('http://homeassistant.lan:8123' ~ pic) if pic else none, + "ttl_minutes": [((state_attr(p, 'media_duration') or 7200) / 60) | int + 15, 1440] | min + } | to_json }} + frame_cancel_ephemeral: + url: http://smart-frame.lan:8000/api/queue/ephemeral + method: DELETE + headers: + X-API-Key: !secret smart_frame_api_key + +automation: + - alias: Frame - now playing + mode: queued + trigger: + - platform: state + entity_id: media_player.living_room + to: playing + - platform: state + entity_id: media_player.living_room + attribute: media_title + condition: + - condition: state + entity_id: media_player.living_room + state: playing + action: + - choose: + - conditions: "{{ state_attr('media_player.living_room', 'media_content_type') == 'music' }}" + sequence: + - service: rest_command.frame_now_playing + - conditions: "{{ state_attr('media_player.living_room', 'media_content_type') in ['movie', 'tvshow', 'episode'] }}" + sequence: + - service: rest_command.frame_tv_poster + - alias: Frame - playback stopped + trigger: + - platform: state + entity_id: media_player.living_room + from: playing + for: "00:02:00" # ignore short pauses + action: + - service: rest_command.frame_cancel_ephemeral +``` + +The now-playing call is deduplicated, so the `media_title` trigger only re-renders when the +track really changes. A deep-sleeping frame wakes up to the right picture: covers whose +song has ended are dropped from the queue, and the previous photo comes back. + ## Development ```bash @@ -346,6 +562,14 @@ The palette, color metric, Atkinson kernel and `.bin` layouts follow the officia builds on Toon-nooT's [PhotoPainter Spectra 6 converter](https://github.com/Toon-nooT/PhotoPainter-E-Ink-Spectra-6-image-converter). +Templates use the [Inter](https://github.com/rsms/inter) typeface by Rasmus Andersson, +bundled under the SIL Open Font License 1.1 (`app/assets/fonts/OFL.txt`). + +This product uses the TMDB API but is not endorsed or certified by +[TMDB](https://www.themoviedb.org). Album covers come from the +[Deezer API](https://developers.deezer.com), [MusicBrainz](https://musicbrainz.org) and the +[Cover Art Archive](https://coverartarchive.org). + ## License [MIT](LICENSE) From 8625fb464633d51eddce6e554ebe88b49e58799a Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sun, 15 Nov 2026 16:32:37 +0100 Subject: [PATCH 60/86] fix: match album covers more reliably Found while rendering sample covers against the live services: - Deezer album searches are flooded with covers, singles and remix EPs of the same name ("Back to Black"), and a tribute act can have the exact title ("Abbey Road" by a ukulele tribute). Rank results by artist (exact name before a name merely containing it), then album title (exact, then the same title with an edition suffix such as "(Remastered 2009)" or "(2019 Mix)"; remixes, live, tribute or cover versions never count), then albums before EPs and singles. Also use the track search, whose results carry the real album. - Only a sure Deezer match (exact artist and title or edition) is used directly; otherwise MusicBrainz is tried before falling back to the best approximate Deezer result. - Throttled MusicBrainz requests (HTTP 503/429) are retried twice with a backoff instead of failing the lookup. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- app/providers/music/artwork.py | 193 ++++++++++++++++++++++----------- tests/test_music_artwork.py | 158 ++++++++++++++++++++++++++- 2 files changed, 286 insertions(+), 65 deletions(-) diff --git a/app/providers/music/artwork.py b/app/providers/music/artwork.py index bc835f6..c981e30 100644 --- a/app/providers/music/artwork.py +++ b/app/providers/music/artwork.py @@ -1,10 +1,14 @@ """High-resolution album cover lookup for now-playing displays (no API key needed). -1. **Deezer** public search API: ``/search/album`` (artist + album) or ``/search`` (artist + - track) and the ``cover_xl`` picture (1000x1000). +1. **Deezer** public search API: ``/search/album`` (artist + album), then ``/search`` + (artist + track, whose results carry the real album) and the ``cover_xl`` picture + (1000x1000). Only a result whose album title matches is accepted at this stage: album + searches are often flooded with covers, singles and remix EPs of the same name. 2. **MusicBrainz** release-group search (rate-limited to one request per second as their - policy requires, with a descriptive User-Agent) and the matching **Cover Art Archive** - front cover (``front-1200``; the archive answers with a redirect to its storage). + policy requires, with a descriptive User-Agent, and retried with a backoff when the + service throttles) and the matching **Cover Art Archive** front cover (``front-1200``; + the archive answers with a redirect to its storage). +3. The best approximate Deezer result, as a last resort. Lookups are cached in memory (including "no cover" answers, but never transient errors), so Home Assistant attribute updates do not hammer the services. The resolver never @@ -15,6 +19,7 @@ import asyncio import logging +import re import time from collections import OrderedDict from collections.abc import Awaitable, Callable @@ -38,6 +43,17 @@ SEARCH_LIMIT: Final = 10 #: Minimum MusicBrainz search score (0-100) to accept a release group. MIN_MUSICBRAINZ_SCORE: Final = 80 +_TRAILING_PARENTHESIS: Final = re.compile(r"\s*[(\[]([^()\[\]]*)[)\]]\s*$") +_EDITION_WORDS: Final = re.compile( + r"\b(remaster(ed)?|deluxe|edition|anniversary|expanded|mono|stereo|bonus|version|" + r"\d{4} mix)\b" +) +_VARIANT_WORDS: Final = re.compile( + r"\b(remix(es)?|live|karaoke|instrumental|tribute|covers?|acoustic|lullab(y|ies)|" + r"piano|ukulele|8[- ]?bit)\b" +) +#: Delays before retrying a throttled MusicBrainz request (HTTP 503/429). +MUSICBRAINZ_RETRY_DELAYS_S: Final = (2.0, 4.0) #: Recordings fetched per search: a hit song exists as dozens of equally scored recordings #: (live, compilations, DJ mixes); the studio album often is not among the first five. RECORDING_SEARCH_LIMIT: Final = 25 @@ -52,6 +68,10 @@ class ArtworkLookupError(Exception): """A transient lookup failure (network, rate limit): the answer must not be cached.""" +class ArtworkRateLimitError(ArtworkLookupError): + """The service throttled the request (HTTP 429/503).""" + + @dataclass(frozen=True, slots=True) class ArtworkMatch: """A cover found for a track or album.""" @@ -76,16 +96,44 @@ def lucene_quote(value: str) -> str: return f'"{escaped}"' -def _same(a: str | None, b: str | None) -> bool: - return bool(a) and bool(b) and fold(a or "") == fold(b or "") +def artist_match_level(wanted: str, candidate: str | None) -> int | None: + """0 = same artist, 1 = one name contains the other ("Queen" / "Queen + Bowie", but + also tribute acts), ``None`` = different artist.""" + if not candidate: + return None + a, b = fold(wanted), fold(candidate) + if not a or not b: + return None + if a == b: + return 0 + return 1 if a in b or b in a else None def _artist_matches(wanted: str, candidate: str | None) -> bool: - """Exact folded match, or one name containing the other ("Queen" / "Queen + Bowie").""" - if not candidate: - return False - a, b = fold(wanted), fold(candidate) - return bool(a) and bool(b) and (a == b or a in b or b in a) + return artist_match_level(wanted, candidate) is not None + + +def _strip_edition(title: str) -> str: + """``title`` without trailing edition suffixes: "Abbey Road (Remastered 2009)".""" + while (suffix := _TRAILING_PARENTHESIS.search(title)) is not None: + inside = suffix.group(1).casefold() + if not _EDITION_WORDS.search(inside) or _VARIANT_WORDS.search(inside): + break + title = title[: suffix.start()] + return title + + +def title_match_level(wanted: str | None, candidate: str | None) -> int: + """0 = same title, 1 = same title with an edition suffix, 2 = something else. + + Remixes, live albums, tributes, karaoke or cover versions are never editions. + """ + if not wanted or not candidate: + return 2 + target = fold(wanted) + if fold(candidate) == target: + return 0 + return 1 if fold(_strip_edition(candidate)) == target else 2 class MinIntervalLimiter: @@ -113,6 +161,12 @@ async def wait(self) -> None: await self._sleep(delay) self._last = self._clock() + async def backoff(self, seconds: float) -> None: + """Hold every caller for ``seconds`` (the service asked us to slow down).""" + async with self._lock: + await self._sleep(seconds) + self._last = self._clock() + class ArtworkResolver: """Finds and downloads album covers from Deezer, then MusicBrainz / Cover Art Archive.""" @@ -175,11 +229,13 @@ async def lookup(self, *, title: str, artist: str, album: str | None) -> Artwork async def _search(self, *, title: str, artist: str, album: str | None) -> ArtworkMatch | None: config = self._config_store.config.music transient = False + approximate: ArtworkMatch | None = None if config.deezer_enabled: try: - match = await self._deezer(title=title, artist=artist, album=album) - if match is not None: + match, exact = await self._deezer(title=title, artist=artist, album=album) + if match is not None and exact: return match + approximate = match except ArtworkLookupError as exc: logger.info("Deezer cover lookup failed: %s", exc) transient = True @@ -191,6 +247,8 @@ async def _search(self, *, title: str, artist: str, album: str | None) -> Artwor except ArtworkLookupError as exc: logger.info("MusicBrainz cover lookup failed: %s", exc) transient = True + if approximate is not None: + return approximate if transient: raise ArtworkLookupError("no cover found and a service failed") return None @@ -201,7 +259,7 @@ async def _get_json(self, url: str, params: dict[str, Any], service: str) -> dic except httpx.HTTPError as exc: raise ArtworkLookupError(f"{service} unreachable ({type(exc).__name__})") from None if response.status_code in {429, 503}: - raise ArtworkLookupError(f"{service} rate limit (HTTP {response.status_code})") + raise ArtworkRateLimitError(f"{service} rate limit (HTTP {response.status_code})") if response.status_code != 200: raise ArtworkLookupError(f"{service} answered HTTP {response.status_code}") try: @@ -212,7 +270,14 @@ async def _get_json(self, url: str, params: dict[str, Any], service: str) -> dic raise ArtworkLookupError(f"{service} returned an unexpected payload") return payload - async def _deezer(self, *, title: str, artist: str, album: str | None) -> ArtworkMatch | None: + async def _deezer( + self, *, title: str, artist: str, album: str | None + ) -> tuple[ArtworkMatch | None, bool]: + """The Deezer cover and whether its album title matches exactly. + + Without a requested album, any track result by the artist counts as exact. + """ + approximate: ArtworkMatch | None = None if album: payload = await self._get_json( f"{DEEZER_API}/search/album", @@ -220,16 +285,20 @@ async def _deezer(self, *, title: str, artist: str, album: str | None) -> Artwor "Deezer", ) self._check_deezer_error(payload) - match = self._pick_deezer_album(payload.get("data"), artist, album) - if match is not None: - return match + found = self._pick_deezer(payload.get("data"), artist, album, track_results=False) + if found is not None and found[1]: + return found[0], True + approximate = found[0] if found else None payload = await self._get_json( f"{DEEZER_API}/search", {"q": f'artist:"{artist}" track:"{title}"', "limit": SEARCH_LIMIT}, "Deezer", ) self._check_deezer_error(payload) - return self._pick_deezer_track(payload.get("data"), artist, album) + found = self._pick_deezer(payload.get("data"), artist, album, track_results=True) + if found is not None and found[1]: + return found[0], True + return approximate or (found[0] if found else None), False @staticmethod def _check_deezer_error(payload: dict[str, Any]) -> None: @@ -239,74 +308,57 @@ def _check_deezer_error(payload: dict[str, Any]) -> None: raise ArtworkLookupError(f"Deezer error {error.get('code')}: {error.get('message')}") @staticmethod - def _pick_deezer_album(data: object, artist: str, album: str) -> ArtworkMatch | None: - if not isinstance(data, list): - return None - candidates = [ - item - for item in data - if isinstance(item, dict) - and isinstance(item.get("cover_xl"), str) - and _artist_matches(artist, (item.get("artist") or {}).get("name")) - ] - candidates.sort(key=lambda item: not _same(item.get("title"), album)) - if not candidates: - return None - best = candidates[0] - return ArtworkMatch( - url=best["cover_xl"], - source="deezer", - album=best.get("title"), - artist=(best.get("artist") or {}).get("name"), - ) - - @staticmethod - def _pick_deezer_track(data: object, artist: str, album: str | None) -> ArtworkMatch | None: + def _pick_deezer( + data: object, artist: str, album: str | None, *, track_results: bool + ) -> tuple[ArtworkMatch, bool] | None: + """The best Deezer album (or track's album) and whether it is a sure match. + + Ranked by artist (exact name before a name merely containing it, e.g. a tribute + act), then album title (exact, then the same title with an edition suffix), then + real albums before EPs and singles. A sure match has the exact artist and the exact + (or edition) title; without a requested album, the exact artist is enough. + """ if not isinstance(data, list): return None - candidates = [] + ranked: list[tuple[tuple[int, int, bool], dict[str, Any]]] = [] for item in data: if not isinstance(item, dict): continue - item_album = item.get("album") or {} - if not isinstance(item_album.get("cover_xl"), str): + record = (item.get("album") or {}) if track_results else item + if not isinstance(record, dict) or not isinstance(record.get("cover_xl"), str): continue - if not _artist_matches(artist, (item.get("artist") or {}).get("name")): + artist_rank = artist_match_level(artist, (item.get("artist") or {}).get("name")) + if artist_rank is None: continue - candidates.append(item) - if album: - candidates.sort( - key=lambda item: not _same((item.get("album") or {}).get("title"), album) - ) - if not candidates: + title_rank = title_match_level(album, record.get("title")) if album else 0 + is_album = (record.get("record_type") or item.get("record_type") or "album") == "album" + ranked.append(((artist_rank, title_rank, not is_album), item)) + if not ranked: return None - best = candidates[0] - return ArtworkMatch( - url=best["album"]["cover_xl"], + (artist_rank, title_rank, _), best = min(ranked, key=lambda pair: pair[0]) + record = (best.get("album") or {}) if track_results else best + match = ArtworkMatch( + url=record["cover_xl"], source="deezer", - album=best["album"].get("title"), + album=record.get("title"), artist=(best.get("artist") or {}).get("name"), ) + return match, artist_rank == 0 and title_rank <= 1 async def _musicbrainz( self, *, title: str, artist: str, album: str | None ) -> ArtworkMatch | None: if album: query = f"releasegroup:{lucene_quote(album)} AND artist:{lucene_quote(artist)}" - await self._limiter.wait() - payload = await self._get_json( - f"{MUSICBRAINZ_API}/release-group/", - {"query": query, "fmt": "json", "limit": 5}, - "MusicBrainz", + payload = await self._musicbrainz_get( + f"{MUSICBRAINZ_API}/release-group/", {"query": query, "fmt": "json", "limit": 5} ) group = self._pick_release_group(payload.get("release-groups"), artist) else: query = f"recording:{lucene_quote(title)} AND artist:{lucene_quote(artist)}" - await self._limiter.wait() - payload = await self._get_json( + payload = await self._musicbrainz_get( f"{MUSICBRAINZ_API}/recording/", {"query": query, "fmt": "json", "limit": RECORDING_SEARCH_LIMIT}, - "MusicBrainz", ) group = self._group_from_recordings(payload.get("recordings"), artist) if group is None: @@ -319,6 +371,19 @@ async def _musicbrainz( artist=artist, ) + async def _musicbrainz_get(self, url: str, params: dict[str, Any]) -> dict[str, Any]: + """A rate-limited MusicBrainz request, retried with a backoff when throttled.""" + for delay in (*MUSICBRAINZ_RETRY_DELAYS_S, None): + await self._limiter.wait() + try: + return await self._get_json(url, params, "MusicBrainz") + except ArtworkRateLimitError: + if delay is None: + raise + logger.debug("MusicBrainz throttled the request; retrying in %.0f s", delay) + await self._limiter.backoff(delay) + raise AssertionError("unreachable") # pragma: no cover + @staticmethod def _credited(item: dict[str, Any], artist: str) -> bool: credits = item.get("artist-credit") or [] diff --git a/tests/test_music_artwork.py b/tests/test_music_artwork.py index e543836..6e52c82 100644 --- a/tests/test_music_artwork.py +++ b/tests/test_music_artwork.py @@ -14,7 +14,7 @@ from app.core.config_store import ConfigStore from app.core.security import URLPolicy from app.providers.music import ArtworkResolver, MinIntervalLimiter -from app.providers.music.artwork import lucene_quote +from app.providers.music.artwork import artist_match_level, lucene_quote, title_match_level DEEZER = "https://api.deezer.com" MB = "https://musicbrainz.org/ws/2" @@ -297,3 +297,159 @@ async def test_rate_limiter_spaces_out_calls() -> None: def test_lucene_quote_escapes_special_characters() -> None: assert lucene_quote('AC/DC "Live"') == '"AC\\/DC \\"Live\\""' assert lucene_quote("Sigur Rós") == '"Sigur Rós"' + + +@respx.mock +async def test_track_search_finds_the_real_album_hidden_by_lookalikes(setup: Setup) -> None: + """Real case: the album search returns only covers and a remix EP of "Back to Black".""" + respx.get(f"{DEEZER}/search/album").respond( + json={ + "data": [ + deezer_album("Back To Black", "Demi Chang", "https://cdn.test/cover.jpg"), + { + **deezer_album( + "Back To Black - The Singles Remixes", + "Amy Winehouse", + "https://cdn.test/remixes.jpg", + ), + "record_type": "ep", + }, + ] + } + ) + respx.get(f"{DEEZER}/search").respond( + json={ + "data": [ + { + "title": "Rehab", + "artist": {"name": "Amy Winehouse"}, + "album": {"title": "Back To Black", "cover_xl": "https://cdn.test/btb.jpg"}, + } + ] + } + ) + mb = respx.get(f"{MB}/release-group/") + match = await setup.resolver.lookup( + title="Rehab", artist="Amy Winehouse", album="Back to Black" + ) + assert match is not None and match.url == "https://cdn.test/btb.jpg" + assert not mb.called + + +@respx.mock +async def test_musicbrainz_exact_match_beats_an_approximate_deezer_result(setup: Setup) -> None: + respx.get(f"{DEEZER}/search/album").respond( + json={"data": [deezer_album("Homework (Remixes)", "Daft Punk", "https://cdn.test/rmx.jpg")]} + ) + respx.get(f"{DEEZER}/search").respond(json={"data": []}) + respx.get(f"{MB}/release-group/").respond( + json={ + "release-groups": [ + { + "id": "hw", + "score": 100, + "title": "Homework", + "artist-credit": [{"name": "Daft Punk"}], + } + ] + } + ) + match = await setup.resolver.lookup(title="Da Funk", artist="Daft Punk", album="Homework") + assert match is not None and match.source == "musicbrainz" + + +@respx.mock +async def test_approximate_deezer_result_is_the_last_resort(setup: Setup) -> None: + respx.get(f"{DEEZER}/search/album").respond( + json={"data": [deezer_album("Homework (Remixes)", "Daft Punk", "https://cdn.test/rmx.jpg")]} + ) + respx.get(f"{DEEZER}/search").respond(json={"data": []}) + respx.get(f"{MB}/release-group/").respond(json={"release-groups": []}) + match = await setup.resolver.lookup(title="Da Funk", artist="Daft Punk", album="Homework") + assert match is not None and match.url == "https://cdn.test/rmx.jpg" + + +@respx.mock +async def test_throttled_musicbrainz_requests_are_retried(setup: Setup) -> None: + respx.get(f"{DEEZER}/search/album").respond(json={"data": []}) + respx.get(f"{DEEZER}/search").respond(json={"data": []}) + mb = respx.get(f"{MB}/release-group/").mock( + side_effect=[ + httpx.Response(503), + httpx.Response( + 200, + json={ + "release-groups": [ + {"id": "hw", "score": 100, "artist-credit": [{"name": "Daft Punk"}]} + ] + }, + ), + ] + ) + match = await setup.resolver.lookup(title="Da Funk", artist="Daft Punk", album="Homework") + assert match is not None and match.source == "musicbrainz" + assert mb.call_count == 2 + assert 2.0 in setup.limiter.sleeps # backed off before retrying + + +@respx.mock +async def test_musicbrainz_gives_up_after_the_retries(setup: Setup) -> None: + respx.get(f"{DEEZER}/search/album").respond(json={"data": []}) + respx.get(f"{DEEZER}/search").respond(json={"data": []}) + mb = respx.get(f"{MB}/release-group/").respond(503) + assert await setup.resolver.lookup(title="x", artist="A", album="B") is None + assert mb.call_count == 3 + + +@pytest.mark.parametrize( + ("candidate", "level"), + [ + ("Abbey Road", 0), + ("ABBEY ROAD", 0), + ("Abbey Road (Remastered 2009)", 1), + ("Abbey Road (2019 Mix)", 1), + ("Abbey Road (Super Deluxe Edition)", 1), + ("Abbey Road [Anniversary Edition] (Remastered)", 1), + ("Abbey Road (Live)", 2), + ("Abbey Road (Remixes)", 2), + ("Abbey Road - The Singles Remixes", 2), + ("Abbey Road (Tribute Edition)", 2), + ("Let It Be", 2), + ], +) +def test_title_match_level(candidate: str, level: int) -> None: + assert title_match_level("Abbey Road", candidate) == level + + +def test_artist_match_level() -> None: + assert artist_match_level("The Beatles", "the beatles") == 0 + assert artist_match_level("The Beatles", "The Beatles Complete On Ukulele") == 1 + assert artist_match_level("Queen", "Queen + David Bowie") == 1 + assert artist_match_level("Queen", "Madonna") is None + assert artist_match_level("Queen", None) is None + + +@respx.mock +async def test_the_real_artist_beats_a_tribute_with_the_exact_title(setup: Setup) -> None: + """Real case: "Abbey Road" by a ukulele tribute vs "Abbey Road (2019 Mix)" by The Beatles.""" + respx.get(f"{DEEZER}/search/album").respond( + json={ + "data": [ + { + **deezer_album( + "Abbey Road (2019 Mix)", "The Beatles", "https://cdn.test/mix.jpg" + ), + "record_type": "album", + }, + deezer_album( + "Abbey Road", "The Beatles Complete On Ukulele", "https://cdn.test/uke.jpg" + ), + ] + } + ) + mb = respx.get(f"{MB}/release-group/") + match = await setup.resolver.lookup( + title="Come Together", artist="The Beatles", album="Abbey Road" + ) + assert match is not None and match.url == "https://cdn.test/mix.jpg" + assert not mb.called # an edition of the right album by the right artist is a sure match From fff4cc90d9df5bf59f3361d725a6b4da69f6e26f Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sun, 15 Nov 2026 16:32:37 +0100 Subject: [PATCH 61/86] fix: keep the vinyl record visible on dark backgrounds The black record of the vinyl album style disappeared on black backgrounds (e.g. Daft Punk covers). Draw a light rim and a soft sheen arc on the grooves so it stays visible after dithering. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- app/processor/templates.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/app/processor/templates.py b/app/processor/templates.py index 501aca2..1b2ffb6 100644 --- a/app/processor/templates.py +++ b/app/processor/templates.py @@ -51,6 +51,9 @@ VINYL_PEEK: Final = 0.32 VINYL_BLACK: Final[RGB] = (12, 12, 12) VINYL_GROOVE: Final[RGB] = (58, 58, 58) +#: Light rim and sheen so the record stays visible on dark (black) backgrounds. +VINYL_RIM: Final[RGB] = (150, 150, 150) +VINYL_SHEEN: Final[RGB] = (95, 95, 95) #: Background colors are pulled this much toward the nearest panel color (cleaner dither). PALETTE_PULL: Final = 0.35 TITLE_CARD_BACKGROUND: Final[RGB] = (0, 0, 0) @@ -208,6 +211,17 @@ def _vinyl_disc(diameter: int, label: RGB) -> Image.Image: disc = Image.new("RGBA", (big, big), (0, 0, 0, 0)) draw = ImageDraw.Draw(disc) draw.ellipse((0, 0, big - 1, big - 1), fill=(*VINYL_BLACK, 255)) + rim = max(2, round(big * 0.006)) + draw.ellipse((0, 0, big - 1, big - 1), outline=(*VINYL_RIM, 255), width=rim) + # A soft highlight arc on the grooves, like light catching the vinyl. + sheen = round(big * 0.08) + draw.arc( + (sheen, sheen, big - 1 - sheen, big - 1 - sheen), + start=-60, + end=10, + fill=(*VINYL_SHEEN, 255), + width=max(2, round(big * 0.012)), + ) radius = big / 2 groove_width = max(1, round(big * 0.002)) fraction = 0.92 From d80e9e6cda3a7d1bb904dadf161ca8a0f7ceaeb1 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sun, 15 Nov 2026 16:49:03 +0100 Subject: [PATCH 62/86] fix: skip edge sharpening on enlarged artwork The official edge-enhance / smooth / sharpen chain amplifies the blur and JPEG blocks of artwork that has to be enlarged to fit its slot. Templates now skip it in that case (downscaled artwork keeps the official look). Expose poster_slot, poster_target_width and album_cover_side so providers can request artwork at the right resolution. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- app/processor/templates.py | 53 +++++++++++++++++++++++++++++++------- tests/test_templates.py | 26 +++++++++++++++++++ 2 files changed, 70 insertions(+), 9 deletions(-) diff --git a/app/processor/templates.py b/app/processor/templates.py index 1b2ffb6..5880b48 100644 --- a/app/processor/templates.py +++ b/app/processor/templates.py @@ -54,6 +54,8 @@ #: Light rim and sheen so the record stays visible on dark (black) backgrounds. VINYL_RIM: Final[RGB] = (150, 150, 150) VINYL_SHEEN: Final[RGB] = (95, 95, 95) +#: Artwork enlarged by more than this factor skips the edge-enhance / sharpen chain. +UPSCALE_TOLERANCE: Final = 1.02 #: Background colors are pulled this much toward the nearest panel color (cleaner dither). PALETTE_PULL: Final = 0.35 TITLE_CARD_BACKGROUND: Final[RGB] = (0, 0, 0) @@ -312,14 +314,50 @@ def _fit_album_text(layout: AlbumLayout, width: int, height: int, unit: int) -> # --- Templates -------------------------------------------------------------------------- +# --- Geometry (also used by providers to request artwork at the right resolution) --- +def poster_slot(canvas: Canvas) -> Size: + """The area a poster is fitted into.""" + inset = canvas.pad(POSTER_INSET) + return canvas.size[0] - 2 * inset, canvas.size[1] - 2 * inset + + +def poster_target_width(canvas: Canvas, aspect: float = 2 / 3) -> int: + """Width (px) a poster of ``aspect`` (width / height) is displayed at.""" + slot_w, slot_h = poster_slot(canvas) + return min(slot_w, round(slot_h * aspect)) + + +def album_cover_side(canvas: Canvas, style: AlbumStyle) -> int: + """Side (px) of the square album cover.""" + width, height = canvas.size + pad = canvas.pad(0.06) + gap = round(canvas.short_side * 0.045) + group_factor = 1 + VINYL_PEEK if style == "vinyl" else 1.0 + if canvas.portrait: + min_text = round(height * 0.2) + cover = min(round((width - 2 * pad) / group_factor), height - 2 * pad - gap - min_text) + return cover if style == "vinyl" else min(cover, round(width * 0.82)) + text_min = round(width * 0.3) + return min(height - 2 * pad, round((width - 2 * pad - gap - text_min) / group_factor)) + + +def _enhance_artwork(fitted: Image.Image, source: Image.Image, eink: EinkConfig) -> Image.Image: + """eInk enhancement of scaled artwork. + + The edge-enhance / sharpen chain is skipped when the artwork had to be enlarged: + sharpening an upscale only amplifies its blur and JPEG blocks. + """ + upscaled = fitted.width > source.width * UPSCALE_TOLERANCE + return enhance(fitted, eink, edge_filters=not upscaled) + + def compose_poster(image: Image.Image, canvas: Canvas) -> Image.Image: """The full poster centered over a blurred, darkened backdrop of itself.""" width, height = canvas.size backdrop = blurred_background(image, canvas.size) backdrop = ImageEnhance.Brightness(backdrop).enhance(POSTER_BACKDROP_DARKEN) backdrop = enhance(backdrop, canvas.eink, edge_filters=False) - inset = canvas.pad(POSTER_INSET) - poster = enhance(fit_inside(image, (width - 2 * inset, height - 2 * inset)), canvas.eink) + poster = _enhance_artwork(fit_inside(image, poster_slot(canvas)), image, canvas.eink) border = max(2, round(canvas.short_side * 0.003)) origin = ((width - poster.width) // 2, (height - poster.height) // 2) _paste_framed(backdrop, poster, origin, border=border) @@ -336,12 +374,9 @@ def compose_album(image: Image.Image, layout: AlbumLayout, canvas: Canvas) -> Im gap = round(canvas.short_side * 0.045) vinyl = layout.style == "vinyl" group_factor = 1 + VINYL_PEEK if vinyl else 1.0 + cover = album_cover_side(canvas, layout.style) if canvas.portrait: - min_text = round(height * 0.2) - cover = min(round((width - 2 * pad) / group_factor), height - 2 * pad - gap - min_text) - if not vinyl: - cover = min(cover, round(width * 0.82)) text_width = width - 2 * pad text_height = height - 2 * pad - cover - gap block = _fit_album_text(layout, text_width, text_height, canvas.short_side) @@ -351,8 +386,6 @@ def compose_album(image: Image.Image, layout: AlbumLayout, canvas: Canvas) -> Im text_box = (pad, top + cover + gap) align: Align = "center" else: - text_min = round(width * 0.3) - cover = min(height - 2 * pad, round((width - 2 * pad - gap - text_min) / group_factor)) left = pad top = (height - cover) // 2 text_x = left + round(cover * group_factor) + gap @@ -361,7 +394,9 @@ def compose_album(image: Image.Image, layout: AlbumLayout, canvas: Canvas) -> Im text_box = (text_x, (height - block.height) // 2) align = "left" - sleeve = enhance(_square_cover(image, cover, background), canvas.eink) + sleeve = _square_cover(image, cover, background) + upscaled = cover > max(image.size) * UPSCALE_TOLERANCE + sleeve = enhance(sleeve, canvas.eink, edge_filters=not upscaled) if vinyl: disc = _vinyl_disc(cover - 2 * max(2, round(cover * 0.02)), accent_from(image)) disc_x = left + round(cover * VINYL_PEEK) diff --git a/tests/test_templates.py b/tests/test_templates.py index 58b6739..f2d12ef 100644 --- a/tests/test_templates.py +++ b/tests/test_templates.py @@ -198,3 +198,29 @@ def test_render_layout_bytes_decodes_untrusted_data() -> None: def test_finalize_rejects_a_composition_of_the_wrong_size() -> None: with pytest.raises(ValueError, match="expected"): finalize(Image.new("RGB", (100, 100)), options()) + + +def test_upscaled_artwork_skips_the_edge_filters(monkeypatch: pytest.MonkeyPatch) -> None: + import app.processor.templates as templates + + calls: list[bool] = [] + real = templates.enhance + + def spy(image: Image.Image, eink: EinkConfig, *, edge_filters: bool = True) -> Image.Image: + calls.append(edge_filters) + return real(image, eink, edge_filters=edge_filters) + + monkeypatch.setattr(templates, "enhance", spy) + sharp = EinkConfig() # official: edge filters on + compose_layout(Image.new("RGB", (2000, 3000)), PosterLayout(), Canvas((1200, 1600), sharp)) + assert calls[-1] is True # downscaled poster: filters applied + compose_layout(Image.new("RGB", (600, 900)), PosterLayout(), Canvas((1200, 1600), sharp)) + assert calls[-1] is False # enlarged poster: no sharpening of the blur + compose_layout( + Image.new("RGB", (500, 500)), AlbumLayout(title="x"), Canvas((1200, 1600), sharp) + ) + assert calls[-1] is False + compose_layout( + Image.new("RGB", (1200, 1200)), AlbumLayout(title="x"), Canvas((1200, 1600), sharp) + ) + assert calls[-1] is True From f212123cdcb1db3c612b69b77e27ed98bd6a6442 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sun, 15 Nov 2026 16:49:03 +0100 Subject: [PATCH 63/86] fix: download TMDB posters at the resolution the frame needs Posters were fetched at w780 (780 px) and enlarged to the ~987 px poster slot of the 13.3" panel (2x on the 31.5"), and the eInk sharpening then amplified the blur. TMDB also upscales silently when asked for a size larger than the original (a 600 px poster requested as w1280). tmdb.image_size now defaults to "auto": the poster's on-panel width is computed for the configured panel and orientation, and the smallest size that covers it and is a real downscale of the original is used (w780, w1280), else the original. Within a language/region tier, posters large enough for the slot now rank before smaller ones, then by rating (the language priority is unchanged). details.poster_size and poster_original_width report the choice. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- app/core/config_models.py | 8 ++-- app/providers/tmdb/provider.py | 38 +++++++++++----- app/providers/tmdb/ranking.py | 37 ++++++++++++++-- tests/test_api_tmdb.py | 4 +- tests/test_tmdb_provider.py | 80 +++++++++++++++++++++++++++++----- tests/test_tmdb_ranking.py | 33 +++++++++++++- 6 files changed, 170 insertions(+), 30 deletions(-) diff --git a/app/core/config_models.py b/app/core/config_models.py index ac94f34..8eda4fd 100644 --- a/app/core/config_models.py +++ b/app/core/config_models.py @@ -207,9 +207,11 @@ class TmdbConfig(_Section): description="Preferred poster/metadata language and region, e.g. fr-FR or en-US " "(regional posters first, then same language, textless, English)", ) - image_size: Literal["w780", "w1280", "original"] = Field( - default="w780", - description='Poster resolution to download (original is sharper on the 31.5" panel)', + image_size: Literal["auto", "w780", "w1280", "original"] = Field( + default="auto", + description="Poster resolution to download. auto = the smallest size covering the " + "poster's on-panel size that is a real downscale of the original (never a TMDB-side " + "upscale), else the original", ) ephemeral_ttl_minutes: int = Field( default=180, diff --git a/app/providers/tmdb/provider.py b/app/providers/tmdb/provider.py index f1ec67b..8e2033b 100644 --- a/app/providers/tmdb/provider.py +++ b/app/providers/tmdb/provider.py @@ -27,7 +27,7 @@ from app.core.config_store import ConfigStore from app.core.security import InvalidImageError, PayloadTooLargeError, verify_image_bytes from app.core.text import fold -from app.processor.templates import PosterLayout, TitleCardLayout +from app.processor.templates import Canvas, PosterLayout, TitleCardLayout, poster_target_width from app.providers.base import ( BaseImageProvider, ImageAsset, @@ -38,7 +38,12 @@ ) from app.providers.tmdb.client import TmdbClient, image_url from app.providers.tmdb.models import SearchResult, TmdbImage, TmdbRequest -from app.providers.tmdb.ranking import parse_language, pick_result, rank_posters +from app.providers.tmdb.ranking import ( + choose_image_size, + parse_language, + pick_result, + rank_posters, +) logger = logging.getLogger(__name__) @@ -116,14 +121,19 @@ async def fetch(self, request: TmdbRequest) -> ImageAsset: posters = await client.posters( chosen.media_type, chosen.id, include_languages=include ) - ranked = rank_posters(posters, lang, region) - candidates = [poster.file_path for poster in ranked[:MAX_DOWNLOAD_ATTEMPTS]] - if chosen.poster_path and chosen.poster_path not in candidates: - candidates.append(chosen.poster_path) # the default poster as a last resort + needed = self.target_width() + ranked = rank_posters(posters, lang, region, min_width=needed) + candidates = [ + (poster.file_path, choose_image_size(config.image_size, poster.width, needed)) + for poster in ranked[:MAX_DOWNLOAD_ATTEMPTS] + ] + if chosen.poster_path and all(chosen.poster_path != path for path, _ in candidates): + # The default poster as a last resort (its original size is unknown). + candidates.append((chosen.poster_path, choose_image_size(config.image_size, 0, needed))) if not candidates: raise NoCandidateError(f"TMDB has no poster for {chosen.title!r}") - data, path = await self._download(candidates, config.image_size) + data, path, size = await self._download(candidates) poster = next((p for p in ranked if p.file_path == path), None) details: dict[str, JsonValue] = { "title": chosen.title, @@ -135,6 +145,8 @@ async def fetch(self, request: TmdbRequest) -> ImageAsset: "language": language, "poster_language": poster.iso_639_1 if poster else None, "poster_region": poster.iso_3166_1 if poster else None, + "poster_size": size, + "poster_original_width": poster.width if poster else None, } return ImageAsset( data=data, @@ -147,11 +159,17 @@ async def fetch(self, request: TmdbRequest) -> ImageAsset: track_history=False, ) - async def _download(self, paths: list[str], size: str) -> tuple[bytes, str]: + def target_width(self) -> int: + """Width (px) of the poster on the configured panel and orientation.""" + config = self._config_store.config + canvas = Canvas(config.frame_size, config.eink, config.display.safe_margin_px) + return poster_target_width(canvas) + + async def _download(self, candidates: list[tuple[str, str]]) -> tuple[bytes, str, str]: failure: ImageFetchError | None = None - for path in paths: + for path, size in candidates: try: - return await self._fetcher.fetch(image_url(path, size)), path + return await self._fetcher.fetch(image_url(path, size)), path, size except ImageFetchError as exc: logger.info("TMDB poster download failed, trying the next one: %s", exc) failure = exc diff --git a/app/providers/tmdb/ranking.py b/app/providers/tmdb/ranking.py index c969904..1f7f565 100644 --- a/app/providers/tmdb/ranking.py +++ b/app/providers/tmdb/ranking.py @@ -10,7 +10,9 @@ 4. English; 5. anything else. -Within a tier, the best rated poster wins: ``(vote_average, vote_count)`` descending. +Within a tier, posters large enough for the frame come first (``min_width``: a poster +smaller than its on-panel size has to be enlarged and looks soft), then the best rated: +``(vote_average, vote_count)`` descending. The language tiers always take precedence. """ from __future__ import annotations @@ -45,18 +47,47 @@ def poster_tier(image: TmdbImage, lang: str, region: str | None) -> int: return 4 -def rank_posters(images: Sequence[TmdbImage], lang: str, region: str | None) -> list[TmdbImage]: - """Posters ordered by regional preference, then rating (stable for ties).""" +def rank_posters( + images: Sequence[TmdbImage], lang: str, region: str | None, *, min_width: int = 0 +) -> list[TmdbImage]: + """Posters ordered by regional preference, then sharpness, then rating (stable). + + Args: + images: Candidate posters. + lang: Wanted language (``fr``). + region: Wanted region (``FR``) or ``None``. + min_width: On-panel width; narrower originals rank last within their tier. + """ return sorted( images, key=lambda image: ( poster_tier(image, lang, region), + image.width < min_width, -image.vote_average, -image.vote_count, ), ) +#: TMDB poster sizes below "original", by width. +SCALED_SIZES: Final = ((780, "w780"), (1280, "w1280")) + + +def choose_image_size(configured: str, original_width: int, needed_width: int) -> str: + """The TMDB size to download a poster at. + + ``auto`` picks the smallest scaled size that covers ``needed_width`` **and** is a real + downscale of the original (TMDB upscales silently when asked for more pixels than the + original has), else ``original``. An unknown original width (0) gives ``original``. + """ + if configured != "auto": + return configured + for width, name in SCALED_SIZES: + if needed_width <= width <= original_width: + return name + return "original" + + def pick_result( results: Sequence[SearchResult], query: str, year: int | None ) -> SearchResult | None: diff --git a/tests/test_api_tmdb.py b/tests/test_api_tmdb.py index 3469f2b..3167a4a 100644 --- a/tests/test_api_tmdb.py +++ b/tests/test_api_tmdb.py @@ -31,7 +31,7 @@ def mock_amelie() -> None: respx.get(f"{API}/movie/194/images").respond( json={"posters": [{"file_path": "/fr.jpg", "iso_639_1": "fr", "iso_3166_1": "FR"}]} ) - respx.get(f"{IMG}/w780/fr.jpg").respond(content=png_bytes()) + respx.get(f"{IMG}/original/fr.jpg").respond(content=png_bytes()) def tmdb_client(make_client: ClientFactory, **overrides: Any) -> TestClient: @@ -136,7 +136,7 @@ def test_media_alias_accepts_title_and_auto(make_client: ClientFactory) -> None: json={"results": [{"id": 194, "media_type": "movie", "title": "Amélie"}]} ) respx.get(f"{API}/movie/194/images").respond(json={"posters": [{"file_path": "/fr.jpg"}]}) - respx.get(f"{IMG}/w780/fr.jpg").respond(content=png_bytes()) + respx.get(f"{IMG}/original/fr.jpg").respond(content=png_bytes()) client = tmdb_client(make_client) response = client.post( "/api/display/media", diff --git a/tests/test_tmdb_provider.py b/tests/test_tmdb_provider.py index f80497b..e033306 100644 --- a/tests/test_tmdb_provider.py +++ b/tests/test_tmdb_provider.py @@ -72,10 +72,22 @@ async def setup(tmp_path: Path) -> AsyncIterator[Setup]: } AMELIE_POSTERS = { "posters": [ - {"file_path": "/en.jpg", "iso_639_1": "en", "vote_average": 9.0, "vote_count": 50}, - {"file_path": "/fr_ca.jpg", "iso_639_1": "fr", "iso_3166_1": "CA", "vote_average": 6.0}, - {"file_path": "/fr_fr.jpg", "iso_639_1": "fr", "iso_3166_1": "FR", "vote_average": 5.0}, - {"file_path": "/textless.jpg", "iso_639_1": None, "vote_average": 8.0}, + {"file_path": "/en.jpg", "iso_639_1": "en", "vote_average": 9.0, "width": 2000}, + { + "file_path": "/fr_ca.jpg", + "iso_639_1": "fr", + "iso_3166_1": "CA", + "vote_average": 6.0, + "width": 2000, + }, + { + "file_path": "/fr_fr.jpg", + "iso_639_1": "fr", + "iso_3166_1": "FR", + "vote_average": 5.0, + "width": 2000, + }, + {"file_path": "/textless.jpg", "iso_639_1": None, "vote_average": 8.0, "width": 2000}, ] } @@ -84,7 +96,7 @@ async def setup(tmp_path: Path) -> AsyncIterator[Setup]: async def test_fetch_downloads_the_best_regional_poster(setup: Setup) -> None: search = respx.get(f"{API}/search/movie").respond(json=AMELIE_SEARCH) images = respx.get(f"{API}/movie/194/images").respond(json=AMELIE_POSTERS) - download = respx.get(f"{IMG}/w780/fr_fr.jpg").respond(content=png_bytes()) + download = respx.get(f"{IMG}/w1280/fr_fr.jpg").respond(content=png_bytes()) asset = await setup.provider.fetch(TmdbRequest(query="amelie", media_type="movie", year=2001)) @@ -131,7 +143,7 @@ async def test_multi_search_skips_people_and_prefers_an_exact_title(setup: Setup respx.get(f"{API}/tv/1396/images").respond( json={"posters": [{"file_path": "/bb.jpg", "iso_639_1": "en"}]} ) - respx.get(f"{IMG}/w780/bb.jpg").respond(content=png_bytes()) + respx.get(f"{IMG}/original/bb.jpg").respond(content=png_bytes()) asset = await setup.provider.fetch(TmdbRequest(query="breaking bad", language="en-US")) assert asset.details["media_type"] == "tv" assert asset.details["tmdb_id"] == 1396 @@ -145,7 +157,7 @@ async def test_season_posters_with_fallback_to_the_series(setup: Setup) -> None: season = respx.get(f"{API}/tv/1399/season/3/images").respond( json={"posters": [{"file_path": "/s3.jpg", "iso_639_1": "fr"}]} ) - respx.get(f"{IMG}/w780/s3.jpg").respond(content=png_bytes()) + respx.get(f"{IMG}/original/s3.jpg").respond(content=png_bytes()) asset = await setup.provider.fetch( TmdbRequest(query="Game of Thrones", media_type="tv", season=3) ) @@ -155,7 +167,7 @@ async def test_season_posters_with_fallback_to_the_series(setup: Setup) -> None: respx.get(f"{API}/tv/1399/season/9/images").respond(404) respx.get(f"{API}/tv/1399/images").respond(json={"posters": []}) - respx.get(f"{IMG}/w780/series.jpg").respond(content=png_bytes()) + respx.get(f"{IMG}/original/series.jpg").respond(content=png_bytes()) fallback = await setup.provider.fetch( TmdbRequest(query="Game of Thrones", media_type="tv", season=9) ) @@ -166,8 +178,8 @@ async def test_season_posters_with_fallback_to_the_series(setup: Setup) -> None: async def test_a_failed_download_tries_the_next_ranked_poster(setup: Setup) -> None: respx.get(f"{API}/search/movie").respond(json=AMELIE_SEARCH) respx.get(f"{API}/movie/194/images").respond(json=AMELIE_POSTERS) - respx.get(f"{IMG}/w780/fr_fr.jpg").respond(404) - respx.get(f"{IMG}/w780/fr_ca.jpg").respond(content=png_bytes()) + respx.get(f"{IMG}/w1280/fr_fr.jpg").respond(404) + respx.get(f"{IMG}/w1280/fr_ca.jpg").respond(content=png_bytes()) asset = await setup.provider.fetch(TmdbRequest(query="Amélie", media_type="movie")) assert asset.details["poster_region"] == "CA" @@ -211,7 +223,7 @@ async def test_upstream_errors_are_reported(setup: Setup) -> None: async def test_resolver_returns_the_tmdb_poster_when_found(setup: Setup) -> None: respx.get(f"{API}/search/movie").respond(json=AMELIE_SEARCH) respx.get(f"{API}/movie/194/images").respond(json=AMELIE_POSTERS) - respx.get(f"{IMG}/w780/fr_fr.jpg").respond(content=png_bytes()) + respx.get(f"{IMG}/w1280/fr_fr.jpg").respond(content=png_bytes()) asset = await setup.resolver.resolve( TmdbRequest(query="Amélie", media_type="movie"), fallback_url="https://ha.test/pic.png" ) @@ -289,3 +301,49 @@ async def test_resolver_works_without_a_tmdb_key(tmp_path: Path) -> None: assert isinstance(asset.layout, TitleCardLayout) assert asset.layout.subtitle == "Season 2" assert "not configured" in str(asset.details["fallback_reason"]) + + +@respx.mock +async def test_a_low_res_regional_poster_yields_to_a_sharp_one(setup: Setup) -> None: + """Real case: the best rated fr-FR poster of "Intouchables" is only 600x900.""" + respx.get(f"{API}/search/movie").respond(json=AMELIE_SEARCH) + respx.get(f"{API}/movie/194/images").respond( + json={ + "posters": [ + { + "file_path": "/small.jpg", + "iso_639_1": "fr", + "iso_3166_1": "FR", + "vote_average": 9.0, + "width": 600, + }, + { + "file_path": "/sharp.jpg", + "iso_639_1": "fr", + "iso_3166_1": "FR", + "vote_average": 5.0, + "width": 2000, + }, + ] + } + ) + route = respx.get(f"{IMG}/w1280/sharp.jpg").respond(content=png_bytes()) + asset = await setup.provider.fetch(TmdbRequest(query="Amélie", media_type="movie")) + assert route.called + assert asset.details["poster_size"] == "w1280" + assert asset.details["poster_original_width"] == 2000 + + +@respx.mock +async def test_the_31_inch_panel_downloads_the_original(tmp_path: Path) -> None: + setup = Setup(tmp_path) + await setup.store.update({"fraimic": {"panel": "315"}}) + assert setup.provider.target_width() == 1296 + respx.get(f"{API}/search/movie").respond(json=AMELIE_SEARCH) + respx.get(f"{API}/movie/194/images").respond(json=AMELIE_POSTERS) + route = respx.get(f"{IMG}/original/fr_fr.jpg").respond(content=png_bytes()) + try: + await setup.provider.fetch(TmdbRequest(query="Amélie", media_type="movie")) + finally: + await setup.fetcher.aclose() + assert route.called diff --git a/tests/test_tmdb_ranking.py b/tests/test_tmdb_ranking.py index 20a992d..86d8f14 100644 --- a/tests/test_tmdb_ranking.py +++ b/tests/test_tmdb_ranking.py @@ -4,7 +4,13 @@ from app.core.text import fold from app.providers.tmdb.models import SearchResult, TmdbImage, TmdbRequest -from app.providers.tmdb.ranking import parse_language, pick_result, poster_tier, rank_posters +from app.providers.tmdb.ranking import ( + choose_image_size, + parse_language, + pick_result, + poster_tier, + rank_posters, +) def poster( @@ -126,3 +132,28 @@ def test_fold_transliterates_ligatures() -> None: assert fold("Œuvre") == "oeuvre" assert fold("Straße") == "strasse" assert fold("Søren") == "soren" + + +def test_sharp_posters_come_first_within_a_tier_only() -> None: + small = poster("small_fr", "fr", "FR", votes=9.9).model_copy(update={"width": 600}) + big = poster("big_fr", "fr", "FR", votes=5.0).model_copy(update={"width": 2000}) + big_en = poster("big_en", "en", votes=9.0).model_copy(update={"width": 2000}) + ranked = rank_posters([small, big_en, big], "fr", "FR", min_width=987) + assert names(ranked) == ["big_fr", "small_fr", "big_en"] # language still wins + assert names(rank_posters([small, big], "fr", "FR")) == ["small_fr", "big_fr"] + + +@pytest.mark.parametrize( + ("configured", "original", "needed", "expected"), + [ + ("auto", 2000, 987, "w1280"), # 13.3" portrait: a real downscale is enough + ("auto", 2000, 720, "w780"), # 13.3" landscape + ("auto", 2000, 1296, "original"), # 31.5" portrait needs more than w1280 + ("auto", 1000, 987, "original"), # w1280 would be a TMDB-side upscale + ("auto", 600, 987, "original"), # small original: never ask TMDB to upscale + ("auto", 0, 987, "original"), # unknown original size + ("w780", 2000, 1296, "w780"), # an explicit size is respected + ], +) +def test_choose_image_size(configured: str, original: int, needed: int, expected: str) -> None: + assert choose_image_size(configured, original, needed) == expected From 03974d50e818b982216685549faf542487262c1c Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sun, 15 Nov 2026 16:49:03 +0100 Subject: [PATCH 64/86] fix: request album covers at full quality for their on-panel size Deezer's cover_xl is a quality-80 JPEG whose artifacts the eInk sharpening amplified. Covers are now requested for the cover's on-panel size: Deezer at quality 100 (1000 px, or 1400 px for larger slots), the Cover Art Archive at 1200 px or its original when a slot is larger. If the larger URL fails, the standard one is used. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- app/providers/music/artwork.py | 56 +++++++++++++++++++++++++++++----- app/services/now_playing.py | 20 ++++++++++-- tests/test_music_artwork.py | 51 ++++++++++++++++++++++++++++++- 3 files changed, 116 insertions(+), 11 deletions(-) diff --git a/app/providers/music/artwork.py b/app/providers/music/artwork.py index c981e30..57a6690 100644 --- a/app/providers/music/artwork.py +++ b/app/providers/music/artwork.py @@ -52,6 +52,11 @@ r"\b(remix(es)?|live|karaoke|instrumental|tribute|covers?|acoustic|lullab(y|ies)|" r"piano|ukulele|8[- ]?bit)\b" ) +#: Deezer CDN: ``.../1000x1000-000000-80-0-0.jpg`` (side x side - background - quality). +_DEEZER_SIZE: Final = re.compile(r"/\d+x\d+-(?P[0-9a-f]{6})-\d+-0-0\.jpg$") +DEEZER_XL_SIDE: Final = 1000 +DEEZER_MAX_SIDE: Final = 1400 +CAA_THUMB_SIDE: Final = 1200 #: Delays before retrying a throttled MusicBrainz request (HTTP 503/429). MUSICBRAINZ_RETRY_DELAYS_S: Final = (2.0, 4.0) #: Recordings fetched per search: a hit song exists as dozens of equally scored recordings @@ -136,6 +141,25 @@ def title_match_level(wanted: str | None, candidate: str | None) -> int: return 1 if fold(_strip_edition(candidate)) == target else 2 +def sized_cover_url(match: ArtworkMatch, min_side: int) -> str: + """The cover URL at the best quality for a ``min_side`` px slot. + + * Deezer: ``cover_xl`` is a 1000 px JPEG at quality 80. The same CDN pattern serves + quality 100 (no compression artifacts, which the eInk sharpening would amplify) and, + when the slot is larger, 1400 px. + * Cover Art Archive: ``front-1200`` is a real 1200 px rendition; the original upload + (any size) is only requested for larger slots. + + Unknown URL shapes are returned unchanged; callers fall back to ``match.url``. + """ + if match.source == "deezer": + side = DEEZER_XL_SIDE if min_side <= DEEZER_XL_SIDE else DEEZER_MAX_SIDE + return _DEEZER_SIZE.sub(rf"/{side}x{side}-\g-100-0-0.jpg", match.url) + if match.source == "musicbrainz" and min_side > CAA_THUMB_SIDE: + return match.url.removesuffix(f"-{CAA_THUMB_SIDE}") + return match.url + + class MinIntervalLimiter: """Allows one call per ``interval_s`` seconds (shared by concurrent callers).""" @@ -195,17 +219,33 @@ async def aclose(self) -> None: await self._http.aclose() # --- Public API ----------------------------------------------------------------------- - async def find(self, *, title: str, artist: str, album: str | None) -> Artwork | None: - """Download the best cover for a track (``None`` when nothing usable was found).""" + async def find( + self, + *, + title: str, + artist: str, + album: str | None, + min_side: int = DEEZER_XL_SIDE, + ) -> Artwork | None: + """Download the best cover for a track (``None`` when nothing usable was found). + + Args: + title: Track title. + artist: Artist name. + album: Album name, if known. + min_side: Side (px) of the cover on the panel; the cover is requested at least + this large when the service offers it. + """ match = await self.lookup(title=title, artist=artist, album=album) if match is None: return None - try: - data = await self._fetcher.fetch(match.url) - except ImageFetchError as exc: - logger.info("Cover download from %s failed: %s", match.source, exc) - return None - return Artwork(data, match) + urls = list(dict.fromkeys([sized_cover_url(match, min_side), match.url])) + for url in urls: + try: + return Artwork(await self._fetcher.fetch(url), match) + except ImageFetchError as exc: + logger.info("Cover download from %s failed: %s", match.source, exc) + return None async def lookup(self, *, title: str, artist: str, album: str | None) -> ArtworkMatch | None: """The cover URL for a track, from the cache or the services.""" diff --git a/app/services/now_playing.py b/app/services/now_playing.py index 536940c..70cf707 100644 --- a/app/services/now_playing.py +++ b/app/services/now_playing.py @@ -31,7 +31,14 @@ from app.core.config_store import ConfigStore from app.core.security import InvalidImageError, PayloadTooLargeError from app.core.text import fold -from app.processor.templates import AlbumLayout, Layout, TitleCardLayout +from app.processor.templates import ( + AlbumLayout, + AlbumStyle, + Canvas, + Layout, + TitleCardLayout, + album_cover_side, +) from app.providers.music.artwork import ArtworkResolver from app.providers.music.models import NowPlayingRequest from app.services.current_image import CurrentImageStore @@ -144,6 +151,12 @@ async def show(self, request: NowPlayingRequest) -> DisplayResult: ) return await self._display.display_layout(data, layout, meta) + def _cover_side(self, style: AlbumStyle) -> int: + """Side (px) of the album cover on the configured panel and orientation.""" + config = self._config_store.config + canvas = Canvas(config.frame_size, config.eink, config.display.safe_margin_px) + return album_cover_side(canvas, style) + async def _cover( self, request: NowPlayingRequest, config: MusicConfig ) -> tuple[bytes | None, ArtworkOrigin]: @@ -161,7 +174,10 @@ async def _cover( logger.info("Ignoring artwork_url: %s", exc) if request.enrich_artwork and config.enrich_artwork: artwork = await self._artwork.find( - title=request.title, artist=request.artist, album=request.album + title=request.title, + artist=request.artist, + album=request.album, + min_side=self._cover_side(request.style or config.default_style), ) if artwork is not None: return artwork.data, artwork.match.source diff --git a/tests/test_music_artwork.py b/tests/test_music_artwork.py index 6e52c82..7cf7797 100644 --- a/tests/test_music_artwork.py +++ b/tests/test_music_artwork.py @@ -14,7 +14,13 @@ from app.core.config_store import ConfigStore from app.core.security import URLPolicy from app.providers.music import ArtworkResolver, MinIntervalLimiter -from app.providers.music.artwork import artist_match_level, lucene_quote, title_match_level +from app.providers.music.artwork import ( + ArtworkMatch, + artist_match_level, + lucene_quote, + sized_cover_url, + title_match_level, +) DEEZER = "https://api.deezer.com" MB = "https://musicbrainz.org/ws/2" @@ -453,3 +459,46 @@ async def test_the_real_artist_beats_a_tribute_with_the_exact_title(setup: Setup ) assert match is not None and match.url == "https://cdn.test/mix.jpg" assert not mb.called # an edition of the right album by the right artist is a sure match + + +DZ_XL = "https://cdn-images.dzcdn.net/images/cover/abc/1000x1000-000000-80-0-0.jpg" +DZ_Q100 = "https://cdn-images.dzcdn.net/images/cover/abc/1000x1000-000000-100-0-0.jpg" +DZ_1400 = "https://cdn-images.dzcdn.net/images/cover/abc/1400x1400-000000-100-0-0.jpg" + + +@pytest.mark.parametrize( + ("url", "source", "side", "expected"), + [ + (DZ_XL, "deezer", 984, DZ_Q100), # same size, without JPEG artifacts + (DZ_XL, "deezer", 1181, DZ_1400), # larger slot (31.5" panel) + ("https://cdn.test/a.jpg", "deezer", 984, "https://cdn.test/a.jpg"), + ( + f"{CAA}/release-group/g/front-1200", + "musicbrainz", + 984, + f"{CAA}/release-group/g/front-1200", + ), + (f"{CAA}/release-group/g/front-1200", "musicbrainz", 1268, f"{CAA}/release-group/g/front"), + ], +) +def test_sized_cover_url(url: str, source: str, side: int, expected: str) -> None: + assert sized_cover_url(ArtworkMatch(url, source), side) == expected # type: ignore[arg-type] + + +@respx.mock +async def test_find_downloads_the_high_quality_deezer_cover(setup: Setup) -> None: + respx.get(f"{DEEZER}/search/album").respond(json={"data": [deezer_album("B", "A", DZ_XL)]}) + q100 = respx.get(DZ_Q100).respond(content=png_bytes((1, 2, 3))) + xl = respx.get(DZ_XL).respond(content=png_bytes()) + artwork = await setup.resolver.find(title="s", artist="A", album="B", min_side=984) + assert artwork is not None and artwork.data == png_bytes((1, 2, 3)) + assert q100.called and not xl.called + + +@respx.mock +async def test_find_falls_back_to_the_standard_cover_url(setup: Setup) -> None: + respx.get(f"{DEEZER}/search/album").respond(json={"data": [deezer_album("B", "A", DZ_XL)]}) + respx.get(DZ_1400).respond(403) + respx.get(DZ_XL).respond(content=png_bytes()) + artwork = await setup.resolver.find(title="s", artist="A", album="B", min_side=1181) + assert artwork is not None and artwork.data == png_bytes() From 1432546b01a1586f99f42e1e6f242397ea8d608c Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sun, 15 Nov 2026 16:49:03 +0100 Subject: [PATCH 65/86] chore: add a template sample rendering script scripts/template_samples.py renders 8 movie posters and 8 album covers with the composition templates (composition, dithered simulation and contact sheets) into data/template-samples using the real TMDB, Deezer and MusicBrainz lookups, without contacting the frame. Document it and the resolution choices in the README. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- README.md | 27 ++++- scripts/template_samples.py | 227 ++++++++++++++++++++++++++++++++++++ 2 files changed, 250 insertions(+), 4 deletions(-) create mode 100644 scripts/template_samples.py diff --git a/README.md b/README.md index c5dd2f9..350beb5 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,9 @@ lays the artwork out for the frame (portrait or landscape, 13.3" or 31.5"), alwa color sampled from the cover. `style: "vinyl"` slides a record out of the sleeve. - **`title_card`** - a clean typographic card, used when no artwork can be found. +Artwork that still has to be enlarged skips the edge-enhance / sharpen chain, which would +only amplify its blur and JPEG blocks. + Text uses the bundled [Inter](https://rsms.me/inter/) font (never Pillow's bitmap default), wraps and shrinks to fit, ends with an ellipsis when it really is too long, and is drawn in pure black or white, whichever contrasts more with the background. It is rendered @@ -383,9 +386,17 @@ curl -X POST .../api/display/tmdb -H 'Content-Type: application/json' \ **Regional posters.** TMDB tags posters with a language and, for regional variants, a country (`fr`/`FR` for France, `fr`/`CA` for Québec). For `fr-FR`, posters are ranked: exact language and region, then the same language (any or no region), then textless -artwork, then English, then anything else; ties go to the best rated -(`vote_average`, then `vote_count`). Posters are downloaded at `tmdb.image_size` -(`w780` by default; `original` is sharper on the 31.5" panel). +artwork, then English, then anything else. Within a tier, posters at least as large as +their on-panel size come first (a smaller one would have to be enlarged and look soft), +then the best rated (`vote_average`, then `vote_count`). + +**Resolution.** With `tmdb.image_size: auto` (default), the poster's on-panel width is +computed for the configured panel and orientation (987 px on a 13.3" portrait frame, +1296 px on a 31.5" one) and the smallest TMDB size that covers it *and* is a real downscale +of the original is downloaded (`w780` or `w1280`), else the `original`. TMDB silently +upscales when asked for more pixels than the original has, so a bigger size is never +requested for a small original. `details.poster_size` and `details.poster_original_width` +report the choice. **Fallbacks.** When TMDB is not configured, has no match or fails: `fallback_base64` / `fallback_url`, then `./data/assets/tmdb_fallback.png` if you provide one, then a title card @@ -421,7 +432,10 @@ curl -X POST http://localhost:8000/api/display/now-playing -H 'Content-Type: app [Deezer](https://developers.deezer.com/api) public search (1000x1000 `cover_xl`), then [MusicBrainz](https://musicbrainz.org) and the [Cover Art Archive](https://coverartarchive.org) (studio albums are preferred over compilations, live albums and videos; requests are -rate-limited to one per second as MusicBrainz asks). Lookups are cached in memory +rate-limited to one per second as MusicBrainz asks and retried when it throttles). Covers +are requested for their on-panel size: Deezer at JPEG quality 100 (1000 px, or 1400 px +when the cover is displayed larger), the Cover Art Archive at 1200 px (its original when +larger is needed). Lookups are cached in memory (`music.lookup_cache_size`). Without any cover, a typographic card is shown. Disable a service with `music.deezer_enabled` / `music.musicbrainz_enabled`. @@ -555,6 +569,11 @@ ruff check . && ruff format --check . && mypy app && pytest DATA_DIR=./data python -m app # serve on http://localhost:8000 ``` +`python scripts/template_samples.py` renders 8 movie posters and 8 album covers with the +templates (composition and dithered panel simulation, plus contact sheets) into +`data/template-samples/`, using the real TMDB / Deezer / MusicBrainz lookups but never +the frame. `--panel 315` and `--orientation landscape` preview other frames. + ## Credits The palette, color metric, Atkinson kernel and `.bin` layouts follow the official diff --git a/scripts/template_samples.py b/scripts/template_samples.py new file mode 100644 index 0000000..d20f0d5 --- /dev/null +++ b/scripts/template_samples.py @@ -0,0 +1,227 @@ +"""Render sample movie posters and album covers with the composition templates. + +Uses the real providers (TMDB with ``TMDB_API_KEY`` from ``.env``, Deezer, MusicBrainz / +Cover Art Archive) and the real eInk pipeline, but never contacts the frame. For each item +it writes the composition (``.jpg``, what ``/api/current.jpg`` would serve) and the exact +6-color panel simulation (``_dithered.png``), plus four contact sheets. + +Usage:: + + python scripts/template_samples.py # data/template-samples, 13.3" portrait + python scripts/template_samples.py --panel 315 --orientation landscape --out data/samples-315 + +Without a TMDB key, posters fall back to title cards. +""" + +from __future__ import annotations + +import argparse +import asyncio +import io +import tempfile +import time +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +from PIL import Image, ImageDraw + +from app.clients.http_images import ImageFetcher +from app.core.config_store import ConfigStore +from app.core.security import URLPolicy +from app.core.settings import EnvSettings +from app.processor.pipeline import RenderOptions, RenderResult, render_layout_bytes +from app.processor.templates import ( + AlbumLayout, + AlbumStyle, + Canvas, + Layout, + TitleCardLayout, + album_cover_side, +) +from app.processor.typography import load_font +from app.providers.music import ArtworkResolver +from app.providers.tmdb import PosterResolver, TmdbProvider, TmdbRequest + +MOVIES: tuple[TmdbRequest, ...] = ( + TmdbRequest(query="Le Fabuleux Destin d'Amélie Poulain", media_type="movie", year=2001), + TmdbRequest(query="Intouchables", media_type="movie", year=2011), + TmdbRequest(query="Dune", media_type="movie", year=2021), + TmdbRequest(query="Inception", media_type="movie", year=2010), + TmdbRequest(query="Le Dîner de cons", media_type="movie", year=1998), + TmdbRequest(query="Le Voyage de Chihiro", media_type="movie", year=2001), + TmdbRequest(query="Interstellar", media_type="movie", year=2014), + TmdbRequest(query="La La Land", media_type="movie", year=2016), +) +ALBUMS: tuple[tuple[str, str, str, AlbumStyle], ...] = ( + ("So What", "Miles Davis", "Kind of Blue", "sleeve"), + ("Around the World", "Daft Punk", "Homework", "vinyl"), + ("Bohemian Rhapsody", "Queen", "A Night at the Opera", "sleeve"), + ("Get Lucky", "Daft Punk", "Random Access Memories", "vinyl"), + ("Come Together", "The Beatles", "Abbey Road", "sleeve"), + ("Dreams", "Fleetwood Mac", "Rumours", "vinyl"), + ("Rehab", "Amy Winehouse", "Back to Black", "sleeve"), + ("Nés sous la même étoile", "IAM", "L'École du micro d'argent", "vinyl"), +) + +THUMB_SIZE = (300, 400) +SHEET_COLUMNS = 4 +SHEET_PAD = 16 +SHEET_CAPTION = 34 + + +@dataclass(frozen=True) +class Sample: + """One rendered item for the contact sheets.""" + + label: str + composed: Image.Image + dithered: Image.Image + + +def slug(text: str) -> str: + """A file-name friendly version of ``text``.""" + return "".join(c if c.isalnum() else "_" for c in text.lower()).strip("_")[:40] + + +def save(result: RenderResult, out: Path, name: str, label: str) -> Sample: + """Write the composition and the dithered simulation; return the sheet entry.""" + result.composed.save(out / f"{name}.jpg", quality=92) + dithered = result.dithered_png() + (out / f"{name}_dithered.png").write_bytes(dithered) + return Sample(label, result.composed, Image.open(io.BytesIO(dithered)).convert("RGB")) + + +def contact_sheet(samples: list[Sample], path: Path, *, dithered: bool) -> None: + """A grid of thumbnails with captions.""" + thumb_w, thumb_h = THUMB_SIZE + rows = (len(samples) + SHEET_COLUMNS - 1) // SHEET_COLUMNS + sheet = Image.new( + "RGB", + ( + SHEET_COLUMNS * (thumb_w + SHEET_PAD) + SHEET_PAD, + rows * (thumb_h + SHEET_CAPTION + SHEET_PAD) + SHEET_PAD, + ), + (245, 245, 245), + ) + draw = ImageDraw.Draw(sheet) + font = load_font("regular", 16) + for index, sample in enumerate(samples): + image = sample.dithered if dithered else sample.composed + thumb = image.copy() + thumb.thumbnail(THUMB_SIZE, Image.Resampling.LANCZOS) + x = SHEET_PAD + (index % SHEET_COLUMNS) * (thumb_w + SHEET_PAD) + y = SHEET_PAD + (index // SHEET_COLUMNS) * (thumb_h + SHEET_CAPTION + SHEET_PAD) + sheet.paste(thumb, (x, y)) + draw.text((x, y + thumb_h + 8), sample.label[:36], font=font, fill=(20, 20, 20)) + sheet.save(path, quality=90) + + +def build_store(panel: str | None, orientation: str | None) -> ConfigStore: + """Runtime configuration from ``.env`` (scratch file, never ``/data/config.json``).""" + env = EnvSettings() + seed: dict[str, dict[str, Any]] = env.runtime_seed() + if panel: + seed.setdefault("fraimic", {})["panel"] = panel + if orientation: + seed.setdefault("display", {})["orientation"] = orientation + store = ConfigStore(Path(tempfile.mkdtemp()) / "config.json", seed) + store.load() + return store + + +async def render_posters( + resolver: PosterResolver, options: RenderOptions, out: Path +) -> list[Sample]: + """Resolve and render every movie of :data:`MOVIES`.""" + samples: list[Sample] = [] + for index, request in enumerate(MOVIES, 1): + started = time.perf_counter() + asset = await resolver.resolve(request) + if asset.layout is None: # pragma: no cover - posters always carry a layout + raise RuntimeError("Poster asset without a layout") + result = await asyncio.to_thread( + render_layout_bytes, asset.data or None, asset.layout, options + ) + details = asset.details + origin = details.get("fallback") or ( + f"tmdb {details.get('poster_language')}-{details.get('poster_region')} " + f"{details.get('poster_size')} (original {details.get('poster_original_width')}px)" + ) + title = asset.title or request.query + samples.append(save(result, out, f"poster_{index:02d}_{slug(request.query)}", title)) + print(f"poster {index}: {title} [{origin}] {time.perf_counter() - started:.1f}s") + return samples + + +async def render_albums( + resolver: ArtworkResolver, store: ConfigStore, options: RenderOptions, out: Path +) -> list[Sample]: + """Look up and render every album of :data:`ALBUMS`.""" + config = store.config + canvas = Canvas(config.frame_size, config.eink, config.display.safe_margin_px) + samples: list[Sample] = [] + for index, (title, artist, album, style) in enumerate(ALBUMS, 1): + started = time.perf_counter() + side = album_cover_side(canvas, style) + artwork = await resolver.find(title=title, artist=artist, album=album, min_side=side) + layout: Layout + data: bytes | None + if artwork is not None: + layout = AlbumLayout(title=title, artist=artist, album=album, style=style) + data = artwork.data + with Image.open(io.BytesIO(data)) as cover: + origin = f"{artwork.match.source}: {artwork.match.album} {cover.size[0]}px" + else: + layout = TitleCardLayout( + title=title, subtitle=artist, caption=album, accent=(0, 0, 255) + ) + data, origin = None, "title card" + result = await asyncio.to_thread(render_layout_bytes, data, layout, options) + label = f"{artist} - {album} ({style})" + samples.append(save(result, out, f"album_{index:02d}_{slug(album)}_{style}", label)) + print( + f"album {index}: {label} [{origin}, slot {side}px] {time.perf_counter() - started:.1f}s" + ) + return samples + + +async def main(out: Path, panel: str | None, orientation: str | None) -> None: + """Render all samples into ``out``.""" + out.mkdir(parents=True, exist_ok=True) + store = build_store(panel, orientation) + config = store.config + options = RenderOptions.from_config(config, fit="contain", eink_profile="official") + fetcher = ImageFetcher(URLPolicy(), EnvSettings().max_upload_bytes) + provider = TmdbProvider(store, fetcher) + posters = PosterResolver(provider, fetcher, store, Path(tempfile.mkdtemp())) + covers = ArtworkResolver(store, fetcher) + print( + f"Frame {options.frame_size} (panel {config.fraimic.panel}), TMDB " + f"{'configured' if provider.configured else 'NOT configured'} " + f"({config.tmdb.language}, size {config.tmdb.image_size}, poster slot " + f"{provider.target_width()}px) -> {out}" + ) + try: + poster_samples = await render_posters(posters, options, out) + album_samples = await render_albums(covers, store, options, out) + finally: + await covers.aclose() + await fetcher.aclose() + for name, samples in (("posters", poster_samples), ("albums", album_samples)): + contact_sheet(samples, out / f"_sheet_{name}.jpg", dithered=False) + contact_sheet(samples, out / f"_sheet_{name}_dithered.jpg", dithered=True) + + +def parse_args() -> argparse.Namespace: + """Command-line options.""" + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--out", type=Path, default=Path("data/template-samples")) + parser.add_argument("--panel", choices=["133", "315"], default=None) + parser.add_argument("--orientation", choices=["portrait", "landscape"], default=None) + return parser.parse_args() + + +if __name__ == "__main__": + arguments = parse_args() + asyncio.run(main(arguments.out, arguments.panel, arguments.orientation)) From 412e6874945d1663838204a612fda71e08da4134 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sun, 15 Nov 2026 16:56:52 +0100 Subject: [PATCH 66/86] chore: add a four-frame preview gallery script scripts/preview_gallery.py looks up 8 movie posters (TMDB, original size) and 8 album covers (sleeve and vinyl) once, then renders them for the 13.3" and 31.5" panels in portrait and landscape, writing the composition and the Spectra 6 dithered simulation plus contact sheets per frame into the gitignored preview_gallery/ directory. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- .gitignore | 3 + scripts/preview_gallery.py | 194 +++++++++++++++++++++++++++++++++++++ 2 files changed, 197 insertions(+) create mode 100644 scripts/preview_gallery.py diff --git a/.gitignore b/.gitignore index 753d8e3..c1261e4 100644 --- a/.gitignore +++ b/.gitignore @@ -35,3 +35,6 @@ htmlcov/ *.swp .DS_Store Thumbs.db + +# --- Local visual preview gallery (scripts/preview_gallery.py) --------------- +/preview_gallery/ diff --git a/scripts/preview_gallery.py b/scripts/preview_gallery.py new file mode 100644 index 0000000..9c5d99c --- /dev/null +++ b/scripts/preview_gallery.py @@ -0,0 +1,194 @@ +"""Render a visual gallery: 8 movie posters and 8 album covers on all 4 frame layouts. + +Frames: 13.3" and 31.5" panels, each in portrait and landscape. Artwork is looked up +**once** (TMDB posters at ``original`` size, covers sized for the largest slot) and rendered +for every frame, so all frames show the same sources. For each item and frame it writes the +composition (``.jpg``) and the exact Spectra 6 simulation (``_dithered.png``), plus contact +sheets per frame. Nothing is sent to the frame. + +Usage:: + + python scripts/preview_gallery.py # writes preview_gallery/ (gitignored) + python scripts/preview_gallery.py --out some/dir +""" + +from __future__ import annotations + +import argparse +import asyncio +import io +import tempfile +from dataclasses import dataclass +from pathlib import Path + +from PIL import Image, ImageDraw +from template_samples import ALBUMS, MOVIES, Sample, build_store, save, slug + +from app.clients.http_images import ImageFetcher +from app.core.security import URLPolicy +from app.core.settings import EnvSettings +from app.processor.pipeline import RenderOptions, render_layout_bytes +from app.processor.templates import ( + AlbumLayout, + AlbumStyle, + Canvas, + Layout, + PosterLayout, + TitleCardLayout, + album_cover_side, +) +from app.processor.typography import load_font +from app.providers.music import ArtworkResolver +from app.providers.music.artwork import Artwork +from app.providers.tmdb import PosterResolver, TmdbProvider +from app.providers.tmdb.provider import ImageAsset + +FRAMES: tuple[tuple[str, str], ...] = ( + ("133", "portrait"), + ("133", "landscape"), + ("315", "portrait"), + ("315", "landscape"), +) +THUMB_LONG = 420 +SHEET_COLUMNS = 4 +SHEET_PAD = 16 +SHEET_CAPTION = 34 + + +@dataclass(frozen=True) +class AlbumSource: + """An album's metadata and its downloaded cover (``None`` = title card).""" + + title: str + artist: str + album: str + style: AlbumStyle + artwork: Artwork | None + + +def frame_name(panel: str, orientation: str) -> str: + """Directory name of a frame layout.""" + return f"{panel}-{orientation}" + + +def sheet(samples: list[Sample], path: Path, *, dithered: bool) -> None: + """A contact sheet whose cells follow the frame's aspect ratio.""" + first = samples[0].composed + scale = THUMB_LONG / max(first.size) + cell_w, cell_h = round(first.width * scale), round(first.height * scale) + rows = (len(samples) + SHEET_COLUMNS - 1) // SHEET_COLUMNS + canvas = Image.new( + "RGB", + ( + SHEET_COLUMNS * (cell_w + SHEET_PAD) + SHEET_PAD, + rows * (cell_h + SHEET_CAPTION + SHEET_PAD) + SHEET_PAD, + ), + (245, 245, 245), + ) + draw = ImageDraw.Draw(canvas) + font = load_font("regular", 16) + for index, sample in enumerate(samples): + image = (sample.dithered if dithered else sample.composed).resize( + (cell_w, cell_h), Image.Resampling.LANCZOS + ) + x = SHEET_PAD + (index % SHEET_COLUMNS) * (cell_w + SHEET_PAD) + y = SHEET_PAD + (index // SHEET_COLUMNS) * (cell_h + SHEET_CAPTION + SHEET_PAD) + canvas.paste(image, (x, y)) + draw.text((x, y + cell_h + 8), sample.label[:44], font=font, fill=(20, 20, 20)) + canvas.save(path, quality=90) + + +async def fetch_sources( + fetcher: ImageFetcher, +) -> tuple[list[tuple[str, ImageAsset]], list[AlbumSource]]: + """Look up every poster and cover once, sized for the largest frame.""" + store = build_store("315", "portrait") # the largest poster slot (1296 px) + await store.update({"tmdb": {"image_size": "original"}}) + provider = TmdbProvider(store, fetcher) + posters = PosterResolver(provider, fetcher, store, Path(tempfile.mkdtemp())) + covers = ArtworkResolver(store, fetcher) + config = store.config + canvas = Canvas(config.frame_size, config.eink, config.display.safe_margin_px) + cover_side = max(album_cover_side(canvas, style) for style in ("sleeve", "vinyl")) + print(f"TMDB {'configured' if provider.configured else 'NOT configured'}, size original") + + movie_assets: list[tuple[str, ImageAsset]] = [] + for request in MOVIES: + asset = await posters.resolve(request) + details = asset.details + with_data = Image.open(io.BytesIO(asset.data)).size if asset.data else None + print(f"poster: {asset.title} [{details.get('fallback') or 'tmdb'}] source {with_data}") + movie_assets.append((request.query, asset)) + + albums: list[AlbumSource] = [] + try: + for title, artist, album, style in ALBUMS: + artwork = await covers.find( + title=title, artist=artist, album=album, min_side=cover_side + ) + size = Image.open(io.BytesIO(artwork.data)).size if artwork else None + origin = artwork.match.source if artwork else "title card" + print(f"album: {artist} - {album} ({style}) [{origin}] source {size}") + albums.append(AlbumSource(title, artist, album, style, artwork)) + finally: + await covers.aclose() + return movie_assets, albums + + +async def render_frame( + panel: str, + orientation: str, + movies: list[tuple[str, ImageAsset]], + albums: list[AlbumSource], + out: Path, +) -> None: + """Render every poster and album for one frame layout.""" + store = build_store(panel, orientation) + options = RenderOptions.from_config(store.config, fit="contain", eink_profile="official") + directory = out / frame_name(panel, orientation) + directory.mkdir(parents=True, exist_ok=True) + samples: list[Sample] = [] + for index, (query, asset) in enumerate(movies, 1): + layout: Layout = asset.layout or PosterLayout() + result = await asyncio.to_thread(render_layout_bytes, asset.data or None, layout, options) + label = asset.title or query + samples.append(save(result, directory, f"poster_{index:02d}_{slug(query)}", label)) + for index, source in enumerate(albums, 1): + if source.artwork is not None: + layout = AlbumLayout( + title=source.title, artist=source.artist, album=source.album, style=source.style + ) + data: bytes | None = source.artwork.data + else: + layout = TitleCardLayout( + title=source.title, subtitle=source.artist, caption=source.album + ) + data = None + result = await asyncio.to_thread(render_layout_bytes, data, layout, options) + label = f"{source.artist} - {source.album} ({source.style})" + samples.append( + save(result, directory, f"album_{index:02d}_{slug(source.album)}_{source.style}", label) + ) + posters, covers = samples[: len(movies)], samples[len(movies) :] + for name, group in (("posters", posters), ("albums", covers)): + sheet(group, directory / f"_sheet_{name}.jpg", dithered=False) + sheet(group, directory / f"_sheet_{name}_dithered.jpg", dithered=True) + print(f"{frame_name(panel, orientation)}: {options.frame_size} done") + + +async def main(out: Path) -> None: + """Fetch the artwork once and render all four frame layouts.""" + out.mkdir(parents=True, exist_ok=True) + fetcher = ImageFetcher(URLPolicy(), EnvSettings().max_upload_bytes) + try: + movies, albums = await fetch_sources(fetcher) + finally: + await fetcher.aclose() + for panel, orientation in FRAMES: + await render_frame(panel, orientation, movies, albums, out) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--out", type=Path, default=Path("preview_gallery")) + asyncio.run(main(parser.parse_args().out)) From 58010af22ef88731bce970d292cbfe7f1fa9fb7e Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sun, 15 Nov 2026 17:27:22 +0100 Subject: [PATCH 67/86] feat: choose the eInk profile and dithering automatically eink.profile and eink.dither now default to "auto": the renderer decides per image from its context (photo, movie poster, album cover, title card) and cheap statistics of a 256 px thumbnail (luminance, contrast, highlights, color count, detail, smooth-region share), so nobody has to tune them per image. Explicit values always win, and the decision with its reasons is stored in the image metadata (GET /api/status, current_image.render). New profiles, adapted from the MIT-licensed stillroom converter: soft and vivid (gamut-safe luminance curves that scale chroma once for all channels, preserving hue) and natural (no enhancement). New dithering algorithms: atkinson-classic (6 neighbours), fs-serpentine, stucki and blue-noise (ordered, bundled tileable tile generated by scripts/make_blue_noise.py). The NumPy wavefront now supports any causal kernel (skew computed per kernel); the atkinson output stays byte-identical to the official converter. fs-serpentine and stucki run as numba-compiled loops (about 50 ms for a 13.3" frame instead of 650 ms); without numba, stucki uses the NumPy path and fs-serpentine falls back to fs. numba is now a required dependency. "floyd_steinberg" remains an alias of "fs". Templates no longer force the official profile: they pass their layout as context. Tests that compare with the official converter now pin profile official and dither atkinson. BREAKING CHANGE: the default profile and dithering are now "auto" instead of official and atkinson. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- app/assets/blue_noise_64.npy | Bin 0 -> 8320 bytes app/core/config_models.py | 85 +++++++-- app/processor/auto.py | 220 ++++++++++++++++++++++ app/processor/dither.py | 340 +++++++++++++++++++++++++++++----- app/processor/enhance.py | 49 ++++- app/processor/pipeline.py | 57 +++++- app/services/current_image.py | 6 + app/services/display.py | 8 +- pyproject.toml | 11 +- scripts/make_blue_noise.py | 104 +++++++++++ tests/test_api.py | 11 +- tests/test_api_phase2.py | 20 ++ tests/test_auto.py | 183 ++++++++++++++++++ tests/test_config_models.py | 33 +++- tests/test_dither.py | 124 ++++++++++++- tests/test_enhance.py | 59 ++++++ tests/test_pipeline.py | 12 +- 17 files changed, 1233 insertions(+), 89 deletions(-) create mode 100644 app/assets/blue_noise_64.npy create mode 100644 app/processor/auto.py create mode 100644 scripts/make_blue_noise.py create mode 100644 tests/test_auto.py diff --git a/app/assets/blue_noise_64.npy b/app/assets/blue_noise_64.npy new file mode 100644 index 0000000000000000000000000000000000000000..7a825cb8d68a0773a66729657a28731f829995c3 GIT binary patch literal 8320 zcmbW2V`C6(!$2<^*;rgyUdyg!+pV@-Tidd2F59+k+qP}=1fWX#~(Xr8CotsBShe!Nh4-M-W6Y*b*6xVh+1T-KVUYKD_{mKKuVbP zDhb`JgG8W9!;hmNTb(r)W9)cdkwV=8A2ye4pv;HDNG`QZbfwkYJ`}4m`c1MTXrXJ_ zhA@X%M)&%jva_zi%bS(xu-$`Gs+4vFpKHV65x z6h~YhRzco}-^~vyNn4XgZ6l3ABYgnJz@0Lixhkf?aC+4ZVa4qN9Ru>1arQCkEGqLq zbc)+4LP$B^7oXH|48Zu*kZ^F4Ce?`{p*P`7J%n6gzf@s7P~32*>^!;)WRTrWSymEk z6|3+7^h^$f0F2^wa9!U4B-WeZaKE2dl&#Sm)85CB{onx0uKwYCIz28YuF;|XA^rrj z>4hLAxuRd7&n%1G)IjP1?_G*#y>V0MH1f54-;Q#B^8AVxKf}Nv!sr!4IlFJ z7}MVBrE5>~n}2=~TVk@getN9kK-P+7ZWhamFY8FRgnng9MSV9HRk53WXO6*2`P~+R zZ`nJ3LXKnm{2lWILdW1c)zr)aO?fG|72b2d&@q+-RV9U75t9wC1-yo+>^cvkC)hi9 z%;tyF<#Lc+So)qO03FFFHc|}m_h<_;-d)q*%nBgT09S~e^m}w(gynA8c%-^nLSFqdqx$H^WvQDNH z&!Xq~O(NW!0ux9zv0t4qVJw4Mp=0?&Ul+Ba_sl2t(OzOX!63ZOzayLNNS)WNqIJ|G zw9IU9kt9yO29sP*IGF_4c4!$+Z;rB*E`zRU(!mAlx(Rb@;TQfw^&`c61-?d|hVeyr z+}LvY7%h^AX(BQV_G8s;Z~TU~bd^y)Q;j5mL3pMTWSo4(FMw|(gP&xo>3Z;#Y=c^h zRj>uF?S_iQ>?)jwck}slgejtqh(emf_3jDDC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j<`83l=Y+|?M z2ipv-6UB8ww%)$iDSSOX5bV(7#49?E-&f7>a;Q{tHxhKPoAGXcOg)Cf^-@`k?4)VI zYL*5qCHMSoB+OWsgFZ7S!DIE-*JY>qHL#6dR*QTfeghvn$Zx38sF97tIpjsKo&1Ie z^{tdihVsE;h@qwN536!r6WSWEOkV)#L{rPEv{ zSlEwI_mOs=oECv>GMJ>M^B%CMFM=7bCTqd?b|&s`nxikIC$Fv+83fvs)b0|jEta|g Jsww;K{|6_Nj3592 literal 0 HcmV?d00001 diff --git a/app/core/config_models.py b/app/core/config_models.py index 8eda4fd..84266f1 100644 --- a/app/core/config_models.py +++ b/app/core/config_models.py @@ -29,8 +29,28 @@ PanelModel = Literal["133", "315"] Orientation = Literal["portrait", "landscape"] FitMode = Literal["smart_crop", "contain"] -DitherAlgorithm = Literal["atkinson", "floyd_steinberg"] -EinkProfile = Literal["official", "photo"] +#: ``auto`` decides per image (see :mod:`app.processor.auto`); the others are explicit. +DitherAlgorithm = Literal[ + "auto", + "atkinson", + "atkinson-classic", + "fs", + "floyd_steinberg", # alias of "fs", kept for existing settings and metadata + "fs-serpentine", + "stucki", + "blue-noise", +] +ConcreteDither = Literal[ + "atkinson", + "atkinson-classic", + "fs", + "floyd_steinberg", + "fs-serpentine", + "stucki", + "blue-noise", +] +EinkProfile = Literal["auto", "official", "photo", "soft", "vivid", "natural"] +ConcreteProfile = Literal["official", "photo", "soft", "vivid", "natural"] PowerMode = Literal["continuous", "deepsleep"] @@ -362,15 +382,35 @@ class DisplayConfig(_Section): "edge_filters": False, } +#: ``soft``, ``vivid`` and ``natural`` do their tone and chroma work in +#: :func:`app.processor.enhance.enhance` (gamut-safe curves), so the plain factors stay neutral. +CURVE_PROFILE: Final[dict[str, float | bool]] = { + "brightness": 1.0, + "contrast": 1.0, + "saturation": 1.0, + "sharpness": 1.0, + "edge_filters": False, +} + +PROFILE_VALUES: Final[dict[str, dict[str, float | bool]]] = { + "photo": PHOTO_PROFILE, + "soft": CURVE_PROFILE, + "vivid": CURVE_PROFILE, + "natural": CURVE_PROFILE, +} + class EinkConfig(_Section): """Color eInk optimization. Defaults mirror the official Fraimic converter.""" profile: EinkProfile = Field( - default="official", - description="official = the values below (defaults = official converter); photo = softer " - "preset for photographs that overrides brightness, contrast, saturation, sharpness " - "and edge_filters", + default="auto", + description="auto = chosen per image from its content (photo, poster, album cover, " + "title card) and cheap statistics; official = the values below (defaults = official " + "converter); photo = softer preset for photographs; soft / vivid = gamut-safe tone and " + "chroma curves (lifted shadows / richer colors); natural = no enhancement. " + "Everything but official overrides brightness, contrast, saturation, sharpness and " + "edge_filters", ) brightness: float = Field(default=1.1, ge=0.1, le=3.0, description="1.0 = unchanged") contrast: float = Field(default=1.2, ge=0.1, le=3.0, description="1.0 = unchanged") @@ -380,19 +420,42 @@ class EinkConfig(_Section): default=True, description="Apply the official edge-enhance / smooth / sharpen chain" ) dither: DitherAlgorithm = Field( - default="atkinson", - description="atkinson = tuned color metric (official default); floyd_steinberg = classic", + default="auto", + description="auto = chosen per image (fs-serpentine for detailed photos and posters, " + "stucki for smooth skies and gradients, atkinson-classic for graphics and covers); " + "atkinson = the official converter's 4-neighbour variant; fs = Floyd-Steinberg; " + "fs-serpentine = FS with alternating scan direction; stucki = wide 12-neighbour " + "kernel; blue-noise = ordered blue-noise threshold (fastest, grainy)", ) + @field_validator("dither", mode="before") + @classmethod + def _dither_alias(cls, value: object) -> object: + return "fs" if value == "floyd_steinberg" else value + def effective(self, profile: EinkProfile | None = None) -> EinkConfig: """The values actually used for rendering after applying the profile. + ``auto`` stays ``auto`` here: the renderer resolves it per image + (:mod:`app.processor.auto`) and then calls :meth:`resolved`. + Args: - profile: Overrides :attr:`profile` (e.g. a poster source forcing ``official``). + profile: Overrides :attr:`profile` (e.g. a source forcing ``official``). """ - if (profile or self.profile) == "official": + chosen = profile or self.profile + if chosen == "auto": return self - return self.model_copy(update=PHOTO_PROFILE) + return self.resolved(chosen) + + def resolved(self, profile: ConcreteProfile) -> EinkConfig: + """This configuration with a concrete ``profile`` applied.""" + if profile == "official": + return ( + self + if self.profile == "official" + else self.model_copy(update={"profile": "official"}) + ) + return self.model_copy(update={**PROFILE_VALUES[profile], "profile": profile}) class QualityConfig(_Section): diff --git a/app/processor/auto.py b/app/processor/auto.py new file mode 100644 index 0000000..9b1a345 --- /dev/null +++ b/app/processor/auto.py @@ -0,0 +1,220 @@ +"""Automatic tone-profile and dithering choice (``eink.profile`` / ``eink.dither`` = ``auto``). + +Nobody should have to tune a color profile or a dithering algorithm per image. The engine +decides from the *context* of the image (a photo, a movie poster, an album cover or a title +card) and a handful of cheap statistics measured on a <= 256 px thumbnail (a few +milliseconds, so it is free next to dithering, even on a Raspberry Pi): + +Profile (tone and chroma curve):: + + title card ............................ natural (flat colors stay exactly as drawn) + graphic (few colors, large flat areas) official (the official converter's look) + album cover (photographic) ............ soft (lifted shadows, restrained highlights) + poster, bright highlights / contrasty . soft (protects faces and highlights) + poster, flat or muted ................. vivid (richer colors) + photo, dark or low contrast ........... soft + other photos .......................... photo (the profile tuned on a real panel) + +Dithering:: + + title card, graphic, album cover ..... atkinson-classic (crisp edges, clean flats; covers + carry flat lettering that plain + error diffusion smears downward) + photo with large smooth regions ...... stucki (smooth skies and gradients) + everything else ...................... fs-serpentine (detail without "worm" artifacts; + plain fs if numba is missing) + +An explicit value in the settings always wins; ``auto`` only fills in what was left to the +engine. The decision (with its reasons) is reported with the image in ``GET /api/status``. +Thresholds are module constants, calibrated with ``scripts/quality_ab.py``. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Final, Literal + +import numpy as np +from PIL import Image +from pydantic import BaseModel, ConfigDict, Field + +from app.core.config_models import ConcreteDither, ConcreteProfile, EinkConfig +from app.processor.dither import effective_algorithm +from app.processor.quality import measure + +ContentContext = Literal["photo", "poster", "album", "title_card"] + +THUMBNAIL_LIMIT: Final = 256 +#: 8x8 blocks whose luma standard deviation is at most this count as smooth. +SMOOTH_BLOCK_STD: Final = 4.0 +#: Share of smooth blocks from which a photo counts as "mostly smooth" (sky, gradient, fog). +SMOOTH_PHOTO_SHARE: Final = 0.55 +#: Graphics: this few colors cover 90% of the pixels, or one color covers this share (%). +GRAPHIC_MAX_COLORS: Final = 12 +GRAPHIC_FLAT_SHARE: Final = 45.0 +#: Dark photos (mean luma) and flat-lit ones (luma standard deviation). +DARK_LUMA_MEAN: Final = 85.0 +LOW_CONTRAST_STD: Final = 38.0 +#: Posters with this share (%) of near-white pixels, or this much contrast, keep their +#: highlights (soft) instead of being pushed (vivid). +HIGHLIGHT_LUMA: Final = 235.0 +POSTER_HIGHLIGHT_SHARE: Final = 3.0 +POSTER_HIGH_CONTRAST_STD: Final = 60.0 + + +@dataclass(frozen=True, slots=True) +class ContentStats: + """Cheap statistics of a (thumbnail-sized) image.""" + + luma_mean: float + luma_std: float + highlight_share: float # % of pixels with luma >= HIGHLIGHT_LUMA + flat_share: float # % of pixels sharing the most common (5-bit quantized) color + dominant_colors: int # number of 5-bit colors covering 90% of the pixels + detail: float # mean absolute luma gradient (0..255): high = textured + smooth_share: float # share (0..1) of 8x8 blocks that are nearly flat + + @property + def graphic(self) -> bool: + """Few colors or large flat areas: a logo, an illustration, a typographic cover.""" + return self.dominant_colors <= GRAPHIC_MAX_COLORS or self.flat_share >= GRAPHIC_FLAT_SHARE + + @property + def smooth(self) -> bool: + """Mostly smooth regions (skies, fog, studio backdrops) and not a graphic.""" + return not self.graphic and self.smooth_share >= SMOOTH_PHOTO_SHARE + + @property + def dark(self) -> bool: + """Dark or low-contrast: shadows would clog and highlights are absent.""" + return self.luma_mean < DARK_LUMA_MEAN or self.luma_std < LOW_CONTRAST_STD + + +class RenderDecision(BaseModel): + """What the renderer used for one image, and why (reported in the image metadata).""" + + model_config = ConfigDict(frozen=True) + + context: ContentContext + profile: ConcreteProfile + dither: ConcreteDither + automatic: bool = Field(description="At least one of profile / dither was chosen by 'auto'") + reasons: list[str] = Field(default_factory=list) + + +def measure_content(image: Image.Image) -> ContentStats: + """Measure :class:`ContentStats` on a copy downscaled to at most 256 px.""" + small = image.convert("RGB") + small.thumbnail((THUMBNAIL_LIMIT, THUMBNAIL_LIMIT)) + base = measure(small) + rgb = np.asarray(small, dtype=np.float32) + luma = rgb @ np.array([0.299, 0.587, 0.114], dtype=np.float32) + + if luma.shape[0] > 1 and luma.shape[1] > 1: + detail = float( + (np.abs(np.diff(luma, axis=1)).mean() + np.abs(np.diff(luma, axis=0)).mean()) / 2 + ) + else: + detail = 0.0 + rows, cols = (luma.shape[0] // 8) * 8, (luma.shape[1] // 8) * 8 + if rows and cols: + blocks = luma[:rows, :cols].reshape(rows // 8, 8, cols // 8, 8).std(axis=(1, 3)) + smooth_share = float((blocks <= SMOOTH_BLOCK_STD).mean()) + else: + smooth_share = 0.0 + + quantized = rgb.astype(np.uint8) >> 3 + codes = ( + quantized[..., 0].astype(np.int32) * 1024 + + quantized[..., 1].astype(np.int32) * 32 + + quantized[..., 2].astype(np.int32) + ).ravel() + counts = np.sort(np.bincount(codes))[::-1] + covered = np.cumsum(counts) / codes.size + return ContentStats( + luma_mean=base.luma_mean, + luma_std=base.luma_std, + highlight_share=float((luma >= HIGHLIGHT_LUMA).mean() * 100), + flat_share=base.flat_share, + dominant_colors=int(np.searchsorted(covered, 0.9) + 1), + detail=detail, + smooth_share=smooth_share, + ) + + +def decide_profile( + context: ContentContext, stats: ContentStats | None +) -> tuple[ConcreteProfile, str]: + """The tone and chroma profile for an image (``stats`` is ``None`` without artwork).""" + if context == "title_card" or stats is None: + return "natural", "title card: flat colors stay as drawn" + if stats.graphic: + return "official", ( + f"graphic ({stats.dominant_colors} dominant colors, {stats.flat_share:.0f}% flat)" + ) + if context == "album": + return "soft", "photographic album cover: lifted shadows, restrained highlights" + if context == "poster": + if ( + stats.highlight_share >= POSTER_HIGHLIGHT_SHARE + or stats.luma_std >= POSTER_HIGH_CONTRAST_STD + ): + return "soft", ( + f"contrasty poster ({stats.highlight_share:.1f}% highlights, " + f"contrast {stats.luma_std:.0f}): protect faces and highlights" + ) + return "vivid", f"flat or muted poster (contrast {stats.luma_std:.0f}): richer colors" + if stats.luma_mean < DARK_LUMA_MEAN: + return "soft", f"dark photo (mean luma {stats.luma_mean:.0f}): lift shadows" + if stats.luma_std < LOW_CONTRAST_STD: + return "soft", ( + f"low-contrast photo (contrast {stats.luma_std:.0f}): gentle tones keep the detail" + ) + return "photo", "photo" + + +def decide_dither( + context: ContentContext, stats: ContentStats | None +) -> tuple[ConcreteDither, str]: + """The dithering algorithm for an image.""" + if context == "title_card" or stats is None: + return "atkinson-classic", "title card: crisp text edges and clean flats" + if stats.graphic: + return "atkinson-classic", "graphic: crisp edges and clean flats" + if context == "album": + return "atkinson-classic", "album cover: lettering stays crisp, no error smearing" + if context == "photo" and stats.smooth: + return "stucki", ( + f"mostly smooth ({stats.smooth_share * 100:.0f}% flat blocks): smooth gradients" + ) + return effective_algorithm("fs-serpentine"), "detailed image: no directional artifacts" + + +def resolve( + eink: EinkConfig, context: ContentContext, stats: ContentStats | None +) -> tuple[EinkConfig, RenderDecision]: + """Resolve ``auto`` settings into a concrete :class:`EinkConfig` and the decision. + + Explicit profile and dither settings are kept as they are. + """ + reasons: list[str] = [] + automatic = False + if eink.profile == "auto": + profile, reason = decide_profile(context, stats) + reasons.append(f"profile {profile}: {reason}") + automatic = True + else: + profile = eink.profile + reasons.append(f"profile {profile}: set in the settings") + if eink.dither == "auto": + dither, reason = decide_dither(context, stats) + reasons.append(f"dither {dither}: {reason}") + automatic = True + else: + dither = "fs" if eink.dither == "floyd_steinberg" else eink.dither + reasons.append(f"dither {dither}: set in the settings") + concrete = eink.resolved(profile).model_copy(update={"dither": dither}) + decision = RenderDecision( + context=context, profile=profile, dither=dither, automatic=automatic, reasons=reasons + ) + return concrete, decision diff --git a/app/processor/dither.py b/app/processor/dither.py index f414978..37eceb9 100644 --- a/app/processor/dither.py +++ b/app/processor/dither.py @@ -1,32 +1,78 @@ -"""Exact, NumPy-vectorized error-diffusion dithering onto the Spectra 6 palette. - -Error diffusion is sequential by nature: every pixel depends on the quantization -error of the pixels processed before it. Both supported kernels, however, only push -error to the right neighbour ``(y, x+1)`` and to the three pixels below -``(y+1, x-1..x+1)``. A pixel therefore only depends on pixels with a strictly smaller -wavefront key ``t = x + 2y``, so all pixels sharing the same ``t`` (an anti-diagonal) -can be quantized together in one vectorized step. This turns ``W * H`` Python -iterations into ``W + 2H`` NumPy steps (about 0.7 s for 1200x1600 instead of ~40 s). - -Within a step the down-left contribution is applied before the right contribution, -which reproduces the floating-point summation order of the sequential row-by-row -loop. The result is bit-identical to the official Fraimic converter's Atkinson -implementation (``quantize_atkinson_indexed``), as verified by the test suite. +"""Spectra 6 dithering: exact NumPy wavefront diffusion, compiled kernels and blue noise. + +Algorithms (all quantize onto the six panel colors with the official tuned color metric): + +* ``atkinson`` - the official Fraimic converter's 4-neighbour variant (5/8 of the error). + **Bit-identical** to the official converter, as verified by the test suite. +* ``atkinson-classic`` - the original 6-neighbour Atkinson (3/4 of the error): crisp + edges and clean flats, ideal for graphics, covers and title cards. +* ``fs`` - classic Floyd-Steinberg. ``fs-serpentine`` alternates the scan direction on every + row, which removes the directional "worm" patterns of plain FS. +* ``stucki`` - a wide 12-neighbour kernel: smoother tonal transitions in skies and gradients. +* ``blue-noise`` - ordered dithering against a tileable blue-noise threshold map: no error + diffusion, so it runs in milliseconds on any hardware, with a film-grain look. + +Speed. Error diffusion is sequential by nature, but a *causal* kernel (error only goes +forward: right, and below) only depends on pixels with a strictly smaller wavefront key +``t = x + a*y`` (``a`` = :attr:`DitherKernel.skew`; 2 for FS/Atkinson, 3 for Stucki), so all +pixels of one anti-diagonal are quantized together in one vectorized NumPy step. That turns +``W * H`` Python iterations into ``W + a*H`` steps (about 0.7 s for 1200x1600 instead of +~40 s). Serpentine scanning breaks the wavefront (each row depends on the end of the +previous one), so ``fs-serpentine`` - and ``stucki``, where it is 20x faster - run as +:mod:`numba`-compiled loops (tens of milliseconds on x86). If numba cannot be imported, +``stucki`` falls back to the wavefront and ``fs-serpentine`` to ``fs``. """ from __future__ import annotations +import io +import logging +import os +from collections.abc import Callable from dataclasses import dataclass -from typing import Final +from functools import lru_cache +from importlib import resources +from typing import Any, Final import numpy as np import numpy.typing as npt from PIL import Image -from app.core.config_models import DitherAlgorithm -from app.processor.palette import PALETTE_ARRAY, match_palette +from app.core.config_models import ConcreteDither, DitherAlgorithm +from app.processor.palette import PALETTE_ARRAY, PALETTE_LUMA, match_palette + +logger = logging.getLogger(__name__) + +# --- Optional numba -------------------------------------------------------------------------- +os.environ.setdefault( + "NUMBA_CACHE_DIR", os.path.join(os.environ.get("DATA_DIR", "/data"), ".numba_cache") +) + + +def _import_numba() -> Any: + try: + import numba as numba_module + except Exception: # ImportError, or llvmlite failing to load on an exotic platform + return None + return numba_module + +numba: Any = _import_numba() +NUMBA_AVAILABLE: bool = numba is not None + +def _jit(function: Callable[..., Any]) -> Callable[..., Any]: + """Compile ``function`` with numba, caching to disk when a cache directory is writable.""" + if numba is None: + return function + try: + compiled: Callable[..., Any] = numba.njit(cache=True, nogil=True)(function) + except Exception: # no writable cache locator: compile in memory + compiled = numba.njit(nogil=True)(function) + return compiled + + +# --- Kernels --------------------------------------------------------------------------------- @dataclass(frozen=True, slots=True) class DitherTap: """One error-diffusion target relative to the current pixel.""" @@ -38,9 +84,9 @@ class DitherTap: @dataclass(frozen=True, slots=True) class DitherKernel: - """An error-diffusion kernel compatible with the ``t = x + 2y`` wavefront. + """A causal error-diffusion kernel. - ``taps`` are listed in the order they must be applied within a wavefront step. + ``taps`` are listed in the order they are applied within a wavefront step. """ name: str @@ -49,12 +95,22 @@ class DitherKernel: def __post_init__(self) -> None: for tap in self.taps: forward_in_row = tap.dy == 0 and tap.dx >= 1 - next_row = tap.dy == 1 and tap.dx >= -1 - if not (forward_in_row or next_row): + below = tap.dy >= 1 + if not (forward_in_row or below): raise ValueError( - f"Tap ({tap.dy}, {tap.dx}) is incompatible with the x + 2y wavefront" + f"Tap ({tap.dy}, {tap.dx}) is not causal: the wavefront needs error to " + "go right or to later rows" ) + @property + def skew(self) -> int: + """Smallest ``a`` such that every tap moves forward on ``t = x + a*y``.""" + skew = 1 + for tap in self.taps: + if tap.dy >= 1: + skew = max(skew, (-tap.dx) // tap.dy + 1) + return skew + #: The official Fraimic/PhotoPainter Atkinson variant: 4 neighbours, 5/8 of the error. ATKINSON: Final = DitherKernel( @@ -67,9 +123,22 @@ def __post_init__(self) -> None: ), ) +#: The original Atkinson: 6 neighbours of 1/8 each (3/4 of the error is diffused). +ATKINSON_CLASSIC: Final = DitherKernel( + "atkinson-classic", + ( + DitherTap(1, -1, 1 / 8), + DitherTap(0, 1, 1 / 8), + DitherTap(1, 0, 1 / 8), + DitherTap(1, 1, 1 / 8), + DitherTap(0, 2, 1 / 8), + DitherTap(2, 0, 1 / 8), + ), +) + #: Classic Floyd-Steinberg (7/16, 3/16, 5/16, 1/16) with the tuned palette metric. FLOYD_STEINBERG: Final = DitherKernel( - "floyd_steinberg", + "fs", ( DitherTap(1, -1, 3 / 16), DitherTap(0, 1, 7 / 16), @@ -78,42 +147,60 @@ def __post_init__(self) -> None: ), ) -KERNELS: Final[dict[DitherAlgorithm, DitherKernel]] = { +#: Stucki: 12 neighbours over two rows. +STUCKI: Final = DitherKernel( + "stucki", + ( + DitherTap(1, -2, 2 / 42), + DitherTap(1, -1, 4 / 42), + DitherTap(0, 1, 8 / 42), + DitherTap(0, 2, 4 / 42), + DitherTap(1, 0, 8 / 42), + DitherTap(1, 1, 4 / 42), + DitherTap(1, 2, 2 / 42), + DitherTap(2, -2, 1 / 42), + DitherTap(2, -1, 2 / 42), + DitherTap(2, 0, 4 / 42), + DitherTap(2, 1, 2 / 42), + DitherTap(2, 2, 1 / 42), + ), +) + +KERNELS: Final[dict[str, DitherKernel]] = { "atkinson": ATKINSON, + "atkinson-classic": ATKINSON_CLASSIC, + "fs": FLOYD_STEINBERG, "floyd_steinberg": FLOYD_STEINBERG, + "stucki": STUCKI, } +#: Algorithms that need the compiled serpentine loop. +SERPENTINE: Final = frozenset({"fs-serpentine"}) -def dither( - rgb: npt.NDArray[np.uint8], algorithm: DitherAlgorithm = "atkinson" -) -> npt.NDArray[np.uint8]: - """Quantize an RGB image to Spectra 6 palette indices with error diffusion. - - Args: - rgb: ``(H, W, 3)`` ``uint8`` image. - algorithm: ``"atkinson"`` (official default) or ``"floyd_steinberg"``. - - Returns: - ``(H, W)`` ``uint8`` array of palette indices in ``0..5``. - """ +def _check(rgb: npt.NDArray[np.uint8]) -> tuple[int, int]: if rgb.ndim != 3 or rgb.shape[2] != 3 or rgb.shape[0] < 1 or rgb.shape[1] < 1: raise ValueError(f"Expected an (H, W, 3) RGB array, got shape {rgb.shape}") - kernel = KERNELS[algorithm] - height, width = int(rgb.shape[0]), int(rgb.shape[1]) + return int(rgb.shape[0]), int(rgb.shape[1]) + + +# --- NumPy wavefront (exact, no extra dependency) -------------------------------------------- +def _wavefront(rgb: npt.NDArray[np.uint8], kernel: DitherKernel) -> npt.NDArray[np.uint8]: + height, width = _check(rgb) + skew = kernel.skew # Float32 working buffer, exactly like the official converter. work = rgb.reshape(-1, 3).astype(np.float32) out = np.empty(height * width, dtype=np.uint8) taps = [(tap.dy, tap.dx, tap.dy * width + tap.dx, tap.weight) for tap in kernel.taps] - for step in range(width + 2 * (height - 1)): - # Pixels with x + 2y == step: y in [y_min, y_max], x = step - 2y in [0, width). - y_min = max(0, (step - width + 2) // 2) - y_max = min(height - 1, step // 2) + for step in range(width + skew * (height - 1)): + # Pixels with x + skew*y == step: x = step - skew*y must lie in [0, width). + y_min = max(0, (step - width + skew) // skew) + y_max = min(height - 1, step // skew) if y_min > y_max: continue ys = np.arange(y_min, y_max + 1) - xs = step - 2 * ys + xs = step - skew * ys flat = ys * width + xs old = work[flat] @@ -133,8 +220,175 @@ def dither( return out.reshape(height, width) +# --- Compiled sequential loop (serpentine, Stucki) ------------------------------------------- +_PAL_R: Final = PALETTE_ARRAY[:, 0].astype(np.float64) +_PAL_G: Final = PALETTE_ARRAY[:, 1].astype(np.float64) +_PAL_B: Final = PALETTE_ARRAY[:, 2].astype(np.float64) +_PAL_LUMA: Final = PALETTE_LUMA.astype(np.float64) + + +def _diffuse_loop( + work: Any, + pal_r: Any, + pal_g: Any, + pal_b: Any, + pal_luma: Any, + pal_rgb: Any, + dys: Any, + dxs: Any, + weights: Any, + serpentine: Any, + out: Any, +) -> None: + """Sequential error diffusion with the official metric (compiled by numba).""" + height = work.shape[0] + width = work.shape[1] + taps = dys.shape[0] + for y in range(height): + flip = serpentine and (y % 2 == 1) + for i in range(width): + x = width - 1 - i if flip else i + old_r = work[y, x, 0] + old_g = work[y, x, 1] + old_b = work[y, x, 2] + red = float(int(min(max(old_r, 0.0), 255.0))) + green = float(int(min(max(old_g, 0.0), 255.0))) + blue = float(int(min(max(old_b, 0.0), 255.0))) + luma = (red * 250 + green * 350 + blue * 400) / (255.0 * 1000) + best = 0 + best_total = 1e30 + for index in range(6): + dr = red - pal_r[index] + dg = green - pal_g[index] + db = blue - pal_b[index] + rgb_dist = ( + (dr * dr * 0.250 + dg * dg * 0.350 + db * db * 0.400) * 0.75 / (255.0 * 255.0) + ) + luma_diff = luma - pal_luma[index] + total = 1.5 * rgb_dist + 0.60 * (luma_diff * luma_diff) + if total < best_total: + best_total = total + best = index + out[y, x] = best + err_r = old_r - pal_rgb[best, 0] + err_g = old_g - pal_rgb[best, 1] + err_b = old_b - pal_rgb[best, 2] + for tap in range(taps): + ny = y + dys[tap] + dx = -dxs[tap] if flip else dxs[tap] + nx = x + dx + if ny < height and nx >= 0 and nx < width: + work[ny, nx, 0] += err_r * weights[tap] + work[ny, nx, 1] += err_g * weights[tap] + work[ny, nx, 2] += err_b * weights[tap] + + +_DIFFUSE: Final = _jit(_diffuse_loop) if NUMBA_AVAILABLE else None + + +def _compiled( + rgb: npt.NDArray[np.uint8], kernel: DitherKernel, *, serpentine: bool +) -> npt.NDArray[np.uint8]: + height, width = _check(rgb) + work = np.ascontiguousarray(rgb, dtype=np.float32) + out = np.empty((height, width), dtype=np.uint8) + if _DIFFUSE is None: + raise RuntimeError("The compiled dithering kernel needs numba") + _DIFFUSE( + work, + _PAL_R, + _PAL_G, + _PAL_B, + _PAL_LUMA, + PALETTE_ARRAY, + np.array([tap.dy for tap in kernel.taps], dtype=np.int64), + np.array([tap.dx for tap in kernel.taps], dtype=np.int64), + np.array([tap.weight for tap in kernel.taps], dtype=np.float32), + serpentine, + out, + ) + return out + + +# --- Blue-noise ordered dithering ------------------------------------------------------------ +BLUE_NOISE_FILE: Final = "blue_noise_64.npy" + + +@lru_cache(maxsize=1) +def blue_noise_thresholds() -> npt.NDArray[np.float32]: + """The bundled 64x64 tileable blue-noise tile as thresholds in ``(0, 255)``.""" + resource = resources.files("app").joinpath("assets", BLUE_NOISE_FILE) + ranks = np.load(io.BytesIO(resource.read_bytes())) + return np.asarray((ranks.astype(np.float32) + 0.5) / ranks.size * 255.0, dtype=np.float32) + + +@lru_cache(maxsize=1) +def _corner_lut() -> npt.NDArray[np.uint8]: + """Palette index of each RGB-cube corner (``r*4 + g*2 + b``); cyan and magenta map to + their nearest panel color.""" + corners = np.array( + [[(code >> 2) & 1, (code >> 1) & 1, code & 1] for code in range(8)], dtype=np.int64 + ) + return np.asarray(match_palette(corners * 255), dtype=np.uint8) + + +def _blue_noise(rgb: npt.NDArray[np.uint8]) -> npt.NDArray[np.uint8]: + height, width = _check(rgb) + tile = blue_noise_thresholds() + rows = np.arange(height) % tile.shape[0] + cols = np.arange(width) % tile.shape[1] + threshold = tile[rows[:, None], cols[None, :]] + bits = rgb > threshold[:, :, None] # one shared mask: greys become black/white stipple + code = bits[..., 0] * 4 + bits[..., 1] * 2 + bits[..., 2] + return np.asarray(_corner_lut()[code], dtype=np.uint8) + + +# --- Public API ------------------------------------------------------------------------------ +def effective_algorithm(algorithm: ConcreteDither) -> ConcreteDither: + """The algorithm that will really run (``fs-serpentine`` needs numba, else ``fs``).""" + if algorithm in SERPENTINE and not NUMBA_AVAILABLE: + return "fs" + return algorithm + + +def dither( + rgb: npt.NDArray[np.uint8], algorithm: DitherAlgorithm = "atkinson" +) -> npt.NDArray[np.uint8]: + """Quantize an RGB image to Spectra 6 palette indices. + + Args: + rgb: ``(H, W, 3)`` ``uint8`` image. + algorithm: A concrete algorithm (see the module docstring); ``"auto"`` must be + resolved by the caller (:mod:`app.processor.auto`). + + Returns: + ``(H, W)`` ``uint8`` array of palette indices in ``0..5``. + """ + _check(rgb) + if algorithm == "auto": + raise ValueError('"auto" must be resolved to a concrete dither algorithm first') + name = effective_algorithm(algorithm) + if name != algorithm: + logger.warning("numba is unavailable: using %s instead of %s", name, algorithm) + if name == "blue-noise": + return _blue_noise(rgb) + if name == "fs-serpentine": + return _compiled(rgb, FLOYD_STEINBERG, serpentine=True) + if name == "stucki" and NUMBA_AVAILABLE: + return _compiled(rgb, STUCKI, serpentine=False) + return _wavefront(rgb, KERNELS[name]) + + def dither_image( image: Image.Image, algorithm: DitherAlgorithm = "atkinson" ) -> npt.NDArray[np.uint8]: """Convenience wrapper around :func:`dither` for Pillow images.""" return dither(np.asarray(image.convert("RGB"), dtype=np.uint8), algorithm) + + +def warm_up() -> None: + """Compile (and cache) the numba kernels so the first real render is fast.""" + sample = np.zeros((8, 8, 3), dtype=np.uint8) + algorithms: tuple[ConcreteDither, ...] = ("fs-serpentine", "stucki") + for algorithm in algorithms: + dither(sample, algorithm) diff --git a/app/processor/enhance.py b/app/processor/enhance.py index 0a6a040..9647485 100644 --- a/app/processor/enhance.py +++ b/app/processor/enhance.py @@ -1,28 +1,67 @@ -"""eInk enhancement pipeline (official Fraimic order and defaults). +"""eInk enhancement pipeline (official Fraimic order and defaults, plus gamut-safe curves). -Order: Brightness -> Contrast -> Color (saturation) -> [Sharpness] -> EDGE_ENHANCE -> -SMOOTH -> SHARPEN. With ``sharpness == 1.0`` (default) the extra Sharpness step is -skipped, making the output identical to the official converter's ``process_image``. +Order: [tone/chroma curve] -> Brightness -> Contrast -> Color (saturation) -> [Sharpness] -> +EDGE_ENHANCE -> SMOOTH -> SHARPEN. With ``sharpness == 1.0`` (default) the extra Sharpness +step is skipped, making the output identical to the official converter's ``process_image``. Enhancement must run on the picture only (before letterbox padding) so flat bars do not skew the contrast pivot and filters do not bleed across the picture/bar seam. + +The ``soft`` and ``vivid`` profiles (adapted from the MIT-licensed stillroom converter, based +on the official Fraimic converter) work on luminance in floating point with +endpoint-preserving curves, and compress chroma toward that luminance *only* when it would +leave the RGB gamut - one scale for all three channels, so hue is preserved instead of +clipping individual channels. ``natural`` leaves the source tones untouched. No profile can +recover detail that is already clipped, nor remove the limits of a six-color display. """ from __future__ import annotations +from typing import Final + +import numpy as np from PIL import Image, ImageEnhance, ImageFilter from app.core.config_models import EinkConfig +_LUMA: Final = np.array([0.2126, 0.7152, 0.0722], dtype=np.float32) +#: profile -> (shadow lift, midtone S-curve strength, highlight shoulder, chroma gain) +CURVES: Final[dict[str, tuple[float, float, float, float]]] = { + "soft": (0.12, -0.12, 0.35, 0.98), # lifted shadows, restrained highlights + "vivid": (0.10, 0.50, 0.15, 1.18), # stronger contrast, richer color, gradual roll-off +} + + +def tone_curve(image: Image.Image, profile: str) -> Image.Image: + """Apply the gamut-safe ``soft`` / ``vivid`` curve (see the module docstring).""" + shadow, strength, shoulder, colour = CURVES[profile] + rgb = np.asarray(image.convert("RGB"), dtype=np.float32) / 255.0 + lum = (rgb * _LUMA).sum(axis=2, keepdims=True) + target = ( + lum + + shadow * lum * (1 - lum) + + strength * lum * (1 - lum) * (2 * lum - 1) + - shoulder * lum**4 * (1 - lum) + ) + chroma = (rgb - lum) * colour + # One scale for all channels keeps the hue at the gamut boundary. + room = np.where(chroma > 0, 1 - target, target) + scale = np.minimum(1.0, (room / np.maximum(np.abs(chroma), 1e-8)).min(axis=2, keepdims=True)) + mapped = target + chroma * scale + return Image.fromarray(np.rint(np.clip(mapped, 0, 1) * 255).astype(np.uint8)) + def enhance(image: Image.Image, eink: EinkConfig, *, edge_filters: bool = True) -> Image.Image: """Apply the eInk color and detail adjustments. Args: image: RGB picture (already scaled to its on-panel size). - eink: Enhancement settings. + eink: Enhancement settings (a concrete profile; an unresolved ``auto`` behaves like + ``official``). edge_filters: Set to ``False`` to skip the edge-enhance/smooth/sharpen chain regardless of ``eink.edge_filters`` (used for blurred backgrounds). """ + if eink.profile in CURVES: + image = tone_curve(image, eink.profile) result = ImageEnhance.Brightness(image).enhance(eink.brightness) result = ImageEnhance.Contrast(result).enhance(eink.contrast) result = ImageEnhance.Color(result).enhance(eink.saturation) diff --git a/app/processor/pipeline.py b/app/processor/pipeline.py index 2513eaa..d1b241d 100644 --- a/app/processor/pipeline.py +++ b/app/processor/pipeline.py @@ -22,7 +22,7 @@ import hashlib import io from collections.abc import Sequence -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace from functools import cached_property from typing import Literal @@ -32,6 +32,12 @@ from app.core.config_models import EinkConfig, EinkProfile, FitMode, PanelSpec, RuntimeConfig from app.core.security import verify_image_bytes +from app.processor.auto import ( + ContentContext, + RenderDecision, + measure_content, + resolve, +) from app.processor.dither import dither from app.processor.enhance import enhance from app.processor.fit import ( @@ -82,6 +88,9 @@ class RenderOptions: background: BackgroundStyle eink: EinkConfig safe_margin_px: int = 0 + #: What the image is, for the automatic profile and dither choice (``eink.profile`` and + #: ``eink.dither`` set to ``auto``). + context: ContentContext = "photo" def __post_init__(self) -> None: native = (self.panel.width, self.panel.height) @@ -101,13 +110,15 @@ def from_config( *, fit: FitMode | None = None, eink_profile: EinkProfile | None = None, + context: ContentContext = "photo", ) -> RenderOptions: """Build options from the effective config. Args: config: Effective runtime configuration. fit: Overrides the default fit mode. - eink_profile: Overrides ``eink.profile`` (e.g. posters always use ``official``). + eink_profile: Overrides ``eink.profile`` (e.g. a source forcing ``official``). + context: What the image is (drives the ``auto`` profile and dither choice). """ rotation: Rotation = ( 0 if config.display.orientation == "portrait" else config.display.landscape_rotation @@ -120,6 +131,7 @@ def from_config( background=config.display.contain_background, eink=config.eink.effective(eink_profile), safe_margin_px=config.display.safe_margin_px, + context=context, ) @@ -131,6 +143,7 @@ class RenderResult: composed: Image.Image = field(repr=False) indices: npt.NDArray[np.uint8] = field(repr=False) bin: bytes = field(repr=False) + decision: RenderDecision | None = None @cached_property def sha256(self) -> str: @@ -157,6 +170,20 @@ def dithered_png(self) -> bytes: return buffer.getvalue() +def resolved_options( + image: Image.Image | None, options: RenderOptions +) -> tuple[RenderOptions, RenderDecision]: + """``options`` with ``auto`` profile and dither resolved for ``image``. + + Args: + image: The source picture (``None`` for a title card). + options: Render options, possibly with ``auto`` settings. + """ + stats = measure_content(image) if image is not None else None + eink, decision = resolve(options.eink, options.context, stats) + return replace(options, eink=eink), decision + + def compose( image: Image.Image, options: RenderOptions, regions: Sequence[FocusRegion] = () ) -> Image.Image: @@ -165,6 +192,8 @@ def compose( The picture fills the frame minus ``safe_margin_px`` on every side; whatever is left over (the margin, or the bars of the ``contain`` fit) is the background. """ + if options.eink.profile == "auto": + options, _ = resolved_options(image, options) margin = options.safe_margin_px area = (options.frame_size[0] - 2 * margin, options.frame_size[1] - 2 * margin) if options.fit == "smart_crop": @@ -179,14 +208,20 @@ def compose( return paste_centered(background, picture) -def finalize(composed: Image.Image, options: RenderOptions) -> RenderResult: +def finalize( + composed: Image.Image, options: RenderOptions, decision: RenderDecision | None = None +) -> RenderResult: """Rotate, dither and encode a frame-sized composition (viewing orientation). + An unresolved ``auto`` dither is decided from the composition itself. + Raises: ValueError: If ``composed`` does not have the frame size of ``options``. """ if composed.size != options.frame_size: raise ValueError(f"Composition is {composed.size}, expected {options.frame_size}") + if options.eink.dither == "auto" or options.eink.profile == "auto": + options, decision = resolved_options(composed, options) composed = composed.convert("RGB") quarter_turns = options.rotation // 90 # Rotate *before* dithering, like the official converter's ``--fit rotate``: error @@ -202,14 +237,20 @@ def finalize(composed: Image.Image, options: RenderOptions) -> RenderResult: composed=composed, indices=indices, bin=encode_bin(portrait, options.panel), + decision=decision, ) def render( image: Image.Image, options: RenderOptions, regions: Sequence[FocusRegion] = () ) -> RenderResult: - """Compose, dither and encode ``image`` for the configured panel.""" - return finalize(compose(image.convert("RGB"), options, regions), options) + """Compose, dither and encode ``image`` for the configured panel. + + ``auto`` profile and dither are resolved once, from the source picture. + """ + source = image.convert("RGB") + resolved, decision = resolved_options(source, options) + return finalize(compose(source, resolved, regions), resolved, decision) def canvas_for(options: RenderOptions) -> Canvas: @@ -222,10 +263,14 @@ def render_layout( ) -> RenderResult: """Compose ``image`` with a template (never cropped), then dither and encode it. + ``auto`` profile and dither are resolved from the artwork and the layout's context. + Raises: ValueError: If the layout needs artwork and ``image`` is ``None``. """ - return finalize(compose_layout(image, layout, canvas_for(options)), options) + options = replace(options, context=layout.name) + resolved, decision = resolved_options(image, options) + return finalize(compose_layout(image, layout, canvas_for(resolved)), resolved, decision) def render_layout_bytes(data: bytes | None, layout: Layout, options: RenderOptions) -> RenderResult: diff --git a/app/services/current_image.py b/app/services/current_image.py index a54c421..f57785f 100644 --- a/app/services/current_image.py +++ b/app/services/current_image.py @@ -28,6 +28,7 @@ from app.core.atomic import atomic_write_bytes from app.core.config_models import DitherAlgorithm, FitMode, PanelModel from app.core.json_store import atomic_write_json, read_json +from app.processor.auto import RenderDecision from app.processor.pipeline import RenderResult logger = logging.getLogger(__name__) @@ -63,6 +64,10 @@ class CurrentImageMeta(BaseModel): template: str | None = Field( default=None, description="Composition template (poster, album, title_card), if any" ) + render: RenderDecision | None = Field( + default=None, + description="The eInk profile and dithering used, and why (automatic or from settings)", + ) pushed: bool = Field(default=True, description="Whether the image was sent to the frame") ephemeral: bool = Field( default=False, description="Temporary image: the previous one comes back afterwards" @@ -209,6 +214,7 @@ def save( sha256=result.sha256, bin_size=len(result.bin), template=template, + render=result.decision, pushed=push, ephemeral=ephemeral, expires_at=expires_at, diff --git a/app/services/display.py b/app/services/display.py index ec19687..d07b408 100644 --- a/app/services/display.py +++ b/app/services/display.py @@ -139,15 +139,13 @@ async def display_layout( ) -> DisplayResult: """Render ``data`` (or nothing, for a title card) with a composition template. - Templates never crop and always use the ``official`` eInk profile (posters and - album art are graphic designs, not photos). + Templates never crop. With ``auto`` settings, the eInk profile and dithering are + chosen from the layout (poster, album cover, title card) and the artwork. Raises: InvalidImageError: If ``data`` is not a supported image. """ - options = RenderOptions.from_config( - self._config_store.config, fit="contain", eink_profile="official" - ) + options = RenderOptions.from_config(self._config_store.config, fit="contain") return await self._display( lambda: render_layout_bytes(data, layout, options), meta, template=layout.name ) diff --git a/pyproject.toml b/pyproject.toml index 40e7db8..67434ef 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -27,6 +27,7 @@ dependencies = [ "pillow>=10.4", "pillow-heif>=0.20", "numpy>=2.0", + "numba>=0.60", "apscheduler>=3.10,<4", "jinja2>=3.1", "python-multipart>=0.0.9", @@ -51,7 +52,13 @@ Issues = "https://github.com/ant1fr/Smart-Frame-Engine/issues" include = ["app*"] [tool.setuptools.package-data] -app = ["py.typed", "templates/*.html", "assets/fonts/*.ttf", "assets/fonts/*.txt"] +app = [ + "py.typed", + "templates/*.html", + "assets/fonts/*.ttf", + "assets/fonts/*.txt", + "assets/*.npy", +] # --- Ruff ----------------------------------------------------------------------- [tool.ruff] @@ -87,7 +94,7 @@ plugins = ["pydantic.mypy"] exclude = ["fraimic-docs/", "build/", "tests/reference/"] [[tool.mypy.overrides]] -module = ["apscheduler.*"] +module = ["apscheduler.*", "numba", "numba.*"] ignore_missing_imports = true [tool.pydantic-mypy] diff --git a/scripts/make_blue_noise.py b/scripts/make_blue_noise.py new file mode 100644 index 0000000..d5501f4 --- /dev/null +++ b/scripts/make_blue_noise.py @@ -0,0 +1,104 @@ +"""Generate the bundled tileable blue-noise tile (``app/assets/blue_noise_64.npy``). + +Void-and-cluster (Ulichney, 1993) on a torus: every cell gets a distinct rank +``0..N*N-1`` such that thresholding at any level yields an evenly spread (blue-noise) +pattern. Deterministic for a given seed, so the committed asset is reproducible:: + + python scripts/make_blue_noise.py # writes app/assets/blue_noise_64.npy +""" + +from __future__ import annotations + +import argparse +from pathlib import Path + +import numpy as np +import numpy.typing as npt + +SIZE = 64 +SIGMA = 1.9 +SEED = 20261115 + + +def gaussian_kernel(size: int, sigma: float) -> npt.NDArray[np.float64]: + """Toroidal Gaussian centered on cell (0, 0).""" + axis = np.minimum(np.arange(size), size - np.arange(size)).astype(np.float64) + distance = axis[:, None] ** 2 + axis[None, :] ** 2 + return np.exp(-distance / (2 * sigma**2)) + + +def void_and_cluster(size: int = SIZE, sigma: float = SIGMA, seed: int = SEED) -> npt.NDArray: + """Rank matrix (``uint16``) of a ``size`` x ``size`` blue-noise tile.""" + rng = np.random.default_rng(seed) + total = size * size + kernel = gaussian_kernel(size, sigma) + + def stamp(y: int, x: int) -> npt.NDArray[np.float64]: + return np.roll(kernel, (y, x), axis=(0, 1)) + + # --- Initial pattern: ~10% random ones, relaxed until the tightest cluster and the + # largest void coincide. + pattern = np.zeros((size, size), dtype=bool) + ones = max(1, total // 10) + pattern.flat[rng.choice(total, ones, replace=False)] = True + energy = np.zeros((size, size)) + for y, x in zip(*np.nonzero(pattern), strict=True): + energy += stamp(y, x) + while True: + masked = np.where(pattern, energy, -np.inf) + cy, cx = np.unravel_index(np.argmax(masked), masked.shape) + pattern[cy, cx] = False + energy -= stamp(cy, cx) + masked = np.where(pattern, np.inf, energy) + vy, vx = np.unravel_index(np.argmin(masked), masked.shape) + pattern[vy, vx] = True + energy += stamp(vy, vx) + if (vy, vx) == (cy, cx): + break + + ranks = np.zeros((size, size), dtype=np.int64) + + # --- Phase 1: remove the tightest cluster repeatedly, ranks count down from `ones`-1. + work = pattern.copy() + work_energy = energy.copy() + for rank in range(ones - 1, -1, -1): + masked = np.where(work, work_energy, -np.inf) + y, x = np.unravel_index(np.argmax(masked), masked.shape) + ranks[y, x] = rank + work[y, x] = False + work_energy -= stamp(y, x) + + # --- Phase 2: from the initial pattern, fill the largest void until half are ones. + work = pattern.copy() + work_energy = energy.copy() + for rank in range(ones, total // 2): + masked = np.where(work, np.inf, work_energy) + y, x = np.unravel_index(np.argmin(masked), masked.shape) + ranks[y, x] = rank + work[y, x] = True + work_energy += stamp(y, x) + + # --- Phase 3: the zeros are now the minority: place the rest at the tightest cluster + # of zeros (the largest void of the inverted pattern). + zero_energy = np.zeros((size, size)) + for y, x in zip(*np.nonzero(~work), strict=True): + zero_energy += stamp(y, x) + for rank in range(total // 2, total): + masked = np.where(work, -np.inf, zero_energy) + y, x = np.unravel_index(np.argmax(masked), masked.shape) + ranks[y, x] = rank + work[y, x] = True + zero_energy -= stamp(y, x) + + return ranks.astype(np.uint16) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--out", type=Path, default=Path("app/assets") / f"blue_noise_{SIZE}.npy") + arguments = parser.parse_args() + tile = void_and_cluster() + if not np.array_equal(np.sort(tile.ravel()), np.arange(SIZE * SIZE)): + raise SystemExit("ranks are not a permutation") + np.save(arguments.out, tile) + print(f"wrote {arguments.out} ({tile.shape}, {tile.dtype})") diff --git a/tests/test_api.py b/tests/test_api.py index 996db90..14e1056 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -143,7 +143,16 @@ def test_config_api_masks_immich_account_keys(make_client: ClientFactory) -> Non def test_eink_profile_is_configurable_over_the_api(make_client: ClientFactory) -> None: client = make_client() - assert client.get("/api/config").json()["config"]["eink"]["profile"] == "official" + eink = client.get("/api/config").json()["config"]["eink"] + assert (eink["profile"], eink["dither"]) == ("auto", "auto") assert client.put("/api/config", json={"eink": {"profile": "photo"}}).status_code == 200 assert client.get("/api/config").json()["config"]["eink"]["profile"] == "photo" + for profile in ("official", "soft", "vivid", "natural", "auto"): + assert client.put("/api/config", json={"eink": {"profile": profile}}).status_code == 200 + for dither in ("fs", "fs-serpentine", "stucki", "atkinson", "atkinson-classic", "blue-noise"): + assert client.put("/api/config", json={"eink": {"dither": dither}}).status_code == 200 + legacy = client.put("/api/config", json={"eink": {"dither": "floyd_steinberg"}}) + assert legacy.status_code == 200 + assert client.get("/api/config").json()["config"]["eink"]["dither"] == "fs" assert client.put("/api/config", json={"eink": {"profile": "poster"}}).status_code == 422 + assert client.put("/api/config", json={"eink": {"dither": "bayer"}}).status_code == 422 diff --git a/tests/test_api_phase2.py b/tests/test_api_phase2.py index 7a87fd5..5544c6f 100644 --- a/tests/test_api_phase2.py +++ b/tests/test_api_phase2.py @@ -341,3 +341,23 @@ def test_preview_endpoints_serve_the_latest_render(make_client: ClientFactory) - assert png.status_code == 200 and png.content[:8] == b"\x89PNG\r\n\x1a\n" assert client.head("/api/preview.jpg").status_code == 200 assert client.get("/api/status").json()["current_image"] is None + + +def test_status_explains_the_render_decision(make_client: ClientFactory) -> None: + client = make_client() + upload(client) + render = client.get("/api/status").json()["current_image"]["render"] + assert render["context"] == "photo" and render["automatic"] is True + assert render["profile"] in {"official", "photo", "soft", "vivid", "natural"} + assert render["dither"] in {"fs", "fs-serpentine", "stucki", "atkinson-classic"} + assert len(render["reasons"]) == 2 + + assert ( + client.put( + "/api/config", json={"eink": {"profile": "official", "dither": "atkinson"}} + ).status_code + == 200 + ) + upload(client) + manual = client.get("/api/status").json()["current_image"] + assert manual["dither"] == "atkinson" and manual["render"]["automatic"] is False diff --git a/tests/test_auto.py b/tests/test_auto.py new file mode 100644 index 0000000..20ca689 --- /dev/null +++ b/tests/test_auto.py @@ -0,0 +1,183 @@ +from __future__ import annotations + +import io +from typing import Any + +import numpy as np +import pytest +from PIL import Image + +from app.core.config_models import EinkConfig, RuntimeConfig +from app.processor import auto +from app.processor.auto import ( + ContentStats, + decide_dither, + decide_profile, + measure_content, + resolve, +) +from app.processor.dither import NUMBA_AVAILABLE +from app.processor.pipeline import RenderOptions, render, render_layout +from app.processor.templates import AlbumLayout, PosterLayout, TitleCardLayout + +SERPENTINE = "fs-serpentine" if NUMBA_AVAILABLE else "fs" + + +def stats(**overrides: Any) -> ContentStats: + base: dict[str, Any] = { + "luma_mean": 120.0, + "luma_std": 55.0, + "highlight_share": 0.5, + "flat_share": 5.0, + "dominant_colors": 300, + "detail": 12.0, + "smooth_share": 0.1, + } + return ContentStats(**{**base, **overrides}) + + +def photo(seed: int = 0, size: tuple[int, int] = (240, 320)) -> Image.Image: + rng = np.random.default_rng(seed) + return Image.fromarray(rng.integers(0, 256, (size[1], size[0], 3), dtype=np.uint8)) + + +# --- measurements --------------------------------------------------------------------------- +def test_measure_content_tells_noise_from_gradients_and_graphics() -> None: + noisy = measure_content(photo()) + assert noisy.detail > 25 and noisy.smooth_share == 0.0 + assert not noisy.graphic and not noisy.smooth + + ramp = np.tile(np.linspace(40, 200, 320, dtype=np.float32), (240, 1)) + sky = measure_content(Image.fromarray(np.dstack([ramp, ramp, ramp + 20]).astype(np.uint8))) + assert sky.smooth_share > 0.9 and sky.detail < 2 + + logo = Image.new("RGB", (300, 300), (255, 255, 255)) + logo.paste((200, 20, 20), (100, 100, 200, 200)) + flat = measure_content(logo) + assert flat.graphic and flat.dominant_colors <= 3 and flat.flat_share > 60 + + +def test_measure_content_handles_tiny_images() -> None: + assert measure_content(Image.new("RGB", (3, 2), (10, 20, 30))).smooth_share == 0.0 + + +# --- profile --------------------------------------------------------------------------------- +@pytest.mark.parametrize( + ("context", "overrides", "expected"), + [ + ("title_card", {}, "natural"), + ("album", {"dominant_colors": 6}, "official"), # graphic cover + ("album", {"flat_share": 60.0}, "official"), + ("album", {}, "soft"), # photographic cover + ("poster", {"highlight_share": 6.0}, "soft"), # bright faces + ("poster", {"luma_std": 70.0}, "soft"), # contrasty + ("poster", {"luma_std": 40.0, "highlight_share": 0.5}, "vivid"), # flat, muted + ("photo", {"luma_mean": 60.0}, "soft"), # dark + ("photo", {"luma_std": 30.0}, "soft"), # low contrast + ("photo", {}, "photo"), + ], +) +def test_profile_decision(context: Any, overrides: dict[str, Any], expected: str) -> None: + assert decide_profile(context, stats(**overrides))[0] == expected + + +def test_a_title_card_or_missing_artwork_is_natural() -> None: + assert decide_profile("poster", None)[0] == "natural" + + +# --- dither ---------------------------------------------------------------------------------- +@pytest.mark.parametrize( + ("context", "overrides", "expected"), + [ + ("title_card", {}, "atkinson-classic"), + ("album", {"dominant_colors": 5}, "atkinson-classic"), + ("poster", {"dominant_colors": 8}, "atkinson-classic"), # flat graphic poster + ("photo", {"smooth_share": 0.7}, "stucki"), + ("photo", {}, SERPENTINE), + ("poster", {"smooth_share": 0.9}, SERPENTINE), # posters keep their detail + ("album", {}, "atkinson-classic"), # lettering must not smear + ], +) +def test_dither_decision(context: Any, overrides: dict[str, Any], expected: str) -> None: + assert decide_dither(context, stats(**overrides))[0] == expected + + +def test_serpentine_falls_back_to_fs_without_numba(monkeypatch: pytest.MonkeyPatch) -> None: + import app.processor.dither as dither_module + + monkeypatch.setattr(dither_module, "NUMBA_AVAILABLE", False) + assert decide_dither("photo", stats())[0] == "fs" + + +# --- resolve --------------------------------------------------------------------------------- +def test_auto_settings_are_filled_in_and_explained() -> None: + concrete, decision = resolve(EinkConfig(), "poster", stats(highlight_share=8.0)) + assert (concrete.profile, concrete.dither) == ("soft", SERPENTINE) + assert decision.automatic and decision.context == "poster" + assert len(decision.reasons) == 2 and "contrasty poster" in decision.reasons[0] + assert (concrete.brightness, concrete.contrast, concrete.edge_filters) == (1.0, 1.0, False) + + +def test_explicit_settings_always_win() -> None: + eink = EinkConfig(profile="official", dither="stucki", contrast=1.4) + concrete, decision = resolve(eink, "title_card", None) + assert (concrete.profile, concrete.dither, concrete.contrast) == ("official", "stucki", 1.4) + assert not decision.automatic + assert all("set in the settings" in reason for reason in decision.reasons) + + +def test_a_manual_profile_with_an_automatic_dither() -> None: + concrete, decision = resolve(EinkConfig(profile="vivid"), "photo", stats(smooth_share=0.8)) + assert (concrete.profile, concrete.dither) == ("vivid", "stucki") + assert decision.automatic + + +# --- pipeline -------------------------------------------------------------------------------- +def options(**eink: Any) -> RenderOptions: + return RenderOptions.from_config(RuntimeConfig.model_validate({"eink": eink})) + + +def test_render_reports_its_decision_and_uses_it() -> None: + result = render(photo(1), options()) + assert result.decision is not None and result.decision.automatic + assert result.options.eink.profile == result.decision.profile + assert result.options.eink.dither == result.decision.dither + assert len(result.bin) == 960_000 + + +def test_manual_override_is_reported_as_such() -> None: + result = render(photo(2), options(profile="official", dither="atkinson")) + assert result.decision is not None and not result.decision.automatic + assert (result.options.eink.profile, result.options.eink.dither) == ("official", "atkinson") + + +@pytest.mark.parametrize( + ("layout", "expected_context"), + [ + (PosterLayout(), "poster"), + (AlbumLayout(title="Song", artist="Artist"), "album"), + (TitleCardLayout(title="Nothing here"), "title_card"), + ], +) +def test_templates_decide_from_their_layout(layout: Any, expected_context: str) -> None: + art = None if isinstance(layout, TitleCardLayout) else photo(3, (300, 450)) + result = render_layout(art, layout, options()) + assert result.decision is not None and result.decision.context == expected_context + if expected_context == "title_card": + assert (result.decision.profile, result.decision.dither) == ( + "natural", + "atkinson-classic", + ) + + +def test_image_bytes_round_trip_through_auto() -> None: + buffer = io.BytesIO() + photo(4).save(buffer, format="PNG") + from app.processor.pipeline import render_bytes + + result = render_bytes(buffer.getvalue(), options()) + assert result.decision is not None + + +def test_auto_module_exports_its_thresholds() -> None: + assert 0 < auto.SMOOTH_PHOTO_SHARE < 1 and auto.GRAPHIC_MAX_COLORS > 0 diff --git a/tests/test_config_models.py b/tests/test_config_models.py index 157e335..d3e002c 100644 --- a/tests/test_config_models.py +++ b/tests/test_config_models.py @@ -30,7 +30,7 @@ def test_defaults_follow_official_converter() -> None: assert config.fraimic.panel == "133" assert config.fraimic.upload_path == "/api/image" assert config.fraimic.status_path == "/api/info" - assert config.eink.dither == "atkinson" + assert (config.eink.profile, config.eink.dither) == ("auto", "auto") assert (config.eink.brightness, config.eink.contrast, config.eink.saturation) == ( 1.1, 1.2, @@ -213,22 +213,40 @@ def test_dump_config_reveals_or_masks_secrets() -> None: # --- eInk profiles ----------------------------------------------------------------------------- -def test_official_profile_is_the_default_and_leaves_values_untouched() -> None: +def test_auto_is_the_default_and_stays_unresolved_until_render_time() -> None: from app.core.config_models import EinkConfig - config = EinkConfig(contrast=1.4, dither="floyd_steinberg") - assert config.profile == "official" + config = EinkConfig(contrast=1.4) + assert (config.profile, config.dither) == ("auto", "auto") assert config.effective() is config +def test_official_profile_leaves_values_untouched_and_floyd_steinberg_is_an_alias() -> None: + from app.core.config_models import EinkConfig + + config = EinkConfig(profile="official", contrast=1.4, dither="floyd_steinberg") + assert config.dither == "fs" + assert config.effective() is config + + +@pytest.mark.parametrize("profile", ["soft", "vivid", "natural"]) +def test_curve_profiles_neutralize_the_plain_factors(profile: str) -> None: + from app.core.config_models import EinkConfig + + effective = EinkConfig(profile=profile, contrast=1.5).effective() # type: ignore[arg-type] + assert effective.profile == profile + assert (effective.brightness, effective.contrast, effective.saturation) == (1.0, 1.0, 1.0) + assert effective.edge_filters is False and effective.sharpness == 1.0 + + def test_photo_profile_overrides_the_five_tuning_fields_but_keeps_dithering() -> None: from app.core.config_models import PHOTO_PROFILE, EinkConfig - config = EinkConfig(profile="photo", contrast=1.5, dither="floyd_steinberg") + config = EinkConfig(profile="photo", contrast=1.5, dither="stucki") effective = config.effective() for name, value in PHOTO_PROFILE.items(): assert getattr(effective, name) == value - assert effective.dither == "floyd_steinberg" + assert effective.dither == "stucki" assert effective.edge_filters is False and effective.saturation == 0.85 assert config.contrast == 1.5 # the stored configuration is not modified @@ -237,7 +255,8 @@ def test_effective_profile_can_be_forced_per_source() -> None: from app.core.config_models import EinkConfig photo = EinkConfig(profile="photo") - assert photo.effective("official") is photo + official = photo.effective("official") + assert official.profile == "official" and official.saturation == 1.2 assert EinkConfig().effective("photo").saturation == 0.85 diff --git a/tests/test_dither.py b/tests/test_dither.py index c260d92..c8df589 100644 --- a/tests/test_dither.py +++ b/tests/test_dither.py @@ -7,13 +7,21 @@ import pytest from PIL import Image +from app.processor import dither as dither_module from app.processor.dither import ( ATKINSON, + ATKINSON_CLASSIC, FLOYD_STEINBERG, + NUMBA_AVAILABLE, + STUCKI, DitherKernel, DitherTap, + _compiled, + _wavefront, + blue_noise_thresholds, dither, dither_image, + effective_algorithm, ) from app.processor.palette import PALETTE_ARRAY, PALETTE_RGB from tests.reference import fraimic_converter as ref @@ -50,6 +58,16 @@ def gradient_image(height: int, width: int) -> npt.NDArray[np.uint8]: return np.dstack([gx, gy, np.full_like(gx, 128)]).astype(np.uint8) +ALL_ALGORITHMS = [ + "atkinson", + "atkinson-classic", + "fs", + "floyd_steinberg", + "fs-serpentine", + "stucki", + "blue-noise", +] + CASES = [ pytest.param(random_image(23, 37, 1), id="random-37x23"), pytest.param(random_image(48, 64, 2), id="random-64x48"), @@ -80,7 +98,7 @@ def test_sequential_reference_agrees_with_official_atkinson() -> None: assert np.array_equal(sequential_reference(rgb, ATKINSON), expected) -@pytest.mark.parametrize("algorithm", ["atkinson", "floyd_steinberg"]) +@pytest.mark.parametrize("algorithm", ALL_ALGORITHMS) def test_output_range_and_dtype(algorithm: str) -> None: result = dither(random_image(40, 30, 11), algorithm) # type: ignore[arg-type] assert result.dtype == np.uint8 @@ -88,14 +106,14 @@ def test_output_range_and_dtype(algorithm: str) -> None: assert set(np.unique(result).tolist()) <= set(range(6)) -@pytest.mark.parametrize("algorithm", ["atkinson", "floyd_steinberg"]) +@pytest.mark.parametrize("algorithm", ALL_ALGORITHMS) @pytest.mark.parametrize("index", range(6)) def test_flat_palette_colors_stay_flat(algorithm: str, index: int) -> None: rgb = np.full((16, 24, 3), PALETTE_RGB[index], dtype=np.uint8) assert np.all(dither(rgb, algorithm) == index) # type: ignore[arg-type] -@pytest.mark.parametrize("algorithm", ["atkinson", "floyd_steinberg"]) +@pytest.mark.parametrize("algorithm", ALL_ALGORITHMS) @pytest.mark.parametrize("level", [64, 128, 192]) def test_flat_grey_preserves_average_color(algorithm: str, level: int) -> None: """Greys are rendered as color mixes (e.g. yellow + blue) whose average stays grey.""" @@ -117,10 +135,102 @@ def test_rejects_bad_shapes(shape: tuple[int, ...]) -> None: def test_kernel_validation() -> None: - with pytest.raises(ValueError, match="wavefront"): - DitherKernel("bad", (DitherTap(1, -2, 0.5),)) - with pytest.raises(ValueError, match="wavefront"): - DitherKernel("bad", (DitherTap(2, 0, 0.5),)) + for backwards in (DitherTap(0, -1, 0.5), DitherTap(0, 0, 0.5), DitherTap(-1, 0, 0.5)): + with pytest.raises(ValueError, match="causal"): + DitherKernel("bad", (backwards,)) + DitherKernel("wide", (DitherTap(1, -3, 0.5), DitherTap(2, 0, 0.5))) # any forward tap + + +def test_wavefront_skew_follows_the_widest_down_left_tap() -> None: + assert ATKINSON.skew == FLOYD_STEINBERG.skew == ATKINSON_CLASSIC.skew == 2 + assert STUCKI.skew == 3 + assert DitherKernel("right-only", (DitherTap(0, 1, 1.0),)).skew == 1 + + +@pytest.mark.skipif(not NUMBA_AVAILABLE, reason="needs numba") +@pytest.mark.parametrize( + "kernel", [FLOYD_STEINBERG, STUCKI, ATKINSON_CLASSIC], ids=lambda k: k.name +) +@pytest.mark.parametrize("rgb", CASES) +def test_compiled_loop_matches_the_wavefront( + kernel: DitherKernel, rgb: npt.NDArray[np.uint8] +) -> None: + assert np.array_equal(_compiled(rgb, kernel, serpentine=False), _wavefront(rgb, kernel)) + + +@pytest.mark.parametrize("kernel", [STUCKI, ATKINSON_CLASSIC], ids=lambda k: k.name) +@pytest.mark.parametrize("rgb", CASES) +def test_wide_kernels_match_the_sequential_loop( + kernel: DitherKernel, rgb: npt.NDArray[np.uint8] +) -> None: + """Only the float summation order of overlapping taps may differ (rare pixel flips).""" + expected = sequential_reference(rgb, kernel) + assert (_wavefront(rgb, kernel) == expected).mean() > 0.995 + + +@pytest.mark.skipif(not NUMBA_AVAILABLE, reason="needs numba") +def test_serpentine_differs_from_plain_fs_but_keeps_the_mean() -> None: + rgb = gradient_image(60, 80) + plain = dither(rgb, "fs") + serpentine = dither(rgb, "fs-serpentine") + assert not np.array_equal(plain, serpentine) + palette = np.array(PALETTE_RGB, dtype=np.float64) + assert np.allclose( + palette[plain].reshape(-1, 3).mean(axis=0), + palette[serpentine].reshape(-1, 3).mean(axis=0), + atol=6, + ) + # Row 0 scans left to right like FS; row 1 runs right to left. + assert np.array_equal(plain[0], serpentine[0]) + + +def test_fs_serpentine_falls_back_to_fs_without_numba(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(dither_module, "NUMBA_AVAILABLE", False) + rgb = random_image(30, 40, 12) + assert effective_algorithm("fs-serpentine") == "fs" + assert effective_algorithm("stucki") == "stucki" + assert np.array_equal(dither(rgb, "fs-serpentine"), dither(rgb, "fs")) + assert np.array_equal(dither(rgb, "stucki"), _wavefront(rgb, STUCKI)) + + +def test_auto_must_be_resolved_before_dithering() -> None: + with pytest.raises(ValueError, match="auto"): + dither(random_image(4, 4, 1), "auto") + + +def test_blue_noise_tile_is_a_permutation_with_even_density() -> None: + thresholds = blue_noise_thresholds() + assert thresholds.shape == (64, 64) + assert np.unique(thresholds).size == 64 * 64 + for level in (0.1, 0.5, 0.9): + mask = thresholds > level * 255 + blocks = mask.reshape(4, 16, 4, 16).mean(axis=(1, 3)) + assert np.all(np.abs(blocks - (1 - level)) < 0.08), level + + +def test_blue_noise_greys_are_black_and_white_only_and_tile_seamlessly() -> None: + result = dither(np.full((130, 150, 3), 128, dtype=np.uint8), "blue-noise") + assert set(np.unique(result).tolist()) == {0, 1} + assert 0.45 < (result == 1).mean() < 0.55 + assert np.array_equal(result[:64, :64], result[64:128, 64:128]) # tiled + + +def test_blue_noise_maps_cyan_and_magenta_to_panel_colors() -> None: + cyan = dither(np.full((8, 8, 3), (0, 255, 255), dtype=np.uint8), "blue-noise") + magenta = dither(np.full((8, 8, 3), (255, 0, 255), dtype=np.uint8), "blue-noise") + assert np.unique(cyan).size == 1 and np.unique(magenta).size == 1 + assert int(cyan[0, 0]) in range(6) and int(magenta[0, 0]) in range(6) + + +@pytest.mark.slow +@pytest.mark.parametrize("algorithm", ["fs-serpentine", "stucki", "blue-noise", "atkinson-classic"]) +@pytest.mark.parametrize(("width", "height", "budget_s"), [(1200, 1600, 5.0), (1440, 2560, 8.0)]) +def test_new_algorithms_stay_fast(algorithm: str, width: int, height: int, budget_s: float) -> None: + rgb = random_image(height, width, 43) + dither(rgb[:16, :16], algorithm) # type: ignore[arg-type] # compile outside the timing + started = time.perf_counter() + dither(rgb, algorithm) # type: ignore[arg-type] + assert time.perf_counter() - started < budget_s @pytest.mark.slow diff --git a/tests/test_enhance.py b/tests/test_enhance.py index d43afd2..4cd8d90 100644 --- a/tests/test_enhance.py +++ b/tests/test_enhance.py @@ -1,6 +1,7 @@ from __future__ import annotations import numpy as np +import pytest from PIL import Image from app.core.config_models import EinkConfig @@ -44,3 +45,61 @@ def test_sharpness_is_applied_when_not_neutral() -> None: base = EinkConfig(edge_filters=False) sharp = EinkConfig(edge_filters=False, sharpness=2.0) assert not np.array_equal(np.asarray(enhance(image, base)), np.asarray(enhance(image, sharp))) + + +# --- gamut-safe curves --------------------------------------------------------------------------- +def _curve(profile: str, pixels: np.ndarray) -> np.ndarray: + from app.core.config_models import EinkConfig as Eink + + image = Image.fromarray(pixels.astype(np.uint8)) + return np.asarray(enhance(image, Eink().resolved(profile))) # type: ignore[arg-type] + + +def test_natural_leaves_the_source_untouched() -> None: + pixels = np.random.default_rng(1).integers(0, 256, (20, 30, 3), dtype=np.uint8) + assert np.array_equal(_curve("natural", pixels), pixels) + + +@pytest.mark.parametrize("profile", ["soft", "vivid"]) +def test_curves_preserve_black_and_white(profile: str) -> None: + ends = np.array([[[0, 0, 0], [255, 255, 255]]], dtype=np.uint8) + assert _curve(profile, ends).tolist() == ends.tolist() + + +@pytest.mark.parametrize("profile", ["soft", "vivid"]) +def test_curves_are_monotonic_on_greys(profile: str) -> None: + ramp = np.arange(256, dtype=np.uint8) + out = _curve(profile, np.dstack([ramp[None, :]] * 3))[0, :, 0].astype(int) + assert np.all(np.diff(out) >= 0) + + +def test_soft_lifts_shadows_and_vivid_adds_contrast() -> None: + grey = lambda v: np.full((1, 1, 3), v, dtype=np.uint8) # noqa: E731 + assert _curve("soft", grey(30))[0, 0, 0] > 30 + assert _curve("soft", grey(250))[0, 0, 0] < 250 # restrained highlights + assert _curve("vivid", grey(60))[0, 0, 0] < 60 # S-curve: darker below the middle... + assert _curve("vivid", grey(190))[0, 0, 0] > 190 # ...lighter above it + + +@pytest.mark.parametrize("profile", ["soft", "vivid"]) +def test_curves_keep_hue_instead_of_clipping_channels(profile: str) -> None: + rng = np.random.default_rng(7) + pixels = rng.integers(0, 256, (60, 80, 3), dtype=np.uint8) + out = _curve(profile, pixels).astype(int) + src = pixels.astype(int) + distinct = ( + (src[..., 0] != src[..., 1]) & (src[..., 1] != src[..., 2]) & (src[..., 0] != src[..., 2]) + ) + order_in = np.argsort(src, axis=2)[distinct] + order_out = np.argsort(out, axis=2)[distinct] + assert (order_in == order_out).mean() > 0.98 # chroma ordering survives (allow rounding ties) + assert out.min() >= 0 and out.max() <= 255 + + +def test_vivid_saturates_a_muted_color_without_leaving_the_gamut() -> None: + muted = np.full((1, 1, 3), (150, 110, 100), dtype=np.uint8) + pure = np.full((1, 1, 3), (255, 0, 0), dtype=np.uint8) + out = _curve("vivid", muted)[0, 0].astype(int) + assert out.max() - out.min() > 150 - 100 + red = _curve("vivid", pure)[0, 0] + assert red[0] > 200 and red[1] < 20 and red[2] < 20 # still pure red (toned down, hue kept) diff --git a/tests/test_pipeline.py b/tests/test_pipeline.py index a0b45b7..59ad843 100644 --- a/tests/test_pipeline.py +++ b/tests/test_pipeline.py @@ -13,6 +13,8 @@ from tests.reference import fraimic_converter as ref RED, WHITE = 3, 1 +#: The official converter's look; the default settings choose per image (``auto``). +OFFICIAL_EINK = {"profile": "official", "dither": "atkinson"} def config(**sections: Any) -> RuntimeConfig: @@ -105,7 +107,10 @@ def test_contain_compose_equals_official_letterbox_pipeline() -> None: rng = np.random.default_rng(8) image = Image.fromarray(rng.integers(0, 256, (900, 1600, 3), dtype=np.uint8)) options = RenderOptions.from_config( - config(display={"default_fit": "contain", "contain_background": "black"}) + config( + display={"default_fit": "contain", "contain_background": "black"}, + eink=OFFICIAL_EINK, + ) ) panel = ref.Panel(1200, 1600) expected = ref.pad_to_frame( @@ -117,7 +122,9 @@ def test_contain_compose_equals_official_letterbox_pipeline() -> None: def test_smart_crop_compose_equals_official_crop_pipeline() -> None: rng = np.random.default_rng(9) image = Image.fromarray(rng.integers(0, 256, (900, 1600, 3), dtype=np.uint8)) - options = RenderOptions.from_config(config(display={"default_fit": "smart_crop"})) + options = RenderOptions.from_config( + config(display={"default_fit": "smart_crop"}, eink=OFFICIAL_EINK) + ) expected = ref.enhance(ref.scale_to_frame(image, "crop", ref.Panel(1200, 1600))) assert np.array_equal(np.asarray(compose(image, options)), np.asarray(expected)) @@ -171,6 +178,7 @@ def _official_rotate_image(image: Image.Image, background: tuple[int, int, int]) def _landscape_options(**eink: Any) -> RenderOptions: + eink = {**OFFICIAL_EINK, **eink} return RenderOptions.from_config( config( display={ From 868494393319f815e975429348d0a9201072cee6 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sun, 15 Nov 2026 17:27:30 +0100 Subject: [PATCH 68/86] feat: verify every .bin against the panel specification verify_bin() checks the compliance items that do not depend on the image: exact size (no header or footer), only the valid device-code nibbles {0x0,0x1,0x2,0x3,0x5,0x6}, and for the EL315 the 0x11 white padding in bytes [80:400] of every row of IC4 and IC8. encode_bin() runs it on every frame before returning. The pixel layouts of both panels were already covered by the byte-for-byte tests against the official converter and the specifications' worked examples. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- app/processor/packing.py | 47 +++++++++++++++++++++++++++++++++++++--- tests/test_packing.py | 40 +++++++++++++++++++++++++++++++++- 2 files changed, 83 insertions(+), 4 deletions(-) diff --git a/app/processor/packing.py b/app/processor/packing.py index 26d8d62..9272b54 100644 --- a/app/processor/packing.py +++ b/app/processor/packing.py @@ -114,6 +114,47 @@ def unpack_el315(data: UInt8Array) -> UInt8Array: return np.flipud(np.concatenate(halves, axis=0)) +#: Bytes whose two nibbles are both valid device codes (``0x11`` is the EL315 padding). +_VALID_BYTES: Final = np.zeros(256, dtype=bool) +for _high in DEVICE_CODES: + for _low in DEVICE_CODES: + _VALID_BYTES[(int(_high) << 4) | int(_low)] = True + +#: EL315 IC blocks whose rows end in padding, and where the padding starts in a row. +EL315_PADDED_BLOCKS: Final = (3, 7) # IC4 and IC8 +EL315_PADDING_START: Final = EL315_PADDED_PIXELS // 2 +EL315_ROW_BYTES: Final = EL315_BLOCK_PIXELS // 2 +PADDING_BYTE: Final = (WHITE_CODE << 4) | WHITE_CODE + + +def verify_bin(data: bytes, spec: PanelSpec) -> None: + """Check ``data`` against the panel's ``.bin`` compliance checklist. + + Covers the checks that can be made without knowing the image: the exact size (no header + or footer), only valid device-code nibbles ``{0x0,0x1,0x2,0x3,0x5,0x6}``, and, for the + EL315, the ``0x11`` white padding in every row of IC4 and IC8 (bytes ``[80:400]``). + The pixel layout itself is covered by the byte-for-byte tests against the official + converter and the specifications' worked examples. + + Raises: + BinFormatError: On the first violated rule. + """ + if len(data) != spec.bin_size: + raise BinFormatError(f"{spec.label} .bin must be {spec.bin_size} bytes, got {len(data)}") + raw = np.frombuffer(data, dtype=np.uint8) + if not bool(_VALID_BYTES[raw].all()): + raise BinFormatError("The .bin contains nibbles outside {0x0,0x1,0x2,0x3,0x5,0x6}") + if spec.key == "315": + blocks = raw.reshape(8, EL315_BLOCK_ROWS, EL315_ROW_BYTES) + for block in EL315_PADDED_BLOCKS: + padding = blocks[block, :, EL315_PADDING_START:] + if not bool((padding == PADDING_BYTE).all()): + raise BinFormatError( + f"IC{block + 1} rows must end with 0x11 padding (bytes " + f"[{EL315_PADDING_START}:{EL315_ROW_BYTES}])" + ) + + PACKERS: Final[dict[PanelModel, Callable[[UInt8Array], UInt8Array]]] = { "133": pack_el133uf1, "315": pack_el315, @@ -144,9 +185,9 @@ def encode_bin(indices: UInt8Array, spec: PanelSpec) -> bytes: raise BinFormatError("Palette indices must be in 0..5") codes = DEVICE_CODES[indices.astype(np.intp, copy=False)] packed = PACKERS[spec.key](codes) - if packed.size != spec.bin_size: - raise BinFormatError(f"Encoded {packed.size} bytes, expected exactly {spec.bin_size}") - return packed.tobytes() + data = packed.tobytes() + verify_bin(data, spec) + return data def decode_bin(data: bytes, spec: PanelSpec) -> UInt8Array: diff --git a/tests/test_packing.py b/tests/test_packing.py index f40d989..c91360d 100644 --- a/tests/test_packing.py +++ b/tests/test_packing.py @@ -5,7 +5,7 @@ import pytest from app.core.config_models import PANEL_SPECS -from app.processor.packing import BinFormatError, decode_bin, encode_bin +from app.processor.packing import BinFormatError, decode_bin, encode_bin, verify_bin from app.processor.palette import DEVICE_CODES from tests.reference import fraimic_converter as ref @@ -135,3 +135,41 @@ def test_decode_rejects_bad_data() -> None: decode_bin(b"\x00" * 10, SPEC_133) with pytest.raises(BinFormatError, match="nibbles"): decode_bin(bytes([0x44]) * 960_000, SPEC_133) + + +# --- compliance check ---------------------------------------------------------------------------- +@pytest.mark.parametrize("key", ["133", "315"]) +def test_verify_bin_accepts_an_encoded_frame(key: str) -> None: + spec = PANEL_SPECS[key] # type: ignore[index] + rng = np.random.default_rng(5) + indices = rng.integers(0, 6, (spec.height, spec.width), dtype=np.uint8) + verify_bin(encode_bin(indices, spec), spec) + + +@pytest.mark.parametrize("key", ["133", "315"]) +def test_verify_bin_rejects_a_wrong_size_or_header(key: str) -> None: + spec = PANEL_SPECS[key] # type: ignore[index] + good = encode_bin(np.zeros((spec.height, spec.width), dtype=np.uint8), spec) + for bad in (good[:-1], good + b"\x00", b"\x00\x00\x00\x00" + good): + with pytest.raises(BinFormatError, match="bytes"): + verify_bin(bad, spec) + + +@pytest.mark.parametrize("key", ["133", "315"]) +@pytest.mark.parametrize("bad_byte", [0x04, 0x40, 0x70, 0xF0, 0x0F]) +def test_verify_bin_rejects_codes_outside_the_palette(key: str, bad_byte: int) -> None: + spec = PANEL_SPECS[key] # type: ignore[index] + data = bytearray(encode_bin(np.zeros((spec.height, spec.width), dtype=np.uint8), spec)) + data[1234] = bad_byte + with pytest.raises(BinFormatError, match="nibbles"): + verify_bin(bytes(data), spec) + + +@pytest.mark.parametrize("block", [3, 7]) +def test_verify_bin_rejects_broken_el315_padding(block: int) -> None: + spec = PANEL_SPECS["315"] + data = bytearray(encode_bin(np.zeros((spec.height, spec.width), dtype=np.uint8), spec)) + # Row 5 of IC4/IC8: a valid nibble pair, but not the 0x11 padding the spec mandates. + data[block * 288_000 + 5 * 400 + 200] = 0x00 + with pytest.raises(BinFormatError, match=f"IC{block + 1}"): + verify_bin(bytes(data), spec) From a060afdeefd58000f5de8b2668018f8817bf3d53 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sun, 15 Nov 2026 17:27:30 +0100 Subject: [PATCH 69/86] docs: add the A/B script, prewarm numba and document the automatic look scripts/quality_ab.py renders a dark photo, a bright photo, a poster and an album cover with the previous look (official + atkinson) and with auto, side by side (composition and dithered simulation), with the decision reasons and render times. The Dockerfile compiles the numba kernels at build time into an image-local cache so the first render is fast on a Raspberry Pi. The README documents the automatic decision matrix, the profiles and dithering algorithms with their timings, and the numba fallback. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- CLAUDE.md | 2 +- Dockerfile | 7 ++ README.md | 84 +++++++++++++--- scripts/quality_ab.py | 223 ++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 300 insertions(+), 16 deletions(-) create mode 100644 scripts/quality_ab.py diff --git a/CLAUDE.md b/CLAUDE.md index ad10ea0..45e83f1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -33,7 +33,7 @@ Implement two providers initially: - `smart_crop`: Intelligent crop centered on face bounding boxes detected by Immich, fitted to target frame dimensions (`FRAME_WIDTH`, `FRAME_HEIGHT`, `ORIENTATION=landscape|portrait`). - `contain`: Full image display with adaptive padding or blurred background (ideal for movie/TV posters). - **eInk Optimization:** Configurable contrast, saturation, and sharpness adjustments. -- **Fraimic Binary Encoding:** Implement the exact `.bin` binary format and error-diffusion dithering (Atkinson by default, as in the official converter, or Floyd-Steinberg) with the official tuned color metric on the official Fraimic color palette, strictly following the reference documentation and official converter code located in `/fraimic-docs` (specifically `/fraimic-docs/fraimic_bin_converter`). +- **Fraimic Binary Encoding:** Implement the exact `.bin` binary format and error-diffusion dithering with the official tuned color metric: `eink.profile` / `eink.dither` default to `auto` (decided per image from its context and cheap statistics; explicit values always win), with `atkinson` kept byte-identical to the official converter, plus `atkinson-classic`, `fs`, `fs-serpentine`, `stucki` and `blue-noise` on the official Fraimic color palette, strictly following the reference documentation and official converter code located in `/fraimic-docs` (specifically `/fraimic-docs/fraimic_bin_converter`). - **Cache:** Save the latest processed image in `/data/cache/`: `current.jpg` (clean composition for the web UI and Home Assistant), `current_dithered.png` (exact 6-color preview), `current.bin` (for Fraimic) and `current.json` (metadata, written last); `base.*` keeps the last pushed non-ephemeral image (restored when an ephemeral one expires or is cancelled) and `preview.*` the latest render (`push_to_fraimic=false` only writes the preview). The deep-sleep upload queue lives in `/data/queue/` (`pending.bin` + `pending.json`); the last delivery is persisted in `/data/last_delivery.json`. ### 3. Fraimic Communication & Power Management (`clients/fraimic.py`) diff --git a/Dockerfile b/Dockerfile index bfade39..cd3646e 100644 --- a/Dockerfile +++ b/Dockerfile @@ -32,7 +32,14 @@ COPY README.md LICENSE ./ COPY app ./app RUN pip install --no-deps . +# numba compiles the dithering kernels on first use (seconds on a Raspberry Pi). Compile them +# at build time into an image-local cache so the first render is fast; the app user may +# refresh it, and DATA_DIR/.numba_cache is the fallback outside Docker. +ENV NUMBA_CACHE_DIR=/app/.numba_cache +RUN mkdir -p /app/.numba_cache && chown app:app /app/.numba_cache + USER app +RUN python -c "from app.processor.dither import warm_up; warm_up()" VOLUME ["/data"] EXPOSE 8000 diff --git a/README.md b/README.md index 350beb5..8d0af1e 100644 --- a/README.md +++ b/README.md @@ -28,21 +28,66 @@ takes precedence over built-in defaults. `POST /api/config/reset` removes saved ## eInk pipeline Images are fitted to the panel (`smart_crop` around faces, or `contain` on a blurred / -black / white background), enhanced (brightness 1.1, contrast 1.2, saturation 1.2, -edge-enhance, smooth, sharpen) and dithered onto the 6-color Spectra 6 palette with -the official tuned color metric. Dithering is vectorized along anti-diagonals: the -Atkinson output is byte-identical to the official Fraimic converter while running in -about 0.7 s (13.3") / 1.1 s (31.5") instead of ~40 s. Landscape mode rotates the image -into the panel's portrait buffer *before* dithering, like the official `--fit rotate`, -so its `.bin` is byte-identical too. HEIC/HEIF (iPhone) images decode natively. - -**Photos vs the official look.** The official settings (contrast and saturation +20%, -edge-enhance/sharpen chain) suit posters and graphics, but make dim indoor photos look -outlined, over-saturated and grainy on the panel. Set `eink.profile` to `photo` for a softer -result (no edge filters, saturation 0.85, sharpness 0.8, brightness and contrast 1.0; dithering -stays as configured). `official` (default) keeps the values of the `eink` fields, whose -defaults are the official converter's. Tested on a real 13.3" panel: lifting brightness, -white-balance correction and dither jitter did not improve on it. +black / white background), enhanced and dithered onto the 6-color Spectra 6 palette with +the official tuned color metric. Landscape mode rotates the image into the panel's portrait +buffer *before* dithering, like the official `--fit rotate`, so its `.bin` is +byte-identical too. HEIC/HEIF (iPhone) images decode natively. Every `.bin` is checked +against the panel specification before it is stored (exact size, only valid palette codes, +the `0x11` padding of the 31.5" IC4/IC8 blocks). + +**Automatic look (default).** Nobody should have to tune a profile or a dithering algorithm +per image: `eink.profile` and `eink.dither` default to `auto`, and the engine decides from +the kind of image (photo, movie poster, album cover, title card) and a few cheap statistics +of a 256 px thumbnail (a few milliseconds): + +| Image | Profile | Dithering | +| --- | --- | --- | +| Title card | `natural` | `atkinson-classic` | +| Graphic (few colors, large flat areas) | `official` | `atkinson-classic` | +| Album cover | `soft` | `atkinson-classic` (flat lettering must not smear) | +| Poster with bright highlights or strong contrast | `soft` (protects faces) | `fs-serpentine` | +| Flat or muted poster | `vivid` | `fs-serpentine` | +| Dark or low-contrast photo | `soft` | `fs-serpentine` | +| Photo with large smooth regions (sky, fog) | `photo` | `stucki` | +| Other photos | `photo` | `fs-serpentine` | + +An explicit value always wins and `auto` only fills in the rest. `GET /api/status` reports +what was used and why in `current_image.render` (`profile`, `dither`, `reasons`). + +| `eink.profile` | Look | +| --- | --- | +| `auto` | Chosen per image (above) | +| `official` | The official converter: the `eink` brightness / contrast / saturation / sharpness / `edge_filters` fields (defaults +10% / +20% / +20%, edge-enhance, smooth, sharpen) | +| `photo` | Softer preset tuned on a real panel: no edge filters, saturation 0.85, sharpness 0.8 | +| `soft` | Gamut-safe curve: lifted shadows, restrained highlights, no clipping | +| `vivid` | Gamut-safe curve: stronger contrast, richer color, gradual highlight roll-off | +| `natural` | No enhancement | + +`soft` and `vivid` work on luminance in floating point and compress chroma toward it only +where it would leave the RGB gamut (one scale for all channels, so hue is kept instead of +clipping individual channels); adapted from the MIT-licensed stillroom +converter (© Fraimic). + +| `eink.dither` | Algorithm | 13.3" | +| --- | --- | --- | +| `atkinson` | The official converter's 4-neighbour Atkinson, **byte-identical** to it | 0.7 s | +| `atkinson-classic` | Original 6-neighbour Atkinson (3/4 of the error): crisp edges, clean flats | 0.8 s | +| `fs` | Floyd-Steinberg | 0.7 s | +| `fs-serpentine` | Floyd-Steinberg with alternating scan direction: no directional "worm" patterns | 0.05 s | +| `stucki` | Wide 12-neighbour kernel: smoother skies and gradients | 0.06 s | +| `blue-noise` | Ordered blue-noise threshold (a bundled tileable tile): film-grain look, no diffusion | 0.03 s | + +Error diffusion is sequential, but the plain kernels run along anti-diagonals in vectorized +NumPy (about 0.7 s instead of ~40 s). Serpentine scanning cannot be vectorized that way, so +`fs-serpentine` and `stucki` run as [numba](https://numba.pydata.org)-compiled loops (x86 +timings; a Raspberry Pi is roughly 5-10x slower and still well under a second). The kernels +are compiled at Docker build time (`NUMBA_CACHE_DIR=/app/.numba_cache`; outside Docker the +cache goes to `DATA_DIR/.numba_cache`). If numba cannot be imported, `stucki` falls back to +the NumPy path and `fs-serpentine` to `fs`, with a warning. `floyd_steinberg` is still +accepted as an alias of `fs`. + +Compare the previous look with `auto` side by side on your own photos with +`python scripts/quality_ab.py` (see [Development](#development)). If a mat or bezel hides the panel edges, set `display.safe_margin_px` (default `0`): the picture is inset by that many pixels on every side and the margin is filled with @@ -569,6 +614,12 @@ ruff check . && ruff format --check . && mypy app && pytest DATA_DIR=./data python -m app # serve on http://localhost:8000 ``` +`python scripts/quality_ab.py` renders a dark photo, a bright photo, a poster and an album +cover with the previous look (official + atkinson) and with `auto`, side by side (composition +and dithered), into `preview_gallery/quality-ab/`; `--dark`/`--bright` take your own photos, +otherwise a CLIP search on Immich is used. `python scripts/preview_gallery.py` renders posters +and covers on all four frame layouts. + `python scripts/template_samples.py` renders 8 movie posters and 8 album covers with the templates (composition and dithered panel simulation, plus contact sheets) into `data/template-samples/`, using the real TMDB / Deezer / MusicBrainz lookups but never @@ -581,6 +632,9 @@ The palette, color metric, Atkinson kernel and `.bin` layouts follow the officia builds on Toon-nooT's [PhotoPainter Spectra 6 converter](https://github.com/Toon-nooT/PhotoPainter-E-Ink-Spectra-6-image-converter). +The `soft` / `vivid` curves and the dithering kernels follow the MIT-licensed +stillroom converter (© 2026 Fraimic). + Templates use the [Inter](https://github.com/rsms/inter) typeface by Rasmus Andersson, bundled under the SIL Open Font License 1.1 (`app/assets/fonts/OFL.txt`). diff --git a/scripts/quality_ab.py b/scripts/quality_ab.py new file mode 100644 index 0000000..7a11394 --- /dev/null +++ b/scripts/quality_ab.py @@ -0,0 +1,223 @@ +"""Visual A/B test: the previous look (official + atkinson) against ``auto``. + +For a dark photo, a bright photo, a movie poster and an album cover it renders both settings +for the same frame and writes side-by-side images (left = A, right = B): the composition +(``_composed.jpg``) and the exact Spectra 6 simulation (``_dithered.png``), with +what ``auto`` chose and why, and the render times. Nothing is sent to the frame. + +Sources: + +* photos: ``--dark PATH`` / ``--bright PATH``, else a CLIP search on the configured Immich + (``IMMICH_URL`` / ``IMMICH_API_KEY`` in ``.env``), else the case is skipped; +* poster: TMDB (``TMDB_API_KEY``), falling back to a title card; +* album cover: Deezer, then MusicBrainz / Cover Art Archive. + +Usage:: + + python scripts/quality_ab.py # preview_gallery/quality-ab + python scripts/quality_ab.py --dark night.jpg --bright beach.jpg --panel 315 +""" + +from __future__ import annotations + +import argparse +import asyncio +import io +import tempfile +import time +from dataclasses import dataclass, replace +from pathlib import Path + +from PIL import Image, ImageDraw +from template_samples import build_store + +from app.clients.http_images import ImageFetcher +from app.core.config_store import ConfigStore +from app.core.history_store import HistoryStore +from app.core.security import URLPolicy +from app.core.settings import EnvSettings +from app.processor.fit import FocusRegion +from app.processor.pipeline import ( + RenderOptions, + RenderResult, + decode_image, + render, + render_layout, +) +from app.processor.templates import AlbumLayout, Layout, PosterLayout, TitleCardLayout +from app.processor.typography import load_font +from app.providers.immich import ( + ImmichDisplayRequest, + ImmichGateway, + ImmichProvider, + PeopleDirectory, +) +from app.providers.music import ArtworkResolver +from app.providers.tmdb import PosterResolver, TmdbProvider, TmdbRequest + +CAPTION_HEIGHT = 96 +GAP = 24 +DARK_QUERY = "night, dark scene, low light" +BRIGHT_QUERY = "bright sunny beach, snow, white sky" + + +@dataclass(frozen=True) +class Case: + """One image to compare.""" + + name: str + image: Image.Image | None + layout: Layout | None = None + regions: tuple[FocusRegion, ...] = () + + +def run(case: Case, options: RenderOptions) -> tuple[RenderResult, float]: + """Render ``case`` and return the result with its render time.""" + started = time.perf_counter() + if case.layout is not None: + result = render_layout(case.image, case.layout, options) + elif case.image is not None: + result = render(case.image, options, case.regions) + else: # pragma: no cover - cases always have an image or a layout + raise ValueError(f"{case.name}: nothing to render") + return result, time.perf_counter() - started + + +def side_by_side( + left: Image.Image, right: Image.Image, captions: tuple[list[str], list[str]] +) -> Image.Image: + """Two same-size images next to each other, each with a caption block underneath.""" + width, height = left.size + sheet = Image.new("RGB", (2 * width + GAP, height + CAPTION_HEIGHT), (245, 245, 245)) + draw = ImageDraw.Draw(sheet) + font = load_font("regular", 22) + for column, (image, lines) in enumerate(zip((left, right), captions, strict=True)): + x = column * (width + GAP) + sheet.paste(image, (x, 0)) + for row, line in enumerate(lines[:3]): + draw.text((x + 8, height + 8 + row * 28), line, font=font, fill=(20, 20, 20)) + return sheet + + +async def immich_photo( + store: ConfigStore, fetcher_policy: URLPolicy, query: str, max_bytes: int, tmp: Path +) -> tuple[Image.Image, tuple[FocusRegion, ...]] | None: + """A photo found by a CLIP search on the configured Immich, or ``None``.""" + if not store.config.immich.accounts: + return None + gateway = ImmichGateway(store, fetcher_policy) + history = HistoryStore(tmp / "history.json") + history.load() + provider = ImmichProvider( + store, gateway, PeopleDirectory(store, gateway), history, max_bytes=max_bytes + ) + request = ImmichDisplayRequest.model_validate( + { + "mode": "search", + "clip_queries": [query], + "ignore_history": True, + "skip_quality_gate": True, + "push_to_fraimic": False, + } + ) + try: + asset = await provider.fetch(request) + except Exception as exc: # network, no match...: the case is simply skipped + print(f"Immich search {query!r} failed: {exc}") + return None + return decode_image(asset.data), asset.regions + + +async def load_cases(args: argparse.Namespace, store: ConfigStore, tmp: Path) -> list[Case]: + """Build the four cases from files, Immich, TMDB and Deezer.""" + env = EnvSettings() + policy = URLPolicy() + fetcher = ImageFetcher(policy, env.max_upload_bytes) + cases: list[Case] = [] + try: + for name, path, query in ( + ("dark photo", args.dark, DARK_QUERY), + ("bright photo", args.bright, BRIGHT_QUERY), + ): + if path is not None: + cases.append(Case(name, decode_image(path.read_bytes()))) + continue + found = await immich_photo(store, policy, query, env.max_upload_bytes, tmp) + if found is None: + print(f"{name}: no file given and no Immich photo found; skipped") + continue + cases.append(Case(name, found[0], regions=found[1])) + + posters = PosterResolver(TmdbProvider(store, fetcher), fetcher, store, tmp) + asset = await posters.resolve(TmdbRequest(query=args.poster, media_type="movie")) + poster_image = decode_image(asset.data) if asset.data else None + layout: Layout = asset.layout or PosterLayout() + cases.append(Case(f"poster: {args.poster}", poster_image, layout)) + + covers = ArtworkResolver(store, fetcher) + try: + artwork = await covers.find(title=args.track, artist=args.artist, album=args.album) + finally: + await covers.aclose() + if artwork is not None: + album: Layout = AlbumLayout(title=args.track, artist=args.artist, album=args.album) + cases.append(Case(f"album: {args.album}", decode_image(artwork.data), album)) + else: + card = TitleCardLayout(title=args.track, subtitle=args.artist, caption=args.album) + cases.append(Case("album (title card)", None, card)) + finally: + await fetcher.aclose() + return cases + + +async def main(args: argparse.Namespace) -> None: + """Render every case with the previous settings (A) and with ``auto`` (B).""" + args.out.mkdir(parents=True, exist_ok=True) + store = build_store(args.panel, args.orientation) + config = store.config + tmp = Path(tempfile.mkdtemp()) + cases = await load_cases(args, store, tmp) + + auto_eink = config.eink.model_copy(update={"profile": "auto", "dither": "auto"}) + official_eink = config.eink.model_copy(update={"profile": "official", "dither": "atkinson"}) + for case in cases: + base = RenderOptions.from_config(config, fit="smart_crop") + a_result, a_time = run(case, replace(base, eink=official_eink)) + b_result, b_time = run(case, replace(base, eink=auto_eink)) + decision = b_result.decision + chosen = f"{decision.profile} + {decision.dither}" if decision else "?" + reasons = decision.reasons if decision else [] + captions = ( + ["A: official + atkinson (previous default)", f"render {a_time:.2f} s"], + [f"B: auto -> {chosen}", f"render {b_time:.2f} s", *(r[:70] for r in reasons)], + ) + slug = "".join(c if c.isalnum() else "_" for c in case.name.lower()).strip("_") + side_by_side(a_result.composed, b_result.composed, captions).save( + args.out / f"{slug}_composed.jpg", quality=92 + ) + a_dither = Image.open(io.BytesIO(a_result.dithered_png())).convert("RGB") + b_dither = Image.open(io.BytesIO(b_result.dithered_png())).convert("RGB") + side_by_side(a_dither, b_dither, captions).save(args.out / f"{slug}_dithered.png") + print(f"{case.name}: A {a_time:.2f}s | B {b_time:.2f}s | {chosen}") + for reason in reasons: + print(f" {reason}") + print(f"-> {args.out}") + + +def parse_args() -> argparse.Namespace: + """Command-line options.""" + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--out", type=Path, default=Path("preview_gallery/quality-ab")) + parser.add_argument("--panel", choices=["133", "315"], default=None) + parser.add_argument("--orientation", choices=["portrait", "landscape"], default=None) + parser.add_argument("--dark", type=Path, default=None, help="a dark photo (default: Immich)") + parser.add_argument("--bright", type=Path, default=None, help="a bright photo (Immich)") + parser.add_argument("--poster", default="Intouchables", help="movie title for TMDB") + parser.add_argument("--track", default="So What") + parser.add_argument("--artist", default="Miles Davis") + parser.add_argument("--album", default="Kind of Blue") + return parser.parse_args() + + +if __name__ == "__main__": + asyncio.run(main(parse_args())) From 91107f19047b507d18c02dc96bd9c8c7518cf275 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sun, 15 Nov 2026 17:40:29 +0100 Subject: [PATCH 70/86] fix: tune the automatic profile rules after the A/B review - Posters with bright highlights or strong contrast now use the photo profile instead of soft: soft lifted the blacks too much (grey-brown speckle, dull hoodie and title). Flat or muted posters keep vivid. - Bright photos without blacks (mean luma >= 150, under 2% black: snow, beach, fog) now use vivid, which keeps the whites and the cloud texture; measured on a real snow photo, photo, soft and natural all rendered it flat grey. - "Graphic" no longer applies to photos: a night shot with a big black sky (3 dominant colors, 78% flat) was read as a drawing. Title cards are always graphic, album covers need very few colors or large flat areas, and posters need very few colors (dark backdrops are common). Added the black_share statistic. - Tests that check geometry pin profile official instead of relying on the default. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- README.md | 11 ++++-- app/processor/auto.py | 82 +++++++++++++++++++++++++++++------------- tests/test_auto.py | 35 +++++++++++++++--- tests/test_pipeline.py | 1 + 4 files changed, 97 insertions(+), 32 deletions(-) diff --git a/README.md b/README.md index 8d0af1e..588dd7e 100644 --- a/README.md +++ b/README.md @@ -43,14 +43,19 @@ of a 256 px thumbnail (a few milliseconds): | Image | Profile | Dithering | | --- | --- | --- | | Title card | `natural` | `atkinson-classic` | -| Graphic (few colors, large flat areas) | `official` | `atkinson-classic` | +| Graphic: an album cover with very few colors or large flat areas, a poster with very few colors | `official` | `atkinson-classic` | | Album cover | `soft` | `atkinson-classic` (flat lettering must not smear) | -| Poster with bright highlights or strong contrast | `soft` (protects faces) | `fs-serpentine` | +| Poster with bright highlights or strong contrast | `photo` (deep blacks, rich colors, natural skin) | `fs-serpentine` | | Flat or muted poster | `vivid` | `fs-serpentine` | -| Dark or low-contrast photo | `soft` | `fs-serpentine` | +| Dark photo | `soft` (lifted shadows) | `fs-serpentine` | +| Bright photo without blacks (snow, beach, fog) | `vivid` (keeps the whites) | `fs-serpentine` | +| Low-contrast photo | `soft` | `fs-serpentine` | | Photo with large smooth regions (sky, fog) | `photo` | `stucki` | | Other photos | `photo` | `fs-serpentine` | +A photo is never treated as a graphic, however flat its background: a night shot with a big +black sky or a snowfield is still a photograph. + An explicit value always wins and `auto` only fills in the rest. `GET /api/status` reports what was used and why in `current_image.render` (`profile`, `dither`, `reasons`). diff --git a/app/processor/auto.py b/app/processor/auto.py index 9b1a345..ad4b502 100644 --- a/app/processor/auto.py +++ b/app/processor/auto.py @@ -8,13 +8,19 @@ Profile (tone and chroma curve):: title card ............................ natural (flat colors stay exactly as drawn) - graphic (few colors, large flat areas) official (the official converter's look) + graphic ............................... official (the official converter's look) album cover (photographic) ............ soft (lifted shadows, restrained highlights) - poster, bright highlights / contrasty . soft (protects faces and highlights) + poster, contrasty / bright highlights . photo (deep blacks, rich colors, no burnt skin) poster, flat or muted ................. vivid (richer colors) - photo, dark or low contrast ........... soft + photo, dark ........................... soft (lifted shadows) + photo, bright (snow, beach, fog) ...... vivid (keeps the bright whites) + photo, low contrast ................... soft other photos .......................... photo (the profile tuned on a real panel) +"Graphic" depends on what the image is: title cards always; album covers with very few +colors or large flat areas; posters with very few colors. A photo is never graphic: a night +shot with a big black sky or a snowfield is still a photograph. + Dithering:: title card, graphic, album cover ..... atkinson-classic (crisp edges, clean flats; covers @@ -49,15 +55,22 @@ SMOOTH_BLOCK_STD: Final = 4.0 #: Share of smooth blocks from which a photo counts as "mostly smooth" (sky, gradient, fog). SMOOTH_PHOTO_SHARE: Final = 0.55 -#: Graphics: this few colors cover 90% of the pixels, or one color covers this share (%). +#: Graphic album covers: this few colors cover 90% of the pixels, or one color covers this +#: share (%). Posters often have a big dark background, so only the color count counts. GRAPHIC_MAX_COLORS: Final = 12 GRAPHIC_FLAT_SHARE: Final = 45.0 +GRAPHIC_POSTER_MAX_COLORS: Final = 24 #: Dark photos (mean luma) and flat-lit ones (luma standard deviation). DARK_LUMA_MEAN: Final = 85.0 LOW_CONTRAST_STD: Final = 38.0 -#: Posters with this share (%) of near-white pixels, or this much contrast, keep their -#: highlights (soft) instead of being pushed (vivid). +#: Bright photos (snow, beach, fog): a high mean and almost no black. They keep their whites +#: with ``vivid`` instead of turning grey. +HIGH_KEY_LUMA_MEAN: Final = 150.0 +HIGH_KEY_MAX_BLACK_SHARE: Final = 2.0 +#: Posters with this share (%) of near-white pixels, or this much contrast, are "contrasty": +#: they keep deep blacks and natural skin tones (photo) instead of being pushed (vivid). HIGHLIGHT_LUMA: Final = 235.0 +BLACK_LUMA: Final = 20.0 POSTER_HIGHLIGHT_SHARE: Final = 3.0 POSTER_HIGH_CONTRAST_STD: Final = 60.0 @@ -73,21 +86,36 @@ class ContentStats: dominant_colors: int # number of 5-bit colors covering 90% of the pixels detail: float # mean absolute luma gradient (0..255): high = textured smooth_share: float # share (0..1) of 8x8 blocks that are nearly flat + black_share: float = 0.0 # % of pixels with luma <= BLACK_LUMA + + def is_graphic(self, context: ContentContext) -> bool: + """A drawing rather than a photograph (logo, illustration, typographic cover). + + Photos are never graphic, however flat their background: a night shot is 24-78% + black and a snowfield is almost white, yet both are photographs. + """ + if context == "title_card": + return True + if context == "album": + return ( + self.dominant_colors <= GRAPHIC_MAX_COLORS or self.flat_share >= GRAPHIC_FLAT_SHARE + ) + if context == "poster": + return self.dominant_colors <= GRAPHIC_POSTER_MAX_COLORS + return False + + def is_smooth(self, context: ContentContext) -> bool: + """A photo with large smooth regions (sky, fog, studio backdrop).""" + return ( + context == "photo" + and not self.is_graphic(context) + and self.smooth_share >= SMOOTH_PHOTO_SHARE + ) @property - def graphic(self) -> bool: - """Few colors or large flat areas: a logo, an illustration, a typographic cover.""" - return self.dominant_colors <= GRAPHIC_MAX_COLORS or self.flat_share >= GRAPHIC_FLAT_SHARE - - @property - def smooth(self) -> bool: - """Mostly smooth regions (skies, fog, studio backdrops) and not a graphic.""" - return not self.graphic and self.smooth_share >= SMOOTH_PHOTO_SHARE - - @property - def dark(self) -> bool: - """Dark or low-contrast: shadows would clog and highlights are absent.""" - return self.luma_mean < DARK_LUMA_MEAN or self.luma_std < LOW_CONTRAST_STD + def high_key(self) -> bool: + """Bright and without blacks (snow, beach, fog).""" + return self.luma_mean >= HIGH_KEY_LUMA_MEAN and self.black_share < HIGH_KEY_MAX_BLACK_SHARE class RenderDecision(BaseModel): @@ -135,6 +163,7 @@ def measure_content(image: Image.Image) -> ContentStats: luma_mean=base.luma_mean, luma_std=base.luma_std, highlight_share=float((luma >= HIGHLIGHT_LUMA).mean() * 100), + black_share=float((luma <= BLACK_LUMA).mean() * 100), flat_share=base.flat_share, dominant_colors=int(np.searchsorted(covered, 0.9) + 1), detail=detail, @@ -148,7 +177,7 @@ def decide_profile( """The tone and chroma profile for an image (``stats`` is ``None`` without artwork).""" if context == "title_card" or stats is None: return "natural", "title card: flat colors stay as drawn" - if stats.graphic: + if stats.is_graphic(context): return "official", ( f"graphic ({stats.dominant_colors} dominant colors, {stats.flat_share:.0f}% flat)" ) @@ -159,13 +188,18 @@ def decide_profile( stats.highlight_share >= POSTER_HIGHLIGHT_SHARE or stats.luma_std >= POSTER_HIGH_CONTRAST_STD ): - return "soft", ( + return "photo", ( f"contrasty poster ({stats.highlight_share:.1f}% highlights, " - f"contrast {stats.luma_std:.0f}): protect faces and highlights" + f"contrast {stats.luma_std:.0f}): deep blacks, rich colors, natural skin" ) return "vivid", f"flat or muted poster (contrast {stats.luma_std:.0f}): richer colors" if stats.luma_mean < DARK_LUMA_MEAN: return "soft", f"dark photo (mean luma {stats.luma_mean:.0f}): lift shadows" + if stats.high_key: + return "vivid", ( + f"bright photo (mean luma {stats.luma_mean:.0f}, {stats.black_share:.1f}% black): " + "keeps the whites" + ) if stats.luma_std < LOW_CONTRAST_STD: return "soft", ( f"low-contrast photo (contrast {stats.luma_std:.0f}): gentle tones keep the detail" @@ -179,11 +213,11 @@ def decide_dither( """The dithering algorithm for an image.""" if context == "title_card" or stats is None: return "atkinson-classic", "title card: crisp text edges and clean flats" - if stats.graphic: + if stats.is_graphic(context): return "atkinson-classic", "graphic: crisp edges and clean flats" if context == "album": return "atkinson-classic", "album cover: lettering stays crisp, no error smearing" - if context == "photo" and stats.smooth: + if stats.is_smooth(context): return "stucki", ( f"mostly smooth ({stats.smooth_share * 100:.0f}% flat blocks): smooth gradients" ) diff --git a/tests/test_auto.py b/tests/test_auto.py index 20ca689..ab9746d 100644 --- a/tests/test_auto.py +++ b/tests/test_auto.py @@ -28,6 +28,7 @@ def stats(**overrides: Any) -> ContentStats: "luma_mean": 120.0, "luma_std": 55.0, "highlight_share": 0.5, + "black_share": 1.0, "flat_share": 5.0, "dominant_colors": 300, "detail": 12.0, @@ -45,7 +46,7 @@ def photo(seed: int = 0, size: tuple[int, int] = (240, 320)) -> Image.Image: def test_measure_content_tells_noise_from_gradients_and_graphics() -> None: noisy = measure_content(photo()) assert noisy.detail > 25 and noisy.smooth_share == 0.0 - assert not noisy.graphic and not noisy.smooth + assert not noisy.is_graphic("photo") and not noisy.is_smooth("photo") ramp = np.tile(np.linspace(40, 200, 320, dtype=np.float32), (240, 1)) sky = measure_content(Image.fromarray(np.dstack([ramp, ramp, ramp + 20]).astype(np.uint8))) @@ -54,7 +55,8 @@ def test_measure_content_tells_noise_from_gradients_and_graphics() -> None: logo = Image.new("RGB", (300, 300), (255, 255, 255)) logo.paste((200, 20, 20), (100, 100, 200, 200)) flat = measure_content(logo) - assert flat.graphic and flat.dominant_colors <= 3 and flat.flat_share > 60 + assert flat.is_graphic("album") and flat.dominant_colors <= 3 and flat.flat_share > 60 + assert not flat.is_graphic("photo") # a photo is never graphic, whatever its colors def test_measure_content_handles_tiny_images() -> None: @@ -69,11 +71,15 @@ def test_measure_content_handles_tiny_images() -> None: ("album", {"dominant_colors": 6}, "official"), # graphic cover ("album", {"flat_share": 60.0}, "official"), ("album", {}, "soft"), # photographic cover - ("poster", {"highlight_share": 6.0}, "soft"), # bright faces - ("poster", {"luma_std": 70.0}, "soft"), # contrasty + ("poster", {"highlight_share": 6.0}, "photo"), # bright faces: deep blacks, rich colors + ("poster", {"luma_std": 70.0}, "photo"), # contrasty ("poster", {"luma_std": 40.0, "highlight_share": 0.5}, "vivid"), # flat, muted + ("poster", {"dominant_colors": 13}, "official"), # flat-color graphic poster + ("poster", {"flat_share": 60.0, "luma_std": 40.0}, "vivid"), # dark backdrop only ("photo", {"luma_mean": 60.0}, "soft"), # dark ("photo", {"luma_std": 30.0}, "soft"), # low contrast + ("photo", {"luma_mean": 178.0, "luma_std": 34.0, "black_share": 0.0}, "vivid"), # snow + ("photo", {"luma_mean": 170.0, "black_share": 6.0}, "photo"), # bright but has blacks ("photo", {}, "photo"), ], ) @@ -85,6 +91,24 @@ def test_a_title_card_or_missing_artwork_is_natural() -> None: assert decide_profile("poster", None)[0] == "natural" +def test_a_dark_photo_with_a_big_flat_background_is_not_graphic() -> None: + """Real case: a night photo (3 dominant colors, 78% flat black) was read as a drawing.""" + night = stats(dominant_colors=3, flat_share=78.0, luma_mean=20.0, black_share=78.0) + assert not night.is_graphic("photo") + profile, reason = decide_profile("photo", night) + assert profile == "soft" and "dark photo" in reason + assert decide_dither("photo", night)[0] != "atkinson-classic" + # ...while the same numbers on an album cover are a graphic. + assert decide_profile("album", night)[0] == "official" + + +def test_a_bright_snow_photo_keeps_its_whites() -> None: + snow = stats(luma_mean=178.0, luma_std=34.0, black_share=0.0, highlight_share=0.0) + profile, reason = decide_profile("photo", snow) + assert profile == "vivid" and "bright photo" in reason + assert decide_profile("photo", stats(luma_mean=60.0, black_share=0.0))[0] == "soft" # dark wins + + # --- dither ---------------------------------------------------------------------------------- @pytest.mark.parametrize( ("context", "overrides", "expected"), @@ -92,6 +116,7 @@ def test_a_title_card_or_missing_artwork_is_natural() -> None: ("title_card", {}, "atkinson-classic"), ("album", {"dominant_colors": 5}, "atkinson-classic"), ("poster", {"dominant_colors": 8}, "atkinson-classic"), # flat graphic poster + ("photo", {"dominant_colors": 3, "flat_share": 78.0}, SERPENTINE), # night photo ("photo", {"smooth_share": 0.7}, "stucki"), ("photo", {}, SERPENTINE), ("poster", {"smooth_share": 0.9}, SERPENTINE), # posters keep their detail @@ -112,7 +137,7 @@ def test_serpentine_falls_back_to_fs_without_numba(monkeypatch: pytest.MonkeyPat # --- resolve --------------------------------------------------------------------------------- def test_auto_settings_are_filled_in_and_explained() -> None: concrete, decision = resolve(EinkConfig(), "poster", stats(highlight_share=8.0)) - assert (concrete.profile, concrete.dither) == ("soft", SERPENTINE) + assert (concrete.profile, concrete.dither) == ("photo", SERPENTINE) assert decision.automatic and decision.context == "poster" assert len(decision.reasons) == 2 and "contrasty poster" in decision.reasons[0] assert (concrete.brightness, concrete.contrast, concrete.edge_filters) == (1.0, 1.0, False) diff --git a/tests/test_pipeline.py b/tests/test_pipeline.py index 59ad843..406d6ff 100644 --- a/tests/test_pipeline.py +++ b/tests/test_pipeline.py @@ -28,6 +28,7 @@ def neutral_eink() -> dict[str, Any]: "contrast": 1.0, "saturation": 1.0, "edge_filters": False, + "profile": "official", # not "auto": these tests check geometry, not the look "dither": "floyd_steinberg", } From e212e89b7ef559942330a87220761cbc2ffd8729 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sun, 15 Nov 2026 17:51:45 +0100 Subject: [PATCH 71/86] fix: prefer the studio album over a single with the same title on MusicBrainz A MusicBrainz release-group search for the album "Thriller" by Michael Jackson returns two groups with the same title and score 100: a 12-inch Single (listed first) and the Album. The first one was taken, so the yellow maxi-single cover was shown instead of the famous album cover. Release groups are now ranked by title match (an edition suffix counts), then studio album before single, EP or compilation, then MusicBrainz's own order. Found while testing on a real frame; Deezer had no result for this artist, so MusicBrainz was the only source. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- app/providers/music/artwork.py | 27 +++++++++--- tests/test_music_artwork.py | 78 ++++++++++++++++++++++++++++++++++ 2 files changed, 99 insertions(+), 6 deletions(-) diff --git a/app/providers/music/artwork.py b/app/providers/music/artwork.py index 57a6690..4c9f372 100644 --- a/app/providers/music/artwork.py +++ b/app/providers/music/artwork.py @@ -393,7 +393,7 @@ async def _musicbrainz( payload = await self._musicbrainz_get( f"{MUSICBRAINZ_API}/release-group/", {"query": query, "fmt": "json", "limit": 5} ) - group = self._pick_release_group(payload.get("release-groups"), artist) + group = self._pick_release_group(payload.get("release-groups"), artist, album) else: query = f"recording:{lucene_quote(title)} AND artist:{lucene_quote(artist)}" payload = await self._musicbrainz_get( @@ -431,17 +431,32 @@ def _credited(item: dict[str, Any], artist: str) -> bool: return any(_artist_matches(artist, name) for name in names) @classmethod - def _pick_release_group(cls, groups: object, artist: str) -> tuple[str, str | None] | None: + def _pick_release_group( + cls, groups: object, artist: str, album: str + ) -> tuple[str, str | None] | None: + """The best release group for ``album`` by ``artist``. + + Several groups often share the title and the top score ("Thriller" is both the + 1982 album and a 12-inch single): the requested title first (an edition suffix + counts), then the studio album before singles, EPs and compilations, then + MusicBrainz's own order. + """ if not isinstance(groups, list): return None - for group in groups: + candidates: list[tuple[int, int, int, dict[str, Any]]] = [] + for order, group in enumerate(groups): if not isinstance(group, dict) or not isinstance(group.get("id"), str): continue if int(group.get("score") or 0) < MIN_MUSICBRAINZ_SCORE: continue - if cls._credited(group, artist): - return group["id"], group.get("title") - return None + if not cls._credited(group, artist): + continue + title_level = title_match_level(album, group.get("title")) + candidates.append((title_level, cls._release_group_rank(group), order, group)) + if not candidates: + return None + best = min(candidates, key=lambda candidate: candidate[:3])[3] + return best["id"], best.get("title") @staticmethod def _release_group_rank(group: dict[str, Any]) -> int: diff --git a/tests/test_music_artwork.py b/tests/test_music_artwork.py index 7cf7797..67dd539 100644 --- a/tests/test_music_artwork.py +++ b/tests/test_music_artwork.py @@ -502,3 +502,81 @@ async def test_find_falls_back_to_the_standard_cover_url(setup: Setup) -> None: respx.get(DZ_XL).respond(content=png_bytes()) artwork = await setup.resolver.find(title="s", artist="A", album="B", min_side=1181) assert artwork is not None and artwork.data == png_bytes() + + +@respx.mock +async def test_musicbrainz_prefers_the_album_over_a_single_with_the_same_title( + setup: Setup, +) -> None: + """Real case: "Thriller" by Michael Jackson is a Single (listed first) and the Album.""" + respx.get(f"{DEEZER}/search/album").respond(json={"data": []}) + respx.get(f"{DEEZER}/search").respond(json={"data": []}) + credit = [{"name": "Michael Jackson"}] + respx.get(f"{MB}/release-group/").respond( + json={ + "release-groups": [ + { + "id": "single", + "score": 100, + "title": "Thriller", + "primary-type": "Single", + "artist-credit": credit, + }, + { + "id": "album", + "score": 100, + "title": "Thriller", + "primary-type": "Album", + "artist-credit": credit, + }, + { + "id": "demos", + "score": 87, + "title": "The Thriller Demos", + "primary-type": "Album", + "secondary-types": ["Demo"], + "artist-credit": credit, + }, + ] + } + ) + match = await setup.resolver.lookup( + title="Thriller", artist="Michael Jackson", album="Thriller" + ) + assert match is not None and match.url.endswith("/release-group/album/front-1200") + + +@respx.mock +async def test_musicbrainz_title_beats_type_and_order_breaks_ties(setup: Setup) -> None: + respx.get(f"{DEEZER}/search/album").respond(json={"data": []}) + respx.get(f"{DEEZER}/search").respond(json={"data": []}) + credit = [{"name": "Band"}] + respx.get(f"{MB}/release-group/").respond( + json={ + "release-groups": [ + { + "id": "greatest", + "score": 100, + "title": "Greatest Hits", + "primary-type": "Album", + "artist-credit": credit, + }, + { + "id": "first", + "score": 95, + "title": "Wanted", + "primary-type": "Single", + "artist-credit": credit, + }, + { + "id": "second", + "score": 95, + "title": "Wanted", + "primary-type": "Single", + "artist-credit": credit, + }, + ] + } + ) + match = await setup.resolver.lookup(title="x", artist="Band", album="Wanted") + assert match is not None and "/first/" in match.url # exact title wins, then MB order From ef22fa6afbe4b55d6af8c4f3238f0b218bad53cd Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sun, 15 Nov 2026 18:18:19 +0100 Subject: [PATCH 72/86] feat: add an admin login, session cookies and API key management ADMIN_PASSWORD enables a web UI login for the user "admin": a signed HttpOnly, SameSite=Strict session cookie (Secure behind HTTPS, scoped to ROOT_PATH, SESSION_TTL_HOURS long), with per-client exponential backoff after failed attempts. The signing key derives from SESSION_SECRET (or a generated one) and the password, so changing the password signs everyone out. Without ADMIN_PASSWORD, the login accepts the API key. With ADMIN_PASSWORD set, every route except /api/health, the login and the public image endpoints requires a session or the API key, and browsers asking for a page are redirected to the login. Cookie-authenticated mutations must send X-Requested-With: SmartFrame (CSRF). The API key is also accepted as "Authorization: Bearer". A key is generated into /data/secrets.json when APP_API_KEY is empty, and the signed-in admin can view and regenerate it (an APP_API_KEY from .env stays pinned). The default port is now 8080 (settings, Dockerfile, docker-compose and the CI smoke test). BREAKING CHANGE: the default port moves from 8000 to 8080, and setting ADMIN_PASSWORD locks read endpoints such as GET /api/status too. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- .github/workflows/ci.yml | 8 +- Dockerfile | 6 +- app/api/deps.py | 7 + app/api/routes/auth.py | 195 ++++++++++++++++++++++ app/api/routes/system.py | 6 +- app/core/auth.py | 244 +++++++++++++++++++++++----- app/core/secrets_store.py | 116 +++++++++++++ app/core/sessions.py | 103 ++++++++++++ app/core/settings.py | 30 +++- app/main.py | 38 ++++- app/templates/login.html | 113 +++++++++++++ docker-compose.yml | 2 +- tests/test_auth.py | 2 +- tests/test_settings.py | 2 +- tests/test_web_auth.py | 331 ++++++++++++++++++++++++++++++++++++++ 15 files changed, 1139 insertions(+), 64 deletions(-) create mode 100644 app/api/routes/auth.py create mode 100644 app/core/secrets_store.py create mode 100644 app/core/sessions.py create mode 100644 app/templates/login.html create mode 100644 tests/test_web_auth.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 45443cc..47f0917 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -74,14 +74,14 @@ jobs: - name: Smoke test run: | - docker run -d --name sfe -p 8000:8000 -e APP_API_KEY=ci-key smart-frame-engine:ci + docker run -d --name sfe -p 8080:8080 -e APP_API_KEY=ci-key smart-frame-engine:ci for i in $(seq 1 30); do - if curl -fsS http://127.0.0.1:8000/api/health; then break; fi + if curl -fsS http://127.0.0.1:8080/api/health; then break; fi sleep 1 done echo - test "$(curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:8000/api/config)" = "401" - test "$(curl -s -o /dev/null -w '%{http_code}' -H 'X-API-Key: ci-key' http://127.0.0.1:8000/api/config)" = "200" + test "$(curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:8080/api/config)" = "401" + test "$(curl -s -o /dev/null -w '%{http_code}' -H 'X-API-Key: ci-key' http://127.0.0.1:8080/api/config)" = "200" test "$(docker exec sfe id -u)" = "1000" - name: Container logs diff --git a/Dockerfile b/Dockerfile index cd3646e..bae3a84 100644 --- a/Dockerfile +++ b/Dockerfile @@ -11,7 +11,7 @@ ENV PYTHONDONTWRITEBYTECODE=1 \ PIP_NO_CACHE_DIR=1 \ PIP_DISABLE_PIP_VERSION_CHECK=1 \ DATA_DIR=/data \ - PORT=8000 + PORT=8080 WORKDIR /app @@ -41,9 +41,9 @@ RUN mkdir -p /app/.numba_cache && chown app:app /app/.numba_cache USER app RUN python -c "from app.processor.dither import warm_up; warm_up()" VOLUME ["/data"] -EXPOSE 8000 +EXPOSE 8080 HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \ - CMD ["python", "-c", "import os, urllib.request; urllib.request.urlopen('http://127.0.0.1:%s/api/health' % os.environ.get('PORT', '8000'), timeout=4)"] + CMD ["python", "-c", "import os, urllib.request; urllib.request.urlopen('http://127.0.0.1:%s/api/health' % os.environ.get('PORT', '8080'), timeout=4)"] CMD ["python", "-m", "app"] diff --git a/app/api/deps.py b/app/api/deps.py index d0132a7..35853b7 100644 --- a/app/api/deps.py +++ b/app/api/deps.py @@ -6,6 +6,7 @@ from fastapi import Depends, Request +from app.core.auth import AuthState from app.core.config_store import ConfigStore from app.core.history_store import HistoryStore from app.core.settings import EnvSettings @@ -24,6 +25,11 @@ def get_settings(request: Request) -> EnvSettings: return cast(EnvSettings, request.app.state.settings) +def get_auth_state(request: Request) -> AuthState: + """Effective credentials (admin password, API key, session signing).""" + return cast(AuthState, request.app.state.auth_state) + + def get_config_store(request: Request) -> ConfigStore: """The runtime configuration store (initialized during app startup).""" return cast(ConfigStore, request.app.state.config_store) @@ -80,6 +86,7 @@ def get_people_directory(request: Request) -> PeopleDirectory: SettingsDep = Annotated[EnvSettings, Depends(get_settings)] +AuthStateDep = Annotated[AuthState, Depends(get_auth_state)] ConfigStoreDep = Annotated[ConfigStore, Depends(get_config_store)] HistoryStoreDep = Annotated[HistoryStore, Depends(get_history_store)] CurrentImageStoreDep = Annotated[CurrentImageStore, Depends(get_current_image_store)] diff --git a/app/api/routes/auth.py b/app/api/routes/auth.py new file mode 100644 index 0000000..a542a78 --- /dev/null +++ b/app/api/routes/auth.py @@ -0,0 +1,195 @@ +"""Web UI login, session status and API key management.""" + +from __future__ import annotations + +from datetime import UTC, datetime +from functools import lru_cache +from importlib import resources +from typing import Literal + +from fastapi import APIRouter, HTTPException, Request, Security +from fastapi.responses import HTMLResponse, JSONResponse +from pydantic import AwareDatetime, BaseModel, Field + +from app.api.deps import AuthStateDep +from app.core.auth import ADMIN_USER, AuthMode, AuthVia, api_key_scheme +from app.core.secrets_store import ApiKeyManagedByEnvError, ApiKeySource +from app.core.sessions import COOKIE_NAME + +router = APIRouter(tags=["auth"]) + + +@lru_cache(maxsize=4) +def page(name: str) -> str: + """A bundled HTML page (``app/templates/``).""" + return resources.files("app").joinpath("templates", name).read_text(encoding="utf-8") + + +def _cookie_path(request: Request) -> str: + root_path: str = request.scope.get("root_path", "") + return root_path or "/" + + +class LoginRequest(BaseModel): + """Credentials of the web UI login.""" + + username: str = Field(default=ADMIN_USER, max_length=64) + password: str = Field(min_length=1, max_length=512) + + +class SessionView(BaseModel): + """Who the caller is, and how the instance is protected.""" + + mode: AuthMode = Field( + description="open = no authentication; key = API key only; password = admin login" + ) + authenticated: bool + via: AuthVia | None = Field(default=None, description="api_key or session") + user: str | None = None + expires_at: AwareDatetime | None = Field(default=None, description="Session expiry") + api_key_source: ApiKeySource = Field(description="env (APP_API_KEY), generated or none") + + +class ApiKeyView(BaseModel): + """The API key for Home Assistant and other clients.""" + + api_key: str + source: ApiKeySource + regenerable: bool = Field(description="False when APP_API_KEY manages the key") + + +@router.get("/login", include_in_schema=False) +async def login_page() -> HTMLResponse: + """The login page (relative URLs, works under any reverse-proxy sub-path).""" + return HTMLResponse(page("login.html"), headers={"Cache-Control": "no-store"}) + + +@router.get("/api/auth/session", response_model=SessionView, summary="Current session") +async def session(request: Request, auth: AuthStateDep) -> SessionView: + """Authentication mode and whether the caller is signed in (always reachable).""" + via = auth.authenticate(request.scope) if auth.mode != "open" else None + expires = None + if via == "session": + expiry = auth.session_expiry(request.cookies.get(COOKIE_NAME)) + expires = datetime.fromtimestamp(expiry, UTC) if expiry else None + return SessionView( + mode=auth.mode, + authenticated=auth.mode == "open" or via is not None, + via=via, + user=ADMIN_USER if via == "session" else None, + expires_at=expires, + api_key_source=auth.secrets.api_key_source, + ) + + +@router.post( + "/api/auth/login", + responses={ + 401: {"description": "Wrong user name or password"}, + 409: {"description": "No login is configured (set ADMIN_PASSWORD)"}, + 429: {"description": "Too many failed attempts; see Retry-After"}, + }, + summary="Sign in to the web UI", +) +async def login(body: LoginRequest, request: Request, auth: AuthStateDep) -> JSONResponse: + """Check ``admin`` + ``ADMIN_PASSWORD`` and set an HttpOnly session cookie. + + Without ``ADMIN_PASSWORD`` but with an API key, the API key is accepted as the password. + """ + if auth.mode == "open": + raise HTTPException(status_code=409, detail="No login is configured: set ADMIN_PASSWORD") + client = request.client.host if request.client else "unknown" + wait = auth.throttle.retry_after(client) + if wait > 0: + return JSONResponse( + {"detail": "Too many failed attempts, try again later"}, + status_code=429, + headers={"Retry-After": str(int(wait) + 1)}, + ) + if not auth.check_login(body.username, body.password): + auth.throttle.failure(client) + raise HTTPException(status_code=401, detail="Wrong user name or password") + auth.throttle.success(client) + token, expires = auth.issue_session() + response = JSONResponse( + { + "authenticated": True, + "user": ADMIN_USER, + "expires_at": datetime.fromtimestamp(expires, UTC).isoformat(), + } + ) + response.set_cookie( + COOKIE_NAME, + token, + max_age=int(auth.session_ttl_s), + path=_cookie_path(request), + secure=request.url.scheme == "https", + httponly=True, + samesite="strict", + ) + return response + + +@router.post( + "/api/auth/logout", + dependencies=[Security(api_key_scheme)], + summary="Sign out of the web UI", +) +async def logout(request: Request) -> JSONResponse: + """Remove the session cookie.""" + response = JSONResponse({"authenticated": False}) + response.delete_cookie( + COOKIE_NAME, + path=_cookie_path(request), + secure=request.url.scheme == "https", + httponly=True, + samesite="strict", + ) + return response + + +@router.get( + "/api/auth/api-key", + response_model=ApiKeyView, + dependencies=[Security(api_key_scheme)], + summary="Show the API key", +) +async def api_key(auth: AuthStateDep) -> ApiKeyView: + """The key Home Assistant and the frame use (``X-API-Key`` / ``Authorization: Bearer``).""" + source = auth.secrets.api_key_source + return ApiKeyView( + api_key=auth.api_key, + source=source, + regenerable=source != "env" and auth.mode == "password", + ) + + +@router.post( + "/api/auth/api-key/regenerate", + response_model=ApiKeyView, + dependencies=[Security(api_key_scheme)], + responses={ + 403: {"description": "Only a signed-in admin session can regenerate the key"}, + 409: {"description": "APP_API_KEY manages the key, or no ADMIN_PASSWORD is set"}, + }, + summary="Generate a new API key", +) +async def regenerate_api_key(request: Request, auth: AuthStateDep) -> ApiKeyView: + """Replace the stored API key; clients using the old one must be updated.""" + via: Literal["api_key", "session"] | None = getattr(request.state, "auth_via", None) + if auth.mode != "password": + raise HTTPException( + status_code=409, detail="Set ADMIN_PASSWORD to manage the API key from the UI" + ) + if via != "session": + raise HTTPException( + status_code=403, detail="Sign in to the web UI to regenerate the API key" + ) + try: + key = auth.secrets.regenerate_api_key() + except ApiKeyManagedByEnvError as exc: + raise HTTPException(status_code=409, detail=str(exc)) from exc + refresh = getattr(request.app.state, "refresh_masked_secrets", None) + if callable(refresh): + refresh() + return ApiKeyView(api_key=key, source="generated", regenerable=True) diff --git a/app/api/routes/system.py b/app/api/routes/system.py index eea0d60..461979d 100644 --- a/app/api/routes/system.py +++ b/app/api/routes/system.py @@ -10,6 +10,7 @@ from app import __version__ from app.api.deps import ( + AuthStateDep, ConfigStoreDep, CurrentImageStoreDep, DeliveryServiceDep, @@ -65,6 +66,7 @@ class StatusResponse(BaseModel): version: str uptime_s: float auth_enabled: bool + auth_mode: str = Field(description="open, key (API key only) or password (admin login)") public_image_endpoints: bool frame: FrameStatus delivery: DeliveryStatus @@ -88,6 +90,7 @@ async def health() -> HealthResponse: async def status( request: Request, settings: SettingsDep, + auth: AuthStateDep, store: ConfigStoreDep, current: CurrentImageStoreDep, delivery: DeliveryServiceDep, @@ -101,7 +104,8 @@ async def status( return StatusResponse( version=__version__, uptime_s=round(time.monotonic() - started_at, 1), - auth_enabled=settings.auth_enabled, + auth_enabled=auth.mode != "open", + auth_mode=auth.mode, public_image_endpoints=settings.public_image_endpoints, frame=FrameStatus( panel=config.fraimic.panel, diff --git a/app/core/auth.py b/app/core/auth.py index fc984c6..7f9eb5c 100644 --- a/app/core/auth.py +++ b/app/core/auth.py @@ -1,35 +1,53 @@ -"""Adaptive API key authentication (pure ASGI middleware). +"""Adaptive authentication (pure ASGI middleware): API key, Bearer token and login session. -Rules when ``APP_API_KEY`` is set (no-op when it is empty): +Three modes, chosen from the environment and ``/data/secrets.json``: -* ``POST``/``PUT``/``PATCH``/``DELETE`` on any route require the key. -* ``/api/config`` and ``/api/immich`` (family member names, albums) and everything - below them require the key for every method. -* ``/api/current.jpg``, ``/api/current.bin``, ``/api/current_dithered.png``, - ``/api/preview.jpg`` and ``/api/preview_dithered.png`` require the key only when - ``PUBLIC_IMAGE_ENDPOINTS=false``. -* Everything else (UI, ``/docs``, ``/openapi.json``, ``/api/health``, ``GET /api/status``) - stays public so the UI can load and prompt for the key. +* **open** - no ``ADMIN_PASSWORD`` and no API key: pure LAN usage, everything is open. +* **key** - an API key (``APP_API_KEY``) but no password. As before: -The key is accepted from the ``X-API-Key`` header or the ``api_key`` query parameter and -compared in constant time. + * ``POST``/``PUT``/``PATCH``/``DELETE`` on any route require credentials; + * ``/api/config``, ``/api/immich`` (family member names, albums) and ``/api/smart-mix`` + require them for every method; + * the image endpoints (``/api/current.*``, ``/api/preview.*``) require them only when + ``PUBLIC_IMAGE_ENDPOINTS=false``; + * everything else stays public. + +* **password** - ``ADMIN_PASSWORD`` is set (an API key is generated if none exists). Every + route requires credentials except ``/api/health``, the login (``/login``, + ``POST /api/auth/login``, ``GET /api/auth/session``) and the image endpoints while + ``PUBLIC_IMAGE_ENDPOINTS=true``. Browsers asking for a page are redirected to the login. + +Credentials: the API key in the ``X-API-Key`` header, an ``Authorization: Bearer`` header or +the ``api_key`` query parameter (constant-time comparison), or the signed ``sfe_session`` +cookie of a web UI login. A cookie-authenticated ``POST``/``PUT``/``PATCH``/``DELETE`` must +also carry ``X-Requested-With: SmartFrame``: browsers cannot add that header cross-site +without a CORS preflight, which blocks cross-site request forgery. """ from __future__ import annotations import hmac -from typing import Final +import time +from collections.abc import Callable +from http.cookies import SimpleCookie +from typing import Final, Literal from urllib.parse import parse_qsl from fastapi.security import APIKeyHeader -from starlette.responses import JSONResponse +from starlette.responses import JSONResponse, RedirectResponse, Response from starlette.types import ASGIApp, Receive, Scope, Send +from app.core.secrets_store import SecretsStore +from app.core.sessions import COOKIE_NAME, LoginThrottle, issue_token, signing_key, token_expiry + API_KEY_HEADER: Final = "X-API-Key" API_KEY_QUERY_PARAM: Final = "api_key" +CSRF_HEADER: Final = "X-Requested-With" +CSRF_VALUE: Final = "SmartFrame" +ADMIN_USER: Final = "admin" MUTATING_METHODS: Final = frozenset({"POST", "PUT", "PATCH", "DELETE"}) -PROTECTED_PREFIXES: Final = ("/api/config", "/api/immich", "/api/smart-mix") +PROTECTED_PREFIXES: Final = ("/api/config", "/api/immich", "/api/smart-mix", "/api/auth/api-key") IMAGE_ENDPOINTS: Final = frozenset( { "/api/current.jpg", @@ -39,13 +57,22 @@ "/api/preview_dithered.png", } ) +#: Reachable without credentials in every mode (the login itself and the liveness probe). +ALWAYS_PUBLIC: Final = frozenset( + {"/api/health", "/login", "/api/auth/login", "/api/auth/session", "/favicon.ico"} +) +PUBLIC_PREFIXES: Final = ("/static/",) + +AuthMode = Literal["open", "key", "password"] +AuthVia = Literal["api_key", "session"] #: OpenAPI-only security scheme so ``/docs`` offers an "Authorize" button. Enforcement -#: is done by :class:`APIKeyMiddleware`, never by this dependency. +#: is done by :class:`AuthMiddleware`, never by this dependency. api_key_scheme = APIKeyHeader( name=API_KEY_HEADER, auto_error=False, - description="Required for mutating routes and /api/config when APP_API_KEY is set.", + description="API key (or a web UI login session). Also accepted as " + "'Authorization: Bearer ' or '?api_key='.", ) @@ -66,7 +93,7 @@ def route_path(scope: Scope) -> str: def requires_api_key(method: str, path: str, *, public_image_endpoints: bool) -> bool: - """Decide whether a request must carry a valid API key.""" + """The ``key`` mode rules: whether a request must carry credentials.""" method = method.upper() if method == "OPTIONS": return False @@ -78,12 +105,40 @@ def requires_api_key(method: str, path: str, *, public_image_endpoints: bool) -> return normalized in IMAGE_ENDPOINTS and not public_image_endpoints +def needs_credentials( + method: str, path: str, mode: AuthMode, *, public_image_endpoints: bool +) -> bool: + """Whether a request must carry credentials in ``mode``.""" + if mode == "open" or method.upper() == "OPTIONS": + return False + normalized = path.rstrip("/") or "/" + if normalized in ALWAYS_PUBLIC or path.startswith(PUBLIC_PREFIXES): + return False + if mode == "key": + return requires_api_key(method, path, public_image_endpoints=public_image_endpoints) + if normalized in IMAGE_ENDPOINTS: + return not public_image_endpoints + return True + + +def _header(scope: Scope, name: str) -> str | None: + wanted = name.lower().encode("latin-1") + for key, value in scope.get("headers", []): + if key.lower() == wanted: + return bytes(value).decode("latin-1") + return None + + def extract_api_key(scope: Scope) -> str | None: - """Read the API key from the ``X-API-Key`` header or the ``api_key`` query param.""" - header_name = API_KEY_HEADER.lower().encode("latin-1") - for name, value in scope.get("headers", []): - if name.lower() == header_name: - return bytes(value).decode("latin-1").strip() + """The API key from ``X-API-Key``, ``Authorization: Bearer`` or ``?api_key=``.""" + header = _header(scope, API_KEY_HEADER) + if header is not None: + return header.strip() + authorization = _header(scope, "authorization") + if authorization is not None: + scheme, _, token = authorization.strip().partition(" ") + if scheme.lower() == "bearer" and token.strip(): + return token.strip() query: bytes = scope.get("query_string", b"") if query: for name, value in parse_qsl(query.decode("latin-1"), keep_blank_values=True): @@ -92,6 +147,20 @@ def extract_api_key(scope: Scope) -> str | None: return None +def extract_session_cookie(scope: Scope) -> str | None: + """The raw ``sfe_session`` cookie value, if any.""" + header = _header(scope, "cookie") + if not header: + return None + cookie = SimpleCookie() + try: + cookie.load(header) + except Exception: # malformed Cookie header: treat as absent + return None + morsel = cookie.get(COOKIE_NAME) + return morsel.value if morsel is not None else None + + def keys_match(provided: str | None, expected: str) -> bool: """Constant-time comparison of a provided key against the expected key.""" if not provided or not expected: @@ -99,36 +168,127 @@ def keys_match(provided: str | None, expected: str) -> bool: return hmac.compare_digest(provided.encode("utf-8"), expected.encode("utf-8")) -class APIKeyMiddleware: - """Enforce :func:`requires_api_key` rules for HTTP requests.""" +class AuthState: + """Effective credentials: the admin password, the API key and session signing.""" + + def __init__( + self, + secrets: SecretsStore, + *, + password: str = "", + session_ttl_s: float = 7 * 24 * 3600, + clock: Callable[[], float] = time.time, + ) -> None: + self.secrets = secrets + self.password = password + self.session_ttl_s = session_ttl_s + self.throttle = LoginThrottle() + self._clock = clock - def __init__(self, app: ASGIApp, *, api_key: str, public_image_endpoints: bool) -> None: + def load(self) -> None: + """Read the stored secrets; a password without any key generates one.""" + self.secrets.load() + if self.password: + self.secrets.ensure_api_key() + + @property + def mode(self) -> AuthMode: + """``password`` when a login is configured, else ``key`` or ``open``.""" + if self.password: + return "password" + return "key" if self.api_key else "open" + + @property + def api_key(self) -> str: + """The effective API key (empty when none exists).""" + return self.secrets.api_key + + def _signing_key(self) -> bytes: + return signing_key(self.secrets.session_secret, self.password) + + def issue_session(self) -> tuple[str, int]: + """A new session token and its expiry (Unix seconds).""" + return issue_token(self._signing_key(), self.session_ttl_s, now=self._clock()) + + def session_expiry(self, token: str | None) -> int | None: + """The expiry of a valid session token (``None`` when invalid or expired).""" + if not token or self.mode == "open": + return None + return token_expiry(token, self._signing_key(), now=self._clock()) + + def check_login(self, username: str, password: str) -> bool: + """Validate a login: ``admin`` + the password, or the API key when no password is set.""" + if self.mode == "password": + user_ok = hmac.compare_digest(username.strip().encode(), ADMIN_USER.encode()) + return keys_match(password, self.password) and user_ok + if self.mode == "key": + return keys_match(password, self.api_key) + return False + + def authenticate(self, scope: Scope) -> AuthVia | None: + """How the request is authenticated (``None`` = not at all).""" + if keys_match(extract_api_key(scope), self.api_key): + return "api_key" + if self.session_expiry(extract_session_cookie(scope)) is not None: + return "session" + return None + + +def _wants_html(scope: Scope, path: str) -> bool: + accept = _header(scope, "accept") or "" + return not path.startswith("/api/") and "text/html" in accept + + +class AuthMiddleware: + """Enforce :func:`needs_credentials` and record how each request authenticated.""" + + def __init__(self, app: ASGIApp, *, state: AuthState, public_image_endpoints: bool) -> None: """Wrap ``app``. Args: app: Downstream ASGI application. - api_key: Expected key; an empty string disables authentication. - public_image_endpoints: Keep current.jpg/current.bin readable without a key. + state: Effective credentials (read on every request: keys can be regenerated). + public_image_endpoints: Keep the image endpoints readable without credentials. """ self.app = app - self.api_key = api_key + self.state = state self.public_image_endpoints = public_image_endpoints async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: - if scope["type"] != "http" or not self.api_key: + if scope["type"] != "http": await self.app(scope, receive, send) return + method: str = scope.get("method", "GET").upper() + path = route_path(scope) + via = self.state.authenticate(scope) if self.state.mode != "open" else None + scope.setdefault("state", {})["auth_via"] = via - method: str = scope.get("method", "GET") - if requires_api_key( - method, route_path(scope), public_image_endpoints=self.public_image_endpoints - ) and not keys_match(extract_api_key(scope), self.api_key): - response = JSONResponse( - {"detail": "Missing or invalid API key"}, - status_code=401, - headers={"WWW-Authenticate": f'APIKey header="{API_KEY_HEADER}"'}, - ) - await response(scope, receive, send) - return - + if needs_credentials( + method, path, self.state.mode, public_image_endpoints=self.public_image_endpoints + ): + response = self._refusal(scope, method, path, via) + if response is not None: + await response(scope, receive, send) + return await self.app(scope, receive, send) + + def _refusal( + self, scope: Scope, method: str, path: str, via: AuthVia | None + ) -> Response | None: + if via == "api_key": + return None + if via == "session": + if method in MUTATING_METHODS and _header(scope, CSRF_HEADER) != CSRF_VALUE: + return JSONResponse( + {"detail": f"Session requests must send '{CSRF_HEADER}: {CSRF_VALUE}'"}, + status_code=403, + ) + return None + if method == "GET" and self.state.mode == "password" and _wants_html(scope, path): + root_path: str = scope.get("root_path", "") + return RedirectResponse(f"{root_path}/login", status_code=303) + return JSONResponse( + {"detail": "Missing or invalid API key or session"}, + status_code=401, + headers={"WWW-Authenticate": f'APIKey header="{API_KEY_HEADER}"'}, + ) diff --git a/app/core/secrets_store.py b/app/core/secrets_store.py new file mode 100644 index 0000000..0dc63a5 --- /dev/null +++ b/app/core/secrets_store.py @@ -0,0 +1,116 @@ +"""Generated secrets persisted in ``/data/secrets.json``: the API key and the session key. + +* **API key.** ``APP_API_KEY`` from the environment always wins and can never be changed + through the API it protects. Without it, a key is generated and stored here as soon as an + admin password is configured (secure by default: Home Assistant and the frame need a key + once the UI is locked), and an authenticated admin can regenerate it. +* **Session key.** ``SESSION_SECRET`` from the environment, else a random key generated once + and stored here, so web UI sessions survive restarts. + +The file is written atomically and readable by its owner only (where the OS supports it). +""" + +from __future__ import annotations + +import logging +import os +import secrets +import threading +from pathlib import Path +from typing import Final, Literal + +from app.core.json_store import atomic_write_json, read_json + +logger = logging.getLogger(__name__) + +KEY_BYTES: Final = 32 +ApiKeySource = Literal["env", "generated", "none"] + + +class ApiKeyManagedByEnvError(RuntimeError): + """The API key comes from ``APP_API_KEY`` and cannot be changed from the API.""" + + +def new_secret() -> str: + """A fresh URL-safe random secret (256 bits).""" + return secrets.token_urlsafe(KEY_BYTES) + + +class SecretsStore: + """Reads, generates and persists the generated secrets.""" + + def __init__(self, path: Path, *, env_api_key: str = "", env_session_secret: str = "") -> None: + self._path = path + self._env_api_key = env_api_key.strip() + self._env_session_secret = env_session_secret.strip() + self._lock = threading.Lock() + self._stored: dict[str, str] = {} + + # --- Lifecycle ------------------------------------------------------------------------ + def load(self) -> None: + """Read the stored secrets (a missing or malformed file means "none").""" + raw = read_json(self._path, dict) + with self._lock: + self._stored = { + key: value + for key, value in (raw if isinstance(raw, dict) else {}).items() + if isinstance(key, str) and isinstance(value, str) and value + } + + # --- API key -------------------------------------------------------------------------- + @property + def api_key(self) -> str: + """The effective API key (empty when none is configured).""" + return self._env_api_key or self._stored.get("api_key", "") + + @property + def api_key_source(self) -> ApiKeySource: + """Where the effective API key comes from.""" + if self._env_api_key: + return "env" + return "generated" if self._stored.get("api_key") else "none" + + def ensure_api_key(self) -> str: + """Generate and store an API key unless one exists (environment or stored).""" + if self.api_key: + return self.api_key + return self._store("api_key", new_secret()) + + def regenerate_api_key(self) -> str: + """Replace the stored API key. + + Raises: + ApiKeyManagedByEnvError: The key comes from ``APP_API_KEY``. + """ + if self._env_api_key: + raise ApiKeyManagedByEnvError( + "The API key is set by APP_API_KEY; change it in .env and restart" + ) + key = self._store("api_key", new_secret()) + logger.info("Generated a new API key") + return key + + # --- Session key ---------------------------------------------------------------------- + @property + def session_secret(self) -> str: + """The key signing session cookies (generated and stored on first use).""" + if self._env_session_secret: + return self._env_session_secret + stored = self._stored.get("session_secret") + return stored if stored else self._store("session_secret", new_secret()) + + def values(self) -> list[str]: + """Every secret held here (for log masking).""" + return [value for value in (self.api_key, self._stored.get("session_secret", "")) if value] + + # --- Internals ------------------------------------------------------------------------ + def _store(self, name: str, value: str) -> str: + with self._lock: + updated = {**self._stored, name: value} + atomic_write_json(self._path, updated) + try: + os.chmod(self._path, 0o600) + except OSError: # pragma: no cover - e.g. some network filesystems + logger.debug("Could not restrict the permissions of %s", self._path) + self._stored = updated + return value diff --git a/app/core/sessions.py b/app/core/sessions.py new file mode 100644 index 0000000..fa5f084 --- /dev/null +++ b/app/core/sessions.py @@ -0,0 +1,103 @@ +"""Web UI login sessions: signed cookie tokens and a login throttle. + +A session token is ``v1...``: the expiry (Unix seconds), a random +nonce and an HMAC-SHA256 signature of both. The signing key is derived from the session +secret *and* the admin password, so changing the password (or the session secret) signs +everyone out. Nothing is stored server-side. +""" + +from __future__ import annotations + +import base64 +import hashlib +import hmac +import secrets +import threading +import time +from collections.abc import Callable +from dataclasses import dataclass +from typing import Final + +VERSION: Final = "v1" +COOKIE_NAME: Final = "sfe_session" +#: Failed logins from one client before throttling starts, and the longest wait (seconds). +FREE_ATTEMPTS: Final = 5 +MAX_LOCKOUT_S: Final = 300.0 + +Clock = Callable[[], float] + + +def _b64(data: bytes) -> str: + return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii") + + +def signing_key(session_secret: str, password: str) -> bytes: + """Key of the session signatures; changes with the secret or the password.""" + fingerprint = hashlib.sha256(password.encode("utf-8")).digest() + return hmac.new( + session_secret.encode("utf-8"), b"sfe-session:" + fingerprint, "sha256" + ).digest() + + +def _signature(key: bytes, payload: str) -> str: + return _b64(hmac.new(key, payload.encode("ascii"), "sha256").digest()) + + +def issue_token(key: bytes, ttl_s: float, *, now: float | None = None) -> tuple[str, int]: + """A new session token and its expiry (Unix seconds).""" + expires = int((time.time() if now is None else now) + ttl_s) + payload = f"{VERSION}.{expires}.{secrets.token_urlsafe(12)}" + return f"{payload}.{_signature(key, payload)}", expires + + +def token_expiry(token: str | None, key: bytes, *, now: float | None = None) -> int | None: + """The expiry of a valid, unexpired ``token``, else ``None``.""" + if not token: + return None + parts = token.split(".") + if len(parts) != 4 or parts[0] != VERSION or not parts[1].isdigit(): + return None + payload = ".".join(parts[:3]) + if not hmac.compare_digest(_signature(key, payload), parts[3]): + return None + expires = int(parts[1]) + return expires if expires > (time.time() if now is None else now) else None + + +@dataclass(slots=True) +class _Failures: + count: int = 0 + blocked_until: float = 0.0 + + +class LoginThrottle: + """Per-client exponential backoff after repeated failed logins.""" + + def __init__(self, *, clock: Clock = time.monotonic) -> None: + self._clock = clock + self._failures: dict[str, _Failures] = {} + self._lock = threading.Lock() + + def retry_after(self, client: str) -> float: + """Seconds before ``client`` may try again (0 = now).""" + with self._lock: + entry = self._failures.get(client) + if entry is None: + return 0.0 + return max(0.0, entry.blocked_until - self._clock()) + + def failure(self, client: str) -> None: + """Record a failed attempt.""" + with self._lock: + entry = self._failures.setdefault(client, _Failures()) + entry.count += 1 + if entry.count >= FREE_ATTEMPTS: + delay = min(2.0 ** (entry.count - FREE_ATTEMPTS), MAX_LOCKOUT_S) + entry.blocked_until = self._clock() + delay + if len(self._failures) > 10_000: # bound memory under a distributed attack + self._failures.clear() + + def success(self, client: str) -> None: + """Forget the failures of ``client``.""" + with self._lock: + self._failures.pop(client, None) diff --git a/app/core/settings.py b/app/core/settings.py index 96d6b87..9ae87b7 100644 --- a/app/core/settings.py +++ b/app/core/settings.py @@ -40,13 +40,25 @@ class EnvSettings(BaseSettings): # --- Infrastructure ------------------------------------------------------- data_dir: Path = Field(default=Path("/data"), description="Persistent data directory") host: str = Field(default="0.0.0.0", description="Bind address") # noqa: S104 - port: int = Field(default=8000, ge=1, le=65535, description="Bind port") + port: int = Field(default=8080, ge=1, le=65535, description="Bind port") log_level: LogLevel = Field(default="INFO", description="Python log level") app_api_key: SecretStr = Field( default=SecretStr(""), description="When set, mutating routes and /api/config require X-API-Key", ) + admin_password: SecretStr = Field( + default=SecretStr(""), + description="Password of the 'admin' web UI login. When set, every route except " + "/api/health, the public image endpoints and the login needs a session or the API key", + ) + session_ttl_hours: float = Field( + default=168.0, gt=0, le=8760, description="Lifetime of a web UI login session" + ) + session_secret: SecretStr = Field( + default=SecretStr(""), + description="Key signing the session cookies (generated into /data/secrets.json if empty)", + ) public_image_endpoints: bool = Field( default=True, description="Serve /api/current.jpg and /api/current.bin without an API key", @@ -135,10 +147,15 @@ def api_key(self) -> str: """The configured API key (empty string when authentication is disabled).""" return self.app_api_key.get_secret_value().strip() + @property + def password(self) -> str: + """The admin web UI password (empty string when the login is disabled).""" + return self.admin_password.get_secret_value() + @property def auth_enabled(self) -> bool: - """Whether API key authentication is enforced.""" - return bool(self.api_key) + """Whether authentication is configured in the environment (key or password).""" + return bool(self.api_key or self.password) @property def cors_origin_list(self) -> list[str]: @@ -185,6 +202,11 @@ def last_delivery_path(self) -> Path: """Location of the last successful frame delivery (what the frame shows).""" return self.data_dir / "last_delivery.json" + @property + def secrets_path(self) -> Path: + """Generated secrets (API key, session signing key), readable by the owner only.""" + return self.data_dir / "secrets.json" + @property def scheduler_state_path(self) -> Path: """Location of the scheduler state (replayable rule, timer, last run).""" @@ -192,7 +214,7 @@ def scheduler_state_path(self) -> Path: def secret_values(self) -> list[str]: """All secret values provided through the environment (for log masking).""" - values = [self.api_key] + values = [self.api_key, self.password, self.session_secret.get_secret_value()] for secret in (self.immich_api_key, self.tmdb_api_key): if secret is not None: values.append(secret.get_secret_value()) diff --git a/app/main.py b/app/main.py index 3b1f2ee..79f3b4d 100644 --- a/app/main.py +++ b/app/main.py @@ -19,6 +19,7 @@ from fastapi.responses import JSONResponse, RedirectResponse from app import __version__ +from app.api.routes import auth as auth_routes from app.api.routes import config as config_routes from app.api.routes import display as display_routes from app.api.routes import fraimic as fraimic_routes @@ -31,13 +32,14 @@ from app.api.routes import system as system_routes from app.api.routes import tmdb as tmdb_routes from app.clients.http_images import ImageFetcher -from app.core.auth import APIKeyMiddleware +from app.core.auth import AuthMiddleware, AuthState from app.core.config_models import RuntimeConfig from app.core.config_store import ConfigStore from app.core.history_store import HistoryStore from app.core.limits import MULTIPART_OVERHEAD_BYTES, BodySizeLimitMiddleware from app.core.logging_config import masking_filter, setup_logging from app.core.proxy import RootPathMiddleware +from app.core.secrets_store import SecretsStore from app.core.security import URLPolicy from app.core.settings import EnvSettings, get_env_settings from app.providers.immich import ImmichGateway, ImmichProvider, PeopleDirectory @@ -56,8 +58,10 @@ Fetch images from modular sources (Immich, TMDB posters, URLs), optimize them for a color eInk panel and push them to a Fraimic frame. -**Authentication:** when `APP_API_KEY` is set, every `POST`/`PUT`/`DELETE` route and -`/api/config` require the `X-API-Key` header (or `?api_key=`). Use **Authorize** above. +**Authentication:** with `ADMIN_PASSWORD` set, every route except `/api/health`, the login +and the public images needs a web UI session or the API key. With only `APP_API_KEY`, every +`POST`/`PUT`/`DELETE` route and `/api/config` need the key. Send it as `X-API-Key`, +`Authorization: Bearer ` or `?api_key=`; use **Authorize** above. """ @@ -84,11 +88,21 @@ def create_app(settings: EnvSettings | None = None) -> FastAPI: settings: Environment settings; defaults to :func:`get_env_settings`. """ settings = settings or get_env_settings() + auth_state = AuthState( + SecretsStore( + settings.secrets_path, + env_api_key=settings.api_key, + env_session_secret=settings.session_secret.get_secret_value(), + ), + password=settings.password, + session_ttl_s=settings.session_ttl_hours * 3600, + ) @asynccontextmanager async def lifespan(app: FastAPI) -> AsyncIterator[None]: setup_logging(settings.log_level) _prepare_data_dir(settings) + auth_state.load() config_store = ConfigStore(settings.config_path, settings.runtime_seed()) config_store.load() @@ -96,7 +110,15 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]: history_store.load() def _refresh_masked_secrets() -> None: - masking_filter.set_secrets([*settings.secret_values(), *config_store.secret_values()]) + masking_filter.set_secrets( + [ + *settings.secret_values(), + *config_store.secret_values(), + *auth_state.secrets.values(), + ] + ) + + app.state.refresh_masked_secrets = _refresh_masked_secrets async def _on_config_change(_: RuntimeConfig) -> None: _refresh_masked_secrets() @@ -170,7 +192,7 @@ async def _on_config_change(_: RuntimeConfig) -> None: "power_mode=%s, pending=%s, scheduler=%s)", __version__, settings.data_dir, - "enabled" if settings.auth_enabled else "disabled", + auth_state.mode, settings.root_path, config.fraimic.panel, config.fraimic.power_mode, @@ -194,6 +216,7 @@ async def _on_config_change(_: RuntimeConfig) -> None: lifespan=lifespan, ) app.state.settings = settings + app.state.auth_state = auth_state app.state.started_at = time.monotonic() # Middleware added last runs first. Order (outermost first): @@ -201,8 +224,8 @@ async def _on_config_change(_: RuntimeConfig) -> None: # CORS wraps auth so 401 responses keep CORS headers; RootPath must run before auth # so protected paths are recognized under a sub-path. app.add_middleware( - APIKeyMiddleware, - api_key=settings.api_key, + AuthMiddleware, + state=auth_state, public_image_endpoints=settings.public_image_endpoints, ) origins = settings.cors_origin_list @@ -228,6 +251,7 @@ async def _validation_handler(_: Request, exc: RequestValidationError) -> JSONRe ] return JSONResponse({"detail": jsonable_encoder(errors)}, status_code=422) + app.include_router(auth_routes.router) app.include_router(system_routes.router) app.include_router(config_routes.router) app.include_router(image_routes.router) diff --git a/app/templates/login.html b/app/templates/login.html new file mode 100644 index 0000000..de10918 --- /dev/null +++ b/app/templates/login.html @@ -0,0 +1,113 @@ + + + + + + + Smart Frame · Sign in + + + + + +

+
+
+ +

Smart Frame

+

Sign in to manage your frame

+
+ +
+
+ + +
+
+ + + +
+ + +
+

Home Assistant and the frame keep using the API key.

+
+
+ + + + diff --git a/docker-compose.yml b/docker-compose.yml index b3cff14..8223605 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -11,6 +11,6 @@ services: - path: .env required: false ports: - - "${HOST_PORT:-8000}:8000" + - "${HOST_PORT:-8080}:8080" volumes: - ./data:/data diff --git a/tests/test_auth.py b/tests/test_auth.py index 6898db6..123419d 100644 --- a/tests/test_auth.py +++ b/tests/test_auth.py @@ -85,7 +85,7 @@ def test_protected_routes_require_key(make_client: ClientFactory) -> None: denied = client.get("/api/config") assert denied.status_code == 401 - assert denied.json() == {"detail": "Missing or invalid API key"} + assert denied.json() == {"detail": "Missing or invalid API key or session"} assert denied.headers["www-authenticate"].startswith("APIKey") assert client.get("/api/config", headers={"X-API-Key": "wrong"}).status_code == 401 diff --git a/tests/test_settings.py b/tests/test_settings.py index e8fa8d0..00c4168 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -12,7 +12,7 @@ def test_defaults(make_settings: SettingsFactory, data_dir: Path) -> None: settings = make_settings() assert settings.data_dir == data_dir - assert settings.port == 8000 + assert settings.port == 8080 assert settings.auth_enabled is False assert settings.public_image_endpoints is True assert settings.root_path == "" diff --git a/tests/test_web_auth.py b/tests/test_web_auth.py new file mode 100644 index 0000000..aef9364 --- /dev/null +++ b/tests/test_web_auth.py @@ -0,0 +1,331 @@ +"""Admin login, sessions, API key management and the lockdown rules.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from fastapi.testclient import TestClient + +from app.core.auth import AuthState, needs_credentials +from app.core.secrets_store import ApiKeyManagedByEnvError, SecretsStore +from app.core.sessions import ( + COOKIE_NAME, + FREE_ATTEMPTS, + LoginThrottle, + issue_token, + signing_key, + token_expiry, +) +from tests.conftest import ClientFactory + +PASSWORD = "correct horse battery staple" +ENV_KEY = "env-api-key-0123456789" +CSRF = {"X-Requested-With": "SmartFrame"} + + +def login(client: TestClient, password: str = PASSWORD, user: str = "admin") -> int: + response = client.post("/api/auth/login", json={"username": user, "password": password}) + return response.status_code + + +# --- rules -------------------------------------------------------------------------------- +@pytest.mark.parametrize( + ("method", "path", "mode", "public_images", "expected"), + [ + ("GET", "/api/status", "open", True, False), + ("POST", "/api/refresh", "open", True, False), + ("GET", "/api/status", "key", True, False), # today's rules + ("POST", "/api/refresh", "key", True, True), + ("GET", "/api/auth/api-key", "key", True, True), # never leak the key + ("GET", "/api/status", "password", True, True), # lockdown + ("GET", "/docs", "password", True, True), + ("GET", "/", "password", True, True), + ("GET", "/api/health", "password", True, False), + ("GET", "/login", "password", True, False), + ("POST", "/api/auth/login", "password", True, False), + ("POST", "/api/auth/login", "key", True, False), + ("GET", "/api/auth/session", "password", True, False), + ("GET", "/api/current.jpg", "password", True, False), + ("GET", "/api/current.jpg", "password", False, True), + ("OPTIONS", "/api/status", "password", True, False), + ], +) +def test_needs_credentials( + method: str, path: str, mode: str, public_images: bool, expected: bool +) -> None: + result = needs_credentials(method, path, mode, public_image_endpoints=public_images) # type: ignore[arg-type] + assert result is expected + + +# --- sessions ------------------------------------------------------------------------------ +def test_session_tokens_expire_and_resist_tampering() -> None: + key = signing_key("secret", "pw") + token, expires = issue_token(key, 60, now=1000.0) + assert expires == 1060 + assert token_expiry(token, key, now=1059.0) == 1060 + assert token_expiry(token, key, now=1061.0) is None # expired + assert token_expiry(token, signing_key("secret", "other password"), now=1001.0) is None + assert token_expiry(token, signing_key("other secret", "pw"), now=1001.0) is None + version, expiry, nonce, signature = token.split(".") + forged = f"{version}.{int(expiry) + 999}.{nonce}.{signature}" + assert token_expiry(forged, key, now=1001.0) is None + for junk in ("", "v1", "v2.1.2.3", "v1.x.y.z", None): + assert token_expiry(junk, key, now=1001.0) is None + + +def test_login_throttle_backs_off_exponentially() -> None: + now = [0.0] + throttle = LoginThrottle(clock=lambda: now[0]) + for _ in range(FREE_ATTEMPTS - 1): + throttle.failure("1.2.3.4") + assert throttle.retry_after("1.2.3.4") == 0 + throttle.failure("1.2.3.4") + assert throttle.retry_after("1.2.3.4") == pytest.approx(1.0) + throttle.failure("1.2.3.4") + assert throttle.retry_after("1.2.3.4") == pytest.approx(2.0) + assert throttle.retry_after("5.6.7.8") == 0 # per client + throttle.success("1.2.3.4") + assert throttle.retry_after("1.2.3.4") == 0 + + +# --- secrets store ------------------------------------------------------------------------- +def test_secrets_store_generates_persists_and_respects_env(tmp_path: Path) -> None: + path = tmp_path / "secrets.json" + store = SecretsStore(path) + store.load() + assert store.api_key == "" and store.api_key_source == "none" + key = store.ensure_api_key() + assert len(key) >= 32 and store.api_key_source == "generated" + assert store.ensure_api_key() == key # idempotent + session_secret = store.session_secret + reloaded = SecretsStore(path) + reloaded.load() + assert reloaded.api_key == key and reloaded.session_secret == session_secret + assert reloaded.regenerate_api_key() != key + assert set(json.loads(path.read_text(encoding="utf-8"))) == {"api_key", "session_secret"} + + env = SecretsStore(path, env_api_key=ENV_KEY, env_session_secret="env-secret") + env.load() + assert env.api_key == ENV_KEY and env.api_key_source == "env" + assert env.session_secret == "env-secret" + with pytest.raises(ApiKeyManagedByEnvError): + env.regenerate_api_key() + + +def test_auth_state_modes(tmp_path: Path) -> None: + open_state = AuthState(SecretsStore(tmp_path / "a.json")) + open_state.load() + assert open_state.mode == "open" and open_state.api_key == "" + + key_state = AuthState(SecretsStore(tmp_path / "b.json", env_api_key=ENV_KEY)) + key_state.load() + assert key_state.mode == "key" + assert key_state.check_login("anyone", ENV_KEY) # the key works as a password + assert not key_state.check_login("admin", "nope") + + locked = AuthState(SecretsStore(tmp_path / "c.json"), password=PASSWORD) + locked.load() + assert locked.mode == "password" + assert locked.api_key # generated: Home Assistant needs one once the UI is locked + assert locked.check_login("admin", PASSWORD) + assert not locked.check_login("root", PASSWORD) + assert not locked.check_login("admin", "wrong") + + +# --- open and key modes -------------------------------------------------------------------- +def test_open_mode_has_no_login(make_client: ClientFactory) -> None: + client = make_client() + session = client.get("/api/auth/session").json() + assert session["mode"] == "open" and session["authenticated"] is True + assert login(client) == 409 + assert client.get("/api/status").json()["auth_mode"] == "open" + + +def test_key_mode_keeps_todays_rules_and_accepts_bearer(make_client: ClientFactory) -> None: + client = make_client(app_api_key=ENV_KEY) + assert client.get("/api/status").status_code == 200 # still public + assert client.post("/api/refresh").status_code == 401 + assert ( + client.get("/api/config", headers={"Authorization": f"Bearer {ENV_KEY}"}).status_code == 200 + ) + assert client.get("/api/config", headers={"Authorization": "Bearer nope"}).status_code == 401 + assert ( + client.get("/api/config", headers={"Authorization": f"Basic {ENV_KEY}"}).status_code == 401 + ) + assert client.get("/api/auth/api-key").status_code == 401 + view = client.get("/api/auth/api-key", headers={"X-API-Key": ENV_KEY}).json() + assert view == {"api_key": ENV_KEY, "source": "env", "regenerable": False} + + +def test_key_mode_login_uses_the_api_key(make_client: ClientFactory) -> None: + client = make_client(app_api_key=ENV_KEY) + assert login(client, password="wrong") == 401 + assert login(client, password=ENV_KEY) == 200 + assert client.get("/api/config").status_code == 200 # the cookie works + + +# --- password mode ------------------------------------------------------------------------- +def test_password_mode_locks_everything_but_health_login_and_images( + make_client: ClientFactory, +) -> None: + client = make_client(admin_password=PASSWORD) + assert client.get("/api/health").status_code == 200 + assert client.get("/login").status_code == 200 + assert client.get("/api/auth/session").json() == { + "mode": "password", + "authenticated": False, + "via": None, + "user": None, + "expires_at": None, + "api_key_source": "generated", + } + for path in ("/api/status", "/api/queue", "/openapi.json", "/api/smart-mix"): + assert client.get(path).status_code == 401, path + assert client.get("/api/current.jpg").status_code == 404 # public, nothing rendered yet + + +def test_browsers_are_redirected_to_the_login_page(make_client: ClientFactory) -> None: + client = make_client(admin_password=PASSWORD) + for path in ("/", "/docs"): + page = client.get(path, headers={"Accept": "text/html"}, follow_redirects=False) + assert page.status_code == 303 and page.headers["location"] == "/login" + api = client.get("/api/status", headers={"Accept": "text/html"}, follow_redirects=False) + assert api.status_code == 401 # APIs never redirect + + +def test_login_session_cookie_and_logout(make_client: ClientFactory) -> None: + client = make_client(admin_password=PASSWORD) + response = client.post("/api/auth/login", json={"username": "admin", "password": PASSWORD}) + assert response.status_code == 200 + cookie = response.headers["set-cookie"] + assert f"{COOKIE_NAME}=" in cookie + for attribute in ("HttpOnly", "SameSite=strict", "Path=/"): + assert attribute.lower() in cookie.lower() + assert "secure" not in cookie.lower() # plain http + session = client.get("/api/auth/session").json() + assert session["authenticated"] and session["via"] == "session" and session["user"] == "admin" + assert client.get("/api/status").status_code == 200 + + assert client.post("/api/auth/logout").status_code == 403 # CSRF header missing + assert client.post("/api/auth/logout", headers=CSRF).status_code == 200 + assert client.get("/api/status").status_code == 401 + + +def test_cookie_mutations_need_the_csrf_header_but_keys_do_not( + make_client: ClientFactory, +) -> None: + client = make_client(admin_password=PASSWORD) + key = client.app.state.auth_state.api_key # type: ignore[attr-defined] + assert login(client) == 200 + body = {"eink": {"contrast": 1.3}} + forged = client.put("/api/config", json=body) + assert forged.status_code == 403 and "X-Requested-With" in forged.json()["detail"] + assert client.put("/api/config", json=body, headers=CSRF).status_code == 200 + client.cookies.clear() + assert client.put("/api/config", json=body, headers={"X-API-Key": key}).status_code == 200 + + +def test_wrong_credentials_and_throttling(make_client: ClientFactory) -> None: + client = make_client(admin_password=PASSWORD) + assert login(client, user="root") == 401 + for _ in range(FREE_ATTEMPTS - 1): + assert login(client, password="wrong") == 401 + blocked = client.post("/api/auth/login", json={"username": "admin", "password": PASSWORD}) + assert blocked.status_code == 429 and int(blocked.headers["retry-after"]) >= 1 + + +def test_tampered_or_foreign_cookies_are_rejected(make_client: ClientFactory) -> None: + client = make_client(admin_password=PASSWORD) + client.cookies.set(COOKIE_NAME, "v1.99999999999.nonce.signature") + assert client.get("/api/status").status_code == 401 + + +def test_changing_the_password_signs_everyone_out( + make_client: ClientFactory, data_dir: Path +) -> None: + first = make_client(admin_password=PASSWORD) + assert login(first) == 200 + token = first.cookies.get(COOKIE_NAME) + second = make_client(admin_password="a new password", data_dir=data_dir) + second.cookies.set(COOKIE_NAME, token or "") + assert second.get("/api/status").status_code == 401 + + +def test_sessions_survive_a_restart(make_client: ClientFactory, data_dir: Path) -> None: + first = make_client(admin_password=PASSWORD) + assert login(first) == 200 + token = first.cookies.get(COOKIE_NAME) + again = make_client(admin_password=PASSWORD, data_dir=data_dir) + again.cookies.set(COOKIE_NAME, token or "") + assert again.get("/api/status").status_code == 200 + + +def test_api_key_view_and_regeneration(make_client: ClientFactory) -> None: + client = make_client(admin_password=PASSWORD) + assert login(client) == 200 + view = client.get("/api/auth/api-key").json() + assert view["source"] == "generated" and view["regenerable"] is True + old = view["api_key"] + assert client.get("/api/status", headers={"X-API-Key": old}).status_code == 200 + + new = client.post("/api/auth/api-key/regenerate", headers=CSRF).json()["api_key"] + assert new != old + client.cookies.clear() + assert client.get("/api/status", headers={"X-API-Key": old}).status_code == 401 + assert client.get("/api/status", headers={"X-API-Key": new}).status_code == 200 + # A key cannot rotate itself: only a signed-in admin can. + denied = client.post("/api/auth/api-key/regenerate", headers={"X-API-Key": new}) + assert denied.status_code == 403 + + +def test_env_managed_key_cannot_be_regenerated(make_client: ClientFactory) -> None: + client = make_client(admin_password=PASSWORD, app_api_key=ENV_KEY) + assert login(client) == 200 + assert client.get("/api/auth/api-key").json()["source"] == "env" + response = client.post("/api/auth/api-key/regenerate", headers=CSRF) + assert response.status_code == 409 and "APP_API_KEY" in response.json()["detail"] + + +def test_secrets_never_reach_the_logs( + make_client: ClientFactory, caplog: pytest.LogCaptureFixture +) -> None: + import logging + + client = make_client(admin_password=PASSWORD) + key = client.app.state.auth_state.api_key # type: ignore[attr-defined] + logging.getLogger("app.test").warning("leak %s and %s", PASSWORD, key) + text = " ".join( + handler.format(record) + for handler in logging.getLogger().handlers + for record in caplog.records + if record.name == "app.test" + ) + assert PASSWORD not in text and key not in text + + +# --- reverse proxy ------------------------------------------------------------------------- +def test_sub_path_cookie_redirect_and_https(make_client: ClientFactory) -> None: + client = make_client(admin_password=PASSWORD, root_path="/fraimic") + client.base_url = "https://testserver" # type: ignore[assignment] # behind a TLS proxy + page = client.get("/fraimic/", headers={"Accept": "text/html"}, follow_redirects=False) + assert page.status_code == 303 and page.headers["location"] == "/fraimic/login" + assert client.get("/fraimic/login").status_code == 200 + response = client.post( + "/fraimic/api/auth/login", json={"username": "admin", "password": PASSWORD} + ) + cookie = response.headers["set-cookie"].lower() + assert "path=/fraimic" in cookie and "secure" in cookie + assert client.get("/fraimic/api/status").status_code == 200 + # A proxy that strips the prefix forwards the bare path (with the browser's cookie). + token = client.cookies.get(COOKIE_NAME) + stripped = client.get("/api/status", headers={"Cookie": f"{COOKIE_NAME}={token}"}) + assert stripped.status_code == 200 + + +def test_login_page_uses_relative_urls_only(make_client: ClientFactory) -> None: + html = make_client(admin_password=PASSWORD).get("/login").text + for absolute in ('href="/', 'src="/', 'fetch("/', "fetch('/", 'action="/'): + assert absolute not in html, absolute + assert 'fetch("./api/auth/login"' in html From bb58d311a442492f20bab086036f8ad358df4c75 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sun, 15 Nov 2026 18:18:19 +0100 Subject: [PATCH 73/86] docs: document the admin login, API key handling and port 8080 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- .env.example | 21 +++++++++++++----- CLAUDE.md | 9 ++++---- README.md | 61 ++++++++++++++++++++++++++++++++++++---------------- 3 files changed, 64 insertions(+), 27 deletions(-) diff --git a/.env.example b/.env.example index 3dac48c..525d471 100644 --- a/.env.example +++ b/.env.example @@ -10,16 +10,27 @@ # --- Docker Compose (host side) ---------------------------------------------- # Host port published by docker-compose.yml. -HOST_PORT=8000 +HOST_PORT=8080 # Host user/group owning ./data (run `id -u` / `id -g`). PUID=1000 PGID=1000 # --- Security ---------------------------------------------------------------- -# Leave empty for pure LAN usage (no authentication). -# When set, all POST/PUT/DELETE routes and /api/config require the -# `X-API-Key` header (or `?api_key=`). Generate one with: openssl rand -hex 32 +# Password of the "admin" web UI login. When set, every route except /api/health, the +# login and the public images needs a login session or the API key, and an API key is +# generated into /data/secrets.json if APP_API_KEY is empty (shown in the UI). +# Leave empty (with APP_API_KEY empty too) for pure LAN usage without authentication. +ADMIN_PASSWORD= +# API key for Home Assistant and other clients: X-API-Key header, +# "Authorization: Bearer " or ?api_key=. Optional when ADMIN_PASSWORD is set (a key is +# generated and can be regenerated from the UI); setting it here pins it. +# Without ADMIN_PASSWORD, all POST/PUT/DELETE routes and /api/config require it. +# Generate one with: openssl rand -hex 32 APP_API_KEY= +# Lifetime of a web UI login, in hours (default one week). +SESSION_TTL_HOURS=168 +# Optional key signing the login cookies (generated into /data/secrets.json if empty). +SESSION_SECRET= # Keep /api/current.jpg, /api/current.bin and /api/preview.jpg readable without a key # (needed by Home Assistant Generic Camera). Set to false to require ?api_key=. PUBLIC_IMAGE_ENDPOINTS=true @@ -43,7 +54,7 @@ FORWARDED_ALLOW_IPS=* # --- Server ------------------------------------------------------------------ LOG_LEVEL=INFO # Container-internal port; change HOST_PORT instead when using Docker Compose. -# PORT=8000 +# PORT=8080 # DATA_DIR=/data # --- Immich (runtime default) ------------------------------------------------ diff --git a/CLAUDE.md b/CLAUDE.md index 45e83f1..a152472 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -89,10 +89,11 @@ Clean, responsive (mobile/desktop) English web interface allowing users to: ## Security, Privacy & Reverse Proxy Compatibility - **Zero Hardcoded Secrets & Clean Logs:** Never commit API keys, personal local IPs, or passwords. Use `.env` (documented in `.env.example`) and `/data/config.json` (gitignored). Mask tokens/API keys in logs. -- **Adaptive Authentication (`APP_API_KEY`):** - - If `APP_API_KEY` is empty (default for pure LAN usage), API and UI require no authentication. - - If `APP_API_KEY` is set, all `POST`/`PUT`/`DELETE` routes and `/api/config` require the `X-API-Key` header (or `?api_key=` query parameter). - - The UI (`index.html`) must detect `401` responses and display a modal prompting for the API key, storing it in `localStorage`. +- **Adaptive Authentication (`APP_API_KEY`, `ADMIN_PASSWORD`):** + - If both are empty (default for pure LAN usage), API and UI require no authentication. + - If only `APP_API_KEY` is set, all `POST`/`PUT`/`DELETE` routes and `/api/config` require the key (`X-API-Key` header, `Authorization: Bearer` or `?api_key=`). + - If `ADMIN_PASSWORD` is set, the web UI has an `admin` login (signed HttpOnly session cookie, CSRF header `X-Requested-With: SmartFrame` on cookie mutations) and every route except `/api/health`, the login and the public images requires a session or the API key; an API key is generated into `/data/secrets.json` when `APP_API_KEY` is empty and can be viewed/regenerated by the admin. + - The UI (`index.html`) redirects to `./login` on `401`. - Support `PUBLIC_IMAGE_ENDPOINTS=true` (default `true`) so `/api/current.jpg` and `/api/current.bin` remain readable without headers (required for Home Assistant *Generic Camera* and Fraimic pull), while accepting `?api_key=` when set to `false`. - **SSRF & Upload Protection:** Validate external URLs (`http`/`https` only, block unauthorized private/local IP ranges if configured), enforce a 20 MB file size limit, and verify real image magic bytes via Pillow. - **Reverse Proxy Compatibility (Nginx Proxy Manager, Traefik, Caddy, Cloudflare):** diff --git a/README.md b/README.md index 588dd7e..5653a5a 100644 --- a/README.md +++ b/README.md @@ -18,8 +18,33 @@ mkdir -p data # must be writable by PUID:PGID (default 1000:1000) docker compose up -d ``` -- API docs: `http://:8000/docs` -- Health: `http://:8000/api/health` +- API docs: `http://:8080/docs` +- Health: `http://:8080/api/health` + +## Security + +| Setup | Effect | +| --- | --- | +| Nothing set | Pure LAN usage: everything is open. | +| `APP_API_KEY` only | `POST`/`PUT`/`DELETE`, `/api/config`, `/api/immich`, `/api/smart-mix` need the key; reads stay public. | +| `ADMIN_PASSWORD` | Web UI login (`admin` + password). **Everything** needs a session or the API key except `/api/health`, the login and, while `PUBLIC_IMAGE_ENDPOINTS=true`, the image endpoints. | + +- **API key.** Send it as `X-API-Key: `, `Authorization: Bearer ` or `?api_key=`. + With `ADMIN_PASSWORD` and no `APP_API_KEY`, a key is generated into `./data/secrets.json` + (readable by its owner only); the signed-in admin can view, copy and regenerate it + (`GET /api/auth/api-key`, `POST /api/auth/api-key/regenerate`). A key set in `.env` is + pinned and cannot be changed through the API it protects. +- **Login.** `POST /api/auth/login` sets a signed `HttpOnly`, `SameSite=Strict` session + cookie (`Secure` behind HTTPS, scoped to `ROOT_PATH`), valid `SESSION_TTL_HOURS` (one + week). Changing `ADMIN_PASSWORD` signs everyone out. Repeated failures are throttled per + client (exponential backoff, up to 5 minutes). Without `ADMIN_PASSWORD` but with an API + key, the login accepts the API key as the password. +- **CSRF.** Requests authenticated by the cookie that change something must send + `X-Requested-With: SmartFrame`; browsers cannot add it cross-site without a CORS preflight. + API key requests are unaffected. +- `GET /api/auth/session` tells the mode (`open`, `key`, `password`) and whether the caller + is signed in. Home Assistant sensors that poll `/api/status` need the API key once + `ADMIN_PASSWORD` is set. Runtime settings are stored in `./data/config.json` and can be edited with `GET`/`PUT /api/config`. Values saved there take precedence over `.env`, which in turn @@ -146,7 +171,7 @@ IMMICH_URL=http://immich.lan:2283 IMMICH_API_KEY=... # A random photo with Alice and Bob together -curl -X POST http://localhost:8000/api/display/immich -H 'Content-Type: application/json' \ +curl -X POST http://localhost:8080/api/display/immich -H 'Content-Type: application/json' \ -d '{"persons": ["Alice", "Bob"], "match_mode": "all"}' # CLIP search, favorites, or an album @@ -229,7 +254,7 @@ are cropped without face boxes. | `GET /api/immich/albums` | Albums across accounts (`?accounts=`) | | `GET /api/immich/people` / `POST /api/immich/people/refresh` | Resolved people per account, ambiguity and alias mapping | -`GET /api/immich/*` requires the API key when `APP_API_KEY` is set (it lists family member +`GET /api/immich/*` requires the API key (or a login) when authentication is on (it lists family member names). A LAN Immich needs `URL_ALLOWLIST` when `BLOCK_PRIVATE_URLS=true`. ## Frame delivery @@ -264,7 +289,7 @@ rule** every `scheduler.interval_hours` hours (`REFRESH_INTERVAL_HOURS`, default Pin a fixed rule in `scheduler.source_rule` to override the others: ```bash - curl -X PUT http://localhost:8000/api/config -H 'Content-Type: application/json' -d '{"scheduler": {"enabled": true, "source_rule": + curl -X PUT http://localhost:8080/api/config -H 'Content-Type: application/json' -d '{"scheduler": {"enabled": true, "source_rule": {"kind": "immich", "params": {"mode": "favorites", "persons": ["Alice"]}}}}' ``` @@ -294,11 +319,11 @@ rule** every `scheduler.interval_hours` hours (`REFRESH_INTERVAL_HOURS`, default # Home Assistant: a "next photo" button rest_command: frame_next_photo: - url: http://smart-frame.lan:8000/api/refresh + url: http://smart-frame.lan:8080/api/refresh method: POST timeout: 60 # selecting, downloading and dithering a photo takes a few seconds headers: - X-API-Key: !secret smart_frame_api_key # only when APP_API_KEY is set + X-API-Key: !secret smart_frame_api_key # when APP_API_KEY or ADMIN_PASSWORD is set ``` ## Smart Mix and Smart Search @@ -310,7 +335,7 @@ body of the matching display endpoint), and the runner registered for that `kind Adding a provider later needs no change to the configuration. ```bash -curl -X PUT http://localhost:8000/api/config -H 'Content-Type: application/json' -d '{ +curl -X PUT http://localhost:8080/api/config -H 'Content-Type: application/json' -d '{ "scheduler": {"enabled": true, "interval_hours": 3}, "smart_mix": {"enabled": true, "entries": [ {"label": "Family", "kind": "immich", "weight": 5, @@ -346,7 +371,7 @@ curl -X PUT http://localhost:8000/api/config -H 'Content-Type: application/json' **Smart Search** is the same idea for one-off pushes: describe what you want, never an ID. ```bash -curl -X POST http://localhost:8000/api/display/smart-search -H 'Content-Type: application/json' \ +curl -X POST http://localhost:8080/api/display/smart-search -H 'Content-Type: application/json' \ -d '{"query": "rainy sunday", "persons": ["Alice"], "hold_minutes": 120}' curl -X POST .../api/display/smart-search -H 'Content-Type: application/json' \ -d '{"on_this_day": true}' @@ -385,7 +410,7 @@ last refresh (`last_run.entry_label`). # Home Assistant: push a contextual photo on demand, boost the mix while it rains rest_command: frame_smart_search: - url: http://smart-frame.lan:8000/api/display/smart-search + url: http://smart-frame.lan:8080/api/display/smart-search method: POST content_type: application/json payload: '{"query": "{{ query }}", "hold_minutes": {{ hold | default(120) }}}' @@ -393,7 +418,7 @@ rest_command: headers: X-API-Key: !secret smart_frame_api_key frame_rain_boost: - url: http://smart-frame.lan:8000/api/smart-mix/context + url: http://smart-frame.lan:8080/api/smart-mix/context method: POST content_type: application/json payload: '{"queries": ["cozy rainy day"], "weight": 5, "ttl_minutes": 240, "label": "rain"}' @@ -417,7 +442,7 @@ automation: `poster` template. ```bash -curl -X POST http://localhost:8000/api/display/tmdb -H 'Content-Type: application/json' \ +curl -X POST http://localhost:8080/api/display/tmdb -H 'Content-Type: application/json' \ -d '{"query": "Le Fabuleux Destin d'"'"'Amélie Poulain", "media_type": "movie", "year": 2001}' curl -X POST .../api/display/tmdb -H 'Content-Type: application/json' \ -d '{"query": "The Office", "media_type": "tv", "season": 3, "language": "en-US"}' @@ -464,7 +489,7 @@ A non-ephemeral poster (`"ephemeral": false`) becomes the rule replayed by `album` template. ```bash -curl -X POST http://localhost:8000/api/display/now-playing -H 'Content-Type: application/json' \ +curl -X POST http://localhost:8080/api/display/now-playing -H 'Content-Type: application/json' \ -d '{"title": "So What", "artist": "Miles Davis", "album": "Kind of Blue", "duration_seconds": 545, "position_seconds": 12, "style": "vinyl"}' ``` @@ -532,12 +557,12 @@ the app never writes them to its logs. ```yaml rest_command: frame_now_playing: - url: http://smart-frame.lan:8000/api/display/now-playing + url: http://smart-frame.lan:8080/api/display/now-playing method: POST content_type: "application/json; charset=utf-8" timeout: 30 headers: - X-API-Key: !secret smart_frame_api_key # only when APP_API_KEY is set + X-API-Key: !secret smart_frame_api_key # when APP_API_KEY or ADMIN_PASSWORD is set payload: >- {% set p = 'media_player.living_room' %} {% set pic = state_attr(p, 'entity_picture') %} @@ -550,7 +575,7 @@ rest_command: "position_seconds": state_attr(p, 'media_position') } | to_json }} frame_tv_poster: - url: http://smart-frame.lan:8000/api/display/tmdb + url: http://smart-frame.lan:8080/api/display/tmdb method: POST content_type: "application/json; charset=utf-8" timeout: 30 @@ -568,7 +593,7 @@ rest_command: "ttl_minutes": [((state_attr(p, 'media_duration') or 7200) / 60) | int + 15, 1440] | min } | to_json }} frame_cancel_ephemeral: - url: http://smart-frame.lan:8000/api/queue/ephemeral + url: http://smart-frame.lan:8080/api/queue/ephemeral method: DELETE headers: X-API-Key: !secret smart_frame_api_key @@ -616,7 +641,7 @@ python -m venv .venv source .venv/bin/activate # Windows: .venv\Scripts\activate pip install -e ".[dev]" ruff check . && ruff format --check . && mypy app && pytest -DATA_DIR=./data python -m app # serve on http://localhost:8000 +DATA_DIR=./data python -m app # serve on http://localhost:8080 ``` `python scripts/quality_ab.py` renders a dark photo, a bright photo, a poster and an album From b542cee7712bd2dc8d64b3bec03078fa773ae3f0 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sun, 15 Nov 2026 18:45:09 +0100 Subject: [PATCH 74/86] feat: add the web UI dashboard, playground and settings Serve a single-page UI at / (Tailwind + Alpine from CDN, relative URLs, light/dark, responsive) with a live dashboard, a render playground and graphical settings, plus the endpoints it needs: - GET /api/activity: recent renders and masked log lines (ring buffers) - POST /api/playground/render: compare profile/dither variants, never stored - POST /api/display/title-card: typographic card, ephemeral by default - GET /api/tmdb/search and POST /api/tmdb/test - POST /api/immich/test and GET /api/immich/thumbnail/{account}/{kind}/{id} Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- README.md | 40 +- app/api/deps.py | 30 +- app/api/routes/activity.py | 32 + app/api/routes/display.py | 104 ++- app/api/routes/immich.py | 112 ++- app/api/routes/playground.py | 203 +++++ app/api/routes/tmdb.py | 99 ++- app/core/auth.py | 10 +- app/main.py | 23 +- app/providers/immich/client.py | 45 +- app/providers/immich/models.py | 2 + app/providers/immich/provider.py | 1 + app/providers/tmdb/client.py | 9 + app/providers/tmdb/provider.py | 46 +- app/services/activity.py | 147 ++++ app/services/display.py | 11 + app/templates/index.html | 1209 ++++++++++++++++++++++++++++++ tests/immich_fake.py | 7 + tests/test_api.py | 6 +- tests/test_api_immich.py | 9 +- tests/test_root_path.py | 8 +- tests/test_web_ui.py | 357 +++++++++ 22 files changed, 2460 insertions(+), 50 deletions(-) create mode 100644 app/api/routes/activity.py create mode 100644 app/api/routes/playground.py create mode 100644 app/services/activity.py create mode 100644 app/templates/index.html create mode 100644 tests/test_web_ui.py diff --git a/README.md b/README.md index 5653a5a..de78d77 100644 --- a/README.md +++ b/README.md @@ -7,8 +7,7 @@ friendly, runs standalone in Docker. > **Status:** early development (`v0.x`). The core service, the eInk pipeline, frame > delivery (continuous and deep-sleep), the Immich provider, TMDB posters, now-playing -> album covers, ephemeral images and the autonomous scheduler are in place; the web UI is -> being added milestone by milestone. +> album covers, ephemeral images, the autonomous scheduler and the web UI are in place. ## Quickstart @@ -18,15 +17,50 @@ mkdir -p data # must be writable by PUID:PGID (default 1000:1000) docker compose up -d ``` +- Web UI: `http://:8080/` - API docs: `http://:8080/docs` - Health: `http://:8080/api/health` +## Web UI + +A single page served at `/` (Tailwind CSS and Alpine.js from a CDN, no build step). It +follows the system light/dark theme (toggle in the header), works on phones, and only +uses relative URLs, so it runs unchanged behind a reverse proxy on a domain or a sub-path +(`ROOT_PATH`). + +- **Dashboard.** The current composition next to the exact 6-color Spectra output (click + to zoom at actual pixels), the eInk profile and dithering used with the reasons, the mode + (slideshow with the next refresh, or ephemeral with a countdown and *Restore previous + image*), the frame state (battery, Wi-Fi, last seen, queued upload in deep-sleep mode), + recent images and the last log lines. *Next photo* and *Force push* are one click away. +- **Playground.** Search TMDB and preview or send a poster, a Now Playing album cover + (sleeve or vinyl) or a title card. A preview never reaches the frame until you press + *Send this preview*. The **render lab** renders an uploaded image with up to four + profile/dither variants side by side (`auto` against manual choices) without storing or + sending anything. +- **Settings.** Frame and schedule; Immich accounts with *Test connection*, then album + and people pickers with thumbnails; TMDB key with *Test key*; Smart Mix entries with + weight sliders and live percentages; eInk profile and dithering (`auto` by default); + the photo quality gate; the API key (show, copy, regenerate). + +Endpoints added for the UI (all need the API key or a session when authentication is on): + +| Endpoint | Purpose | +| --- | --- | +| `GET /api/activity` | Last ~30 displayed images and ~200 log lines (secrets redacted, in memory only). | +| `POST /api/playground/render` | Multipart image + `variants` (JSON list of `{profile, dither}`, up to 4) + optional `template` (`poster`, `album`, `title_card`): data URLs, the decision and the time of each variant. Never stored or pushed. | +| `POST /api/display/title-card` | `title`, `subtitle`, `caption`, `accent` (`red`, `yellow`, `blue`, `green`, `white`); ephemeral by default (`ttl_minutes`, default 60). | +| `GET /api/tmdb/search?q=` | Matches with a `w185` poster thumbnail URL (`media_type`, `year`, `language`). | +| `POST /api/tmdb/test` | Checks the stored key or an unsaved one. | +| `POST /api/immich/test` | Checks a saved account or an unsaved URL and key: version, people and album counts. | +| `GET /api/immich/thumbnail/{account}/{asset\|person}/{id}` | Album cover or face thumbnail, proxied so the browser never sees Immich keys. | + ## Security | Setup | Effect | | --- | --- | | Nothing set | Pure LAN usage: everything is open. | -| `APP_API_KEY` only | `POST`/`PUT`/`DELETE`, `/api/config`, `/api/immich`, `/api/smart-mix` need the key; reads stay public. | +| `APP_API_KEY` only | `POST`/`PUT`/`DELETE`, `/api/config`, `/api/immich`, `/api/smart-mix`, `/api/tmdb`, `/api/activity` need the key; other reads stay public. Sign in to the web UI with the key. | | `ADMIN_PASSWORD` | Web UI login (`admin` + password). **Everything** needs a session or the API key except `/api/health`, the login and, while `PUBLIC_IMAGE_ENDPOINTS=true`, the image endpoints. | - **API key.** Send it as `X-API-Key: `, `Authorization: Bearer ` or `?api_key=`. diff --git a/app/api/deps.py b/app/api/deps.py index 35853b7..7462d2f 100644 --- a/app/api/deps.py +++ b/app/api/deps.py @@ -9,9 +9,11 @@ from app.core.auth import AuthState from app.core.config_store import ConfigStore from app.core.history_store import HistoryStore +from app.core.security import URLPolicy from app.core.settings import EnvSettings -from app.providers.immich import ImmichProvider, PeopleDirectory -from app.providers.tmdb import PosterResolver +from app.providers.immich import ImmichGateway, ImmichProvider, PeopleDirectory +from app.providers.tmdb import PosterResolver, TmdbProvider +from app.services.activity import ActivityLog from app.services.current_image import CurrentImageStore from app.services.delivery import DeliveryService from app.services.display import DisplayService @@ -80,6 +82,26 @@ def get_now_playing_service(request: Request) -> NowPlayingService: return cast(NowPlayingService, request.app.state.now_playing_service) +def get_immich_gateway(request: Request) -> ImmichGateway: + """Opens validated clients for the configured Immich accounts.""" + return cast(ImmichGateway, request.app.state.immich_gateway) + + +def get_url_policy(request: Request) -> URLPolicy: + """Outbound URL policy (BLOCK_PRIVATE_URLS / URL_ALLOWLIST).""" + return cast(URLPolicy, request.app.state.url_policy) + + +def get_tmdb_provider(request: Request) -> TmdbProvider: + """The TMDB poster provider (search and key checks).""" + return cast(TmdbProvider, request.app.state.tmdb_provider) + + +def get_activity_log(request: Request) -> ActivityLog: + """Recent renders and log lines.""" + return cast(ActivityLog, request.app.state.activity_log) + + def get_people_directory(request: Request) -> PeopleDirectory: """Cache of the people known to each Immich account.""" return cast(PeopleDirectory, request.app.state.people_directory) @@ -94,7 +116,11 @@ def get_people_directory(request: Request) -> PeopleDirectory: DisplayServiceDep = Annotated[DisplayService, Depends(get_display_service)] ImmichProviderDep = Annotated[ImmichProvider, Depends(get_immich_provider)] PeopleDirectoryDep = Annotated[PeopleDirectory, Depends(get_people_directory)] +ImmichGatewayDep = Annotated[ImmichGateway, Depends(get_immich_gateway)] +URLPolicyDep = Annotated[URLPolicy, Depends(get_url_policy)] SchedulerDep = Annotated[SchedulerService, Depends(get_scheduler_service)] EphemeralServiceDep = Annotated[EphemeralService, Depends(get_ephemeral_service)] PosterResolverDep = Annotated[PosterResolver, Depends(get_poster_resolver)] +TmdbProviderDep = Annotated[TmdbProvider, Depends(get_tmdb_provider)] +ActivityLogDep = Annotated[ActivityLog, Depends(get_activity_log)] NowPlayingServiceDep = Annotated[NowPlayingService, Depends(get_now_playing_service)] diff --git a/app/api/routes/activity.py b/app/api/routes/activity.py new file mode 100644 index 0000000..e99a38e --- /dev/null +++ b/app/api/routes/activity.py @@ -0,0 +1,32 @@ +"""Recent activity (renders and log lines) for the web UI dashboard.""" + +from __future__ import annotations + +from typing import Annotated + +from fastapi import APIRouter, Query, Security + +from app.api.deps import ActivityLogDep +from app.core.auth import api_key_scheme +from app.services.activity import MAX_LOG_LINES, ActivitySnapshot + +router = APIRouter(prefix="/api", tags=["system"], dependencies=[Security(api_key_scheme)]) + + +@router.get( + "/activity", + response_model=ActivitySnapshot, + summary="Recent renders and log lines (newest first)", +) +async def activity( + log: ActivityLogDep, + logs: Annotated[ + int, Query(ge=0, le=MAX_LOG_LINES, description="Maximum number of log lines") + ] = MAX_LOG_LINES, +) -> ActivitySnapshot: + """The last displayed images (with their render decision) and the last log lines. + + Kept in memory only (lost on restart). Log lines have secrets redacted. Protected by the + API key (or a web UI session) whenever authentication is enabled. + """ + return log.snapshot(logs=logs) diff --git a/app/api/routes/display.py b/app/api/routes/display.py index 6d50cc0..a6e0d64 100644 --- a/app/api/routes/display.py +++ b/app/api/routes/display.py @@ -3,16 +3,19 @@ from __future__ import annotations import re +from datetime import timedelta from pathlib import PurePath -from typing import Annotated, Any +from typing import Annotated, Any, Final, Literal from fastapi import APIRouter, File, Form, HTTPException, Security, UploadFile +from pydantic import BaseModel, ConfigDict, Field, field_validator from app.api.deps import DisplayServiceDep, SchedulerDep, SettingsDep from app.core.auth import api_key_scheme from app.core.config_models import FitMode from app.core.security import InvalidImageError, PayloadTooLargeError, read_upload -from app.services.display import DisplayResult +from app.processor.templates import TitleCardLayout +from app.services.display import DisplayMeta, DisplayResult router = APIRouter(prefix="/api/display", tags=["display"], dependencies=[Security(api_key_scheme)]) @@ -97,3 +100,100 @@ async def display_upload( if push_to_fraimic: await scheduler.record_manual(None, ephemeral=ephemeral, hold_minutes=hold_minutes) return result + + +# --- Title card --------------------------------------------------------------------------- +TITLE_CARD_SOURCE: Final = "title_card" +#: Accent colors of the rule under the title (exact panel colors). +ACCENTS: Final[dict[str, tuple[int, int, int]]] = { + "red": (255, 0, 0), + "yellow": (255, 255, 0), + "blue": (0, 0, 255), + "green": (0, 255, 0), + "white": (255, 255, 255), +} + + +class TitleCardRequest(BaseModel): + """Body of ``POST /api/display/title-card``.""" + + model_config = ConfigDict(extra="forbid") + + title: str = Field(min_length=1, max_length=200, description="Large centered text") + subtitle: str | None = Field(default=None, max_length=200) + caption: str | None = Field(default=None, max_length=200, description="Small text below") + accent: Literal["red", "yellow", "blue", "green", "white"] = Field( + default="red", description="Color of the rule under the title" + ) + push_to_fraimic: bool = Field( + default=True, description="false only renders a preview (/api/preview.jpg)" + ) + ephemeral: bool = Field( + default=True, description="Temporary: the previous image comes back afterwards" + ) + ttl_minutes: int | None = Field( + default=60, + ge=1, + le=10080, + description="Ephemeral only: minutes before the previous image returns " + "(null = until cancelled or replaced)", + ) + hold_minutes: int | None = Field( + default=None, ge=1, le=10080, description="Protect it from scheduled refreshes" + ) + + @field_validator("title") + @classmethod + def _clean_title(cls, value: str) -> str: + cleaned = _UNSAFE_CHARS.sub(" ", value).strip() + if not cleaned: + raise ValueError("must not be blank") + return cleaned + + @field_validator("subtitle", "caption") + @classmethod + def _clean_text(cls, value: str | None) -> str | None: + if value is None: + return None + return _UNSAFE_CHARS.sub(" ", value).strip() or None + + +@router.post( + "/title-card", + response_model=DisplayResult, + summary="Display a typographic card (title, subtitle, caption)", +) +async def display_title_card( + body: TitleCardRequest, display: DisplayServiceDep, scheduler: SchedulerDep +) -> DisplayResult: + """Render large centered text on black with an accent rule, e.g. a welcome message. + + Ephemeral by default: after ``ttl_minutes`` (or ``DELETE /api/queue/ephemeral``) the + previous image comes back. + """ + layout = TitleCardLayout( + title=body.title, + subtitle=body.subtitle, + caption=body.caption, + accent=ACCENTS[body.accent], + ) + expires_at = ( + scheduler.now() + timedelta(minutes=body.ttl_minutes) + if body.ephemeral and body.ttl_minutes is not None + else None + ) + details: dict[str, Any] = {"subtitle": body.subtitle, "caption": body.caption} + meta = DisplayMeta( + TITLE_CARD_SOURCE, + body.title, + {key: value for key, value in details.items() if value}, + push=body.push_to_fraimic, + ephemeral=body.ephemeral, + expires_at=expires_at, + ) + result = await display.display_layout(None, layout, meta) + if body.push_to_fraimic: + await scheduler.record_manual( + None, ephemeral=body.ephemeral, hold_minutes=body.hold_minutes + ) + return result diff --git a/app/api/routes/immich.py b/app/api/routes/immich.py index b14d523..b56c26f 100644 --- a/app/api/routes/immich.py +++ b/app/api/routes/immich.py @@ -2,23 +2,30 @@ from __future__ import annotations +import asyncio +import re from datetime import datetime -from typing import Annotated, Any +from typing import Annotated, Any, Final, Literal from fastapi import APIRouter, HTTPException, Query, Security -from pydantic import BaseModel, Field +from fastapi.responses import Response +from pydantic import BaseModel, Field, SecretStr, ValidationError from app.api.deps import ( ConfigStoreDep, DisplayServiceDep, + ImmichGatewayDep, ImmichProviderDep, PeopleDirectoryDep, SchedulerDep, + URLPolicyDep, ) from app.api.errors import PROVIDER_ERROR_RESPONSES, provider_http_error from app.core.auth import api_key_scheme -from app.core.security import InvalidImageError +from app.core.config_models import ImmichAccountConfig, is_masked +from app.core.security import InvalidImageError, UnsafeURLError, validate_external_url from app.providers.base import InvalidSelectionError, ProviderError +from app.providers.immich.client import ImmichClient from app.providers.immich.models import AlbumInfo, ImmichDisplayRequest from app.providers.immich.people import PeopleSnapshot, resolve_person from app.providers.immich.provider import ImmichProvider @@ -199,3 +206,102 @@ async def refresh_people( ) -> PeopleResponse: """Bypass the cache and fetch the people lists again.""" return await _people_response(directory, config, accounts, refresh=True) + + +# --- UI helpers: thumbnails and connection test ---------------------------------------------- +_ITEM_ID: Final = re.compile(r"^[A-Za-z0-9-]{1,64}$") +THUMBNAIL_MAX_BYTES: Final = 2 * 1024 * 1024 + + +def _image_type(data: bytes) -> str: + if data[:3] == b"\xff\xd8\xff": + return "image/jpeg" + if data[:8] == b"\x89PNG\r\n\x1a\n": + return "image/png" + if data[:4] == b"RIFF" and data[8:12] == b"WEBP": + return "image/webp" + return "application/octet-stream" + + +@router.get( + "/thumbnail/{account}/{kind}/{item_id}", + responses={**_ERRORS, 200: {"content": {"image/jpeg": {}, "image/webp": {}}}}, + summary="Small thumbnail of an asset (album cover) or a person (face)", +) +async def thumbnail( + account: str, + kind: Literal["asset", "person"], + item_id: str, + gateway: ImmichGatewayDep, +) -> Response: + """Proxy an Immich thumbnail with the account key, so the browser never sees Immich keys.""" + if not _ITEM_ID.match(item_id): + raise HTTPException(status_code=422, detail="Invalid id") + try: + async with gateway.client(account) as client: + if kind == "asset": + data = await client.download( + item_id, variant="thumbnail", max_bytes=THUMBNAIL_MAX_BYTES + ) + else: + data = await client.person_thumbnail(item_id, max_bytes=THUMBNAIL_MAX_BYTES) + except ProviderError as exc: + status = getattr(exc, "status_code", None) + if status == 404: + raise HTTPException(status_code=404, detail="No thumbnail") from exc + raise provider_http_error(exc) from exc + return Response( + data, media_type=_image_type(data), headers={"Cache-Control": "private, max-age=86400"} + ) + + +class ConnectionTestRequest(BaseModel): + """Test a configured account, or unsaved settings typed in the UI.""" + + account: str | None = Field(default=None, description="A configured account name") + url: str | None = Field(default=None, description="Unsaved Immich URL") + api_key: str | None = Field( + default=None, description="Unsaved API key (a masked value means the stored one)" + ) + + +class ConnectionTestResult(BaseModel): + """Outcome of an Immich connection test.""" + + ok: bool + version: str | None = None + people: int | None = None + albums: int | None = None + error: str | None = None + + +@router.post( + "/test", + response_model=ConnectionTestResult, + summary="Test an Immich connection (saved or unsaved settings)", +) +async def test_connection( + body: ConnectionTestRequest, config: ConfigStoreDep, policy: URLPolicyDep +) -> ConnectionTestResult: + """Check reachability, the API key and what the key can see (people and albums).""" + stored = config.config.immich.accounts.get(body.account) if body.account else None + url = body.url or (stored.url if stored else None) + key = body.api_key + if (key is None or is_masked(key)) and stored is not None: + key = stored.api_key.get_secret_value() + if not url or not key: + return ConnectionTestResult(ok=False, error="Give a URL and an API key") + try: + account = ImmichAccountConfig(url=url, api_key=SecretStr(key)) + await validate_external_url(account.url, policy) + except (ValidationError, UnsafeURLError) as exc: + detail = exc.errors()[0]["msg"] if isinstance(exc, ValidationError) else str(exc) + return ConnectionTestResult(ok=False, error=detail) + name = body.account or "test" + try: + async with ImmichClient(name, account) as client: + version = await client.version() + people, albums = await asyncio.gather(client.people(), client.albums()) + except ProviderError as exc: + return ConnectionTestResult(ok=False, error=str(exc)) + return ConnectionTestResult(ok=True, version=version, people=len(people), albums=len(albums)) diff --git a/app/api/routes/playground.py b/app/api/routes/playground.py new file mode 100644 index 0000000..be346d6 --- /dev/null +++ b/app/api/routes/playground.py @@ -0,0 +1,203 @@ +"""Render playground: compare eInk profiles and dithering on an image, without displaying it.""" + +from __future__ import annotations + +import base64 +import json +import time +from dataclasses import replace +from typing import Annotated, Any, Final, Literal + +from fastapi import APIRouter, File, Form, HTTPException, Security, UploadFile +from pydantic import BaseModel, ConfigDict, Field, TypeAdapter, ValidationError + +from app.api.deps import ConfigStoreDep, DisplayServiceDep, SettingsDep +from app.core.auth import api_key_scheme +from app.core.config_models import DitherAlgorithm, EinkProfile, FitMode, RuntimeConfig +from app.core.security import InvalidImageError, PayloadTooLargeError, read_upload +from app.processor.auto import RenderDecision +from app.processor.pipeline import RenderOptions, RenderResult, decode_image, render, render_layout +from app.processor.templates import ( + AlbumLayout, + AlbumStyle, + Layout, + PosterLayout, + TitleCardLayout, +) + +router = APIRouter( + prefix="/api/playground", tags=["playground"], dependencies=[Security(api_key_scheme)] +) + +MAX_VARIANTS: Final = 4 +MAX_TEXT_LENGTH: Final = 200 +PREVIEW_JPEG_QUALITY: Final = 85 +PlaygroundTemplate = Literal["none", "poster", "album", "title_card"] + + +class PlaygroundVariant(BaseModel): + """One rendering to try: ``auto`` lets the engine decide, like a real display.""" + + model_config = ConfigDict(extra="forbid") + + profile: EinkProfile = "auto" + dither: DitherAlgorithm = "auto" + + +_VARIANTS: Final = TypeAdapter(list[PlaygroundVariant]) +DEFAULT_VARIANTS: Final = '[{"profile": "auto", "dither": "auto"}]' + + +class VariantResult(BaseModel): + """The output of one variant, as data URLs ready for an ````.""" + + requested: PlaygroundVariant + decision: RenderDecision | None = Field(description="What was actually used, and why") + composed: str = Field(description="data:image/jpeg URL of the composition (before dither)") + dithered: str = Field(description="data:image/png URL of the exact 6-color panel output") + elapsed_ms: float = Field(description="Rendering time (compose + dither + encode)") + + +class PlaygroundResult(BaseModel): + """Body of ``POST /api/playground/render``.""" + + template: PlaygroundTemplate + frame_size: tuple[int, int] + variants: list[VariantResult] + + +def _parse_variants(raw: str) -> list[PlaygroundVariant]: + try: + variants = _VARIANTS.validate_python(json.loads(raw or DEFAULT_VARIANTS)) + except (ValueError, ValidationError) as exc: + raise HTTPException( + status_code=422, detail="variants must be a JSON list of {profile, dither}" + ) from exc + if not 1 <= len(variants) <= MAX_VARIANTS: + raise HTTPException(status_code=422, detail=f"Give between 1 and {MAX_VARIANTS} variants") + return variants + + +def _layout( + template: PlaygroundTemplate, + title: str | None, + subtitle: str | None, + caption: str | None, + style: AlbumStyle, +) -> Layout | None: + if template == "poster": + return PosterLayout() + if template == "album": + return AlbumLayout(title=title or "Title", artist=subtitle, album=caption, style=style) + if template == "title_card": + return TitleCardLayout(title=title or "Title card", subtitle=subtitle, caption=caption) + return None + + +def _data_url(media_type: str, data: bytes) -> str: + return f"data:{media_type};base64,{base64.b64encode(data).decode('ascii')}" + + +def _run_variants( + data: bytes | None, + layout: Layout | None, + fit: FitMode | None, + config: RuntimeConfig, + variants: list[PlaygroundVariant], +) -> list[VariantResult]: + """Decode once, then render every variant (worker thread).""" + image = decode_image(data) if data is not None else None + base = RenderOptions.from_config(config, fit="contain" if layout is not None else fit) + results: list[VariantResult] = [] + for variant in variants: + eink = config.eink.model_copy( + update={"profile": variant.profile, "dither": variant.dither} + ).effective() + options = replace(base, eink=eink) + started = time.perf_counter() + result: RenderResult + if layout is not None: + result = render_layout(image, layout, options) + elif image is not None: + result = render(image, options) + else: + raise InvalidImageError("No image to render") + elapsed = (time.perf_counter() - started) * 1000 + results.append( + VariantResult( + requested=variant, + decision=result.decision, + composed=_data_url("image/jpeg", result.preview_jpeg(PREVIEW_JPEG_QUALITY)), + dithered=_data_url("image/png", result.dithered_png()), + elapsed_ms=round(elapsed, 1), + ) + ) + return results + + +_RESPONSES: dict[int | str, dict[str, Any]] = { + 413: {"description": "File larger than MAX_UPLOAD_MB"}, + 415: {"description": "Not a supported image"}, + 422: {"description": "Invalid variants, or no image for a template that needs one"}, +} + + +@router.post( + "/render", + response_model=PlaygroundResult, + responses=_RESPONSES, + summary="Render an image with several eInk profiles / dithers (never displayed)", +) +async def render_playground( + settings: SettingsDep, + config: ConfigStoreDep, + display: DisplayServiceDep, + file: Annotated[ + UploadFile | None, File(description="Image (not needed for the title card)") + ] = None, + template: Annotated[ + PlaygroundTemplate, + Form(description="none = a photo with the fit mode; or a composition template"), + ] = "none", + fit: Annotated[FitMode | None, Form(description="Fit mode without a template")] = None, + variants: Annotated[ + str, + Form(description=f"JSON list of up to {MAX_VARIANTS} {{profile, dither}} objects"), + ] = DEFAULT_VARIANTS, + title: Annotated[str | None, Form(max_length=MAX_TEXT_LENGTH)] = None, + subtitle: Annotated[ + str | None, Form(max_length=MAX_TEXT_LENGTH, description="Album artist / card subtitle") + ] = None, + caption: Annotated[ + str | None, Form(max_length=MAX_TEXT_LENGTH, description="Album name / card caption") + ] = None, + style: Annotated[AlbumStyle, Form(description="Album template style")] = "sleeve", +) -> PlaygroundResult: + """Compare renderings side by side, e.g. ``auto`` against ``vivid`` + ``stucki``. + + Each variant returns the composition and the exact 6-color dithered output as data + URLs, the decision actually applied and the rendering time. Nothing is stored, shown + on the frame or added to the history; renders wait for any display in progress. + """ + chosen = _parse_variants(variants) + data: bytes | None = None + if file is not None: + try: + data = await read_upload(file, settings.max_upload_bytes) + except PayloadTooLargeError as exc: + raise HTTPException(status_code=413, detail=str(exc)) from exc + finally: + await file.close() + if data is None and template != "title_card": + raise HTTPException(status_code=422, detail="Upload an image to render") + layout = _layout(template, title, subtitle, caption, style) + snapshot = config.config + try: + results = await display.render_detached( + lambda: _run_variants( + data if template != "title_card" else None, layout, fit, snapshot, chosen + ) + ) + except InvalidImageError as exc: + raise HTTPException(status_code=415, detail=str(exc)) from exc + return PlaygroundResult(template=template, frame_size=snapshot.frame_size, variants=results) diff --git a/app/api/routes/tmdb.py b/app/api/routes/tmdb.py index 23b2596..af00fe4 100644 --- a/app/api/routes/tmdb.py +++ b/app/api/routes/tmdb.py @@ -3,24 +3,38 @@ from __future__ import annotations from datetime import timedelta -from typing import Any +from typing import Annotated, Any, Final -from fastapi import APIRouter, HTTPException, Security +from fastapi import APIRouter, HTTPException, Query, Security +from pydantic import BaseModel, Field -from app.api.deps import ConfigStoreDep, DisplayServiceDep, PosterResolverDep, SchedulerDep +from app.api.deps import ( + ConfigStoreDep, + DisplayServiceDep, + PosterResolverDep, + SchedulerDep, + TmdbProviderDep, +) from app.api.errors import PROVIDER_ERROR_RESPONSES, provider_http_error from app.core.auth import api_key_scheme +from app.core.config_models import is_masked from app.core.config_store import ConfigStore from app.core.security import InvalidImageError from app.providers.base import ProviderError from app.providers.tmdb import PosterResolver -from app.providers.tmdb.models import TmdbDisplayRequest +from app.providers.tmdb.client import image_url +from app.providers.tmdb.models import TmdbDisplayRequest, TmdbMediaType, validate_language from app.services.display import DisplayResult, DisplayService from app.services.scheduler import SchedulerService, tmdb_rule display_router = APIRouter( prefix="/api/display", tags=["display"], dependencies=[Security(api_key_scheme)] ) +router = APIRouter(prefix="/api/tmdb", tags=["tmdb"], dependencies=[Security(api_key_scheme)]) + +#: Poster thumbnails in search results (loaded by the browser from the public TMDB CDN). +THUMBNAIL_SIZE: Final = "w185" +MAX_SEARCH_RESULTS: Final = 12 _ERRORS: dict[int | str, dict[str, Any]] = { **PROVIDER_ERROR_RESPONSES, @@ -104,3 +118,80 @@ async def show_tmdb( hold = body.hold_minutes if body.hold_minutes is not None else settings.hold_minutes await scheduler.record_manual(tmdb_rule(body), ephemeral=body.ephemeral, hold_minutes=hold) return result + + +# --- UI helpers: search and key test ------------------------------------------------------ +class TmdbSearchHit(BaseModel): + """One movie or series in ``GET /api/tmdb/search``.""" + + id: int + media_type: str + title: str + original_title: str | None = None + year: int | None = None + poster_thumbnail: str | None = Field( + default=None, description="Small poster URL on the public TMDB image CDN" + ) + + +@router.get( + "/search", + response_model=list[TmdbSearchHit], + responses=PROVIDER_ERROR_RESPONSES, + summary="Search movies and series (for the web UI picker)", +) +async def search( + tmdb: TmdbProviderDep, + q: Annotated[str, Query(min_length=1, max_length=200, description="Title to search")], + media_type: Annotated[TmdbMediaType, Query(description="movie, tv or multi")] = "multi", + year: Annotated[int | None, Query(ge=1870, le=2200)] = None, + language: Annotated[str | None, Query(description="Overrides tmdb.language")] = None, +) -> list[TmdbSearchHit]: + """The most relevant matches with a poster thumbnail; nothing is displayed.""" + try: + language = validate_language(language) + except ValueError as exc: + raise HTTPException(status_code=422, detail=f"language {exc}") from exc + try: + results = await tmdb.search(q.strip(), media_type, year=year, language=language) + except ProviderError as exc: + raise provider_http_error(exc) from exc + return [ + TmdbSearchHit( + id=result.id, + media_type=result.media_type, + title=result.title, + original_title=result.original_title, + year=result.year, + poster_thumbnail=image_url(result.poster_path, THUMBNAIL_SIZE) + if result.poster_path + else None, + ) + for result in results[:MAX_SEARCH_RESULTS] + ] + + +class TmdbTestRequest(BaseModel): + """Test the stored key, or an unsaved one typed in the UI.""" + + api_key: str | None = Field( + default=None, description="Unsaved key (empty or masked = the stored one)" + ) + + +class TmdbTestResult(BaseModel): + """Outcome of a TMDB key test.""" + + ok: bool + error: str | None = None + + +@router.post("/test", response_model=TmdbTestResult, summary="Test a TMDB API key") +async def test_key(body: TmdbTestRequest, tmdb: TmdbProviderDep) -> TmdbTestResult: + """Check that TMDB is reachable and accepts the key (v3 key or v4 read token).""" + key = None if body.api_key is None or is_masked(body.api_key) else body.api_key + try: + await tmdb.check_key(key) + except ProviderError as exc: + return TmdbTestResult(ok=False, error=str(exc)) + return TmdbTestResult(ok=True) diff --git a/app/core/auth.py b/app/core/auth.py index 7f9eb5c..1ac3a07 100644 --- a/app/core/auth.py +++ b/app/core/auth.py @@ -47,7 +47,15 @@ ADMIN_USER: Final = "admin" MUTATING_METHODS: Final = frozenset({"POST", "PUT", "PATCH", "DELETE"}) -PROTECTED_PREFIXES: Final = ("/api/config", "/api/immich", "/api/smart-mix", "/api/auth/api-key") +PROTECTED_PREFIXES: Final = ( + "/api/config", + "/api/immich", + "/api/smart-mix", + "/api/auth/api-key", + "/api/tmdb", + "/api/activity", + "/api/playground", +) IMAGE_ENDPOINTS: Final = frozenset( { "/api/current.jpg", diff --git a/app/main.py b/app/main.py index 79f3b4d..80991f5 100644 --- a/app/main.py +++ b/app/main.py @@ -16,9 +16,10 @@ from fastapi.encoders import jsonable_encoder from fastapi.exceptions import RequestValidationError from fastapi.middleware.cors import CORSMiddleware -from fastapi.responses import JSONResponse, RedirectResponse +from fastapi.responses import HTMLResponse, JSONResponse from app import __version__ +from app.api.routes import activity as activity_routes from app.api.routes import auth as auth_routes from app.api.routes import config as config_routes from app.api.routes import display as display_routes @@ -26,6 +27,7 @@ from app.api.routes import images as image_routes from app.api.routes import immich as immich_routes from app.api.routes import now_playing as now_playing_routes +from app.api.routes import playground as playground_routes from app.api.routes import queue as queue_routes from app.api.routes import refresh as refresh_routes from app.api.routes import smart_mix as smart_mix_routes @@ -45,6 +47,7 @@ from app.providers.immich import ImmichGateway, ImmichProvider, PeopleDirectory from app.providers.music import ArtworkResolver from app.providers.tmdb import PosterResolver, TmdbProvider +from app.services.activity import ActivityLog from app.services.current_image import CurrentImageStore from app.services.delivery import DeliveryService from app.services.display import DisplayService @@ -88,6 +91,7 @@ def create_app(settings: EnvSettings | None = None) -> FastAPI: settings: Environment settings; defaults to :func:`get_env_settings`. """ settings = settings or get_env_settings() + activity = ActivityLog() auth_state = AuthState( SecretsStore( settings.secrets_path, @@ -101,6 +105,7 @@ def create_app(settings: EnvSettings | None = None) -> FastAPI: @asynccontextmanager async def lifespan(app: FastAPI) -> AsyncIterator[None]: setup_logging(settings.log_level) + activity.attach() _prepare_data_dir(settings) auth_state.load() @@ -133,6 +138,7 @@ async def _on_config_change(_: RuntimeConfig) -> None: ) delivery.load() display = DisplayService(config_store, current_store, delivery, history_store) + display.add_listener(activity.record_render) url_policy = URLPolicy.from_entries( settings.block_private_urls, settings.url_allowlist_entries ) @@ -176,11 +182,15 @@ async def _on_config_change(_: RuntimeConfig) -> None: app.state.delivery_service = delivery app.state.display_service = display app.state.people_directory = people + app.state.immich_gateway = immich_gateway + app.state.url_policy = url_policy app.state.immich_provider = immich app.state.scheduler_service = scheduler app.state.ephemeral_service = ephemeral app.state.image_fetcher = image_fetcher app.state.poster_resolver = poster_resolver + app.state.tmdb_provider = tmdb + app.state.activity_log = activity app.state.now_playing_service = now_playing await ephemeral.start() # before the delivery worker can drop an expired image @@ -208,6 +218,7 @@ async def _on_config_change(_: RuntimeConfig) -> None: await artwork.aclose() await image_fetcher.aclose() logger.info("Smart Frame Engine stopped") + activity.detach() app = FastAPI( title="Smart Frame Engine", @@ -265,11 +276,13 @@ async def _validation_handler(_: Request, exc: RequestValidationError) -> JSONRe app.include_router(smart_mix_routes.router) app.include_router(fraimic_routes.router) app.include_router(queue_routes.router) + app.include_router(tmdb_routes.router) + app.include_router(playground_routes.router) + app.include_router(activity_routes.router) @app.get("/", include_in_schema=False) - async def index(request: Request) -> RedirectResponse: - """Redirect to the API docs (the web UI replaces this in a later milestone).""" - root_path: str = request.scope.get("root_path", "") - return RedirectResponse(url=f"{root_path}/docs", status_code=307) + async def index() -> HTMLResponse: + """The web UI (relative URLs: works under any reverse-proxy sub-path).""" + return HTMLResponse(auth_routes.page("index.html"), headers={"Cache-Control": "no-store"}) return app diff --git a/app/providers/immich/client.py b/app/providers/immich/client.py index fea4ce9..44fa615 100644 --- a/app/providers/immich/client.py +++ b/app/providers/immich/client.py @@ -219,6 +219,33 @@ async def faces(self, asset_id: str) -> list[FaceDto]: """Detected faces of an asset (``GET /api/faces?id=``), with their person.""" return self._parse(_FACES, await self._json("GET", "/api/faces", params={"id": asset_id})) + async def person_thumbnail(self, person_id: str, *, max_bytes: int) -> bytes: + """The face thumbnail of a person (``GET /api/people/{id}/thumbnail``). + + Raises: + ImmichResponseError: Error status (``status_code`` set) or oversized body. + """ + return await self._bytes(f"/api/people/{person_id}/thumbnail", {}, max_bytes) + + async def _bytes(self, path: str, params: dict[str, str | bool], max_bytes: int) -> bytes: + try: + async with self._http.stream( + "GET", path, params=params, headers={"Accept": "*/*"} + ) as response: + self._check(response) + declared = response.headers.get("content-length") + return await read_limited( + response.aiter_bytes(), + max_bytes, + declared_length=int(declared) if declared and declared.isdigit() else None, + ) + except PayloadTooLargeError: + raise ImmichResponseError( + f"Immich asset exceeds the {max_bytes // (1024 * 1024)} MB limit", 413 + ) from None + except httpx.HTTPError as exc: + raise self._fail(exc) from None + async def download( self, asset_id: str, @@ -247,23 +274,7 @@ async def download( else: path = f"/api/assets/{asset_id}/thumbnail" params["size"] = variant - try: - async with self._http.stream( - "GET", path, params=params, headers={"Accept": "*/*"} - ) as response: - self._check(response) - declared = response.headers.get("content-length") - return await read_limited( - response.aiter_bytes(), - max_bytes, - declared_length=int(declared) if declared and declared.isdigit() else None, - ) - except PayloadTooLargeError: - raise ImmichResponseError( - f"Immich asset exceeds the {max_bytes // (1024 * 1024)} MB limit", 413 - ) from None - except httpx.HTTPError as exc: - raise self._fail(exc) from None + return await self._bytes(path, params, max_bytes) class ImmichGateway: diff --git a/app/providers/immich/models.py b/app/providers/immich/models.py index 5c7581b..2adb757 100644 --- a/app/providers/immich/models.py +++ b/app/providers/immich/models.py @@ -31,6 +31,7 @@ class AlbumDto(_Dto): albumName: str = "" assetCount: int = 0 shared: bool = False + albumThumbnailAssetId: str | None = None class ExifDto(_Dto): @@ -116,6 +117,7 @@ class AlbumInfo(BaseModel): name: str asset_count: int shared: bool + thumbnail_asset_id: str | None = None class OnThisDay(BaseModel): diff --git a/app/providers/immich/provider.py b/app/providers/immich/provider.py index 24c4681..28de906 100644 --- a/app/providers/immich/provider.py +++ b/app/providers/immich/provider.py @@ -251,6 +251,7 @@ async def albums( name=album.albumName, asset_count=album.assetCount, shared=album.shared, + thumbnail_asset_id=album.albumThumbnailAssetId, ) ) except ProviderUnavailableError as exc: diff --git a/app/providers/tmdb/client.py b/app/providers/tmdb/client.py index 001e7cb..327a9be 100644 --- a/app/providers/tmdb/client.py +++ b/app/providers/tmdb/client.py @@ -92,6 +92,15 @@ async def _get(self, path: str, params: dict[str, Any]) -> dict[str, Any] | None raise ProviderUnavailableError("TMDB returned an unexpected payload") return payload + async def check(self) -> None: + """Validate the key with a cheap request (``GET /configuration``). + + Raises: + ProviderUnavailableError: Unreachable, rejected key or unexpected answer. + """ + if await self._get("/configuration", {}) is None: + raise ProviderUnavailableError("TMDB answered HTTP 404") + async def search( self, query: str, media_type: TmdbMediaType, *, year: int | None, language: str ) -> list[SearchResult]: diff --git a/app/providers/tmdb/provider.py b/app/providers/tmdb/provider.py index 8e2033b..2b253ff 100644 --- a/app/providers/tmdb/provider.py +++ b/app/providers/tmdb/provider.py @@ -37,7 +37,7 @@ ProviderUnavailableError, ) from app.providers.tmdb.client import TmdbClient, image_url -from app.providers.tmdb.models import SearchResult, TmdbImage, TmdbRequest +from app.providers.tmdb.models import SearchResult, TmdbImage, TmdbMediaType, TmdbRequest from app.providers.tmdb.ranking import ( choose_image_size, parse_language, @@ -85,6 +85,44 @@ def configured(self) -> bool: """Whether a TMDB key is set.""" return bool(self._config_store.config.tmdb.api_key.get_secret_value().strip()) + def _api_key(self) -> str: + api_key = self._config_store.config.tmdb.api_key.get_secret_value().strip() + if not api_key: + raise ProviderNotConfiguredError( + "TMDB is not configured: set TMDB_API_KEY or tmdb.api_key" + ) + return api_key + + async def search( + self, + query: str, + media_type: TmdbMediaType = "multi", + *, + year: int | None = None, + language: str | None = None, + ) -> list[SearchResult]: + """Movies and series matching ``query`` (for pickers; nothing is downloaded). + + Raises: + ProviderNotConfiguredError: No TMDB key. + ProviderUnavailableError: TMDB failed or rejected the key. + """ + api_key = self._api_key() + language = language or self._config_store.config.tmdb.language + async with self._client_factory(api_key) as client: + return await client.search(query, media_type, year=year, language=language) + + async def check_key(self, api_key: str | None = None) -> None: + """Check ``api_key`` (default: the configured one) against TMDB. + + Raises: + ProviderNotConfiguredError: No key given or configured. + ProviderUnavailableError: TMDB is unreachable or rejected the key. + """ + key = (api_key or "").strip() or self._api_key() + async with self._client_factory(key) as client: + await client.check() + async def fetch(self, request: TmdbRequest) -> ImageAsset: """Find the title and download its best poster. @@ -94,11 +132,7 @@ async def fetch(self, request: TmdbRequest) -> ImageAsset: ProviderUnavailableError: TMDB or its image CDN failed. """ config = self._config_store.config.tmdb - api_key = config.api_key.get_secret_value().strip() - if not api_key: - raise ProviderNotConfiguredError( - "TMDB is not configured: set TMDB_API_KEY or tmdb.api_key" - ) + api_key = self._api_key() language = request.language or config.language lang, region = parse_language(language) include = ",".join(dict.fromkeys([lang, "en", "null"])) diff --git a/app/services/activity.py b/app/services/activity.py new file mode 100644 index 0000000..9fb93ed --- /dev/null +++ b/app/services/activity.py @@ -0,0 +1,147 @@ +"""Recent activity for the web UI: the last displayed images and the last log lines. + +Both live in bounded in-memory ring buffers (nothing is persisted): the dashboard only +needs "what happened lately", and the full history stays in the container logs. + +* Renders are recorded by a :class:`~app.services.display.DisplayService` listener, so every + change of the current image (push, ephemeral expiry, revert) appears. +* Log lines are captured by a :class:`logging.Handler` that redacts secrets with the + process-wide :data:`~app.core.logging_config.masking_filter` before storing anything. +""" + +from __future__ import annotations + +import logging +import threading +from collections import deque +from datetime import UTC, datetime +from typing import Final, Literal + +from pydantic import AwareDatetime, BaseModel, Field + +from app.core.logging_config import masking_filter +from app.processor.auto import RenderDecision +from app.services.current_image import CurrentImageMeta + +MAX_RENDERS: Final = 30 +MAX_LOG_LINES: Final = 200 +MAX_MESSAGE_LENGTH: Final = 1000 + +LogLevel = Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] + + +class RenderEvent(BaseModel): + """One change of the current image.""" + + at: AwareDatetime + source: str + title: str | None = None + template: str | None = None + render: RenderDecision | None = None + ephemeral: bool = False + expires_at: AwareDatetime | None = None + sha256: str + + +class LogLine(BaseModel): + """One captured log record (secrets already redacted).""" + + at: AwareDatetime + level: LogLevel + logger: str + message: str + + +class ActivitySnapshot(BaseModel): + """Body of ``GET /api/activity`` (newest first).""" + + renders: list[RenderEvent] = Field(description="Last displayed images, newest first") + logs: list[LogLine] = Field(description="Last log lines, newest first") + + +def _level(record: logging.LogRecord) -> LogLevel: + if record.levelno >= logging.CRITICAL: + return "CRITICAL" + if record.levelno >= logging.ERROR: + return "ERROR" + if record.levelno >= logging.WARNING: + return "WARNING" + return "INFO" if record.levelno >= logging.INFO else "DEBUG" + + +class _RingHandler(logging.Handler): + """Stores formatted, masked records in the activity log.""" + + def __init__(self, sink: ActivityLog, level: int) -> None: + super().__init__(level) + self._sink = sink + + def emit(self, record: logging.LogRecord) -> None: + try: + message = masking_filter.mask(record.getMessage()) + if record.exc_info and record.exc_info[0] is not None: + message = f"{message} ({record.exc_info[0].__name__})" + self._sink.add_log( + LogLine( + at=datetime.fromtimestamp(record.created, tz=UTC), + level=_level(record), + logger=record.name, + message=message[:MAX_MESSAGE_LENGTH], + ) + ) + except Exception: # pragma: no cover - logging must never raise + self.handleError(record) + + +class ActivityLog: + """Bounded buffers of recent renders and log lines (thread-safe).""" + + def __init__(self, *, max_renders: int = MAX_RENDERS, max_logs: int = MAX_LOG_LINES) -> None: + self._lock = threading.Lock() + self._renders: deque[RenderEvent] = deque(maxlen=max_renders) + self._logs: deque[LogLine] = deque(maxlen=max_logs) + self._handler: _RingHandler | None = None + + # --- Renders -------------------------------------------------------------------------- + def record_render(self, meta: CurrentImageMeta) -> None: + """Display listener: remember a new current image.""" + event = RenderEvent( + at=meta.processed_at, + source=meta.source, + title=meta.title, + template=meta.template, + render=meta.render, + ephemeral=meta.ephemeral, + expires_at=meta.expires_at, + sha256=meta.sha256, + ) + with self._lock: + self._renders.append(event) + + # --- Logs ----------------------------------------------------------------------------- + def add_log(self, line: LogLine) -> None: + """Store one log line.""" + with self._lock: + self._logs.append(line) + + def attach(self, logger: logging.Logger | None = None, level: int = logging.INFO) -> None: + """Start capturing records of ``logger`` (default: the root logger).""" + if self._handler is not None: + return + self._handler = _RingHandler(self, level) + (logger or logging.getLogger()).addHandler(self._handler) + + def detach(self, logger: logging.Logger | None = None) -> None: + """Stop capturing log records.""" + if self._handler is None: + return + (logger or logging.getLogger()).removeHandler(self._handler) + self._handler = None + + # --- Reading -------------------------------------------------------------------------- + def snapshot(self, *, logs: int = MAX_LOG_LINES) -> ActivitySnapshot: + """Newest-first copy of both buffers (``logs`` caps the number of log lines).""" + with self._lock: + renders = list(reversed(self._renders)) + lines = list(reversed(self._logs))[: max(0, logs)] + return ActivitySnapshot(renders=renders, logs=lines) diff --git a/app/services/display.py b/app/services/display.py index d07b408..7449f6a 100644 --- a/app/services/display.py +++ b/app/services/display.py @@ -17,6 +17,7 @@ from collections.abc import Callable, Sequence from dataclasses import dataclass from datetime import datetime +from typing import TypeVar from pydantic import BaseModel, Field, JsonValue @@ -38,6 +39,7 @@ logger = logging.getLogger(__name__) DisplayListener = Callable[[CurrentImageMeta], None] +_T = TypeVar("_T") class NoCurrentImageError(LookupError): @@ -225,6 +227,15 @@ async def _display( self._notify(stored) return DisplayResult(image=stored, delivery=delivery) + async def render_detached(self, job: Callable[[], _T]) -> _T: + """Run a rendering ``job`` in a worker thread, serialized with every display. + + Nothing is stored or delivered: used by the render playground, which must not + compete with real displays for memory and CPU. + """ + async with self._render_lock: + return await asyncio.to_thread(job) + # --- Ephemeral support ---------------------------------------------------------------- async def extend_expiry( self, content_key: str, expires_at: datetime | None diff --git a/app/templates/index.html b/app/templates/index.html new file mode 100644 index 0000000..2cc5a49 --- /dev/null +++ b/app/templates/index.html @@ -0,0 +1,1209 @@ + + + + + + + Smart Frame + + + + + + +
+ + +
+
+ + + +
+ + + +
+
+
+ +
+ + +
+
+ +
+
+
+

Now on the frame

+

+

+ + + · +

+
+
+ + +
+
+ + +
+ + +
+ +
+
+

Mode

+ +
+ + +
+ + +
+
+

Frame

+ +
+ +
+ + +
+

Services

+
    +
  • Immich
  • +
  • TMDB
  • +
  • Smart Mix
  • +
  • Version
  • +
+
+
+
+ + +
+
+

Recent images

+

Nothing since the last restart.

+
    + +
+
+
+
+

Logs

+ +
+
+

No log lines.

+ +
+
+
+
+ + +
+
+ +
+
+

Movie or TV poster

+

Search TMDB, then preview or send the poster (ephemeral).

+
+
+ + + +
+

No match.

+
+ +
+
+ Selected: + + + +
+
+ + +
+
+

Now Playing

+

Album cover (Deezer, then MusicBrainz) with the track underneath.

+
+
+ + + + +
+
+ + + +
+
+ + +
+
+

Title card

+

Large text on black, e.g. a welcome message.

+
+
+ + + + + +
+
+ + +
+
+ + +
+
+

Last preview

+ +
+ +

Use Preview on any card: nothing reaches the frame until you send it.

+
+
+ + +
+
+

Render lab

+

Upload an image and compare the automatic choice with manual profiles and dithering. Nothing is stored or sent.

+
+
+
+ +
+ + +
+
+
+

Variants

+ +
+ + +
+
+
+
+ +
+
+ +
+
+
+ + +
+ + +
Loading settings…
+
+ + + + + + + + + + + + + + + + + + +
+
+
+ + +
+
+ + + +
+
+ +
+
+ + +
+ +
+
+ + + + + + + diff --git a/tests/immich_fake.py b/tests/immich_fake.py index 1273baf..5c496a8 100644 --- a/tests/immich_fake.py +++ b/tests/immich_fake.py @@ -78,6 +78,7 @@ def __init__(self, base: str = "http://immich.test", key: str = "good-key") -> N self.base = base self.key = key self.people: list[dict[str, Any]] = [] + self.person_thumbnails: dict[str, bytes] = {} self.albums: list[dict[str, Any]] = [] # each: {"id", "albumName", "assetIds": [...]} self.assets: dict[str, dict[str, Any]] = {} self.faces: dict[str, list[dict[str, Any]]] = {} @@ -142,6 +143,11 @@ def _handle(self, request: httpx.Request) -> httpx.Response: return httpx.Response(401, json={"message": "Invalid API key"}) if path == "/api/people": return self._people(query) + if path.startswith("/api/people/") and path.endswith("/thumbnail"): + person_id = path.split("/")[3] + if person_id in self.person_thumbnails: + return httpx.Response(200, content=self.person_thumbnails[person_id]) + return httpx.Response(404) if path == "/api/albums": return httpx.Response( 200, @@ -151,6 +157,7 @@ def _handle(self, request: httpx.Request) -> httpx.Response: "albumName": a["albumName"], "assetCount": len(a["assetIds"]), "shared": False, + "albumThumbnailAssetId": a["assetIds"][0] if a["assetIds"] else None, } for a in self.albums ], diff --git a/tests/test_api.py b/tests/test_api.py index 14e1056..526f313 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -112,10 +112,10 @@ def test_openapi_documents_api_key_scheme(make_client: ClientFactory) -> None: assert spec["paths"]["/api/config"]["put"]["security"] == [{"APIKeyHeader": []}] -def test_index_redirects_to_docs(make_client: ClientFactory) -> None: +def test_index_serves_the_web_ui(make_client: ClientFactory) -> None: response = make_client().get("/", follow_redirects=False) - assert response.status_code == 307 - assert response.headers["location"] == "/docs" + assert response.status_code == 200 + assert "Smart Frame" in response.text def test_config_api_masks_immich_account_keys(make_client: ClientFactory) -> None: diff --git a/tests/test_api_immich.py b/tests/test_api_immich.py index 7e8b221..508a580 100644 --- a/tests/test_api_immich.py +++ b/tests/test_api_immich.py @@ -187,7 +187,14 @@ def test_albums_endpoint(make_client: ClientFactory) -> None: with servers(fake, frame=False): body = client.get("/api/immich/albums").json() assert body["albums"] == [ - {"account": "default", "id": "al1", "name": "Summer", "asset_count": 2, "shared": False} + { + "account": "default", + "id": "al1", + "name": "Summer", + "asset_count": 2, + "shared": False, + "thumbnail_asset_id": body["albums"][0]["thumbnail_asset_id"], + } ] assert body["errors"] == {} diff --git a/tests/test_root_path.py b/tests/test_root_path.py index d6de1e4..68b3bd5 100644 --- a/tests/test_root_path.py +++ b/tests/test_root_path.py @@ -39,10 +39,12 @@ def test_auth_applies_under_prefixed_paths(make_client: ClientFactory) -> None: assert client.get("/fraimic/api/health").status_code == 200 -def test_index_redirect_honors_root_path(make_client: ClientFactory) -> None: +def test_index_is_served_under_root_path(make_client: ClientFactory) -> None: client = make_client(root_path="/fraimic") - response = client.get("/", follow_redirects=False) - assert response.headers["location"] == "/fraimic/docs" + for path in ("/", "/fraimic/"): + response = client.get(path, follow_redirects=False) + assert response.status_code == 200 + assert "./api/" in response.text and 'fetch("/' not in response.text def test_runner_trusts_forwarded_headers(monkeypatch: pytest.MonkeyPatch) -> None: diff --git a/tests/test_web_ui.py b/tests/test_web_ui.py new file mode 100644 index 0000000..c846e04 --- /dev/null +++ b/tests/test_web_ui.py @@ -0,0 +1,357 @@ +"""Web UI pages and the endpoints added for them (activity, playground, title card, helpers).""" + +from __future__ import annotations + +import base64 +import io +import json +import logging +import re +from collections.abc import Iterator +from contextlib import contextmanager +from typing import Any + +import httpx +import pytest +import respx +from fastapi.testclient import TestClient +from PIL import Image + +from app.api.routes.auth import page +from tests.conftest import ClientFactory +from tests.immich_fake import FakeImmich + +TMDB = "https://api.themoviedb.org/3" +TMDB_KEY = "0123456789abcdef0123456789abcdef" + + +def png_bytes( + size: tuple[int, int] = (320, 240), color: tuple[int, int, int] = (40, 120, 200) +) -> bytes: + buffer = io.BytesIO() + Image.new("RGB", size, color).save(buffer, format="PNG") + return buffer.getvalue() + + +def decode_data_url(url: str) -> Image.Image: + header, payload = url.split(",", 1) + assert header.startswith("data:image/") and header.endswith(";base64") + return Image.open(io.BytesIO(base64.b64decode(payload))) + + +# --- Pages ------------------------------------------------------------------------------ +ABSOLUTE_URL = re.compile(r"""(?:href|src|action)=["']/(?!/)|fetch\(\s*["'`]/|["'`]/api/""") + + +@pytest.mark.parametrize("name", ["index.html", "login.html"]) +def test_pages_only_use_relative_urls(name: str) -> None: + html = page(name) + assert not ABSOLUTE_URL.search(html), ABSOLUTE_URL.search(html) + # Third-party scripts are pinned to exact versions. + for url in re.findall(r'src="(https://[^"]+)"', html): + assert re.search(r"\d+\.\d+\.\d+", url), url + + +def test_index_is_served_at_root(make_client: ClientFactory) -> None: + client = make_client() + response = client.get("/") + assert response.status_code == 200 + assert response.headers["content-type"].startswith("text/html") + assert response.headers["cache-control"] == "no-store" + assert 'x-data="app()"' in response.text + assert client.get("/docs").status_code == 200 + + +def test_index_under_root_path_and_password(make_client: ClientFactory) -> None: + client = make_client(root_path="/fraimic", admin_password="correct horse") + anonymous = client.get("/fraimic/", headers={"Accept": "text/html"}, follow_redirects=False) + assert anonymous.status_code == 303 + assert anonymous.headers["location"] == "/fraimic/login" + + login = client.post( + "/fraimic/api/auth/login", + json={"username": "admin", "password": "correct horse"}, + headers={"X-Requested-With": "SmartFrame"}, + ) + assert login.status_code == 200 + assert client.get("/fraimic/").status_code == 200 + assert client.get("/fraimic/api/activity").status_code == 200 + + +@pytest.mark.parametrize("path", ["/api/activity", "/api/tmdb/search?q=x"]) +def test_ui_helpers_need_the_key_in_key_mode(make_client: ClientFactory, path: str) -> None: + client = make_client(app_api_key="secret-key-1234") + assert client.get(path).status_code == 401 + + +# --- Activity --------------------------------------------------------------------------- +def test_activity_records_renders_and_masked_logs(make_client: ClientFactory) -> None: + client = make_client(app_api_key="secret-key-1234") + headers = {"X-API-Key": "secret-key-1234"} + upload = client.post( + "/api/display/upload", + files={"file": ("beach.png", png_bytes(), "image/png")}, + data={"push_to_fraimic": "true"}, + headers=headers, + ) + assert upload.status_code == 200, upload.text + logging.getLogger("app.test").warning("leaked secret-key-1234 here") + + body = client.get("/api/activity", headers=headers).json() + assert body["renders"][0]["source"] == "upload" + assert body["renders"][0]["title"] == "beach.png" + assert body["renders"][0]["render"]["profile"] + messages = [line["message"] for line in body["logs"]] + assert any("leaked *** here" in message for message in messages) + assert not any("secret-key-1234" in message for message in messages) + + limited = client.get("/api/activity?logs=1", headers=headers).json() + assert len(limited["logs"]) == 1 + + +def test_preview_renders_are_not_activity(make_client: ClientFactory) -> None: + client = make_client() + response = client.post( + "/api/display/upload", + files={"file": ("x.png", png_bytes(), "image/png")}, + data={"push_to_fraimic": "false"}, + ) + assert response.status_code == 200 + assert client.get("/api/activity").json()["renders"] == [] + + +# --- Title card ------------------------------------------------------------------------- +def test_title_card_preview_and_push(make_client: ClientFactory) -> None: + client = make_client() + preview = client.post( + "/api/display/title-card", + json={"title": "Welcome home", "subtitle": "Grandma", "push_to_fraimic": False}, + ) + assert preview.status_code == 200, preview.text + image = preview.json()["image"] + assert image["template"] == "title_card" + assert image["pushed"] is False + assert image["render"]["context"] == "title_card" + assert client.get("/api/status").json()["current_image"] is None + + pushed = client.post( + "/api/display/title-card", json={"title": "Dinner", "accent": "blue", "ttl_minutes": 5} + ) + assert pushed.status_code == 200 + current = client.get("/api/status").json() + assert current["current_image"]["title"] == "Dinner" + assert current["ephemeral"]["active"] is True + assert current["ephemeral"]["expires_at"] is not None + + +@pytest.mark.parametrize( + "body", + [{"title": " "}, {"title": "x", "accent": "purple"}, {"title": "x", "extra": 1}], +) +def test_title_card_validation(make_client: ClientFactory, body: dict[str, Any]) -> None: + assert make_client().post("/api/display/title-card", json=body).status_code == 422 + + +# --- Playground ------------------------------------------------------------------------- +def test_playground_renders_variants_without_displaying(make_client: ClientFactory) -> None: + client = make_client() + variants = [{"profile": "auto", "dither": "auto"}, {"profile": "vivid", "dither": "stucki"}] + response = client.post( + "/api/playground/render", + files={"file": ("p.png", png_bytes(), "image/png")}, + data={"variants": json.dumps(variants)}, + ) + assert response.status_code == 200, response.text + body = response.json() + assert body["template"] == "none" + width, height = body["frame_size"] + assert len(body["variants"]) == 2 + auto, manual = body["variants"] + assert auto["decision"]["automatic"] is True + assert manual["decision"] == { + "context": "photo", + "profile": "vivid", + "dither": "stucki", + "automatic": False, + "reasons": manual["decision"]["reasons"], + } + for variant in body["variants"]: + assert decode_data_url(variant["composed"]).size == (width, height) + dithered = decode_data_url(variant["dithered"]) + assert dithered.size == (width, height) and dithered.mode == "P" + assert variant["elapsed_ms"] > 0 + + status = client.get("/api/status").json() + assert status["current_image"] is None + assert client.get("/api/preview.jpg").status_code == 404 + + +def test_playground_templates(make_client: ClientFactory) -> None: + client = make_client() + card = client.post("/api/playground/render", data={"template": "title_card", "title": "Hello"}) + assert card.status_code == 200, card.text + assert card.json()["variants"][0]["decision"]["context"] == "title_card" + + album = client.post( + "/api/playground/render", + files={"file": ("c.png", png_bytes((300, 300)), "image/png")}, + data={"template": "album", "title": "Billie Jean", "subtitle": "Michael Jackson"}, + ) + assert album.status_code == 200 + assert album.json()["variants"][0]["decision"]["context"] == "album" + + +@pytest.mark.parametrize( + ("data", "files", "status"), + [ + ({}, None, 422), # no image + ({"variants": "not json"}, "png", 422), + ({"variants": json.dumps([{"profile": "nope"}])}, "png", 422), + ({"variants": json.dumps([{}] * 5)}, "png", 422), + ({"variants": "[]"}, "png", 422), + ({}, "text", 415), + ], +) +def test_playground_rejects_bad_input( + make_client: ClientFactory, data: dict[str, str], files: str | None, status: int +) -> None: + upload = None + if files == "png": + upload = {"file": ("p.png", png_bytes(), "image/png")} + elif files == "text": + upload = {"file": ("p.txt", b"not an image at all", "text/plain")} + response = make_client().post("/api/playground/render", data=data, files=upload) + assert response.status_code == status, response.text + + +# --- TMDB helpers ----------------------------------------------------------------------- +@respx.mock +def test_tmdb_search_returns_thumbnails(make_client: ClientFactory) -> None: + route = respx.get(f"{TMDB}/search/multi").respond( + json={ + "results": [ + { + "id": 77338, + "media_type": "movie", + "title": "Intouchables", + "release_date": "2011-11-02", + "poster_path": "/poster.jpg", + }, + {"id": 1, "media_type": "person", "name": "Someone"}, + {"id": 2, "media_type": "tv", "name": "No Poster", "first_air_date": ""}, + ] + } + ) + client = make_client(tmdb_api_key=TMDB_KEY) + response = client.get("/api/tmdb/search", params={"q": " Intouchables ", "language": "en-US"}) + assert response.status_code == 200, response.text + hits = response.json() + assert hits[0] == { + "id": 77338, + "media_type": "movie", + "title": "Intouchables", + "original_title": None, + "year": 2011, + "poster_thumbnail": "https://image.tmdb.org/t/p/w185/poster.jpg", + } + assert hits[1]["poster_thumbnail"] is None and len(hits) == 2 + sent = route.calls.last.request.url.params + assert sent["query"] == "Intouchables" and sent["language"] == "en-US" + + +def test_tmdb_search_errors(make_client: ClientFactory) -> None: + client = make_client() + assert client.get("/api/tmdb/search", params={"q": "x"}).status_code in {409, 503} + keyed = make_client(tmdb_api_key=TMDB_KEY) + bad_language = keyed.get("/api/tmdb/search", params={"q": "x", "language": "french"}) + assert bad_language.status_code == 422 + + +@respx.mock +def test_tmdb_key_test(make_client: ClientFactory) -> None: + route = respx.get(f"{TMDB}/configuration") + route.side_effect = lambda request: httpx.Response( + 200 if request.url.params.get("api_key") == TMDB_KEY else 401, json={} + ) + client = make_client(tmdb_api_key=TMDB_KEY) + masked = client.get("/api/config").json()["config"]["tmdb"]["api_key"] + assert client.post("/api/tmdb/test", json={"api_key": masked}).json() == { + "ok": True, + "error": None, + } + assert client.post("/api/tmdb/test", json={}).json()["ok"] is True + rejected = client.post("/api/tmdb/test", json={"api_key": "wrong"}).json() + assert rejected == {"ok": False, "error": "TMDB rejected the API key"} + + +def test_tmdb_key_test_without_any_key(make_client: ClientFactory) -> None: + result = make_client().post("/api/tmdb/test", json={}).json() + assert result["ok"] is False and "not configured" in result["error"] + + +# --- Immich helpers --------------------------------------------------------------------- +@contextmanager +def immich(fake: FakeImmich) -> Iterator[None]: + with respx.mock(assert_all_called=False) as router: + fake.mount(router) + yield + + +def library() -> FakeImmich: + fake = FakeImmich() + fake.add_person("p1", "Alice") + fake.add_asset("a1", people=[("p1", "Alice")]) + fake.add_album("al1", "Holidays", ["a1"]) + fake.person_thumbnails["p1"] = png_bytes((64, 64)) + fake.files[("a1", "thumbnail")] = png_bytes((250, 250)) + return fake + + +def immich_client(make_client: ClientFactory) -> TestClient: + return make_client(immich_url="http://immich.test", immich_api_key="good-key") + + +def test_album_thumbnails_and_person_faces(make_client: ClientFactory) -> None: + client = immich_client(make_client) + with immich(library()): + albums = client.get("/api/immich/albums").json()["albums"] + assert albums[0]["thumbnail_asset_id"] == "a1" + cover = client.get("/api/immich/thumbnail/default/asset/a1") + assert cover.status_code == 200 + assert cover.headers["cache-control"] == "private, max-age=86400" + face = client.get("/api/immich/thumbnail/default/person/p1") + assert face.status_code == 200 and face.headers["content-type"] == "image/png" + assert client.get("/api/immich/thumbnail/default/person/nobody").status_code == 404 + assert client.get("/api/immich/thumbnail/default/person/bad%20id").status_code == 422 + assert client.get("/api/immich/thumbnail/default/album/a1").status_code == 422 + assert client.get("/api/immich/thumbnail/ghost/asset/a1").status_code == 422 + + +def test_immich_connection_test(make_client: ClientFactory) -> None: + client = immich_client(make_client) + with immich(library()): + stored = client.post("/api/immich/test", json={"account": "default"}).json() + assert stored["ok"] is True and stored["people"] == 1 and stored["albums"] == 1 + assert stored["version"] + + masked = client.get("/api/config").json()["config"]["immich"]["accounts"]["default"] + same = client.post( + "/api/immich/test", json={"account": "default", "api_key": masked["api_key"]} + ).json() + assert same["ok"] is True + + wrong = client.post( + "/api/immich/test", json={"url": "http://immich.test", "api_key": "bad-key"} + ).json() + assert wrong["ok"] is False and wrong["error"] + + missing = client.post("/api/immich/test", json={"url": "http://immich.test"}).json() + assert missing == { + "ok": False, + "version": None, + "people": None, + "albums": None, + "error": "Give a URL and an API key", + } + invalid = client.post("/api/immich/test", json={"url": "ftp://x", "api_key": "k"}).json() + assert invalid["ok"] is False From 8f9d561c6a44cce7a20289569297de624cb7c12b Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sun, 15 Nov 2026 19:56:24 +0100 Subject: [PATCH 75/86] feat: add Family Mode, Random Discovery, ambient context and Zeroconf - Locked Folder assets are never selected, in every pipeline - family settings: members, private albums/people, context override - smart_mix.discovery_share: whole-library random photo with quality gate - POST/GET/DELETE /api/context with per-field TTL persisted in scheduler state - advertise _smartframe._tcp.local. over mDNS (ZEROCONF_ENABLED) - Settings: Family Mode pickers, Discovery slider; dashboard ambient card Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- .env.example | 2 + README.md | 70 ++++++ app/api/routes/context.py | 91 ++++++++ app/core/auth.py | 1 + app/core/config_models.py | 73 ++++++ app/core/context.py | 3 + app/core/settings.py | 5 + app/main.py | 15 ++ app/providers/immich/client.py | 23 ++ app/providers/immich/family.py | 121 ++++++++++ app/providers/immich/models.py | 12 +- app/providers/immich/provider.py | 44 +++- app/services/ambient.py | 257 +++++++++++++++++++++ app/services/discovery.py | 93 ++++++++ app/services/scheduler.py | 73 +++++- app/services/smart_mix.py | 18 +- app/templates/index.html | 128 +++++++++- docker-compose.yml | 2 + pyproject.toml | 1 + tests/conftest.py | 1 + tests/immich_fake.py | 18 ++ tests/test_ambient_family.py | 385 +++++++++++++++++++++++++++++++ tests/test_api.py | 2 + tests/test_api_refresh.py | 8 + tests/test_api_smart_mix.py | 4 +- tests/test_api_tmdb.py | 5 +- tests/test_immich_client.py | 1 + tests/test_smart_mix.py | 5 +- 28 files changed, 1440 insertions(+), 21 deletions(-) create mode 100644 app/api/routes/context.py create mode 100644 app/providers/immich/family.py create mode 100644 app/services/ambient.py create mode 100644 app/services/discovery.py create mode 100644 tests/test_ambient_family.py diff --git a/.env.example b/.env.example index 525d471..ba17314 100644 --- a/.env.example +++ b/.env.example @@ -34,6 +34,8 @@ SESSION_SECRET= # Keep /api/current.jpg, /api/current.bin and /api/preview.jpg readable without a key # (needed by Home Assistant Generic Camera). Set to false to require ?api_key=. PUBLIC_IMAGE_ENDPOINTS=true +# Advertise _smartframe._tcp.local. over mDNS (Docker needs network_mode: host for it). +ZEROCONF_ENABLED=true # Max size of uploaded/downloaded images, in MB. MAX_UPLOAD_MB=20 # Reject external image URLs (posters, album covers, Home Assistant pictures) resolving to diff --git a/README.md b/README.md index de78d77..4c274c2 100644 --- a/README.md +++ b/README.md @@ -469,6 +469,76 @@ automation: - service: rest_command.frame_rain_boost ``` +## Family Mode, Random Discovery and ambient context + +**Locked Folder (always on).** Photos in Immich's Locked Folder are never selected by any +pipeline (Smart Mix, Random Discovery, smart search, refresh), with Family Mode on or off. + +**Family Mode** (`family` settings, Settings → Family Mode) filters every Immich selection +over the *whole library*, automatically, with no per-photo curation: + +| Setting | Effect | +| --- | --- | +| `enabled` | Apply the filters (a live `family_mode` in `/api/context` overrides it). | +| `members` | Recognized people (Immich faces): keep photos showing **at least one** of them. Empty = the whole library. | +| `require_member` | `false` keeps the members list but only applies the exclusions below. | +| `private_albums` | Album names or IDs: every photo in them is excluded (membership cached for `immich.people_cache_ttl_s`). | +| `private_people` | People whose photos are never shown. | + +**Random Discovery** (`smart_mix.discovery_share`, 0 to 0.5, default 0.15): each scheduled +refresh first rolls this share. On a hit it shows a random photo of the whole library +(ignoring the default persons/album filters) with the quality gate enforced, so +screenshots, low-resolution shots, documents and blank frames are skipped, and Family Mode +and the Locked Folder rule applied. If nothing suitable is found, the weighted entries are +used. Memes have no reliable detector: the screenshot rule (no camera EXIF plus a flat or +phone-shaped image) catches many but not all. + +**Ambient context** (`POST`/`GET`/`DELETE /api/context`, API key): short-lived facts from +Home Assistant. Every field expires on its own (`ttl_minutes`, default +`ambient.default_ttl_minutes` = 180) and is stored in `scheduler_state.json`, so it survives +a restart. A field is either the bare value or `{"value" | "values": ..., "ttl_minutes": n}`; +an empty list or text clears a field, `DELETE /api/context?field=presence` clears one. + +| Field | Effect | +| --- | --- | +| `family_mode` (bool) | Forces Family Mode on or off while live. | +| `presence` (names) | Adds a candidate showing any of these people (weight `ambient.boost_weight`). | +| `boost_people` (names) | Same, for people to favour. | +| `boost_tags` (phrases) | Adds a CLIP search candidate (`beach`, `birthday`...). | +| `weather` (keyword) | Adds the CLIP phrase of `ambient.weather_queries` (`sunny`, `rainy`, `cloudy`, `snowy`, `stormy`, `foggy`, `clear-night`; edit the map to taste). | +| `season` | Replaces the calendar season in `{season}` placeholders. | + +Candidates only matter while the Smart Mix is the active rule. The dashboard shows the live +context with its expiries. `/api/smart-mix/context` stays available for one-off rule boosts. + +```yaml +rest_command: + frame_guests_over: + url: http://smart-frame.lan:8080/api/context + method: POST + content_type: application/json + payload: '{"family_mode": {"value": true, "ttl_minutes": 360}}' + headers: + X-API-Key: !secret smart_frame_api_key + frame_context_home: + url: http://smart-frame.lan:8080/api/context + method: POST + content_type: application/json + payload: '{"presence": {{ presence | tojson }}, "weather": "{{ weather }}", "ttl_minutes": 120}' + headers: + X-API-Key: !secret smart_frame_api_key +``` + +### Zeroconf / mDNS + +With `ZEROCONF_ENABLED=true` (default) the engine advertises `_smartframe._tcp.local.` with +TXT records `version`, `path` (`ROOT_PATH`, `/` when empty) and `auth` (`open`, `key` or +`password`). Any error is logged and ignored. Docker's default bridge network drops +multicast: to be discoverable, run the container with `network_mode: host` (and drop the +`ports:` mapping; set `PORT` instead). Home Assistant only discovers this service type +through an integration that declares it, which does not exist yet: add the engine manually +with its URL. + ## Movie and TV posters (TMDB) `POST /api/display/tmdb` finds a movie or series on [TMDB](https://www.themoviedb.org) diff --git a/app/api/routes/context.py b/app/api/routes/context.py new file mode 100644 index 0000000..8bb0cb5 --- /dev/null +++ b/app/api/routes/context.py @@ -0,0 +1,91 @@ +"""Ambient context API: ``POST``/``GET``/``DELETE /api/context``. + +Home Assistant pushes short-lived facts (who is home, the weather, guests over...) and the +engine adapts the Smart Mix and Family Mode. Every field expires by itself. +""" + +from __future__ import annotations + +from typing import Annotated, Literal + +from fastapi import APIRouter, HTTPException, Query, Security +from pydantic import BaseModel, Field + +from app.api.deps import ConfigStoreDep, ImmichProviderDep, SchedulerDep +from app.core.auth import api_key_scheme +from app.services.ambient import AmbientRequest, AmbientState + +router = APIRouter(prefix="/api/context", tags=["context"], dependencies=[Security(api_key_scheme)]) + +AmbientField = Literal["presence", "family_mode", "weather", "season", "boost_tags", "boost_people"] + + +class AmbientView(BaseModel): + """The live ambient context and what it currently does.""" + + context: AmbientState + family_active: bool = Field(description="Whether Family Mode applies right now") + smart_mix_enabled: bool = Field( + description="Presence, boosts and weather only act while the Smart Mix is enabled" + ) + extra_candidates: list[str] = Field(description="Labels of the candidates added to the mix") + + +def _view( + scheduler: SchedulerDep, config: ConfigStoreDep, provider: ImmichProviderDep +) -> AmbientView: + return AmbientView( + context=scheduler.live_ambient(), + family_active=provider.family_active(), + smart_mix_enabled=config.config.smart_mix.enabled, + extra_candidates=[c.label or c.rule.kind for c in scheduler.ambient_extras()], + ) + + +@router.post( + "", + response_model=AmbientView, + responses={422: {"description": "Unknown weather keyword or season"}}, + summary="Set ambient context fields (each expires on its own)", +) +async def set_context( + body: AmbientRequest, + scheduler: SchedulerDep, + config: ConfigStoreDep, + provider: ImmichProviderDep, +) -> AmbientView: + """Merge the given fields into the live context. + + Unset fields are left alone; an empty list or text clears the field. Each field takes + either the bare value or ``{"values"|"value": ..., "ttl_minutes": n}``. + """ + live = scheduler.live_ambient() + try: + updated = body.apply(live, config.config.ambient, scheduler.now()) + except ValueError as exc: + raise HTTPException(status_code=422, detail=str(exc)) from exc + await scheduler.set_ambient(updated) + return _view(scheduler, config, provider) + + +@router.get("", response_model=AmbientView, summary="The live ambient context") +async def get_context( + scheduler: SchedulerDep, config: ConfigStoreDep, provider: ImmichProviderDep +) -> AmbientView: + """Fields that have not expired, with their expiry, and their effect.""" + return _view(scheduler, config, provider) + + +@router.delete("", response_model=AmbientView, summary="Clear the ambient context") +async def clear_context( + scheduler: SchedulerDep, + config: ConfigStoreDep, + provider: ImmichProviderDep, + field: Annotated[AmbientField | None, Query(description="Clear only this field")] = None, +) -> AmbientView: + """Drop every field, or only ``field``.""" + if field is None: + await scheduler.set_ambient(AmbientState()) + else: + await scheduler.set_ambient(scheduler.live_ambient().model_copy(update={field: None})) + return _view(scheduler, config, provider) diff --git a/app/core/auth.py b/app/core/auth.py index 1ac3a07..4f67790 100644 --- a/app/core/auth.py +++ b/app/core/auth.py @@ -51,6 +51,7 @@ "/api/config", "/api/immich", "/api/smart-mix", + "/api/context", "/api/auth/api-key", "/api/tmdb", "/api/activity", diff --git a/app/core/config_models.py b/app/core/config_models.py index 84266f1..183df4d 100644 --- a/app/core/config_models.py +++ b/app/core/config_models.py @@ -99,6 +99,16 @@ class _Section(BaseModel): model_config = ConfigDict(extra="forbid", validate_assignment=True) +DEFAULT_WEATHER_QUERIES: Final[dict[str, str]] = { + "sunny": "bright sunny day outdoors", + "rainy": "cozy rainy day", + "cloudy": "calm cloudy sky landscape", + "snowy": "snow winter landscape", + "stormy": "dramatic sky storm clouds", + "foggy": "misty foggy morning", + "clear-night": "starry night sky", +} + ACCOUNT_NAME_RE: Final = re.compile(r"^[A-Za-z0-9_-]{1,32}$") @@ -570,6 +580,67 @@ class SmartMixConfig(_Section): hemisphere: Literal["north", "south"] = Field( default="north", description="Used to map months to {season}" ) + discovery_share: float = Field( + default=0.15, + ge=0.0, + le=0.5, + description="Random Discovery: chance that a scheduled refresh shows a random photo " + "of the whole library (quality gate and Family Mode still apply) instead of an entry", + ) + + +class FamilyConfig(_Section): + """Family Mode: keep every Immich selection family-friendly, automatically. + + No per-photo curation: the filters run on every candidate of every Immich selection + (Smart Mix, Random Discovery, smart search, refresh). + """ + + enabled: bool = Field( + default=False, description="Apply the filters below (POST /api/context can override)" + ) + members: list[str] = Field( + default_factory=list, + description="Immich recognized people; only photos with at least one of them are used " + "(empty = the whole library)", + ) + require_member: bool = Field( + default=True, description="Enforce `members` (false keeps only the private exclusions)" + ) + private_albums: list[str] = Field( + default_factory=list, description="Album names or IDs whose photos are never shown" + ) + private_people: list[str] = Field( + default_factory=list, description="People whose photos are never shown" + ) + + @field_validator("members", "private_albums", "private_people") + @classmethod + def _clean(cls, value: list[str]) -> list[str]: + return _clean_names(value) + + +class AmbientConfig(_Section): + """How `POST /api/context` signals (weather, presence...) shape the Smart Mix.""" + + weather_queries: dict[str, str] = Field( + default_factory=lambda: dict(DEFAULT_WEATHER_QUERIES), + description="Weather keyword -> CLIP search phrase added to the mix while it is live", + ) + boost_weight: float = Field( + default=3.0, gt=0, le=1000, description="Weight of each ambient candidate in the mix" + ) + default_ttl_minutes: int = Field( + default=180, ge=1, le=10080, description="Lifetime of a context field without ttl_minutes" + ) + + @field_validator("weather_queries") + @classmethod + def _clean_weather(cls, value: dict[str, str]) -> dict[str, str]: + cleaned = {k.strip().casefold(): v.strip() for k, v in value.items()} + if any(not k or not v for k, v in cleaned.items()): + raise ValueError("weather keywords and phrases must not be empty") + return cleaned class SchedulerConfig(_Section): @@ -648,6 +719,8 @@ class RuntimeConfig(BaseModel): eink: EinkConfig = Field(default_factory=EinkConfig) scheduler: SchedulerConfig = Field(default_factory=SchedulerConfig) smart_mix: SmartMixConfig = Field(default_factory=SmartMixConfig) + family: FamilyConfig = Field(default_factory=FamilyConfig) + ambient: AmbientConfig = Field(default_factory=AmbientConfig) quality: QualityConfig = Field(default_factory=QualityConfig) @property diff --git a/app/core/context.py b/app/core/context.py index fab1deb..0e2552d 100644 --- a/app/core/context.py +++ b/app/core/context.py @@ -39,6 +39,7 @@ class RuleContext: now: datetime tz: ZoneInfo hemisphere: Hemisphere = "north" + season_override: Season | None = None @property def local(self) -> datetime: @@ -46,6 +47,8 @@ def local(self) -> datetime: @property def season(self) -> Season: + if self.season_override is not None: + return self.season_override season = _NORTH[self.local.month] return season if self.hemisphere == "north" else _OPPOSITE[season] diff --git a/app/core/settings.py b/app/core/settings.py index 9ae87b7..b170012 100644 --- a/app/core/settings.py +++ b/app/core/settings.py @@ -70,6 +70,11 @@ class EnvSettings(BaseSettings): default="*", description="Proxy IPs trusted for X-Forwarded-* headers" ) + zeroconf_enabled: bool = Field( + default=True, + description="Advertise _smartframe._tcp.local. over mDNS (needs host networking in Docker)", + ) + max_upload_mb: int = Field(default=20, ge=1, le=200, description="Max image size in MB") block_private_urls: bool = Field( default=False, diff --git a/app/main.py b/app/main.py index 80991f5..6500a9e 100644 --- a/app/main.py +++ b/app/main.py @@ -22,6 +22,7 @@ from app.api.routes import activity as activity_routes from app.api.routes import auth as auth_routes from app.api.routes import config as config_routes +from app.api.routes import context as context_routes from app.api.routes import display as display_routes from app.api.routes import fraimic as fraimic_routes from app.api.routes import images as image_routes @@ -50,6 +51,7 @@ from app.services.activity import ActivityLog from app.services.current_image import CurrentImageStore from app.services.delivery import DeliveryService +from app.services.discovery import ZeroconfAdvertiser from app.services.display import DisplayService from app.services.ephemeral import EphemeralService from app.services.now_playing import NowPlayingService @@ -150,6 +152,7 @@ async def _on_config_change(_: RuntimeConfig) -> None: people, history_store, max_bytes=settings.max_upload_bytes, + family_override=lambda: scheduler.family_override(), ) image_fetcher = ImageFetcher(url_policy, settings.max_upload_bytes) tmdb = TmdbProvider(config_store, image_fetcher) @@ -196,6 +199,15 @@ async def _on_config_change(_: RuntimeConfig) -> None: await ephemeral.start() # before the delivery worker can drop an expired image await delivery.start() await scheduler.start() + advertiser: ZeroconfAdvertiser | None = None + if settings.zeroconf_enabled: + advertiser = ZeroconfAdvertiser( + port=settings.port, + version=__version__, + root_path=settings.root_path, + auth=auth_state.mode, + ) + await advertiser.start() config = config_store.config logger.info( "Smart Frame Engine %s started (data_dir=%s, auth=%s, root_path=%r, panel=%s, " @@ -212,6 +224,8 @@ async def _on_config_change(_: RuntimeConfig) -> None: try: yield finally: + if advertiser is not None: + await advertiser.stop() await scheduler.stop() await ephemeral.stop() await delivery.stop() @@ -274,6 +288,7 @@ async def _validation_handler(_: Request, exc: RequestValidationError) -> JSONRe app.include_router(refresh_routes.router) app.include_router(smart_mix_routes.display_router) app.include_router(smart_mix_routes.router) + app.include_router(context_routes.router) app.include_router(fraimic_routes.router) app.include_router(queue_routes.router) app.include_router(tmdb_routes.router) diff --git a/app/providers/immich/client.py b/app/providers/immich/client.py index 44fa615..100b09c 100644 --- a/app/providers/immich/client.py +++ b/app/providers/immich/client.py @@ -50,6 +50,8 @@ CONNECT_TIMEOUT_S: Final = 10.0 READ_TIMEOUT_S: Final = 30.0 PEOPLE_PAGE_SIZE: Final = 500 +ALBUM_PAGE_SIZE: Final = 1000 +MAX_ALBUM_PAGES: Final = 50 MAX_PEOPLE_PAGES: Final = 50 _ASSETS: Final = TypeAdapter(list[AssetDto]) @@ -196,6 +198,27 @@ async def albums(self) -> list[AlbumDto]: """Albums the key can see (owned and shared).""" return self._parse(_ALBUMS, await self._json("GET", "/api/albums")) + async def album_asset_ids(self, album_ids: Sequence[str]) -> set[str]: + """IDs of every asset in the given albums (``POST /api/search/metadata``, paged). + + Immich 3.x no longer lists an album's assets in ``GET /api/albums/{id}``. Archived + assets are included (private albums must be excluded entirely); locked ones never + appear in a search unless asked for. + """ + found: set[str] = set() + for page in range(1, MAX_ALBUM_PAGES + 1): + body = {"albumIds": list(album_ids), "page": page, "size": ALBUM_PAGE_SIZE} + data = await self._json("POST", "/api/search/metadata", json=body) + assets = data.get("assets", {}) if isinstance(data, dict) else None + if not isinstance(assets, dict): + raise ImmichResponseError( + f"Immich account {self.name!r} returned a bad search result" + ) + found.update(asset.id for asset in self._parse(_ASSETS, assets.get("items", []))) + if not assets.get("nextPage"): + break + return found + async def search_random(self, filters: SearchFilters, size: int) -> list[AssetDto]: """``POST /api/search/random``.""" data = await self._json("POST", "/api/search/random", json=filters.body(size)) diff --git a/app/providers/immich/family.py b/app/providers/immich/family.py new file mode 100644 index 0000000..2d09945 --- /dev/null +++ b/app/providers/immich/family.py @@ -0,0 +1,121 @@ +"""Family Mode filters for Immich candidates (and the always-on Locked Folder rule). + +Two independent layers: + +* **Locked Folder** (always on): assets Immich marks ``locked`` are never selected, whatever + the mode, unless a caller asks for one explicitly by asset ID (no such path exists today). +* **Family Mode** (``family`` settings, overridable by ``POST /api/context``): keeps photos + showing at least one *member* (when members are set) and drops photos in a *private album* + or showing a *private person*. It needs no per-photo curation: the rules are evaluated + against every candidate. + +The set of private-album asset IDs is cached per account with the people-cache TTL. +""" + +from __future__ import annotations + +import logging +import time +from collections.abc import Callable +from dataclasses import dataclass + +from app.core.config_models import FamilyConfig +from app.core.config_store import ConfigStore +from app.providers.immich.client import ImmichClient, ImmichGateway +from app.providers.immich.models import AssetDto +from app.providers.immich.people import PeopleDirectory, resolve_person + +logger = logging.getLogger(__name__) + +LOCKED = "locked" + + +def is_locked(asset: AssetDto) -> bool: + """Whether the asset lives in Immich's Locked Folder.""" + return asset.visibility.lower() == LOCKED + + +@dataclass(frozen=True, slots=True) +class FamilyRules: + """The Family Mode rules resolved for one account.""" + + member_ids: frozenset[str] = frozenset() + require_member: bool = False + private_people_ids: frozenset[str] = frozenset() + private_asset_ids: frozenset[str] = frozenset() + + def allows(self, asset: AssetDto) -> bool: + """Whether Family Mode lets this asset through.""" + if asset.id in self.private_asset_ids: + return False + present = {person.id for person in asset.people} + if present & self.private_people_ids: + return False + return not (self.require_member and not present & self.member_ids) + + +class FamilyDirectory: + """Resolves :class:`FamilyRules` per account, caching private-album membership.""" + + def __init__( + self, + config_store: ConfigStore, + gateway: ImmichGateway, + people: PeopleDirectory, + *, + clock: Callable[[], float] = time.monotonic, + ) -> None: + self._config_store = config_store + self._gateway = gateway + self._people = people + self._clock = clock + self._albums: dict[tuple[str, tuple[str, ...]], tuple[float, frozenset[str]]] = {} + + async def rules(self, account: str, client: ImmichClient, family: FamilyConfig) -> FamilyRules: + """Rules for ``account`` (unknown names are ignored there: other accounts may know them).""" + immich = self._config_store.config.immich + people = await self._people.get(account) + + def ids(names: list[str]) -> frozenset[str]: + return frozenset( + person_id + for name in names + for person_id in resolve_person(name, account, people, immich.person_aliases) + ) + + return FamilyRules( + member_ids=ids(family.members), + require_member=family.require_member and bool(family.members), + private_people_ids=ids(family.private_people), + private_asset_ids=await self._private_assets(account, client, family.private_albums), + ) + + async def _private_assets( + self, account: str, client: ImmichClient, albums: list[str] + ) -> frozenset[str]: + if not albums: + return frozenset() + key = (account, tuple(sorted(albums, key=str.casefold))) + ttl = self._config_store.config.immich.people_cache_ttl_s + cached = self._albums.get(key) + if cached is not None and self._clock() - cached[0] < ttl: + return cached[1] + wanted = {name.casefold() for name in albums} + album_ids = [ + album.id + for album in await client.albums() + if album.id.casefold() in wanted or album.albumName.casefold() in wanted + ] + assets = frozenset(await client.album_asset_ids(album_ids)) if album_ids else frozenset() + self._albums[key] = (self._clock(), assets) + logger.info( + "Family Mode: %d private album(s), %d asset(s) excluded in account %r", + len(album_ids), + len(assets), + account, + ) + return assets + + def forget(self) -> None: + """Drop the cached private-album membership.""" + self._albums.clear() diff --git a/app/providers/immich/models.py b/app/providers/immich/models.py index 2adb757..2f9843f 100644 --- a/app/providers/immich/models.py +++ b/app/providers/immich/models.py @@ -55,6 +55,7 @@ class AssetDto(_Dto): isArchived: bool = False isTrashed: bool = False isEdited: bool = False + visibility: str = "timeline" localDateTime: str | None = None fileCreatedAt: str | None = None width: int | None = None @@ -93,7 +94,12 @@ class SearchFilters: def body(self, size: int) -> dict[str, object]: """JSON body for ``/search/random`` and ``/search/smart``.""" - body: dict[str, object] = {"type": "IMAGE", "size": size, "withExif": True} + body: dict[str, object] = { + "type": "IMAGE", + "size": size, + "withExif": True, + "withPeople": True, + } if self.person_ids: body["personIds"] = list(self.person_ids) if self.album_ids: @@ -206,6 +212,10 @@ class ImmichDisplayRequest(BaseModel): le=10080, description="Keep this image up for at least this long before a scheduled refresh", ) + whole_library: bool = Field( + default=False, + description="Ignore the default persons, album and favorites filters (Random Discovery)", + ) skip_quality_gate: bool | None = Field( default=None, description="Skip the photo suitability check. Default: skipped in album mode " diff --git a/app/providers/immich/provider.py b/app/providers/immich/provider.py index 28de906..474315e 100644 --- a/app/providers/immich/provider.py +++ b/app/providers/immich/provider.py @@ -38,6 +38,7 @@ from app.providers.immich.client import ImmichClient, ImmichGateway, ImmichResponseError from app.providers.immich.dates import DateWindow, on_this_day_windows from app.providers.immich.faces import face_regions +from app.providers.immich.family import FamilyDirectory, FamilyRules, is_locked from app.providers.immich.models import ( AlbumInfo, AssetDto, @@ -74,6 +75,7 @@ class _Plan: queries: tuple[str, ...] size: int windows: tuple[DateWindow | None, ...] = (None,) + family: bool = False @dataclass(slots=True) @@ -83,6 +85,7 @@ class _AccountResult: known_names: list[str] = field(default_factory=list) target_ids: set[str] = field(default_factory=set) album_found: bool = False + rules: FamilyRules | None = None @dataclass(frozen=True, slots=True) @@ -178,6 +181,8 @@ def __init__( max_bytes: int, rng: random.Random | None = None, clock: Callable[[], datetime] | None = None, + family: FamilyDirectory | None = None, + family_override: Callable[[], bool | None] | None = None, ) -> None: self._config_store = config_store self._gateway = gateway @@ -186,6 +191,13 @@ def __init__( self._max_bytes = max_bytes self._rng = rng or random.Random() # noqa: S311 - not security relevant self._clock = clock or (lambda: datetime.now(UTC)) + self._family = family or FamilyDirectory(config_store, gateway, people) + self._family_override = family_override or (lambda: None) + + def family_active(self) -> bool: + """Whether Family Mode applies now (a live ambient context overrides the setting).""" + override = self._family_override() + return self._config_store.config.family.enabled if override is None else override # --- public API ---------------------------------------------------------------------- async def fetch(self, request: ImmichDisplayRequest) -> ImageAsset: @@ -219,6 +231,9 @@ async def fetch(self, request: ImmichDisplayRequest) -> ImageAsset: account_result = results[chosen.account] async with self._gateway.client(chosen.account) as client: asset = await client.asset(chosen.asset.id) + rules = account_result.rules + if is_locked(asset) or (rules is not None and not rules.allows(asset)): + raise NoCandidateError("The selected photo is not allowed (Locked Folder/Family)") data, quality = await self._download(client, asset) regions = await self._regions(client, asset, account_result.target_ids) title, details = build_title_and_details(chosen.account, asset, quality, len(regions)) @@ -261,24 +276,36 @@ async def albums( # --- planning ------------------------------------------------------------------------ def _plan(self, request: ImmichDisplayRequest, config: ImmichConfig) -> _Plan: - persons = config.persons if request.persons is None else request.persons - always = config.always_include if request.always_include is None else request.always_include + whole = request.whole_library + persons = [] if whole else (config.persons if request.persons is None else request.persons) + if whole: + always: list[str] = [] + elif request.always_include is None: + always = config.always_include + else: + always = request.always_include album_id = (request.album_id or "").strip() album_name = (request.album_name or "").strip() - if not album_id and not album_name: + if not album_id and not album_name and not whole: album_name = config.album.strip() if request.mode == "album" and not album_id and not album_name: raise InvalidSelectionError("mode 'album' needs album_name or album_id") + names = _merge_names(persons, always) + family = self.family_active() + family_config = self._config_store.config.family + if family and not names and family_config.members and family_config.require_member: + names = _merge_names(family_config.members, ()) return _Plan( - names=_merge_names(persons, always), + names=names, match_mode=request.match_mode or config.match_mode, album_name=album_name, album_id=album_id, - favorites=request.mode == "favorites" or config.favorites_only, + favorites=request.mode == "favorites" or (config.favorites_only and not whole), exclude_archived=config.exclude_archived, queries=tuple(request.clip_queries) if request.mode == "search" else (), size=config.search_candidates, windows=self._windows(request), + family=family, ) def _windows(self, request: ImmichDisplayRequest) -> tuple[DateWindow | None, ...]: @@ -336,6 +363,11 @@ async def _gather(self, account: str, plan: _Plan, config: ImmichConfig) -> _Acc if asset.id not in seen: seen.add(asset.id) result.assets.append(asset) + if plan.family: + result.rules = await self._family.rules( + account, client, self._config_store.config.family + ) + result.assets = [a for a in result.assets if result.rules.allows(a)] return result @staticmethod @@ -384,7 +416,7 @@ def _merge(results: dict[str, _AccountResult]) -> list[_Candidate]: seen: set[str] = set() for account, result in results.items(): for asset in result.assets: - if asset.isTrashed or asset.type.upper() != "IMAGE": + if asset.isTrashed or asset.type.upper() != "IMAGE" or is_locked(asset): continue key = history_key(account, asset) if key not in seen: diff --git a/app/services/ambient.py b/app/services/ambient.py new file mode 100644 index 0000000..57d76dc --- /dev/null +++ b/app/services/ambient.py @@ -0,0 +1,257 @@ +"""Ambient context: short-lived signals (presence, weather, season...) that shape the mix. + +Home Assistant (or anything else) posts facts such as "Alice is home", "it is rainy" or +"guests are over" to ``POST /api/context``. Every field expires on its own (``ttl_minutes``) +and the live fields are stored in ``scheduler_state.json``, so they survive a restart. + +Effects: + +* ``family_mode`` overrides ``family.enabled`` while live; +* ``presence`` and ``boost_people`` add an Immich candidate showing any of those people; +* ``boost_tags`` and ``weather`` (through ``ambient.weather_queries``) add CLIP search + candidates; +* ``season`` replaces the calendar season in ``{season}`` placeholders. + +The extra candidates join the Smart Mix pool with ``ambient.boost_weight``; they only matter +while the Smart Mix is the active rule. +""" + +from __future__ import annotations + +from datetime import datetime, timedelta +from typing import Final, Literal + +from pydantic import AwareDatetime, BaseModel, ConfigDict, Field, field_validator + +from app.core.config_models import AmbientConfig, SourceRule +from app.services.smart_mix import MixCandidate + +Season = Literal["spring", "summer", "autumn", "winter"] +MAX_ITEMS: Final = 20 +MAX_MINUTES: Final = 10080 # one week + + +def _clean(values: list[str]) -> list[str]: + seen: dict[str, str] = {} + for value in values: + stripped = value.strip() + if stripped: + seen.setdefault(stripped.casefold(), stripped) + return list(seen.values()) + + +class TimedList(BaseModel): + """A list of names or phrases with an expiry.""" + + model_config = ConfigDict(extra="forbid") + + values: list[str] = Field(max_length=MAX_ITEMS) + expires_at: AwareDatetime + + _normalize = field_validator("values")(_clean) + + +class TimedText(BaseModel): + """One word or phrase with an expiry.""" + + model_config = ConfigDict(extra="forbid") + + value: str = Field(min_length=1, max_length=80) + expires_at: AwareDatetime + + +class TimedFlag(BaseModel): + """A boolean with an expiry.""" + + model_config = ConfigDict(extra="forbid") + + value: bool + expires_at: AwareDatetime + + +class AmbientState(BaseModel): + """The live ambient fields (``None`` = not set).""" + + model_config = ConfigDict(extra="ignore") + + presence: TimedList | None = None + family_mode: TimedFlag | None = None + weather: TimedText | None = None + season: TimedText | None = None + boost_tags: TimedList | None = None + boost_people: TimedList | None = None + + def live(self, now: datetime) -> AmbientState: + """A copy without the expired fields.""" + update = { + name: None + for name in AMBIENT_FIELDS + if (entry := getattr(self, name)) is not None and entry.expires_at <= now + } + return self.model_copy(update=update) + + @property + def empty(self) -> bool: + """Whether no field is set.""" + return all(getattr(self, name) is None for name in AMBIENT_FIELDS) + + def season_override(self) -> Season | None: + """The overriding season, if one is set and valid.""" + if self.season is not None and self.season.value in SEASONS: + return self.season.value # type: ignore[return-value] + return None + + +AMBIENT_FIELDS: Final = tuple(AmbientState.model_fields) +SEASONS: Final = ("spring", "summer", "autumn", "winter") + + +class ListInput(BaseModel): + """``{"values": [...], "ttl_minutes": 30}``: a list with its own lifetime.""" + + model_config = ConfigDict(extra="forbid") + + values: list[str] = Field(max_length=MAX_ITEMS) + ttl_minutes: int | None = Field(default=None, ge=1, le=MAX_MINUTES) + + +class TextInput(BaseModel): + """``{"value": "rainy", "ttl_minutes": 30}``.""" + + model_config = ConfigDict(extra="forbid") + + value: str = Field(max_length=80) + ttl_minutes: int | None = Field(default=None, ge=1, le=MAX_MINUTES) + + +class FlagInput(BaseModel): + """``{"value": true, "ttl_minutes": 30}``.""" + + model_config = ConfigDict(extra="forbid") + + value: bool + ttl_minutes: int | None = Field(default=None, ge=1, le=MAX_MINUTES) + + +def _fresh_list(given: ListInput | list[str], default_ttl: int, now: datetime) -> TimedList | None: + values, ttl = ( + (given.values, given.ttl_minutes) if isinstance(given, ListInput) else (given, None) + ) + cleaned = _clean(values) + if not cleaned: + return None # an empty list clears the field + return TimedList(values=cleaned, expires_at=now + timedelta(minutes=ttl or default_ttl)) + + +def _fresh_text(given: TextInput | str, default_ttl: int, now: datetime) -> TimedText | None: + value, ttl = (given.value, given.ttl_minutes) if isinstance(given, TextInput) else (given, None) + value = value.strip() + if not value: + return None + return TimedText(value=value, expires_at=now + timedelta(minutes=ttl or default_ttl)) + + +class AmbientRequest(BaseModel): + """Body of ``POST /api/context``; unset fields keep their value, empty ones clear it. + + Each field is either the bare value or an object with its own ``ttl_minutes``; + ``ttl_minutes`` at the top level is the default for fields without one. + """ + + model_config = ConfigDict(extra="forbid") + + presence: ListInput | list[str] | None = Field( + default=None, description="People at home (Immich names): their photos are boosted" + ) + family_mode: FlagInput | bool | None = Field( + default=None, description="Temporarily forces Family Mode on or off" + ) + weather: TextInput | str | None = Field( + default=None, description="Keyword of ambient.weather_queries, e.g. rainy" + ) + season: TextInput | Season | None = Field( + default=None, description="Replaces the calendar season in {season} placeholders" + ) + boost_tags: ListInput | list[str] | None = Field( + default=None, description="CLIP search phrases to favour (e.g. beach, birthday)" + ) + boost_people: ListInput | list[str] | None = Field( + default=None, description="People (Immich names) to favour" + ) + ttl_minutes: int | None = Field( + default=None, ge=1, le=MAX_MINUTES, description="Default lifetime of the fields below" + ) + + def apply(self, state: AmbientState, config: AmbientConfig, now: datetime) -> AmbientState: + """``state`` updated with the fields of this request. + + Raises: + ValueError: Unknown weather keyword or season. + """ + ttl = self.ttl_minutes or config.default_ttl_minutes + update: dict[str, TimedList | TimedText | TimedFlag | None] = {} + for name in ("presence", "boost_tags", "boost_people"): + given = getattr(self, name) + if given is not None: + update[name] = _fresh_list(given, ttl, now) + if self.family_mode is not None: + flag = self.family_mode + value, own = ( + (flag.value, flag.ttl_minutes) if isinstance(flag, FlagInput) else (flag, None) + ) + update["family_mode"] = TimedFlag( + value=value, expires_at=now + timedelta(minutes=own or ttl) + ) + if self.weather is not None: + weather = _fresh_text(self.weather, ttl, now) + if weather is not None: + weather = weather.model_copy(update={"value": weather.value.casefold()}) + if weather.value not in config.weather_queries: + known = ", ".join(sorted(config.weather_queries)) + raise ValueError(f"Unknown weather {weather.value!r}; configured: {known}") + update["weather"] = weather + if self.season is not None: + season = _fresh_text(self.season, ttl, now) + if season is not None: + season = season.model_copy(update={"value": season.value.casefold()}) + if season.value not in SEASONS: + raise ValueError(f"Unknown season {season.value!r}; use {', '.join(SEASONS)}") + update["season"] = season + return state.model_copy(update=update) + + +def ambient_candidates(state: AmbientState, config: AmbientConfig) -> list[MixCandidate]: + """Smart Mix candidates implied by the live ambient fields.""" + weight = config.boost_weight + candidates: list[MixCandidate] = [] + people = _clean( + [ + *(state.presence.values if state.presence else []), + *(state.boost_people.values if state.boost_people else []), + ] + ) + if people: + rule = SourceRule( + kind="immich", + params={ + "mode": "random", + "persons": list(people), + "always_include": [], + "match_mode": "any", + }, + ) + candidates.append(MixCandidate(rule, weight, None, "ambient:people")) + if state.boost_tags is not None and state.boost_tags.values: + rule = SourceRule( + kind="immich", + params={"mode": "search", "clip_queries": list(state.boost_tags.values)}, + ) + candidates.append(MixCandidate(rule, weight, None, "ambient:tags")) + if state.weather is not None: + phrase = config.weather_queries.get(state.weather.value) + if phrase: + rule = SourceRule(kind="immich", params={"mode": "search", "clip_queries": [phrase]}) + candidates.append( + MixCandidate(rule, weight, None, f"ambient:weather:{state.weather.value}") + ) + return candidates diff --git a/app/services/discovery.py b/app/services/discovery.py new file mode 100644 index 0000000..aba5c97 --- /dev/null +++ b/app/services/discovery.py @@ -0,0 +1,93 @@ +"""mDNS / Zeroconf: advertise ``_smartframe._tcp.local.`` so other devices can find the engine. + +The record carries TXT properties ``version``, ``path`` (``ROOT_PATH``) and ``auth`` +(``none``, ``key`` or ``password``). Advertising is best effort: any failure (no multicast +in a bridged container, no network...) is logged and ignored, the engine runs regardless. +In Docker, mDNS needs ``network_mode: host``. +""" + +from __future__ import annotations + +import logging +import re +import socket +from collections.abc import Callable +from typing import Any, Final + +from zeroconf import IPVersion, ServiceInfo +from zeroconf.asyncio import AsyncZeroconf + +logger = logging.getLogger(__name__) + +SERVICE_TYPE: Final = "_smartframe._tcp.local." +_LABEL_RE: Final = re.compile(r"[^A-Za-z0-9 _-]+") + + +def local_addresses() -> list[str]: + """IPv4 addresses of this host's outgoing interface (no packet is sent).""" + addresses: list[str] = [] + probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + try: + probe.connect(("10.255.255.255", 1)) + addresses.append(str(probe.getsockname()[0])) + except OSError: + pass + finally: + probe.close() + return [a for a in addresses if not a.startswith("0.")] or ["127.0.0.1"] + + +class ZeroconfAdvertiser: + """Registers and unregisters the service; never raises.""" + + def __init__( + self, + *, + port: int, + version: str, + root_path: str, + auth: str, + instance: str = "Smart Frame Engine", + zeroconf_factory: Callable[[], Any] = lambda: AsyncZeroconf(ip_version=IPVersion.V4Only), + addresses: Callable[[], list[str]] = local_addresses, + ) -> None: + label = _LABEL_RE.sub("", instance).strip()[:60] or "Smart Frame Engine" + host = re.sub(r"[^a-z0-9-]+", "-", socket.gethostname().lower()).strip("-") or "smartframe" + self._info = ServiceInfo( + SERVICE_TYPE, + f"{label}.{SERVICE_TYPE}", + port=port, + properties={"version": version, "path": root_path or "/", "auth": auth}, + server=f"{host}.local.", + parsed_addresses=addresses(), + ) + self._factory = zeroconf_factory + self._zeroconf: Any | None = None + + @property + def active(self) -> bool: + """Whether the service is currently advertised.""" + return self._zeroconf is not None + + async def start(self) -> bool: + """Advertise the service; ``False`` (logged) when it could not be registered.""" + try: + zeroconf = self._factory() + await zeroconf.async_register_service(self._info) + except Exception as exc: + logger.warning("Zeroconf advertising disabled: %s: %s", type(exc).__name__, exc) + return False + self._zeroconf = zeroconf + logger.info("Advertising %s on port %s (mDNS)", self._info.name, self._info.port) + return True + + async def stop(self) -> None: + """Withdraw the service (idempotent).""" + zeroconf, self._zeroconf = self._zeroconf, None + if zeroconf is None: + return + try: + await zeroconf.async_unregister_service(self._info) + await zeroconf.async_close() + except Exception as exc: + logger.warning("Zeroconf shutdown failed: %s: %s", type(exc).__name__, exc) diff --git a/app/services/scheduler.py b/app/services/scheduler.py index f5395a3..b485c31 100644 --- a/app/services/scheduler.py +++ b/app/services/scheduler.py @@ -42,7 +42,7 @@ from apscheduler.triggers.date import DateTrigger from pydantic import AwareDatetime, BaseModel, ConfigDict, Field, JsonValue, ValidationError -from app.core.config_models import RuntimeConfig, SchedulerConfig, SourceRule +from app.core.config_models import RuntimeConfig, SchedulerConfig, SmartMixConfig, SourceRule from app.core.config_store import ConfigStore from app.core.context import RuleContext, expand_params from app.core.json_store import atomic_write_json, read_json @@ -51,6 +51,7 @@ from app.providers.immich import ImmichDisplayRequest, ImmichProvider from app.providers.tmdb import PosterResolver from app.providers.tmdb.models import TmdbDisplayRequest +from app.services.ambient import AmbientState, ambient_candidates from app.services.display import DisplayResult, DisplayService from app.services.schedule import QuietWindow, in_quiet, next_run_at from app.services.smart_mix import MixCandidate, MixContext, SmartMixResolver @@ -64,6 +65,11 @@ RefreshReason = Literal["scheduled", "manual", "revert"] RunStatus = Literal["ok", "failed", "skipped"] RuleSource = Literal["pinned", "smart_mix", "last"] +DISCOVERY_LABEL: Final = "discovery" +#: Whole-library random photo: the quality gate stays on (``skip_quality_gate=False``). +DISCOVERY_RULE: Final = SourceRule( + kind="immich", params={"mode": "random", "whole_library": True, "skip_quality_gate": False} +) Clock = Callable[[], datetime] RuleRunner = Callable[[SourceRule], Awaitable[DisplayResult]] @@ -145,6 +151,9 @@ class SchedulerState(BaseModel): hold_until: AwareDatetime | None = Field( default=None, description="A pushed image stays up at least until then" ) + ambient: AmbientState = Field( + default_factory=AmbientState, description="Ambient context fields (POST /api/context)" + ) @dataclass(frozen=True, slots=True) @@ -229,6 +238,7 @@ class SchedulerSnapshot(BaseModel): description="A directly pushed image is protected from scheduled refreshes until then" ) smart_mix: SmartMixStatus + ambient: AmbientState = Field(description="Live ambient context (POST /api/context)") active_rule: ActiveRuleView | None = Field(description="null until something can be replayed") @@ -369,7 +379,28 @@ def context_view(self) -> ContextView | None: def mix_pool(self) -> list[MixCandidate]: """Candidates currently in the Smart Mix (enabled entries plus the live context).""" - return self._resolver.pool(self._config.smart_mix, self.live_context()) + return self._resolver.pool( + self._config.smart_mix, self.live_context(), self.ambient_extras() + ) + + # --- Ambient context --------------------------------------------------------------- + def live_ambient(self) -> AmbientState: + """The ambient context fields that have not expired.""" + return self._state.ambient.live(self._clock()) + + def ambient_extras(self) -> list[MixCandidate]: + """Candidates added to the Smart Mix by the live ambient context.""" + return ambient_candidates(self.live_ambient(), self._config.ambient) + + def family_override(self) -> bool | None: + """``family_mode`` of the live ambient context (``None`` = follow the settings).""" + flag = self.live_ambient().family_mode + return flag.value if flag is not None else None + + async def set_ambient(self, state: AmbientState) -> None: + """Replace the ambient context (an empty state clears it).""" + await self._save(ambient=state) + self._arm() def live_context(self) -> MixContext | None: """The Smart Mix context boost, unless it has expired.""" @@ -382,7 +413,7 @@ def active_rule(self) -> ActiveRule | None: if pinned is not None: return ActiveRule(pinned, "pinned") mix = self._config.smart_mix - if mix.enabled and self._resolver.pool(mix, self.live_context()): + if mix.enabled and self.mix_pool(): return ActiveRule(None, "smart_mix") if self._state.last_rule is not None: return ActiveRule(self._state.last_rule, "last") @@ -419,6 +450,7 @@ def snapshot(self) -> SchedulerSnapshot: entries=sum(1 for e in self._config.smart_mix.entries if e.enabled), context=self.context_view(), ), + ambient=self.live_ambient(), active_rule=( ActiveRuleView(kind=active.kind, source=active.source) if active else None ), @@ -622,8 +654,14 @@ async def _play(self, active: ActiveRule) -> tuple[DisplayResult, MixCandidate]: if active.rule is not None: return await self._attempt(MixCandidate(active.rule)) mix = self._config.smart_mix + discovery = await self._discover(mix) + if discovery is not None: + return discovery order = self._resolver.order( - mix, self.live_context(), last_index=self._state.last_mix_index + mix, + self.live_context(), + last_index=self._state.last_mix_index, + extras=self.ambient_extras(), ) failure: Exception | None = None for candidate in order[: mix.max_attempts]: @@ -644,6 +682,30 @@ async def _play(self, active: ActiveRule) -> tuple[DisplayResult, MixCandidate]: raise NoRuleError("Smart Mix has no enabled entry") raise failure + async def _discover(self, mix: SmartMixConfig) -> tuple[DisplayResult, MixCandidate] | None: + """Random Discovery: on a hit, a photo of the whole library (``None`` = use the mix). + + The quality gate stays on and Family Mode / the Locked Folder rule still apply + (they live in the Immich provider). Any failure falls back to the weighted entries. + """ + context = self.live_context() + if "immich" not in self._runners or (context is not None and context.exclusive): + return None + if not self._resolver.roll(mix.discovery_share): + return None + candidate = MixCandidate(DISCOVERY_RULE, 1.0, None, DISCOVERY_LABEL) + try: + return await self._attempt(candidate) + except asyncio.CancelledError: + raise + except Exception as exc: + if not isinstance(exc, ProviderError | RefreshError | InvalidImageError): + logger.exception("Random Discovery crashed") + logger.info( + "Random Discovery found nothing, using the Smart Mix: %s", _safe_detail(exc) + ) + return None + async def _attempt(self, candidate: MixCandidate) -> tuple[DisplayResult, MixCandidate]: rule = candidate.rule.model_copy(update={"params": self.expand(candidate.rule.params)}) runner = self._runner(rule) @@ -655,6 +717,7 @@ def expand(self, params: dict[str, JsonValue]) -> dict[str, JsonValue]: self._clock(), ZoneInfo(self._config.scheduler.timezone), self._config.smart_mix.hemisphere, + self.live_ambient().season_override(), ) expanded = expand_params(params, context) return expanded if isinstance(expanded, dict) else params @@ -693,7 +756,7 @@ async def _record_success( ) -> LastRun: last_run = self._last_run(reason, "ok", active, chosen=chosen) update = self._timer_reset(last_run.at) - if active.source == "smart_mix": + if active.source == "smart_mix" and chosen.label != DISCOVERY_LABEL: update["last_mix_index"] = chosen.index await self._save(last_run=last_run, **update) logger.info("Refresh done (%s, %s rule %s)", reason, active.source, last_run.rule_kind) diff --git a/app/services/smart_mix.py b/app/services/smart_mix.py index 155012e..39ac743 100644 --- a/app/services/smart_mix.py +++ b/app/services/smart_mix.py @@ -9,6 +9,7 @@ import math import random +from collections.abc import Sequence from dataclasses import dataclass from datetime import datetime @@ -56,9 +57,18 @@ class SmartMixResolver: def __init__(self, rng: random.Random | None = None) -> None: self._rng = rng or random.Random() # noqa: S311 - not security relevant + def roll(self, share: float) -> bool: + """Random Discovery: ``True`` with probability ``share``.""" + return share > 0 and self._rng.random() < share + @staticmethod - def pool(config: SmartMixConfig, context: MixContext | None = None) -> list[MixCandidate]: - """Enabled entries plus the live context (alone when it is exclusive).""" + def pool( + config: SmartMixConfig, + context: MixContext | None = None, + extras: Sequence[MixCandidate] = (), + ) -> list[MixCandidate]: + """Enabled entries plus the live context (alone when it is exclusive) and ``extras`` + (ambient candidates).""" boost = ( MixCandidate(context.rule, context.weight, None, context.label or "context") if context is not None @@ -73,6 +83,7 @@ def pool(config: SmartMixConfig, context: MixContext | None = None) -> list[MixC ] if boost is not None: pool.append(boost) + pool.extend(extras) return pool def order( @@ -81,6 +92,7 @@ def order( context: MixContext | None = None, *, last_index: int | None = None, + extras: Sequence[MixCandidate] = (), ) -> list[MixCandidate]: """Every candidate once, in the order they should be tried. @@ -88,7 +100,7 @@ def order( ``avoid_consecutive`` the entry shown last is moved to the end, so it is still a fallback when everything else fails. """ - pool = self.pool(config, context) + pool = self.pool(config, context, extras) keyed = sorted( pool, key=lambda candidate: math.log(1.0 - self._rng.random()) / candidate.weight, diff --git a/app/templates/index.html b/app/templates/index.html index 2cc5a49..a131db9 100644 --- a/app/templates/index.html +++ b/app/templates/index.html @@ -219,6 +219,22 @@

Frame

+ +
+
+

Ambient context

+ +
+

Nothing set. Home Assistant can post presence, weather or guests to /api/context.

+
    + +
+

Presence, weather and boosts only act while Smart Mix is enabled.

+ +
+

Services

@@ -627,6 +643,73 @@

TMDB (movie and TV posters)

+ + + @@ -784,7 +875,7 @@

API key

tabs: [{ id: "dashboard", label: "Dashboard" }, { id: "playground", label: "Playground" }, { id: "settings", label: "Settings" }], settingsSections: [ { id: "frame", label: "Frame & schedule" }, { id: "immich", label: "Immich" }, { id: "tmdb", label: "TMDB" }, - { id: "mix", label: "Smart Mix" }, { id: "image", label: "Image processing" }, { id: "security", label: "Security" } + { id: "family", label: "Family Mode" }, { id: "mix", label: "Smart Mix" }, { id: "image", label: "Image processing" }, { id: "security", label: "Security" } ], profiles: ["auto", "official", "photo", "soft", "vivid", "natural"], dithers: ["auto", "atkinson", "atkinson-classic", "fs", "fs-serpentine", "stucki", "blue-noise"], @@ -797,7 +888,7 @@

API key

card: { title: "", subtitle: "", caption: "", accent: "red", ttl: 60 }, lab: { file: null, template: "none", fit: "", variants: [{ profile: "auto", dither: "auto" }, { profile: "official", dither: "atkinson" }], results: [], frameSize: null }, config: null, sources: {}, draft: null, accounts: [], mixRows: [], mixView: null, - albums: [], people: [], peopleFilter: "", tmdbTest: null, apiKey: { value: "", shown: false, source: "none", regenerable: false }, + ambient: null, albums: [], people: [], peopleFilter: "", tmdbTest: null, apiKey: { value: "", shown: false, source: "none", regenerable: false }, // --- Lifecycle ------------------------------------------------------------------- async init() { @@ -859,7 +950,28 @@

API key

}, // --- Dashboard ------------------------------------------------------------------- - async loadStatus() { try { this.status = await this.api("api/status"); } catch (e) { /* keep last */ } }, + async loadStatus() { + try { this.status = await this.api("api/status"); } catch (e) { /* keep last */ } + this.loadAmbient(); + }, + async loadAmbient() { try { this.ambient = await this.api("api/context"); } catch (e) { /* optional */ } }, + ambientFields() { + if (!this.ambient) return []; + var labels = { presence: "At home:", family_mode: "Family Mode forced", weather: "Weather:", season: "Season:", boost_tags: "Boost:", boost_people: "Favouring:" }; + var ctx = this.ambient.context; var out = []; + Object.keys(labels).forEach(function (key) { + var f = ctx[key]; + if (!f) return; + var text = f.values ? f.values.join(", ") : (typeof f.value === "boolean" ? (f.value ? "on" : "off") : f.value); + out.push({ key: key, label: labels[key], text: text, expires_at: f.expires_at }); + }); + return out; + }, + async clearAmbient() { + var self = this; + var r = await this.run("ambient", function () { return self.api("api/context", { method: "DELETE" }); }, "Context cleared"); + if (r) this.ambient = r; + }, async loadActivity() { try { this.activity = await this.api("api/activity?logs=120"); } catch (e) { /* optional */ } }, current() { return this.status && this.status.current_image; }, currentUrl(name) { var c = this.current(); return "./api/" + name + "?v=" + (c ? c.sha256.slice(0, 12) : "0"); }, @@ -1019,6 +1131,10 @@

API key

if (this.section === "mix") this.loadMixView(); if (this.section === "security") this.loadKeyInfo(); if (this.section === "immich" && this.accounts.length && !this.people.length) this.loadPeople(false); + if (this.section === "family" && this.accounts.length) { + if (!this.people.length) this.loadPeople(false); + if (!this.albums.length) this.loadAlbums(); + } }, fromEnv(path) { return this.sources[path] === "env"; }, changes(sections, skip) { @@ -1102,6 +1218,12 @@

API key

var q = this.peopleFilter.trim().toLowerCase(); return q ? this.people.filter(function (p) { return p.name.toLowerCase().indexOf(q) !== -1; }) : this.people; }, + hasIn(section, field, name) { return this.draft[section][field].some(function (n) { return n.toLowerCase() === name.toLowerCase(); }); }, + toggleIn(section, field, name) { + var list = this.draft[section][field]; + var i = list.findIndex(function (n) { return n.toLowerCase() === name.toLowerCase(); }); + if (i === -1) list.push(name); else list.splice(i, 1); + }, hasPerson(field, name) { return this.draft.immich[field].some(function (n) { return n.toLowerCase() === name.toLowerCase(); }); }, togglePerson(field, name) { var list = this.draft.immich[field]; diff --git a/docker-compose.yml b/docker-compose.yml index 8223605..d3feb36 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -10,6 +10,8 @@ services: env_file: - path: .env required: false + # mDNS (ZEROCONF_ENABLED) needs host networking: replace `ports:` with + # `network_mode: host` and set PORT in .env if 8080 is taken. ports: - "${HOST_PORT:-8080}:8080" volumes: diff --git a/pyproject.toml b/pyproject.toml index 67434ef..e0fc722 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -32,6 +32,7 @@ dependencies = [ "jinja2>=3.1", "python-multipart>=0.0.9", "tzdata>=2024.1", + "zeroconf>=0.130", ] [project.optional-dependencies] diff --git a/tests/conftest.py b/tests/conftest.py index 873606a..0ac917f 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -22,6 +22,7 @@ def _isolate_env(monkeypatch: pytest.MonkeyPatch) -> None: """Make sure the developer's shell environment never leaks into tests.""" for name in EnvSettings.model_fields: monkeypatch.delenv(name.upper(), raising=False) + monkeypatch.setenv("ZEROCONF_ENABLED", "false") # tests never touch the network _LOCAL_HOSTS = {None, "localhost", "127.0.0.1", "::1", "testserver"} diff --git a/tests/immich_fake.py b/tests/immich_fake.py index 5c496a8..bd9b53a 100644 --- a/tests/immich_fake.py +++ b/tests/immich_fake.py @@ -162,6 +162,8 @@ def _handle(self, request: httpx.Request) -> httpx.Response: for a in self.albums ], ) + if path == "/api/search/metadata": + return self._metadata(body) if path in {"/api/search/random", "/api/search/smart"}: return self._search(path, body) if path == "/api/faces": @@ -222,6 +224,22 @@ def _search(self, path: str, body: dict[str, Any]) -> httpx.Response: ) return httpx.Response(200, json=pool[: body["size"]]) + def _metadata(self, body: dict[str, Any]) -> httpx.Response: + """Paged asset listing (used for album membership); ignores archive/lock filters.""" + members = { + asset_id + for album in self.albums + if album["id"] in (body.get("albumIds") or []) + for asset_id in album["assetIds"] + } + items = [a for a in self.assets.values() if a["id"] in members] + size, page = body["size"], body["page"] + chunk = items[(page - 1) * size : page * size] + next_page = str(page + 1) if page * size < len(items) else None + return httpx.Response( + 200, json={"assets": {"items": chunk, "count": len(chunk), "nextPage": next_page}} + ) + def _asset(self, path: str, query: dict[str, str]) -> httpx.Response: parts = path.split("/") # ['', 'api', 'assets', id, (original|thumbnail)?] asset_id = parts[3] diff --git a/tests/test_ambient_family.py b/tests/test_ambient_family.py new file mode 100644 index 0000000..550be92 --- /dev/null +++ b/tests/test_ambient_family.py @@ -0,0 +1,385 @@ +"""Locked Folder rule, Family Mode, Random Discovery, ambient context and Zeroconf.""" + +from __future__ import annotations + +import asyncio +import random +from datetime import UTC, datetime, timedelta +from pathlib import Path +from typing import Any, cast + +import pytest + +from app.core.config_models import AmbientConfig, SourceRule +from app.core.config_store import ConfigStore +from app.providers.base import NoCandidateError +from app.services.ambient import AmbientRequest, AmbientState, ambient_candidates +from app.services.discovery import SERVICE_TYPE, ZeroconfAdvertiser +from app.services.display import DisplayResult +from app.services.scheduler import DISCOVERY_LABEL, SchedulerService +from app.services.smart_mix import SmartMixResolver +from tests.conftest import ClientFactory +from tests.test_api_immich import immich_client, servers +from tests.test_api_refresh import alice_and_bob +from tests.test_immich_client import mocked +from tests.test_immich_provider import Env, family + +NOW = datetime(2099, 1, 14, 12, 0, tzinfo=UTC) + + +async def pick_all(env: Env, tries: int = 12) -> set[str]: + """Asset IDs seen over several picks (the test rng cycles through the candidates).""" + seen: set[str] = set() + for _ in range(tries): + try: + asset = await env.fetch(ignore_history=True) + except NoCandidateError: + break + seen.add(str(asset.details["asset_id"])) + return seen + + +# --- Locked Folder (always on) ----------------------------------------------------------- +async def test_locked_assets_are_never_selected(tmp_path: Path) -> None: + fake = family() + fake.add_asset("locked1", visibility="locked") + env = Env(tmp_path, {"home": fake}) + with mocked(fake): + seen = await pick_all(env) + assert seen and "locked1" not in seen + + +# --- Family Mode --------------------------------------------------------------------------- +async def test_members_keep_only_photos_with_a_member(tmp_path: Path) -> None: + fake = family() + env = Env(tmp_path, {"home": fake}) + await env.store.update({"family": {"enabled": True, "members": ["Alice"]}}) + with mocked(fake): + seen = await pick_all(env) + assert seen == {"a1", "a3"} # a6 is archived, a2/a4/a5 have no Alice + + +async def test_family_mode_off_leaves_the_library_alone(tmp_path: Path) -> None: + fake = family() + env = Env(tmp_path, {"home": fake}) + await env.store.update({"family": {"enabled": False, "members": ["Alice"]}}) + with mocked(fake): + assert len(await pick_all(env)) > 2 + + +async def test_private_people_are_excluded(tmp_path: Path) -> None: + fake = family() + env = Env(tmp_path, {"home": fake}) + await env.store.update({"family": {"enabled": True, "private_people": ["Kid"]}}) + with mocked(fake): + seen = await pick_all(env) + assert seen and "a4" not in seen + + +async def test_private_albums_are_excluded(tmp_path: Path) -> None: + fake = family() + fake.add_album("alb1", "Private", ["a1", "a5"]) + env = Env(tmp_path, {"home": fake}) + await env.store.update({"family": {"enabled": True, "private_albums": ["private"]}}) + with mocked(fake): + seen = await pick_all(env) + assert seen and not seen & {"a1", "a5"} + + +async def test_require_member_false_keeps_only_exclusions(tmp_path: Path) -> None: + fake = family() + env = Env(tmp_path, {"home": fake}) + await env.store.update( + {"family": {"enabled": True, "members": ["Alice"], "require_member": False}} + ) + with mocked(fake): + assert "a2" in await pick_all(env) + + +async def test_ambient_override_forces_family_mode(tmp_path: Path) -> None: + fake = family() + env = Env(tmp_path, {"home": fake}) + await env.store.update({"family": {"enabled": False, "members": ["Alice"]}}) + flag: list[bool | None] = [True] + env.provider._family_override = lambda: flag[0] + with mocked(fake): + assert await pick_all(env) == {"a1", "a3"} + flag[0] = None + assert len(await pick_all(env)) > 2 + assert env.provider.family_active() is False + flag[0] = False + await env.store.update({"family": {"enabled": True}}) + assert env.provider.family_active() is False + + +async def test_whole_library_ignores_default_filters(tmp_path: Path) -> None: + fake = family() + env = Env(tmp_path, {"home": fake}, persons=["Alice"]) + with mocked(fake): + narrow = await pick_all(env) + wide = set() + for _ in range(12): + asset = await env.fetch(whole_library=True, ignore_history=True) + wide.add(str(asset.details["asset_id"])) + assert narrow <= {"a1", "a3"} and len(wide) > 2 + + +# --- Random Discovery ------------------------------------------------------------------------ +class Scripted(random.Random): + """``random()`` returns the scripted values in turn, then 0.99.""" + + def __init__(self, *values: float) -> None: + super().__init__(0) + self.values = list(values) + + def random(self) -> float: + return self.values.pop(0) if self.values else 0.99 + + +class Runner: + def __init__(self) -> None: + self.calls: list[SourceRule] = [] + self.fail_discovery = False + + async def __call__(self, rule: SourceRule) -> DisplayResult: + self.calls.append(rule) + if self.fail_discovery and rule.params.get("whole_library"): + raise NoCandidateError("nothing in the library") + return cast(DisplayResult, object()) + + +def scheduler(tmp_path: Path, runner: Runner, rng: random.Random, **mix: Any) -> SchedulerService: + store = ConfigStore( + tmp_path / "config.json", + { + "scheduler": {"enabled": True}, + "smart_mix": { + "enabled": True, + "entries": [{"kind": "immich", "label": "alice", "params": {"persons": ["Alice"]}}], + **mix, + }, + }, + ) + store.load() + service = SchedulerService( + tmp_path / "state.json", + store, + {"immich": runner}, + clock=lambda: NOW, + resolver=SmartMixResolver(rng), + ) + service.load() + return service + + +async def test_discovery_hit_shows_a_whole_library_photo(tmp_path: Path) -> None: + runner = Runner() + service = scheduler(tmp_path, runner, Scripted(0.01), discovery_share=0.5) + await service.run("scheduled") + assert runner.calls[0].params["whole_library"] is True + assert runner.calls[0].params["skip_quality_gate"] is False + last = service.state.last_run + assert last is not None and last.entry_label == DISCOVERY_LABEL + + +async def test_discovery_miss_uses_the_weighted_entries(tmp_path: Path) -> None: + runner = Runner() + service = scheduler(tmp_path, runner, Scripted(0.9), discovery_share=0.5) + await service.run("scheduled") + assert runner.calls[0].params == {"persons": ["Alice"]} + + +async def test_discovery_failure_falls_back_to_the_entries(tmp_path: Path) -> None: + runner = Runner() + runner.fail_discovery = True + service = scheduler(tmp_path, runner, Scripted(0.01), discovery_share=0.5) + await service.run("scheduled") + assert [c.params.get("whole_library") for c in runner.calls] == [True, None] + + +async def test_discovery_off_never_rolls_a_hit(tmp_path: Path) -> None: + runner = Runner() + service = scheduler(tmp_path, runner, Scripted(0.0), discovery_share=0.0) + await service.run("scheduled") + assert runner.calls[0].params == {"persons": ["Alice"]} + + +def test_discovery_share_is_capped_at_half() -> None: + from pydantic import ValidationError + + from app.core.config_models import SmartMixConfig + + assert SmartMixConfig().discovery_share == 0.15 + with pytest.raises(ValidationError): + SmartMixConfig(discovery_share=0.6) + + +# --- Ambient context ------------------------------------------------------------------------- +def test_fields_expire_on_their_own() -> None: + config = AmbientConfig() + request = AmbientRequest.model_validate( + { + "presence": {"values": ["Alice"], "ttl_minutes": 10}, + "boost_tags": ["beach"], + "ttl_minutes": 60, + } + ) + state = request.apply(AmbientState(), config, NOW) + assert state.live(NOW + timedelta(minutes=5)).presence is not None + later = state.live(NOW + timedelta(minutes=30)) + assert later.presence is None and later.boost_tags is not None + assert state.live(NOW + timedelta(minutes=61)).empty + + +def test_merge_keeps_unset_fields_and_empty_clears() -> None: + config = AmbientConfig() + first = AmbientRequest.model_validate({"presence": ["Alice"], "weather": "rainy"}) + state = first.apply(AmbientState(), config, NOW) + second = AmbientRequest.model_validate({"presence": [], "season": "winter"}) + merged = second.apply(state, config, NOW) + assert merged.presence is None + assert merged.weather is not None and merged.season is not None + + +def test_candidates_map_people_tags_and_weather() -> None: + config = AmbientConfig() + request = AmbientRequest.model_validate( + { + "presence": ["Alice"], + "boost_people": ["Bob", "alice"], + "boost_tags": ["beach"], + "weather": "RAINY", + } + ) + state = request.apply(AmbientState(), config, NOW) + by_label = {c.label: c for c in ambient_candidates(state, config)} + assert by_label["ambient:people"].rule.params["persons"] == ["Alice", "Bob"] + assert by_label["ambient:tags"].rule.params["clip_queries"] == ["beach"] + assert by_label["ambient:weather:rainy"].rule.params["clip_queries"] == [ + config.weather_queries["rainy"] + ] + assert all(c.weight == config.boost_weight for c in by_label.values()) + + +def test_unknown_weather_and_season_are_rejected() -> None: + config = AmbientConfig() + with pytest.raises(ValueError, match="Unknown weather"): + AmbientRequest(weather="plasma").apply(AmbientState(), config, NOW) + with pytest.raises(ValueError, match="Unknown season"): + AmbientRequest(season={"value": "monsoon"}).apply(AmbientState(), config, NOW) # type: ignore[arg-type] + + +def test_context_api_roundtrip(make_client: ClientFactory) -> None: + client = make_client() + posted = client.post( + "/api/context", + json={"presence": ["Alice"], "family_mode": {"value": True, "ttl_minutes": 30}}, + ) + assert posted.status_code == 200, posted.text + body = posted.json() + assert body["context"]["presence"]["values"] == ["Alice"] + assert body["family_active"] is True # overrides family.enabled=false + assert body["smart_mix_enabled"] is False + assert body["extra_candidates"] == ["ambient:people"] + assert client.get("/api/context").json()["context"]["family_mode"]["value"] is True + status = client.get("/api/status").json()["scheduler"]["ambient"] + assert status["presence"]["values"] == ["Alice"] + + cleared = client.delete("/api/context", params={"field": "presence"}).json() + assert cleared["context"]["presence"] is None and cleared["family_active"] is True + assert client.delete("/api/context").json()["family_active"] is False + + +def test_context_api_validates_input(make_client: ClientFactory) -> None: + client = make_client() + assert client.post("/api/context", json={"weather": "plasma"}).status_code == 422 + assert client.post("/api/context", json={"nope": 1}).status_code == 422 + assert client.post("/api/context", json={"ttl_minutes": 0}).status_code == 422 + + +def test_context_api_requires_the_key(make_client: ClientFactory) -> None: + client = make_client(app_api_key="secret-key") + assert client.get("/api/context").status_code == 401 + assert client.get("/api/context", headers={"X-API-Key": "secret-key"}).status_code == 200 + + +def test_context_survives_a_restart(tmp_path: Path) -> None: + runner = Runner() + first = scheduler(tmp_path, runner, Scripted()) + state = AmbientRequest(presence=["Alice"]).apply(AmbientState(), AmbientConfig(), NOW) + asyncio.run(first.set_ambient(state)) + second = scheduler(tmp_path, runner, Scripted()) + assert second.live_ambient().presence is not None + assert [c.label for c in second.ambient_extras()] == ["ambient:people"] + + +def test_family_mode_override_reaches_the_provider(make_client: ClientFactory) -> None: + fake = alice_and_bob() + client = immich_client(make_client) + client.put("/api/config", json={"family": {"members": ["Alice"]}}) + client.post("/api/context", json={"family_mode": True}) + with servers(fake): + for _ in range(6): + response = client.post("/api/display/immich", json={"ignore_history": True}) + assert response.status_code == 200, response.text + assert "Alice" in response.json()["image"]["details"]["people"] + + +# --- Zeroconf ---------------------------------------------------------------------------------- +class FakeZeroconf: + def __init__(self, fail: bool = False) -> None: + self.fail = fail + self.registered: list[Any] = [] + self.closed = False + + async def async_register_service(self, info: Any) -> None: + if self.fail: + raise OSError("multicast unavailable") + self.registered.append(info) + + async def async_unregister_service(self, info: Any) -> None: + self.registered.remove(info) + + async def async_close(self) -> None: + self.closed = True + + +async def test_zeroconf_advertises_the_service() -> None: + fake = FakeZeroconf() + advertiser = ZeroconfAdvertiser( + port=8080, + version="1.2.3", + root_path="/fraimic", + auth="password", + zeroconf_factory=lambda: fake, + addresses=lambda: ["192.0.2.10"], + ) + assert await advertiser.start() is True and advertiser.active + info = fake.registered[0] + assert info.type == SERVICE_TYPE and info.port == 8080 + assert info.decoded_properties == {"version": "1.2.3", "path": "/fraimic", "auth": "password"} + assert info.parsed_addresses() == ["192.0.2.10"] + await advertiser.stop() + assert fake.closed and not fake.registered and not advertiser.active + await advertiser.stop() # idempotent + + +async def test_zeroconf_errors_are_logged_and_ignored(caplog: pytest.LogCaptureFixture) -> None: + advertiser = ZeroconfAdvertiser( + port=8080, + version="1", + root_path="", + auth="open", + zeroconf_factory=lambda: FakeZeroconf(fail=True), + addresses=lambda: ["192.0.2.10"], + ) + assert await advertiser.start() is False and not advertiser.active + assert "Zeroconf advertising disabled" in caplog.text + await advertiser.stop() + + +def test_zeroconf_is_off_during_tests_and_on_by_default() -> None: + from app.core.settings import EnvSettings + + assert EnvSettings.model_fields["zeroconf_enabled"].default is True + assert EnvSettings(_env_file=None).zeroconf_enabled is False # conftest disables it diff --git a/tests/test_api.py b/tests/test_api.py index 526f313..55198f9 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -102,6 +102,8 @@ def test_config_schema(make_client: ClientFactory) -> None: "eink", "scheduler", "smart_mix", + "family", + "ambient", "quality", } diff --git a/tests/test_api_refresh.py b/tests/test_api_refresh.py index 55dd10a..31714e5 100644 --- a/tests/test_api_refresh.py +++ b/tests/test_api_refresh.py @@ -167,6 +167,14 @@ def test_status_when_disabled(make_client: ClientFactory) -> None: "consecutive_failures": 0, "hold_until": None, "smart_mix": {"enabled": False, "entries": 0, "context": None}, + "ambient": { + "presence": None, + "family_mode": None, + "weather": None, + "season": None, + "boost_tags": None, + "boost_people": None, + }, "active_rule": None, } diff --git a/tests/test_api_smart_mix.py b/tests/test_api_smart_mix.py index 91bfeb5..6eb6758 100644 --- a/tests/test_api_smart_mix.py +++ b/tests/test_api_smart_mix.py @@ -22,7 +22,9 @@ def smart_search(client: TestClient, **body: Any) -> Any: def enable_mix(client: TestClient, *entries: dict[str, Any], **extra: Any) -> None: response = client.put( "/api/config", - json={"smart_mix": {"enabled": True, "entries": list(entries), **extra}}, + json={ + "smart_mix": {"enabled": True, "discovery_share": 0, "entries": list(entries), **extra} + }, ) assert response.status_code == 200, response.text diff --git a/tests/test_api_tmdb.py b/tests/test_api_tmdb.py index 3167a4a..6d493f1 100644 --- a/tests/test_api_tmdb.py +++ b/tests/test_api_tmdb.py @@ -151,7 +151,10 @@ def test_smart_mix_entries_can_replay_posters(make_client: ClientFactory) -> Non mock_amelie() client = tmdb_client(make_client) entry = {"kind": "tmdb", "params": {"query": "Amélie", "media_type": "movie"}, "label": "Film"} - response = client.put("/api/config", json={"smart_mix": {"enabled": True, "entries": [entry]}}) + response = client.put( + "/api/config", + json={"smart_mix": {"enabled": True, "discovery_share": 0, "entries": [entry]}}, + ) assert response.status_code == 200 refreshed = client.post("/api/refresh") assert refreshed.status_code == 200, refreshed.text diff --git a/tests/test_immich_client.py b/tests/test_immich_client.py index 65e195a..19a177e 100644 --- a/tests/test_immich_client.py +++ b/tests/test_immich_client.py @@ -86,6 +86,7 @@ async def test_search_bodies_carry_the_filters() -> None: "type": "IMAGE", "size": 7, "withExif": True, + "withPeople": True, "personIds": ["p1", "p2"], "albumIds": ["al1"], "isFavorite": True, diff --git a/tests/test_smart_mix.py b/tests/test_smart_mix.py index 345c4e2..9edcb6b 100644 --- a/tests/test_smart_mix.py +++ b/tests/test_smart_mix.py @@ -91,7 +91,10 @@ def __init__(self, tmp_path: Path, **smart_mix: Any) -> None: self.other = FakeRunner() self.store = ConfigStore( tmp_path / "config.json", - {"scheduler": {"enabled": True}, "smart_mix": {"enabled": True, **smart_mix}}, + { + "scheduler": {"enabled": True}, + "smart_mix": {"enabled": True, "discovery_share": 0, **smart_mix}, + }, ) self.store.load() self.state_path = tmp_path / "scheduler_state.json" From c1517b490cdb82565f243463d4656711951e5c3f Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sun, 15 Nov 2026 20:24:24 +0100 Subject: [PATCH 76/86] chore: add a Portainer stack file with host port, data path and user settings Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- README.md | 8 ++++++++ docker-compose.portainer.yml | 29 +++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 docker-compose.portainer.yml diff --git a/README.md b/README.md index 4c274c2..8e1cefa 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,14 @@ docker compose up -d - API docs: `http://:8080/docs` - Health: `http://:8080/api/health` +## Portainer + +Use *Stacks → Repository* with the `develop` branch and compose path +`docker-compose.portainer.yml`. The stack variables `HOST_PORT`, `DATA_PATH` (host folder +bound to `/data`), `PUID` and `PGID` configure the deployment; every other variable of +`.env.example` (all optional) is passed to the app. Create `DATA_PATH` first and `chown` it +to `PUID:PGID`. Immich, TMDB and the frame can also be set later in the web UI. + ## Web UI A single page served at `/` (Tailwind CSS and Alpine.js from a CDN, no build step). It diff --git a/docker-compose.portainer.yml b/docker-compose.portainer.yml new file mode 100644 index 0000000..6e17642 --- /dev/null +++ b/docker-compose.portainer.yml @@ -0,0 +1,29 @@ +# Portainer (Stacks -> Repository, branch `develop`, compose path `docker-compose.portainer.yml`). +# +# Deployment settings, set as stack environment variables (all optional): +# HOST_PORT published port on the host (default 8080) +# DATA_PATH host folder bound to /data (default /srv/smart-frame/data) +# PUID/PGID owner of DATA_PATH (`id -u` / `id -g`) (default 1000) +# +# Application settings (IMMICH_URL, TMDB_API_KEY, ADMIN_PASSWORD, TZ...) are passed through +# `stack.env`, which Portainer generates from the stack's environment variables: only define +# the ones you want (see .env.example). Do not define a variable with an empty value. +# +# Create DATA_PATH first and give it to PUID:PGID, e.g. +# mkdir -p /srv/smart-frame/data && chown 1000:1000 /srv/smart-frame/data +services: + smart-frame-engine: + image: ghcr.io/ant1fr/smart-frame-engine:latest + build: . + container_name: smart-frame-engine + restart: unless-stopped + user: "${PUID:-1000}:${PGID:-1000}" + env_file: + - path: stack.env + required: false + # mDNS (ZEROCONF_ENABLED) needs host networking: replace `ports:` with + # `network_mode: host` and set PORT (the engine then listens on it directly). + ports: + - "${HOST_PORT:-8080}:8080" + volumes: + - ${DATA_PATH:-/srv/smart-frame/data}:/data From 72ed5760cfbd4589814633647c33a77645ace018 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Sun, 15 Nov 2026 20:35:41 +0100 Subject: [PATCH 77/86] fix: probe the frame on first dashboard load and add a Check now button Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- app/templates/index.html | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/app/templates/index.html b/app/templates/index.html index a131db9..face324 100644 --- a/app/templates/index.html +++ b/app/templates/index.html @@ -172,6 +172,7 @@

Mode

Frame

+
- + @@ -437,7 +437,7 @@

Render lab

- +
@@ -464,7 +464,7 @@

Render lab

- +
@@ -510,7 +510,7 @@

Frame

-
+

Schedule

@@ -522,7 +522,7 @@

Schedule

-
+
@@ -544,14 +544,14 @@

Immich accounts

- +
-
+
@@ -571,7 +571,7 @@

Selection

Album

- +
+

Filter: photos must show the selected people. Always: merged into every selection.

@@ -615,7 +615,7 @@

Selection

Always: .

-
+
@@ -628,7 +628,7 @@

TMDB (movie and TV posters)

- +
@@ -639,7 +639,7 @@

TMDB (movie and TV posters)

-
+
@@ -652,8 +652,8 @@

Family Mode

Every Immich selection (Smart Mix, Random Discovery, searches) is filtered automatically over the whole library: no photo-by-photo curation. Photos in Immich's Locked Folder are never shown, with or without Family Mode. Home Assistant can switch Family Mode for a while with POST /api/context (family_mode).

- - + +
@@ -706,7 +706,7 @@

Family Mode

-
+
@@ -754,7 +754,7 @@

Smart Mix

That share of scheduled refreshes shows a random photo from the whole library (quality gate on: no screenshots, low-resolution shots, documents or blank frames; Family Mode and the Locked Folder rule still apply). If nothing suitable is found, a regular entry is used.

-
+
@@ -780,7 +780,7 @@

eInk rendering

-
+

Photo quality gate

@@ -789,7 +789,7 @@

Photo quality gate

-
+
@@ -812,7 +812,7 @@

API key

Set by APP_API_KEY in .env: change it there and restart.

- + Clients using the old key stop working immediately.
From 1a4b7b95556ddd314d969f4bd29006e3698c1622 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Wed, 18 Nov 2026 09:33:16 +0100 Subject: [PATCH 79/86] feat: make the track title optional on now-playing covers The cover now shows the artist and album; the track title is only printed when music.show_track_title (or the request's show_title) asks for it, and it is always printed when there is no album. The title only counts in the content key when printed, so every track of an album deduplicates to one picture: the frame is not refreshed between tracks and only the expiry is extended. BREAKING CHANGE: covers no longer print the track title by default; set music.show_track_title to restore it. title is optional when an album is given. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- README.md | 17 +++++-- app/api/routes/playground.py | 2 +- app/core/config_models.py | 5 +++ app/processor/templates.py | 4 +- app/providers/music/models.py | 29 ++++++++++-- app/services/now_playing.py | 39 +++++++++++----- app/templates/index.html | 15 ++++--- tests/test_api_now_playing.py | 84 ++++++++++++++++++++++++++++++++--- 8 files changed, 164 insertions(+), 31 deletions(-) diff --git a/README.md b/README.md index 8e1cefa..6f3716a 100644 --- a/README.md +++ b/README.md @@ -608,13 +608,24 @@ curl -X POST http://localhost:8080/api/display/now-playing -H 'Content-Type: app | Request field | Meaning | | --- | --- | -| `title`, `artist`, `album` | Track details (`media_title`, `media_artist`, `media_album_name` in Home Assistant) | +| `title`, `artist`, `album` | Track details (`media_title`, `media_artist`, `media_album_name` in Home Assistant). `artist` is required, plus `title` or `album` | +| `show_title` | Print the track title on the cover (default `music.show_track_title`, off). See below | | `artwork_url`, `artwork_base64` | Cover provided by the player (base64 is tried first) | | `enrich_artwork` | When no usable cover was provided, look one up (default true; also `music.enrich_artwork`) | | `style` | `sleeve` or `vinyl` (default `music.default_style`) | | `duration_seconds`, `position_seconds`, `ttl_seconds` | When the cover expires (see below) | | `ephemeral`, `hold_minutes`, `push_to_fraimic` | As for posters | +**Track title and deduplication.** By default the cover shows the artist and the album, not +the track title (`music.show_track_title`, or `show_title` per request). The title only +counts in the picture's identity when it is printed, so while an album plays, every track +resolves to the *same* picture: the call returns `deduplicated: true`, nothing is sent to +the frame (no e-ink refresh) and only the expiry is extended. The frame refreshes when the +album, the artist or the style changes. Without an album, the title is always printed (it is +the only thing that tells tracks apart). Keep calling the endpoint on every track change. +**Breaking change:** before, each track was a new picture with its title; set +`music.show_track_title: true` to get that back. + **Cover lookup.** No API key is needed: the [Deezer](https://developers.deezer.com/api) public search (1000x1000 `cover_xl`), then [MusicBrainz](https://musicbrainz.org) and the [Cover Art Archive](https://coverartarchive.org) @@ -742,8 +753,8 @@ automation: - service: rest_command.frame_cancel_ephemeral ``` -The now-playing call is deduplicated, so the `media_title` trigger only re-renders when the -track really changes. A deep-sleeping frame wakes up to the right picture: covers whose +The now-playing call is deduplicated, so the `media_title` trigger only refreshes the frame +when the album changes (every track with the title printed, if you enable `show_track_title`). A deep-sleeping frame wakes up to the right picture: covers whose song has ended are dropped from the queue, and the previous photo comes back. ## Development diff --git a/app/api/routes/playground.py b/app/api/routes/playground.py index be346d6..2e785b3 100644 --- a/app/api/routes/playground.py +++ b/app/api/routes/playground.py @@ -88,7 +88,7 @@ def _layout( if template == "poster": return PosterLayout() if template == "album": - return AlbumLayout(title=title or "Title", artist=subtitle, album=caption, style=style) + return AlbumLayout(title=title or None, artist=subtitle, album=caption, style=style) if template == "title_card": return TitleCardLayout(title=title or "Title card", subtitle=subtitle, caption=caption) return None diff --git a/app/core/config_models.py b/app/core/config_models.py index 183df4d..d23c88e 100644 --- a/app/core/config_models.py +++ b/app/core/config_models.py @@ -280,6 +280,11 @@ class MusicConfig(_Section): default_style: Literal["sleeve", "vinyl"] = Field( default="sleeve", description="Album template style: sleeve, or vinyl (a record peeks out)" ) + show_track_title: bool = Field( + default=False, + description="Print the track title under the cover. Off: artist and album only, so " + "the frame stays still while an album plays (tracks of one album are deduplicated)", + ) default_ttl_minutes: int = Field( default=10, ge=1, diff --git a/app/processor/templates.py b/app/processor/templates.py index 5880b48..ac66ed1 100644 --- a/app/processor/templates.py +++ b/app/processor/templates.py @@ -74,7 +74,7 @@ class PosterLayout: class AlbumLayout: """Square cover with a title / artist / album typography block.""" - title: str + title: str | None = None artist: str | None = None album: str | None = None style: AlbumStyle = "sleeve" @@ -277,7 +277,7 @@ def size(fraction: float) -> int: return max(8, round(unit * fraction * scale)) title = fit_text( - layout.title, + layout.title or "", weight="bold", max_width=width, max_lines=2, diff --git a/app/providers/music/models.py b/app/providers/music/models.py index d0e5931..83bb5bb 100644 --- a/app/providers/music/models.py +++ b/app/providers/music/models.py @@ -4,7 +4,7 @@ from typing import Final, Literal -from pydantic import BaseModel, ConfigDict, Field, field_validator +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator AlbumStyleName = Literal["sleeve", "vinyl"] @@ -18,7 +18,11 @@ class NowPlayingRequest(BaseModel): model_config = ConfigDict(extra="forbid") - title: str = Field(min_length=1, max_length=300, description="Track title (media_title)") + title: str | None = Field( + default=None, + max_length=300, + description="Track title (media_title). Optional when an album is given", + ) artist: str = Field(min_length=1, max_length=300, description="Artist (media_artist)") album: str | None = Field( default=None, max_length=300, description="Album name (media_album_name)" @@ -33,6 +37,12 @@ class NowPlayingRequest(BaseModel): max_length=MAX_ARTWORK_BASE64_LENGTH, description="Cover as base64 (or a data: URI); tried before artwork_url", ) + show_title: bool | None = Field( + default=None, + description="Print the track title on the cover (default music.show_track_title). " + "Without it, every track of the same album shares one picture, so the frame is only " + "refreshed when the album changes. Ignored (title shown) when there is no album", + ) enrich_artwork: bool = Field( default=True, description="When no usable cover was provided, look one up on Deezer, then " @@ -76,9 +86,22 @@ def _clean(cls, value: str | None) -> str | None: cleaned = " ".join(value.split()) return cleaned or None - @field_validator("title", "artist") + @field_validator("artist") @classmethod def _required(cls, value: str | None) -> str: if not value: raise ValueError("must not be blank") return value + + @model_validator(mode="after") + def _identifiable(self) -> NowPlayingRequest: + if not self.title and not self.album: + raise ValueError("give a title or an album") + return self + + def shows_title(self, default: bool) -> bool: + """Whether the title is printed (always when no album tells the tracks apart).""" + if not self.title: + return False + wanted = default if self.show_title is None else self.show_title + return wanted or not self.album diff --git a/app/services/now_playing.py b/app/services/now_playing.py index 70cf707..ec5e9bc 100644 --- a/app/services/now_playing.py +++ b/app/services/now_playing.py @@ -57,9 +57,13 @@ def _utcnow() -> datetime: return datetime.now(UTC) -def content_key(request: NowPlayingRequest, style: str) -> str: - """Identity of the displayed cover (same track, album and style = same picture).""" - parts = [fold(request.title), fold(request.artist), fold(request.album or ""), style] +def content_key(request: NowPlayingRequest, style: str, *, show_title: bool) -> str: + """Identity of the displayed cover: what is printed on it decides what is the same picture. + + The track title only counts when it is printed, so tracks of one album share a key. + """ + title = fold(request.title or "") if show_title else "" + parts = [title, fold(request.artist), fold(request.album or ""), style] return "music:" + hashlib.sha256("\x1f".join(parts).encode("utf-8")).hexdigest()[:32] @@ -102,7 +106,8 @@ async def show(self, request: NowPlayingRequest) -> DisplayResult: """ config = self._config_store.config.music style = request.style or config.default_style - key = content_key(request, style) + show_title = request.shows_title(config.show_track_title) + key = content_key(request, style, show_title=show_title) now = self._clock() expires_at = now + cover_ttl(request, config) if request.ephemeral else None @@ -116,24 +121,36 @@ async def show(self, request: NowPlayingRequest) -> DisplayResult: ): updated = await self._display.extend_expiry(key, expires_at) if updated is not None: - logger.debug("Now playing %r is already displayed; expiry moved", request.title) + logger.debug( + "Now playing by %r is already displayed; expiry moved", request.artist + ) return DisplayResult(image=updated, delivery=None, deduplicated=True) data, origin = await self._cover(request, config) layout: Layout if data is not None: layout = AlbumLayout( - title=request.title, artist=request.artist, album=request.album, style=style + title=request.title if show_title else None, + artist=request.artist, + album=request.album, + style=style, ) - else: + elif show_title: layout = TitleCardLayout( - title=request.title, + title=request.title or "", subtitle=request.artist, caption=request.album, accent=TITLE_CARD_ACCENT, ) + else: + layout = TitleCardLayout( + title=request.album or request.artist, + subtitle=request.artist if request.album else None, + accent=TITLE_CARD_ACCENT, + ) + label = (request.title if show_title else request.album) or request.artist details: dict[str, JsonValue] = { - "title": request.title, + "title": request.title if show_title else None, "artist": request.artist, "album": request.album, "style": style, @@ -142,7 +159,7 @@ async def show(self, request: NowPlayingRequest) -> DisplayResult: } meta = DisplayMeta( source=SOURCE, - title=f"{request.title} — {request.artist}", + title=f"{label} — {request.artist}", details={k: v for k, v in details.items() if v is not None}, push=request.push_to_fraimic, ephemeral=request.ephemeral, @@ -174,7 +191,7 @@ async def _cover( logger.info("Ignoring artwork_url: %s", exc) if request.enrich_artwork and config.enrich_artwork: artwork = await self._artwork.find( - title=request.title, + title=request.title or request.album or "", artist=request.artist, album=request.album, min_side=self._cover_side(request.style or config.default_style), diff --git a/app/templates/index.html b/app/templates/index.html index 18412b6..3eb4163 100644 --- a/app/templates/index.html +++ b/app/templates/index.html @@ -333,20 +333,23 @@

Movie or TV poster

Now Playing

-

Album cover (Deezer, then MusicBrainz) with the track underneath.

+

Album cover (Deezer, then MusicBrainz) with the artist and album underneath. The track title is optional: without it, every track of an album is the same picture and the frame does not refresh between tracks.

- + +
- - + +
@@ -885,7 +888,7 @@

API key

now: Date.now(), toasts: [], zoomed: null, zoomActual: false, busy: {}, preview: null, previewStamp: 0, tmdb: { query: "", mediaType: "multi", results: [], selected: null, searched: false, ttl: 180 }, - music: { title: "", artist: "", album: "", style: "sleeve", enrich: true }, + music: { title: "", artist: "", album: "", style: "sleeve", showTitle: "", enrich: true }, card: { title: "", subtitle: "", caption: "", accent: "red", ttl: 60 }, lab: { file: null, template: "none", fit: "", variants: [{ profile: "auto", dither: "auto" }, { profile: "official", dither: "atkinson" }], results: [], frameSize: null }, config: null, sources: {}, draft: null, accounts: [], mixRows: [], mixView: null, @@ -1072,7 +1075,7 @@

API key

}, async musicShow(push) { var m = this.music; - var body = { title: m.title, artist: m.artist, album: m.album || null, style: m.style, enrich_artwork: m.enrich, push_to_fraimic: push }; + var body = { title: m.title || null, artist: m.artist, album: m.album || null, style: m.style, show_title: m.showTitle ? m.showTitle === "yes" : null, enrich_artwork: m.enrich, push_to_fraimic: push }; await this.showResult(push, this.api("api/display/now-playing", { method: "POST", body: body })); }, async cardShow(push) { diff --git a/tests/test_api_now_playing.py b/tests/test_api_now_playing.py index 910ac91..ac3e8c7 100644 --- a/tests/test_api_now_playing.py +++ b/tests/test_api_now_playing.py @@ -62,7 +62,8 @@ def test_provided_artwork_is_rendered_with_the_album_template(make_client: Clien image = body["image"] assert image["template"] == "album" assert image["source"] == "music" - assert image["title"] == "So What — Miles Davis" + assert image["title"] == "Kind of Blue — Miles Davis" + assert "title" not in image["details"] assert image["details"]["artwork"] == "provided" assert image["ephemeral"] is True expires = datetime.fromisoformat(image["expires_at"]) @@ -153,8 +154,60 @@ def test_same_track_is_deduplicated_and_only_extends_the_expiry( assert queue["pending"]["sha256"] == pending_sha assert datetime.fromisoformat(queue["pending"]["expires_at"]) == new_expiry - other = play(client, title="Freddie Freeloader", album="Kind of Blue", enrich_artwork=False) - assert other["deduplicated"] is False + # Another track of the same album: same picture, nothing is sent, only the expiry moves. + next_track = play(client, title="Freddie Freeloader", album="Kind of Blue", ttl_seconds=300) + assert next_track["deduplicated"] is True + assert next_track["delivery"] is None + assert client.get("/api/queue").json()["pending"]["sha256"] == pending_sha + + other_album = play( + client, title="Blue in Green", album="Sketches of Spain", enrich_artwork=False + ) + assert other_album["deduplicated"] is False + + +@respx.mock +def test_printed_title_makes_every_track_a_new_picture(make_client: ClientFactory) -> None: + frame_asleep() + respx.get("https://ha.test/c.jpg").respond(content=png_bytes()) + client = music_client(make_client) + fields = {"album": "Kind of Blue", "artwork_url": "https://ha.test/c.jpg", "show_title": True} + first = play(client, **fields) + assert first["image"]["title"] == "So What — Miles Davis" + assert first["image"]["details"]["title"] == "So What" + + assert play(client, **fields)["deduplicated"] is True + assert play(client, title="Blue in Green", **fields)["deduplicated"] is False + + +@respx.mock +def test_title_is_kept_without_an_album(make_client: ClientFactory) -> None: + frame_asleep() + respx.get("https://ha.test/c.jpg").respond(content=png_bytes()) + client = music_client(make_client) + first = play(client, artwork_url="https://ha.test/c.jpg", show_title=False) + assert first["image"]["title"] == "So What — Miles Davis" + assert ( + play(client, title="Blue in Green", artwork_url="https://ha.test/c.jpg")["deduplicated"] + is False + ) + + +@respx.mock +def test_title_is_optional_with_an_album(make_client: ClientFactory) -> None: + frame_asleep() + respx.get("https://ha.test/c.jpg").respond(content=png_bytes()) + client = music_client(make_client) + body = client.post( + "/api/display/now-playing", + json={ + "artist": "Miles Davis", + "album": "Kind of Blue", + "artwork_url": "https://ha.test/c.jpg", + }, + ) + assert body.status_code == 200, body.text + assert body.json()["image"]["title"] == "Kind of Blue — Miles Davis" @respx.mock @@ -187,6 +240,7 @@ def test_request_validation(make_client: ClientFactory) -> None: client = music_client(make_client) post = client.post assert post("/api/display/now-playing", json={"title": "x"}).status_code == 422 + assert post("/api/display/now-playing", json={"artist": "a"}).status_code == 422 assert post("/api/display/now-playing", json={"title": " ", "artist": "a"}).status_code == 422 assert ( post( @@ -213,5 +267,25 @@ def test_cover_ttl(fields: dict[str, Any], expected: timedelta) -> None: def test_content_key_ignores_case_accents_but_not_style() -> None: a = NowPlayingRequest(title="Café", artist="Sigur Rós", album="Ágætis byrjun") b = NowPlayingRequest(title="cafe", artist="SIGUR ROS", album="agaetis byrjun") - assert content_key(a, "sleeve") == content_key(b, "sleeve") - assert content_key(a, "sleeve") != content_key(a, "vinyl") + assert content_key(a, "sleeve", show_title=True) == content_key(b, "sleeve", show_title=True) + assert content_key(a, "sleeve", show_title=True) != content_key(a, "vinyl", show_title=True) + + +def test_content_key_ignores_the_title_unless_it_is_printed() -> None: + a = NowPlayingRequest( + title="Speak to Me", artist="Pink Floyd", album="The Dark Side of the Moon" + ) + b = a.model_copy(update={"title": "Breathe"}) + assert content_key(a, "sleeve", show_title=False) == content_key(b, "sleeve", show_title=False) + assert content_key(a, "sleeve", show_title=True) != content_key(b, "sleeve", show_title=True) + + +def test_shows_title_rules() -> None: + with_album = NowPlayingRequest(title="t", artist="a", album="x") + assert with_album.shows_title(False) is False + assert with_album.shows_title(True) is True + assert with_album.model_copy(update={"show_title": True}).shows_title(False) is True + assert with_album.model_copy(update={"show_title": False}).shows_title(True) is False + single = NowPlayingRequest(title="t", artist="a") + assert single.shows_title(False) is True + assert NowPlayingRequest(artist="a", album="x").shows_title(True) is False From 4915967db882aa78171b5802c8e1ebc415735e74 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Wed, 18 Nov 2026 09:40:24 +0100 Subject: [PATCH 80/86] fix: stop the web UI from scrolling horizontally on phones A long unbroken title (or URL, or error text) stretched the auto-sized column of bare grids and overflowed the page. Bare grids now get a one-column minmax(0, 1fr) track and shrinkable children (zero-specificity, so grid-cols-* utilities still win), and the body wraps long words and clips horizontal overflow. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- app/templates/index.html | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/app/templates/index.html b/app/templates/index.html index 18412b6..5163ccb 100644 --- a/app/templates/index.html +++ b/app/templates/index.html @@ -21,6 +21,11 @@ .pixelated { image-rendering: pixelated; } .checker { background-image: linear-gradient(45deg, rgba(148,163,184,.15) 25%, transparent 25%), linear-gradient(-45deg, rgba(148,163,184,.15) 25%, transparent 25%), linear-gradient(45deg, transparent 75%, rgba(148,163,184,.15) 75%), linear-gradient(-45deg, transparent 75%, rgba(148,163,184,.15) 75%); background-size: 16px 16px; background-position: 0 0, 0 8px, 8px -8px, -8px 0; } input[type=range] { accent-color: #2563eb; } + /* Phones: a bare grid has one auto-sized column, which a long unbroken title or URL stretches + past the viewport. Zero-specificity rules, so every grid-cols-* utility still wins. */ + :where(.grid) { grid-template-columns: minmax(0, 1fr); } + :where(.grid) > :where(*) { min-width: 0; } + body { overflow-x: clip; overflow-wrap: anywhere; } @@ -133,7 +138,7 @@

Mode