Speed up explorer scrolling and add Favorites view
Browse filesFiles changed (3)
- app.py+126-62
- explorer.css+7-2
- explorer.js+201-83
20 unmodified lines2122232425262785 unmodified lines1131141151161171181191201212300 unmodified lines242224232424242524262427242824212429243024232424242524262427243124322433243432 unmodified lines2467246824692466247024712472247324747 unmodified lines2482248324842485248624872488248924902491249224932494249559 unmodified lines255525562557254525582559256025612562256325648 unmodified lines2573257425752576257725782579258025812582258325842585258625602561256225632564256525662567258725882589259025912592259325942595259625972598259926002601256926022603260426052606260726081333 unmodified lines39423943394439093945394639473948391339143915391639173918394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639203921397739783979392339243980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240033926400440054006400739294008400940104011401240132 unmodified lines40164017401839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539664019402040214022402340244025402640274028402940304031403271 unmodified lines41044105410641074044404540464047410841094110411141124113411420 unmodified linesfrom datetime import datetime
from functools import lru_cache
from io import BytesIO
from itertools import islice
from pathlib import Path
from urllib.parse import quote, unquote, urlparse
from zoneinfo import ZoneInfo85 unmodified linesPREVIEW_CACHE_SIZE = 256
PREVIEW_QUALITY = 70
PREVIEW_SIZE = 320
EXPLORER_PAGE_SIZE = 80
EXPLORER_MAX_PAGE_SIZE = 200
EXPLORER_DB_TIMEOUT = 30
IMAGE_KEY_CACHE_SIZE = 512
DUPLICATE_HASH_SIZE = 16
DUPLICATE_HASH_DISTANCE = 242300 unmodified lines
def encrypted_image_bytes(image):
return encrypt_image_data(image_png_bytes(image))
def encrypt_image_data(data, salt=None):
salt = os.urandom(SALT_SIZE)
salt = salt if salt is not None else os.urandom(SALT_SIZE)
nonce = os.urandom(NONCE_SIZE)
encrypted = AESGCM(image_key(salt)).encrypt(
nonce,
image_png_bytes(image),
FILE_MAGIC,
)
encrypted = AESGCM(image_key(salt)).encrypt(nonce, data, FILE_MAGIC)
return FILE_MAGIC + salt + nonce + encrypted
32 unmodified lines
def star_database():
STAR_DB.parent.mkdir(parents=True, exist_ok=True)
database = sqlite3.connect(STAR_DB)
database = sqlite3.connect(STAR_DB, timeout=EXPLORER_DB_TIMEOUT)
database.execute("PRAGMA journal_mode=WAL")
database.execute(
"CREATE TABLE IF NOT EXISTS stars (path TEXT PRIMARY KEY)"
)7 unmodified lines artists TEXT NOT NULL
)"""
)
database.execute(
"""CREATE TABLE IF NOT EXISTS image_previews (
path TEXT PRIMARY KEY,
modified INTEGER NOT NULL,
size INTEGER NOT NULL,
data BLOB NOT NULL
)"""
)
return database
59 unmodified lines
def stored_bytes(path):
data = path.read_bytes()
return decrypt_image_data(path.read_bytes())
def decrypt_image_data(data):
if not data.startswith(FILE_MAGIC):
raise HTTPException(500, "invalid encrypted image")
salt_start = len(FILE_MAGIC)8 unmodified lines
@lru_cache(maxsize=PREVIEW_CACHE_SIZE)
def stored_preview(path, modified, size):
relative = path.relative_to(IMAGE_DIR.resolve()).as_posix()
database = star_database()
try:
cached = database.execute(
"""SELECT data FROM image_previews
WHERE path = ? AND modified = ? AND size = ?""",
(relative, modified, size),
).fetchone()
if cached is not None:
return decrypt_image_data(cached[0])
source = path.read_bytes()
with Image.open(BytesIO(stored_bytes(path))) as image:
image.thumbnail((PREVIEW_SIZE, PREVIEW_SIZE))
data = BytesIO()
image.save(
data,
format="WEBP",
quality=PREVIEW_QUALITY,
method=0,
with Image.open(BytesIO(decrypt_image_data(source))) as image:
image.thumbnail((PREVIEW_SIZE, PREVIEW_SIZE))
data = BytesIO()
image.save(
data,
format="WEBP",
quality=PREVIEW_QUALITY,
method=0,
)
preview = data.getvalue()
salt = source[len(FILE_MAGIC):len(FILE_MAGIC) + SALT_SIZE]
database.execute(
"INSERT OR REPLACE INTO image_previews VALUES (?, ?, ?, ?)",
(relative, modified, size, encrypt_image_data(preview, salt)),
)
return data.getvalue()
database.commit()
return preview
finally:
database.close()
def reserve_matrix_grid(folder):1333 unmodified lines )
def explorer_images(folder, starred):
def explorer_files(folder):
path = (IMAGE_DIR / folder).resolve()
if path.parent != IMAGE_DIR.resolve() or not path.is_dir():
raise HTTPException(404, "folder not found")
database = star_database()
images = []
try:
with os.scandir(path) as entries:
files = [
item
with os.scandir(path) as entries:
return [
(Path(folder) / item.name).as_posix()
for item in sorted(entries, key=natural_key, reverse=True)
if Path(item.name).suffix.casefold() in IMAGE_SUFFIXES
and item.is_file()
]
@api.get("/api/images", dependencies=[Depends(require_pass)])
def image_list(
folder: str = Query(None),
infinite: bool = Query(False),
favorites: bool = Query(False),
search: str = Query(""),
offset: int = Query(0, ge=0),
limit: int = Query(EXPLORER_PAGE_SIZE, ge=1, le=EXPLORER_MAX_PAGE_SIZE),
):
grouped = infinite or (favorites and folder is None)
root = IMAGE_DIR
if not root.is_dir():
key = "groups" if grouped else "folders" if folder is None else "images"
return {key: [], "next_offset": None}
if grouped or folder is None:
with os.scandir(root) as entries:
folders = [
item.name
for item in sorted(entries, key=natural_key, reverse=True)
if Path(item.name).suffix.casefold() in IMAGE_SUFFIXES
and item.is_file()
if item.is_dir(follow_symlinks=False)
and (grouped or explorer_folder_has_images(item.path))
]
for item in files:
relative = (Path(folder) / item.name).as_posix()
if not grouped:
return {"folders": [{"name": name} for name in folders]}
else:
folders = [folder]
starred = starred_paths()
if favorites:
favorite_folders = {relative.split("/", 1)[0] for relative in starred}
folders = [name for name in folders if name in favorite_folders]
files = (relative for name in folders for relative in explorer_files(name)
if not favorites or relative in starred)
database = star_database()
try:
query = search.strip().casefold()
if query:
files = (relative for relative in files if (
query in Path(relative).with_suffix(".png").name.casefold()
or any(query in prompt.casefold() for prompt in stored_prompt(
root / relative, relative, database
)[:2])
))
page = list(islice(files, offset, offset + limit + 1))
images = []
for relative in page[:limit]:
prompt, second_prompt, artists = stored_prompt(
Path(item.path), relative, database
root / relative, relative, database
)
stat = (root / relative).stat()
images.append({
"name": Path(item.name).with_suffix(".png").name,
"name": Path(relative).with_suffix(".png").name,
"path": relative,
"version": f"{stat.st_mtime_ns}-{stat.st_size}",
"starred": relative in starred,
"prompt": prompt,
"second_prompt": second_prompt,2 unmodified lines database.commit()
finally:
database.close()
return images
@api.get("/api/images", dependencies=[Depends(require_pass)])
def image_list(folder: str = Query(None), infinite: bool = Query(False)):
root = IMAGE_DIR
if not root.is_dir():
return {"groups": []} if infinite else (
{"folders": []} if folder is None else {"images": []}
)
with os.scandir(root) as entries:
folders = [
item.name
for item in sorted(entries, key=natural_key, reverse=True)
if item.is_dir(follow_symlinks=False)
and explorer_folder_has_images(item.path)
]
if folder is None and not infinite:
return {"folders": [{"name": name} for name in folders]}
starred = starred_paths()
if infinite:
return {
"groups": [
{"name": name, "images": explorer_images(name, starred)}
for name in folders
]
}
return {"images": explorer_images(folder, starred)}
result = {"next_offset": offset + limit if len(page) > limit else None}
if grouped:
groups = {}
for image in images:
name = image["path"].split("/", 1)[0]
groups.setdefault(name, []).append(image)
result["groups"] = [{"name": name, "images": items}
for name, items in groups.items()]
else:
result["images"] = images
return result
@api.post("/api/images/star", dependencies=[Depends(require_pass)])71 unmodified lines path.unlink()
database = star_database()
try:
for table in ("image_prompts", "image_previews"):
database.executemany(
"DELETE FROM image_prompts WHERE path = ?",
((relative,) for relative in relatives),
)
database.executemany(
f"DELETE FROM {table} WHERE path = ?",
((relative,) for relative in relatives),
)
database.commit()
finally:
database.close()1123415 unmodified lines2021222323242526143 unmodified lines170171172173174175176177178179180@import url('https://fonts.googleapis.com/css2?family=Inter:wght@450;600&display=swap');@import url('https://fonts.googleapis.com/css2?family=Spline+Sans:wght@450;600&display=swap');
:root { --bg: #111;15 unmodified linesbody { background: var(--bg); color: var(--text); font-family: Inter, sans-serif; font-family: 'Spline Sans', sans-serif; font-weight: 450; margin: 0;}143 unmodified lines margin-top: 2rem;}
.load-more { display: block; margin: var(--gap) auto;}
.preview { background: var(--bg); border: 0;3 unmodified lines456787891011121314151617181933 unmodified lines5354555657585960619 unmodified lines717273677475767778798081828384858687888990919271727374757677787980818283848586878893949596979192939899100101961021031049910010110210510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817923 unmodified lines20320420513220620720820921021113813914014114214314414514614714814921221321421521621721821922022122222322422522622722812 unmodified lines24124224324424524624724824925025125225325425516917017117217325625725825926026126226326426517726626726826918018118218318418518618718827027127227327427527627727827928028128228328420 unmodified lines30530630730821530931031131225 unmodified lines3383393402472482492503413422513433443453463472573483493503513522593533543553563573583593603613623633643653663673682713693703713723733743753763773783793803813823833843853863873883893903913923933943953962893973983994003 unmodified lines40440540629930030140740840941041141241341441541641741841930730830931031131231342042142242339 unmodified lines46346446535946646746846961 unmodified lines5315325334275345355365372 unmodified lines5405415424364374384395435445455465475485495505515525535545555565575585595603 unmodified linesconst $$ = (selector, root = document) => [...root.querySelectorAll(selector)]
const p = new URLSearchParams(location.search).get("p")
const api = (path, query = {}) => `${path}?${new URLSearchParams({ p, ...query })}`
const preview = path => api("/api/images/preview", { path })
const original = path => api("/api/images/original", { path })
const preview = image => api("/api/images/preview", { path: image.path, v: image.version })
const original = image => api("/api/images/original", { path: image.path, v: image.version })
const MIN_ZOOM = 1
const MAX_ZOOM = 8
const ZOOM_STEP = 1.2
const INFINITE = "*"
const FAVORITES = "favorites"
const SEARCH_DELAY = 250
const LOAD_MARGIN = "640px"
const PREVIEW_MARGIN = "320px"
class ImageExplorer extends HTMLElement {
connectedCallback() {33 unmodified lines </dialog>`
this.cache = new Map()
this.setupPreviews()
this.pageObserver = new IntersectionObserver(entries => {
if (entries.some(entry => entry.isIntersecting)) this.loadMore()
}, { rootMargin: LOAD_MARGIN })
this.load()
$(".back", this).addEventListener("click", () => this.load())
$(".date-prev", this).addEventListener("click", () => this.navigateDate(1))9 unmodified lines this.setupLightbox()
}
async load(folder) {
async load(folder, favoritesOnly = false, query = "") {
clearTimeout(this.searchTimer)
this.controller?.abort()
const controller = new AbortController()
this.controller = controller
this.folder = folder
$(".lightbox", this).close()
this.favoritesOnly = folder === FAVORITES || favoritesOnly
this.searchQuery = query
this.images = []
this.imagePaths = new Set()
this.groupGrids = new Map()
this.nextOffset = folder ? 0 : null
this.loadingPage = false
this.more = null
$(".status", this).textContent = "Loading"
this.previewObserver.disconnect()
this.pageObserver.disconnect()
$(".content", this).replaceChildren()
let data = this.cache.get(folder)
if (!data) {
const query = folder === INFINITE
? { infinite: true }
: folder ? { folder } : {}
const response = await fetch(api("/api/images", query))
if (!response.ok) {
$(".status", this).textContent = "Unable to load images"
return
}
data = await response.json()
this.cache.set(folder, data)
}
this.folder = folder
if (!folder) this.folders = data.folders.map(item => item.name)
$("h1", this).textContent = folder === INFINITE
? "Infinite"
: folder || "Image folders"
$("h1", this).textContent = folder === FAVORITES ? "Favorites"
: folder === INFINITE ? "Infinite" : folder || "Image folders"
$(".back", this).hidden = !folder
$(".all", this).textContent = folder ? "Select loaded" : "Select all"
const favorites = $(".favorites", this)
favorites.hidden = !folder
favorites.setAttribute("aria-pressed", "false")
this.favoritesOnly = false
favorites.hidden = !folder || folder === FAVORITES
favorites.setAttribute("aria-pressed", this.favoritesOnly)
this.updateDateNav()
const search = $("input[type=search]", this)
search.value = ""
search.value = query
search.placeholder = folder ? "Search positive prompts" : "Filter folders"
search.setAttribute("aria-label", search.placeholder)
if (folder === INFINITE) this.addGroups(data.groups)
else if (folder) this.addImages(data.images)
else this.addFolders(data.folders)
this.update()
if (folder) {
if (folder !== INFINITE && folder !== FAVORITES) this.addImages([])
this.more = document.createElement("button")
this.more.className = "load-more"
this.more.type = "button"
this.more.textContent = "Load more"
this.more.addEventListener("click", () => this.loadMore())
$(".content", this).append(this.more)
this.pageObserver.observe(this.more)
await this.loadMore()
return
}
try {
let data = this.cache.get(folder)
if (!data) {
const response = await fetch(api("/api/images"), { signal: controller.signal })
if (!response.ok) throw new Error("Unable to load folders")
data = await response.json()
}
if (controller !== this.controller) return
this.cache.set(folder, data)
this.folders = [FAVORITES, INFINITE, ...data.folders.map(item => item.name)]
this.addFolders(data.folders)
this.update()
} catch (error) {
if (controller === this.controller) $(".status", this).textContent = error.message
}
}
loadMore() {
if (this.loadingPage) return this.pageTask
if (this.nextOffset === null || !this.folder || this.pendingStars?.size) return
this.pageTask = this.loadPage()
return this.pageTask
}
async loadPage() {
const controller = this.controller
const grouped = this.folder === INFINITE || this.folder === FAVORITES
const query = {
offset: this.nextOffset,
favorites: this.favoritesOnly,
search: this.searchQuery,
...(grouped ? { infinite: true } : { folder: this.folder }),
}
this.loadingPage = true
this.more.disabled = true
this.more.textContent = "Loading"
try {
const response = await fetch(api("/api/images", query), { signal: controller.signal })
if (!response.ok) throw new Error("Unable to load images")
const data = await response.json()
if (controller !== this.controller) return
if (grouped) this.addGroups(data.groups)
else this.addImages(data.images)
this.nextOffset = data.next_offset
this.more.hidden = this.nextOffset === null
this.more.textContent = "Load more"
this.update()
this.pageObserver.unobserve(this.more)
if (this.nextOffset !== null) this.pageObserver.observe(this.more)
} catch (error) {
if (controller !== this.controller) return
this.pageObserver.unobserve(this.more)
this.more.textContent = "Retry loading images"
$(".status", this).textContent = error.message
} finally {
if (controller === this.controller) {
this.loadingPage = false
this.more.disabled = false
}
}
}
updateDateNav() {23 unmodified lines delete image.dataset.src
this.previewObserver.unobserve(image)
}
}, { rootMargin: "320px" })
}, { rootMargin: PREVIEW_MARGIN })
}
addFolders(folders) {
const grid = document.createElement("div")
grid.className = "grid folders"
const infinite = document.createElement("div")
infinite.className = "folder entry"
infinite.dataset.name = "infinite"
const infiniteOpen = document.createElement("button")
infiniteOpen.className = "folder-open"
infiniteOpen.type = "button"
infiniteOpen.addEventListener("click", () => this.load(INFINITE))
const infiniteName = document.createElement("strong")
infiniteName.textContent = "∞ Infinite"
infiniteOpen.append(infiniteName)
infinite.append(infiniteOpen)
grid.append(infinite)
for (const [folder, label] of [[FAVORITES, "Favorites"], [INFINITE, "Infinite"]]) {
const card = document.createElement("div")
card.className = "folder entry"
card.dataset.name = label.toLowerCase()
const open = document.createElement("button")
open.className = "folder-open"
open.type = "button"
open.addEventListener("click", () => this.load(folder))
const name = document.createElement("strong")
name.textContent = label
open.append(name)
card.append(open)
grid.append(card)
}
for (const folder of folders) {
const card = document.createElement("div")
card.className = "folder entry"12 unmodified lines $(".content", this).append(grid)
}
appendImages(grid, images) {
const cards = document.createDocumentFragment()
for (const image of images) {
if (this.imagePaths.has(image.path)) continue
this.imagePaths.add(image.path)
this.images.push(image)
cards.append(this.card(image))
}
grid.append(cards)
}
addImages(images) {
this.images = images
const grid = document.createElement("div")
grid.className = "grid"
for (const image of images) grid.append(this.card(image))
$(".content", this).append(grid)
let grid = $(".content > .grid", this)
if (!grid) {
grid = document.createElement("div")
grid.className = "grid"
$(".content", this).append(grid)
}
this.appendImages(grid, images)
}
addGroups(groups) {
this.images = groups.flatMap(group => group.images)
const content = $(".content", this)
for (const group of groups) {
let grid = this.groupGrids.get(group.name)
if (!grid) {
const section = document.createElement("section")
section.className = "date-group"
const heading = document.createElement("h2")
heading.textContent = group.name
const grid = document.createElement("div")
grid.className = "grid"
for (const image of group.images) grid.append(this.card(image))
section.append(heading, grid)
content.append(section)
const section = document.createElement("section")
section.className = "date-group"
const heading = document.createElement("h2")
heading.textContent = group.name
grid = document.createElement("div")
grid.className = "grid"
section.append(heading, grid)
content.insertBefore(section, this.more)
this.groupGrids.set(group.name, grid)
}
this.appendImages(grid, group.images)
grid.parentElement.hidden = !$(".entry:not([hidden])", grid)
}
}
20 unmodified lines open.addEventListener("click", () => this.openImage(image))
const picture = document.createElement("img")
picture.alt = image.name
picture.decoding = "async"
picture.dataset.src = preview(image.path)
picture.dataset.src = preview(image)
this.previewObserver.observe(picture)
open.append(picture)
const star = this.starButton(image, "card-star")25 unmodified lines }
setStar(path, starred) {
for (const data of this.cache.values()) {
const images = data.images || data.groups?.flatMap(group => group.images) || []
for (const image of images) {
if (image.path === path) image.starred = starred
for (const image of this.images) {
if (image.path === path) image.starred = starred
}
}
for (const button of $$(".star", this)) {
if (button.dataset.path === path) this.renderStar(button, starred)
}
for (const card of $$(".image", this)) {
if (card.dataset.path === path) card.classList.toggle("favorite", starred)
if (card.dataset.path !== path) continue
card.classList.toggle("favorite", starred)
card.hidden = this.favoritesOnly && !starred
if (card.hidden) $(".item", card).checked = false
}
this.filter($("input[type=search]", this).value)
for (const group of $$(".date-group", this)) {
group.hidden = !$(".entry:not([hidden])", group)
}
this.update()
}
async toggleStar(image) {
this.pendingStars ||= new Set()
if (this.pendingStars.has(image.path)) return
this.pendingStars.add(image.path)
const controller = this.controller
const buttons = $$(".star", this).filter(button => (
button.dataset.path === image.path
))
for (const button of buttons) button.disabled = true
const starred = !image.starred
this.setStar(image.path, starred)
try {
await this.pageTask
if (controller !== this.controller) return
this.setStar(image.path, starred)
const response = await fetch(api("/api/images/star"), {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ path: image.path, starred }),
})
if (!response.ok) throw new Error("Unable to update star")
if (controller === this.controller && this.favoritesOnly && !starred
&& this.nextOffset !== null) {
this.nextOffset = Math.max(0, this.nextOffset - 1)
}
} catch (error) {
this.setStar(image.path, !starred)
$(".status", this).textContent = error.message
} finally {
this.pendingStars.delete(image.path)
for (const button of buttons) button.disabled = false
if (this.more && this.nextOffset !== null) {
this.pageObserver.unobserve(this.more)
this.pageObserver.observe(this.more)
}
}
}
select(checked) {
for (const input of $$(".item", this)) input.checked = checked
for (const input of $$(".entry:not([hidden]) .item", this)) input.checked = checked
this.update()
}
3 unmodified lines }
toggleFavorites() {
this.favoritesOnly = !this.favoritesOnly
$(".favorites", this).setAttribute("aria-pressed", this.favoritesOnly)
this.filter($("input[type=search]", this).value)
this.load(this.folder, !this.favoritesOnly, $("input[type=search]", this).value)
}
filter(value) {
clearTimeout(this.searchTimer)
if (this.folder) {
this.searchTimer = setTimeout(() => {
this.load(this.folder, this.favoritesOnly, value)
}, SEARCH_DELAY)
return
}
const query = value.trim().toLowerCase()
for (const entry of $$(".entry", this)) {
const nameMatch = !query || entry.dataset.name.includes(query)
|| entry.dataset.prompt?.includes(query)
const favoriteMatch = !this.favoritesOnly || entry.classList.contains("favorite")
entry.hidden = !nameMatch || !favoriteMatch
}
for (const group of $$(".date-group", this)) {
group.hidden = !$(".entry:not([hidden])", group)
entry.hidden = !entry.dataset.name.includes(query)
}
}
39 unmodified lines })
if (!response.ok) throw new Error("Delete failed")
this.cache.clear()
await this.load(this.folder)
await this.load(this.folder, this.favoritesOnly, $("input[type=search]", this).value)
} catch (error) {
$(".status", this).textContent = error.message
} finally {61 unmodified lines
showImage(image) {
const dialog = $(".lightbox", this)
$("img", dialog).src = original(image.path)
$("img", dialog).src = original(image)
$("img", dialog).alt = image.name
$(".prompt", dialog).textContent = this.formatPrompt(image)
$(".upscale-status", dialog).textContent = ""2 unmodified lines this.renderStar(star, image.starred)
}
moveImage(step) {
const count = this.images.length
this.imageIndex = (this.imageIndex + step + count) % count
this.showImage(this.images[this.imageIndex])
async moveImage(step) {
const controller = this.controller
const current = this.images[this.imageIndex]
if (step > 0 && this.imageIndex === this.images.length - 1
&& this.nextOffset !== null) await this.loadMore()
if (controller !== this.controller) return
const images = this.images.filter(image => !this.favoritesOnly || image.starred)
if (!images.length) {
$(".lightbox", this).close()
return
}
const index = images.indexOf(current)
const image = images[(index + step + images.length) % images.length]
this.imageIndex = this.images.indexOf(image)
this.showImage(image)
}
formatPrompt(image) {app.py+126-62
explorer.css+7-2
explorer.js+201-83