Files
ComfyAssets-ComfyUI_PromptM…/py/api/thumbnail_settings.py
T
Vito 2964a3b632 feat(thumbnails): WebP/JPEG XL thumbnails, server-side thumbnail settings and Convert outdated (#319)
* feat(thumbnails): thumbnail format, quality and size as server settings

Thumbnail format (webp default, jxl, jpeg), quality (1-100, default 80)
and size limit (128-2048 px, default 512) are server settings in the
config.json thumbnails section, saved with the settings revision. The
never-read gallery thumbnail_size is gone: older saves wrote its unused
default 256 into config.json.

One module names previews (<stem>_thumb.webp/.jxl/.jpg) and finds the
preview a source owns, preferring the configured format; legacy names
are still found. The encoder module writes every preview atomically and
verifies it decodes. JPEG XL needs no new dependency: Pillow (natively
or with pillow_jxl), ffmpeg with libjxl, or cjxl; without one the
settings refuse jxl (400 jxl-unavailable) and GET says why. Encoder
processes are tracked, bounded and killed at shutdown.

* feat(thumbnails): every preview writer and lookup follows the thumbnail settings

Automatic previews (capture and first view), the thumbnail job, the
legacy gallery routes and the history route write <stem>_thumb.webp
(or .jxl/.jpg) with the configured quality and size limit, for images
and videos alike: video frames, ffmpeg's included (a PNG on stdout,
never upscaled), and the placeholder are encoded like images.

Listings, duplicates, enrichment, the autotag scan and the history
route show any preview the file owns, the current format first, so
older _thumb.png previews keep working until converted. A request for
an older name answers the current preview. Previews are served with
an explicit image/webp or image/jxl type and the same cache headers.

The plan and status count missing, outdated (another format) and
ready previews; the missing job never writes beside an outdated one.
Removing a file removes its previews in every format; the clear
removes .webp and .jxl too. Encoder processes are killed at shutdown.

A preview is only a placeholder: inspection refuses paths under
thumbnails/ and always reads the original, and the inspector cover
accepts the listing's preview in any format the file owns.

* feat(thumbnails): Convert outdated thumbnails as an Activity job

POST /jobs/thumbnails {mode: "convert"} starts "Convert outdated
thumbnails" under the thumbnail job's kind, guarded admission, worker
threads and cancel at a file boundary. For each file whose preview is
in another format, it writes the new preview from the source (atomic,
verified; a video with no decodable frame fails instead of getting the
placeholder), then removes that file's old-format previews in its
thumbnails folder. A failure keeps the old preview; orphan previews
and links are never touched. The final line reports converted, failed
and bytes before and after. The plan counts it with mode=convert; the
legacy gallery stream refuses to attach to a running conversion.

* feat(thumbnails): thumbnail settings in Appearance and Convert outdated in the workspace

System > Appearance gains a Thumbnails surface: format (WebP, JPEG XL,
JPEG), quality and size limit, saved to the server with the settings
revision. JPEG XL is offered only when the server has an encoder, else
the option is disabled with the server's reason (D130); a note says
when this browser cannot show JPEG XL. Saving a new format converts
nothing: the row then says previews keep their old format.

Thumbnail maintenance gains the Convert outdated scope and names the
server's settings instead of its own quality and size fields (D131).
Overview's thumbnail row reads N missing, M outdated, K failed and
offers Convert outdated while previews are outdated.

The workspace decodes a tiny JPEG XL once: where it cannot, cards, the
Library and the inspector cover load the original for a .jxl preview,
and any preview that fails to load falls back to the original. The
viewer and downloads keep using the original (regression test).
README explains enabling JPEG XL; TESTING.md records D130 and D131.

* test(thumbnails): coverage floors for the thumbnail modules and WebP in page workflows

The two new frontend modules enter the coverage baseline (98% lines);
other floors only rise. The visual fixture's preview is WebP and
Appearance has its Thumbnails surface in the System shell check.

