Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: resolve the gallery folder once per image and video listing (#15580)

Daniel Han9f9adae956c5
diff --git a/studio/backend/core/inference/image_gallery.py b/studio/backend/core/inference/image_gallery.py
index 53bc4df8aca..71faee6c049 100644
--- a/studio/backend/core/inference/image_gallery.py
+++ b/studio/backend/core/inference/image_gallery.py
@@ -180,17 +180,21 @@ def save(image: Any, meta: dict[str, Any]) -> dict[str, Any]:
except OSError:
pass
raise
- return _record(image_id, meta)
+ return _record(image_id, meta, directory = directory)
def _record(
image_id: str,
meta: dict[str, Any],
flags: Optional[dict[str, dict[str, Any]]] = None,
+ *,
+ directory: Optional[Path] = None,
) -> dict[str, Any]:
+ if directory is None:
+ directory = gallery_dir()
# flags are library state, not recipe: they come from the sidecar store, never the PNG chunk
if flags is None:
- flags = gallery_flags.read(gallery_dir())
+ flags = gallery_flags.read(directory)
return {
**meta,
"id": image_id,
@@ -198,7 +202,7 @@ def _record(
**gallery_flags.flags_for(flags, image_id),
# The server's own sort key, so a client re-sort agrees with it (created_at can differ).
"order_at": gallery_flags.order_rank(
- flags, image_id, _mtime(gallery_dir() / f"{image_id}.png")
+ flags, image_id, _mtime(directory / f"{image_id}.png")
),
}
@@ -207,9 +211,10 @@ def image_path(image_id: str) -> Optional[Path]:
"""Resolve an id to its on-disk PNG, or None if missing / unsafe."""
if not _ID_RE.match(image_id):
return None
- path = gallery_dir() / f"{image_id}.png"
+ directory = gallery_dir()
+ path = directory / f"{image_id}.png"
try:
- path.resolve().relative_to(gallery_dir().resolve())
+ path.resolve().relative_to(directory.resolve())
except ValueError:
return None
return path if path.is_file() else None
@@ -289,10 +294,11 @@ def list_images(
) -> list[dict[str, Any]]:
"""Pinned first, then mtime; archived selects a shelf, never widens; valid filter runs before paging."""
try:
- paths = list(gallery_dir().glob("*.png"))
+ directory = gallery_dir()
+ paths = list(directory.glob("*.png"))
except OSError:
return []
- flags = gallery_flags.read(gallery_dir())
+ flags = gallery_flags.read(directory)
# Shelf split and pin sort use file stems before any recipe read, keeping the early break intact.
paths = [p for p in paths if gallery_flags.is_archived(flags, p.stem) == archived]
paths.sort(
@@ -309,7 +315,7 @@ def list_images(
meta = _read_meta(path)
if meta is None:
continue
- record = _record(path.stem, meta, flags)
+ record = _record(path.stem, meta, flags, directory = directory)
if valid is not None and not valid(record):
continue
records.append(record)
diff --git a/studio/backend/core/inference/video_gallery.py b/studio/backend/core/inference/video_gallery.py
index 9e740c3728a..e1bd00b8381 100644
--- a/studio/backend/core/inference/video_gallery.py
+++ b/studio/backend/core/inference/video_gallery.py
@@ -157,17 +157,21 @@ def save(
except OSError:
pass
raise
- return _record(video_id, meta)
+ return _record(video_id, meta, directory = directory)
def _record(
video_id: str,
meta: dict[str, Any],
flags: Optional[dict[str, dict[str, Any]]] = None,
+ *,
+ directory: Optional[Path] = None,
) -> dict[str, Any]:
+ if directory is None:
+ directory = gallery_dir()
# flags are library state, not recipe: they come from the .flags.json store, never the sidecar
if flags is None:
- flags = gallery_flags.read(gallery_dir())
+ flags = gallery_flags.read(directory)
return {
**meta,
"id": video_id,
@@ -175,18 +179,20 @@ def _record(
**gallery_flags.flags_for(flags, video_id),
# The server's own sort key, so a client re-sort agrees with it (created_at can differ).
"order_at": gallery_flags.order_rank(
- flags, video_id, _mtime(path) if (path := video_path(video_id)) else 0.0
+ flags, video_id, _mtime(path) if (path := video_path(video_id, directory)) else 0.0
),
}
-def video_path(video_id: str) -> Optional[Path]:
+def video_path(video_id: str, directory: Optional[Path] = None) -> Optional[Path]:
"""Resolve an id to its on-disk MP4, or None if missing / unsafe."""
if not _ID_RE.match(video_id):
return None
- path = gallery_dir() / f"{video_id}.mp4"
+ if directory is None:
+ directory = gallery_dir()
+ path = directory / f"{video_id}.mp4"
try:
- path.resolve().relative_to(gallery_dir().resolve())
+ path.resolve().relative_to(directory.resolve())
except ValueError:
return None
return path if path.is_file() else None
@@ -635,8 +641,8 @@ def _transcode_gif(path: Path) -> bytes:
raise RuntimeError(f"GIF export failed to decode the clip: {exc}") from exc
-def _sidecar_path(video_id: str) -> Path:
- return gallery_dir() / f"{video_id}.json"
+def _sidecar_path(video_id: str, directory: Optional[Path] = None) -> Path:
+ return (gallery_dir() if directory is None else directory) / f"{video_id}.json"
# Keys every genuine Unsloth sidecar carries; delete()/clear() own only pairs with all, so a partial hand-dropped MP4 is never destroyed. Key-presence only.
@@ -702,10 +708,11 @@ def list_videos(
) -> list[dict[str, Any]]:
"""Pinned then newest-first; archived selects one shelf, does not widen it; valid filters run before slicing so has_more counts accepted clips"""
try:
- paths = list(gallery_dir().glob("*.mp4"))
+ directory = gallery_dir()
+ paths = list(directory.glob("*.mp4"))
except OSError:
return []
- flags = gallery_flags.read(gallery_dir())
+ flags = gallery_flags.read(directory)
# Shelf split and pin sort use stems only, before any sidecar read, keeping the early break.
paths = [p for p in paths if gallery_flags.is_archived(flags, p.stem) == archived]
paths.sort(
@@ -719,10 +726,10 @@ def list_videos(
want = None if limit is None else offset + limit
records = []
for path in paths:
- meta = _read_meta(_sidecar_path(path.stem))
+ meta = _read_meta(_sidecar_path(path.stem, directory))
if meta is None:
continue
- record = _record(path.stem, meta, flags)
+ record = _record(path.stem, meta, flags, directory = directory)
if valid is not None and not valid(record):
continue
records.append(record)
diff --git a/studio/backend/tests/test_image_gallery.py b/studio/backend/tests/test_image_gallery.py
index d4207b5e57e..d6ec5bead19 100644
--- a/studio/backend/tests/test_image_gallery.py
+++ b/studio/backend/tests/test_image_gallery.py
@@ -101,6 +101,18 @@ def test_list_paginates_with_limit_offset():
assert len(gallery.list_images(offset = 4)) == 1
+def test_listing_resolves_the_folder_once(monkeypatch):
+ for i in range(4):
+ _save_with_mtime(f"p{i}", float(i))
+ calls = []
+ real = gallery.gallery_dir
+ monkeypatch.setattr(gallery, "gallery_dir", lambda: calls.append(1) or real())
+ listed = gallery.list_images()
+ assert len(calls) == 1
+ assert [r["prompt"] for r in listed] == ["p3", "p2", "p1", "p0"]
+ assert [r["order_at"] for r in listed] == [3.0, 2.0, 1.0, 0.0]
+
+
def test_negative_prompt_recorded_in_parameters():
record = gallery.save(_img(), _meta(negative_prompt = "blurry"))
raw = base64.b64decode(gallery.image_b64(record["id"]))
diff --git a/studio/backend/tests/test_video_gallery.py b/studio/backend/tests/test_video_gallery.py
index 278719db084..52aa0fee034 100644
--- a/studio/backend/tests/test_video_gallery.py
+++ b/studio/backend/tests/test_video_gallery.py
@@ -88,6 +88,18 @@ def test_list_paginates_with_limit_offset():
assert len(gallery.list_videos(offset = 4)) == 1
+def test_listing_resolves_the_folder_once(monkeypatch):
+ for i in range(4):
+ _save_with_mtime(f"p{i}", float(i))
+ calls = []
+ real = gallery.gallery_dir
+ monkeypatch.setattr(gallery, "gallery_dir", lambda: calls.append(1) or real())
+ listed = gallery.list_videos()
+ assert len(calls) == 1
+ assert [r["prompt"] for r in listed] == ["p3", "p2", "p1", "p0"]
+ assert [r["order_at"] for r in listed] == [3.0, 2.0, 1.0, 0.0]
+
+
def test_video_path_rejects_unsafe_ids():
assert gallery.video_path("../../etc/passwd") is None
assert gallery.video_path("/etc/passwd") is None