p101111's picture
Upload 3 files
7897fe2 verified
Raw History Blame Contribute Delete
10.6 kB
"""
API routes for the Output Gallery.
GET /gallery/files – paginated file listing (images + videos)
POST /gallery/rate – set/clear a 1-5 star rating for a file
POST /gallery/download – download selected files as a ZIP archive
"""
from __future__ import annotations
import io
import json
import os
import zipfile
from pathlib import Path
from aiohttp import web
try:
import folder_paths
except ImportError:
folder_paths = None # type: ignore[assignment]
IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".webp", ".gif"}
VIDEO_EXTS = {".mp4", ".webm", ".mov", ".avi", ".mkv"}
# Directory names that are never scanned β€” they typically hold downscaled
# previews/thumbnails generated by external tools or ComfyUI plugins.
_SKIP_DIRS: set[str] = {
"_thumbs",
"thumbs",
"thumbnail",
"thumbnails",
"_thumbnail",
"_thumbnails",
"thumb",
".thumbnails",
".thumbs",
"preview",
"previews",
"_preview",
"_previews",
"cache",
".cache",
}
_RATINGS_PATH = Path(__file__).parent / "ratings.json"
# ── Output directory ─────────────────────────────────────────────────────────
def _output_dir() -> str:
if folder_paths:
return folder_paths.get_output_directory()
return os.path.join(os.path.dirname(__file__), "output")
# ── Ratings persistence ───────────────────────────────────────────────────────
def _load_ratings() -> dict:
try:
if _RATINGS_PATH.exists():
return json.loads(_RATINGS_PATH.read_text(encoding="utf-8"))
except Exception:
pass
return {}
def _save_ratings(ratings: dict) -> None:
_RATINGS_PATH.write_text(
json.dumps(ratings, indent=2, ensure_ascii=False), encoding="utf-8"
)
def _rating_key(filename: str, subfolder: str) -> str:
return f"{subfolder}/{filename}" if subfolder else filename
# ── File scan ─────────────────────────────────────────────────────────────────
def _scan(
media_type: str = "all", min_rating: int = 0, exact_rating: int = 0
) -> list[dict]:
"""Walk the output directory and return metadata, sorted newest-first."""
base = _output_dir()
ratings = _load_ratings()
results: list[dict] = []
for root, dirs, filenames in os.walk(base):
dirs[:] = sorted(
d for d in dirs if not d.startswith(".") and d.lower() not in _SKIP_DIRS
)
for name in filenames:
if name.startswith("."):
continue
ext = os.path.splitext(name)[1].lower()
if ext in VIDEO_EXTS:
kind = "video"
elif ext in IMAGE_EXTS:
kind = "image"
else:
continue
if media_type == "image" and kind != "image":
continue
if media_type == "video" and kind != "video":
continue
full = os.path.join(root, name)
subfolder = os.path.relpath(root, base)
subfolder = "" if subfolder == "." else subfolder
rating = ratings.get(_rating_key(name, subfolder), 0)
if exact_rating > 0:
if rating != exact_rating:
continue
elif min_rating > 0 and rating < min_rating:
continue
try:
st = os.stat(full)
except OSError:
continue
results.append(
{
"filename": name,
"subfolder": subfolder,
"type": "output",
"kind": kind,
"mtime": st.st_mtime,
"size": st.st_size,
"rating": rating,
}
)
results.sort(key=lambda f: f["mtime"], reverse=True)
return results
# ── Route registration ────────────────────────────────────────────────────────
def setup_routes(routes) -> None:
# ── GET /gallery/files ───────────────────────────────────────────────────
@routes.get("/gallery/files")
async def get_files(request): # type: ignore[return]
try:
page = max(1, int(request.rel_url.query.get("page", 1)))
page_size = max(
1, min(200, int(request.rel_url.query.get("page_size", 50)))
)
media_type = request.rel_url.query.get("type", "all")
min_rating = max(0, min(5, int(request.rel_url.query.get("min_rating", 0))))
exact_rating = max(
0, min(5, int(request.rel_url.query.get("exact_rating", 0)))
)
if media_type not in ("all", "image", "video"):
media_type = "all"
files = _scan(media_type, min_rating, exact_rating)
total = len(files)
start = (page - 1) * page_size
end = start + page_size
return web.json_response(
{
"files": files[start:end],
"total": total,
"page": page,
"page_size": page_size,
"has_more": end < total,
}
)
except Exception as exc: # noqa: BLE001
return web.json_response({"error": str(exc)}, status=500)
# ── POST /gallery/rate ───────────────────────────────────────────────────
@routes.post("/gallery/rate")
async def rate_file(request): # type: ignore[return]
try:
data = await request.json()
filename = str(data.get("filename", "")).strip()
subfolder = str(data.get("subfolder", "")).strip()
rating = max(0, min(5, int(data.get("rating", 0))))
if not filename:
return web.json_response({"error": "filename required"}, status=400)
ratings = _load_ratings()
key = _rating_key(filename, subfolder)
if rating == 0:
ratings.pop(key, None)
else:
ratings[key] = rating
_save_ratings(ratings)
return web.json_response({"ok": True, "rating": rating})
except Exception as exc: # noqa: BLE001
return web.json_response({"error": str(exc)}, status=500)
# ── POST /gallery/download ───────────────────────────────────────────────
@routes.post("/gallery/download")
async def bulk_download(request): # type: ignore[return]
try:
data = await request.json()
items = data.get("files", [])
if not items:
return web.json_response({"error": "no files specified"}, status=400)
base = Path(_output_dir()).resolve()
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
for fi in items:
name = str(fi.get("filename", ""))
subfolder = str(fi.get("subfolder", ""))
# Security: keep resolved path inside the output directory
target = (base / subfolder / name).resolve()
base_str = str(base)
if not (
str(target) == base_str
or str(target).startswith(base_str + os.sep)
):
continue
if not target.is_file():
continue
arcname = f"{subfolder}/{name}".lstrip("/") if subfolder else name
zf.write(target, arcname)
buf.seek(0)
return web.Response(
body=buf.getvalue(),
content_type="application/zip",
headers={
"Content-Disposition": 'attachment; filename="gallery_export.zip"'
},
)
except Exception as exc: # noqa: BLE001
return web.json_response({"error": str(exc)}, status=500)
# ── POST /gallery/delete ─────────────────────────────────────────────────
@routes.post("/gallery/delete")
async def delete_files(request): # type: ignore[return]
try:
data = await request.json()
items = data.get("files", [])
if not items:
return web.json_response({"error": "no files specified"}, status=400)
base = Path(_output_dir()).resolve()
deleted = []
ratings = _load_ratings()
ratings_changed = False
for fi in items:
name = str(fi.get("filename", "")).strip()
subfolder = str(fi.get("subfolder", "")).strip()
if not name:
continue
# Security: keep resolved path inside the output directory
target = (base / subfolder / name).resolve()
base_str = str(base)
if not (
str(target) == base_str
or str(target).startswith(base_str + os.sep)
):
continue
if target.is_file():
os.remove(target)
deleted.append({"filename": name, "subfolder": subfolder})
# Also remove rating
key = _rating_key(name, subfolder)
if key in ratings:
ratings.pop(key, None)
ratings_changed = True
if ratings_changed:
_save_ratings(ratings)
return web.json_response({"ok": True, "deleted": deleted})
except Exception as exc: # noqa: BLE001
return web.json_response({"error": str(exc)}, status=500)