* fix(thumbnails): say when the thumbnail settings could not be read

Like Appearance's other server rows, the Thumbnails rows show 'Server
settings could not be read.' while the read failed, instead of only
staying disabled. Firefox exposed the gap: its JPEG XL note arrived
first and changed the row notes the page workflow counted.

* test(thumbnails): accept the legacy preview's spelling a case-insensitive disk finds

On Windows and macOS the '.jpg' lookup finds an older release's
b_thumb.JPG first, so the listed URL spells '.jpg'; it names the same
file there. The test now accepts either spelling and checks the URL
serves that preview.

* fix(thumbnails): address the final review of the thumbnail format work

- ffmpeg writes JPEG XL with -update 1, so a % in a file name is never an
  image-sequence pattern, and reads videos as file:<path>. The clear and a
  startup sweep remove temp files that interrupted writes left behind.
- Convert outdated converts each group of same-stem files once, from the
  first source in the R2 order. An old preview that is already gone counts
  as removed, and each file's bytes count once. A current preview is only
  kept if it decodes.
- An encoder that fails makes the write detect encoders again once. Another
  encoder is used if one is found; with none, the file is written as WebP
  and the availability Appearance shows is refreshed.
- Changing the thumbnail format, quality or size while Convert outdated runs
  returns 409 busy. If the format still changes underneath, the job stops
  without removing anything.
- Legacy preview spellings are matched case-insensitively, so X_thumb.JPG
  counts as outdated.
- History's cover uses the same lookup as Images. It serves .jxl only when
  Accept lists image/jxl, and otherwise the original or the placeholder.
- A video whose thumbnail the browser cannot show keeps its own element
  (Images) or its label (Library).

* fix(thumbnails): keep the new preview, probe encoders only when gone, sweep reused PIDs

- Convert never removes a path that is the preview it just wrote. It
  compares the device and inode, or the resolved and normcased paths when
  the disk has no inode numbers. This covers x_thumb.JPG on a
  case-insensitive disk.
- A JPEG XL encode failure re-runs encoder detection only when the
  encoder's binary or module is gone. A "no encoder" result is checked
  again on the settings read, on a jxl save, and after 60 s, so one slow
  probe no longer turns JPEG XL off until a restart.
- The startup sweep now also removes temp files that carry this process's
  PID but predate its start. Containers reuse PIDs.

* fix(history): let the cover ask for JPEG XL when this browser decodes it

Firefox can decode JPEG XL without listing image/jxl in Accept. When the
workspace's probe decodes JPEG XL, it adds jxl=1 to the History cover URL.
The server serves a .jxl preview when that flag is set or when Accept
lists image/jxl. In every other case it falls back as before. The flag
accepts only 0 or 1, and the response stays no-store.

* fix(thumbnails): keep going past the per-batch cap until every preview is made

The missing, rebuild and Convert outdated jobs stopped after
MAX_THUMBNAIL_FILES (10,000) files and said "N more on the next run", but
nothing ever started that next run. The cap now bounds one batch. After
each batch the job plans again, leaving out every file it already worked
on, and continues until nothing is left, the job is cancelled, or a batch
makes no progress. That last case stops on files that fail every time
instead of looping over them.

Activity progress counts against the overall total, and the final line and
the legacy stream's complete frame report every batch. Admission, worker
threads, cancellation and the #316 rules are unchanged. The Thumbnail
maintenance dialog now counts all the work instead of saying "more on the
next run".
2026-10-24 21:00:30 -07:00

229 lines
8.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Thumbnail settings and names (#317): the one place every preview writer reads.
Settings (System › Appearance, ``POST /prompt_manager/settings``, config.json
``thumbnails``): ``thumbnail_format`` (``webp`` default, ``jxl``, ``jpeg``),
``thumbnail_quality`` (1–100, default 80) and ``thumbnail_edge`` (the longest
edge, 128–2048 px, default 512). ``current()`` is the snapshot a writer takes
once per preview; automatic previews, the Activity job, the history route and
the legacy gallery routes all go through it.
Names: a media file ``<rel>/<stem>.<ext>`` previews as
``thumbnails/<rel>/<stem>_thumb<extension of the format>`` (``.webp``,
``.jxl``, ``.jpg``), images and videos alike. Two files with one stem in one
folder share that name (ruling R2). Older releases kept the source's own
extension (``.png``, ``.jpeg``, ``.gif``, ``.webp``, ``.jpg``; ``.jpg`` for a
video): those are read, served and converted, never written. A preview with a
format extension (``.webp``, ``.jxl``, ``.jpg``) belongs to every same-stem
source; a legacy-only one (``.png``, ``.jpeg``, ``.gif``) only to a source
with that extension (``owns``, ruling R4). Lookups take the first existing
preview the source owns, preferring the configured format.
"""
import os
from dataclasses import dataclass
from pathlib import Path
FORMATS = ("webp", "jxl", "jpeg")
FORMAT_EXTENSIONS = {"webp": ".webp", "jxl": ".jxl", "jpeg": ".jpg"}
FORMAT_LABELS = {"webp": "WebP", "jxl": "JPEG XL", "jpeg": "JPEG"}
DEFAULT_FORMAT = "webp"
DEFAULT_QUALITY = 80
DEFAULT_EDGE = 512
MIN_QUALITY, MAX_QUALITY = 1, 100
MIN_EDGE, MAX_EDGE = 128, 2048
# Extensions a format writes, then the ones only older releases wrote.
WRITTEN_EXTENSIONS = (".webp", ".jxl", ".jpg")
LEGACY_EXTENSIONS = (".png", ".jpeg", ".gif")
THUMBNAIL_EXTENSIONS = WRITTEN_EXTENSIONS + LEGACY_EXTENSIONS
CONTENT_TYPES = {
".webp": "image/webp",
".jxl": "image/jxl",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".png": "image/png",
".gif": "image/gif",
}
THUMB_SUFFIX = "_thumb"
@dataclass(frozen=True)
class ThumbnailSettings:
"""One preview's settings: the format, the quality and the longest edge."""
format: str
quality: int
edge: int
@property
def extension(self):
return FORMAT_EXTENSIONS[self.format]
@property
def size(self):
return (self.edge, self.edge)
def describe(self):
"""``WebP · quality 80 · 512 px`` (log lines and the job's scope)."""
return f"{FORMAT_LABELS[self.format]} · quality {self.quality} · {self.edge} px"
def current():
"""The configured settings now (read once per preview or per run)."""
from ..config import PromptManagerConfig
fmt = PromptManagerConfig.THUMBNAIL_FORMAT
return ThumbnailSettings(
fmt if fmt in FORMATS else DEFAULT_FORMAT,
int(PromptManagerConfig.THUMBNAIL_QUALITY),
int(PromptManagerConfig.THUMBNAIL_EDGE),
)
def _whole(value, low, high, message):
if type(value) is not int or not low <= value <= high:
raise ValueError(message)
return value
def validate_format(value):
if not isinstance(value, str) or value not in FORMATS:
raise ValueError('thumbnail_format must be "webp", "jxl" or "jpeg"')
return value
def validate_quality(value):
return _whole(
value,
MIN_QUALITY,
MAX_QUALITY,
f"thumbnail_quality must be a whole number from {MIN_QUALITY} to {MAX_QUALITY}",
)
def validate_edge(value):
return _whole(
value,
MIN_EDGE,
MAX_EDGE,
"thumbnail_edge must be a whole number of pixels "
f"from {MIN_EDGE} to {MAX_EDGE}",
)
# ── names ────────────────────────────────────────────────────────────
def thumbnail_stem_rel(rel_path):
"""``thumbnails/<rel without extension>_thumb`` (POSIX)."""
return f"thumbnails/{Path(rel_path).with_suffix('').as_posix()}{THUMB_SUFFIX}"
def thumbnail_rel(rel_path, extension=None):
"""The preview of *rel_path* in *extension* (the configured one when None)."""
return thumbnail_stem_rel(rel_path) + (extension or current().extension)
# Ruling R2: files sharing a stem share one preview, made from the first
# source in this order: these images, then videos (by extension name).
IMAGE_SOURCE_ORDER = (".png", ".jpg", ".jpeg", ".webp", ".gif")
def source_rank(source_extension):
"""Sort key of a source extension in R2's order (images first)."""
extension = source_extension.lower()
if extension in IMAGE_SOURCE_ORDER:
return (0, IMAGE_SOURCE_ORDER.index(extension), extension)
return (1, 0, extension)
def owns(thumb_extension, source_extension):
"""Whether a ``_thumb<thumb_extension>`` preview can belong to a source
with *source_extension* (ruling R4)."""
thumb_extension = thumb_extension.lower()
if thumb_extension in WRITTEN_EXTENSIONS:
return True
if thumb_extension in LEGACY_EXTENSIONS:
return thumb_extension == source_extension.lower()
return False
def _legacy_extension(source_extension):
from .inspection_service import VIDEO_EXTENSIONS
source_extension = source_extension.lower()
return ".jpg" if source_extension in VIDEO_EXTENSIONS else source_extension
def candidate_extensions(source_extension, preferred=None):
"""The preview extensions a source owns, in lookup order: the configured
one, the name an older release gave it, then the other written ones."""
preferred = preferred or current().extension
ordered = [preferred, _legacy_extension(source_extension), *WRITTEN_EXTENSIONS]
seen = []
for extension in ordered:
if extension not in seen and owns(extension, source_extension):
seen.append(extension)
return tuple(seen)
def owned_extensions(source_extension, preferred=None):
"""``candidate_extensions`` plus the other spellings an older release
may have given a legacy preview (review M1): the source's own
(``X_thumb.JPG`` for ``X.JPG``) and the upper-case legacy one."""
extensions = list(candidate_extensions(source_extension, preferred))
legacy = _legacy_extension(source_extension)
for spelling in (source_extension, legacy.upper()):
if spelling not in extensions and owns(spelling, source_extension):
extensions.append(spelling)
return tuple(extensions)
def _is_preview_file(path):
try:
return not path.is_symlink() and path.is_file()
except OSError:
return False
def owned_in_folder(folder, stem, source_extension, preferred=None):
"""Yield the existing previews ``<folder>/<stem><ext>`` a source with
*source_extension* owns, in lookup order (regular files, no links; one
file found under two spellings on a case-insensitive disk once)."""
seen = set()
for extension in owned_extensions(source_extension, preferred):
path = Path(folder) / (stem + extension)
if not _is_preview_file(path):
continue
try:
stat = path.stat()
identity = (stat.st_dev, stat.st_ino) if stat.st_ino else str(path)
except OSError:
continue
if identity in seen:
continue # the same file under another case (Windows, macOS)
seen.add(identity)
yield path
def _owned(root, rel_path, preferred):
rel_path = Path(rel_path)
stem = Path(root) / thumbnail_stem_rel(rel_path)
return owned_in_folder(stem.parent, stem.name, rel_path.suffix, preferred)
def owned_thumbnails(root, rel_path, preferred=None):
"""Every existing preview of *rel_path* under *root*, in lookup order."""
return list(_owned(root, rel_path, preferred))
def existing_thumbnail(root, rel_path, preferred=None):
"""The preview a listing shows for *rel_path*: the first owned one that
exists (the configured format first), or None."""
return next(_owned(root, rel_path, preferred), None)
def content_type(path):
"""The Content-Type of a preview file by its extension, or None."""
return CONTENT_TYPES.get(os.path.splitext(str(path))[1].lower())