q6 commited on
Commit
cba1f21
·
1 Parent(s): 1b72208

Add artist prompts and searchable image metadata

Browse files
Files changed (4) hide show
  1. .gitignore +4 -3
  2. app.py +162 -12
  3. explorer.css +22 -0
  4. explorer.js +15 -1
.gitignore CHANGED
@@ -1,5 +1,6 @@
1
  .?
2
  send.py
3
- positive.txt
4
- neg.txt
5
- __pycache__
 
 
1
  .?
2
  send.py
3
+ positive.txt
4
+ neg.txt
5
+ artists.sqlite
6
+ __pycache__
app.py CHANGED
@@ -95,6 +95,8 @@ CUSTOM_NODES_DIR = Path("/tmp/custom_nodes")
95
  OUTPUT_DIR = DATA_DIR / "output"
96
  IMAGE_DIR = DATA_DIR / "img"
97
  STAR_DB = DATA_DIR / "explorer.db"
 
 
98
  TIMEZONE = ZoneInfo("Asia/Singapore")
99
  CPU_DEVICE = torch.device("cpu")
100
  MIB = 1024 * 1024
@@ -352,8 +354,30 @@ def get_local_client():
352
  return local_client
353
 
354
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
355
  def cleanup_mount():
356
  DATA_DIR.mkdir(parents=True, exist_ok=True)
 
357
  if OUTPUT_DIR.exists():
358
  shutil.rmtree(OUTPUT_DIR)
359
  log("Deleted output directory")
@@ -736,6 +760,51 @@ class DirectRequest(BaseModel):
736
  second_cfg: float = Field(DEFAULT_SECOND_CFG, ge=0, le=100)
737
  denoise: float = Field(DEFAULT_DENOISE, ge=0, le=1)
738
  return_scale: float = Field(DEFAULT_RETURN_SCALE, ge=.01, le=1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
739
 
740
 
741
  class ModelRequest(BaseModel):
@@ -2053,6 +2122,7 @@ def model_options(kind, local):
2053
 
2054
 
2055
  def generate_images(request, from_api=True):
 
2056
  if (
2057
  request.width % 8
2058
  or request.height % 8
@@ -2369,9 +2439,60 @@ def star_database():
2369
  database.execute(
2370
  "CREATE TABLE IF NOT EXISTS stars (path TEXT PRIMARY KEY)"
2371
  )
 
 
 
 
 
 
 
 
 
 
2372
  return database
2373
 
2374
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2375
  def starred_paths():
2376
  database = star_database()
2377
  try:
@@ -3761,17 +3882,33 @@ def explorer_images(folder, starred):
3761
  path = (IMAGE_DIR / folder).resolve()
3762
  if path.parent != IMAGE_DIR.resolve() or not path.is_dir():
3763
  raise HTTPException(404, "folder not found")
3764
- with os.scandir(path) as entries:
3765
- return [
3766
- {
 
 
 
 
 
 
 
 
 
 
 
 
 
3767
  "name": Path(item.name).with_suffix(".png").name,
3768
- "path": (Path(folder) / item.name).as_posix(),
3769
- "starred": (Path(folder) / item.name).as_posix() in starred,
3770
- }
3771
- for item in sorted(entries, key=natural_key)
3772
- if Path(item.name).suffix.casefold() in IMAGE_SUFFIXES
3773
- and item.is_file()
3774
- ]
 
 
 
3775
 
3776
 
3777
  @api.get("/api/images", dependencies=[Depends(require_pass)])
@@ -3867,9 +4004,22 @@ def image_download(body: DownloadRequest):
3867
  )
3868
  def image_delete(body: DownloadRequest):
3869
  paths = selected_paths(body.items)
3870
- for path in paths.values():
3871
- set_star(path.relative_to(IMAGE_DIR.resolve()).as_posix(), False)
 
 
 
 
3872
  path.unlink()
 
 
 
 
 
 
 
 
 
3873
  for value in body.items:
3874
  path = (IMAGE_DIR / value).resolve()
3875
  if path.is_dir() and not any(path.iterdir()):
 
95
  OUTPUT_DIR = DATA_DIR / "output"
96
  IMAGE_DIR = DATA_DIR / "img"
97
  STAR_DB = DATA_DIR / "explorer.db"
98
+ ARTIST_DB = Path(tempfile.gettempdir()) / "artists.sqlite"
99
+ ARTIST_PLACEHOLDER = re.compile(r"\{artist(\d+)\}")
100
  TIMEZONE = ZoneInfo("Asia/Singapore")
101
  CPU_DEVICE = torch.device("cpu")
102
  MIB = 1024 * 1024
 
354
  return local_client
355
 
356
 
357
+ def copy_artist_database():
358
+ source = next(
359
+ (
360
+ path
361
+ for path in (
362
+ DATA_MOUNT / "artists.sqlite",
363
+ DATA_DIR / "artists.sqlite",
364
+ Path.cwd() / "artists.sqlite",
365
+ )
366
+ if path.is_file()
367
+ ),
368
+ None,
369
+ )
370
+ if source is None:
371
+ return
372
+ temp = ARTIST_DB.with_suffix(".sqlite.part")
373
+ shutil.copy2(source, temp)
374
+ temp.replace(ARTIST_DB)
375
+ log(f"Copied artist database to {ARTIST_DB}")
376
+
377
+
378
  def cleanup_mount():
379
  DATA_DIR.mkdir(parents=True, exist_ok=True)
380
+ copy_artist_database()
381
  if OUTPUT_DIR.exists():
382
  shutil.rmtree(OUTPUT_DIR)
383
  log("Deleted output directory")
 
760
  second_cfg: float = Field(DEFAULT_SECOND_CFG, ge=0, le=100)
761
  denoise: float = Field(DEFAULT_DENOISE, ge=0, le=1)
762
  return_scale: float = Field(DEFAULT_RETURN_SCALE, ge=.01, le=1)
763
+ artist_min_posts: int = Field(99, ge=0)
764
+ artist_blacklist: str = ""
765
+ selected_artists: list[str] = Field(default_factory=list)
766
+
767
+
768
+ def resolve_artist_prompts(request):
769
+ matches = ARTIST_PLACEHOLDER.findall(
770
+ f"{request.prompt}\n{request.second_prompt}"
771
+ )
772
+ identifiers = list(dict.fromkeys(value.lstrip("0") or "0" for value in matches))
773
+ request.selected_artists = []
774
+ if not identifiers:
775
+ return
776
+ if not ARTIST_DB.is_file():
777
+ copy_artist_database()
778
+ if not ARTIST_DB.is_file():
779
+ raise ValueError("Artist database is unavailable")
780
+ blacklist = {
781
+ artist.strip().casefold()
782
+ for artist in request.artist_blacklist.split(",")
783
+ if artist.strip()
784
+ }
785
+ database = sqlite3.connect(ARTIST_DB)
786
+ try:
787
+ artists = [
788
+ row[0]
789
+ for row in database.execute(
790
+ "SELECT artist FROM artists WHERE post_count >= ?",
791
+ (request.artist_min_posts,),
792
+ )
793
+ if row[0].casefold() not in blacklist
794
+ ]
795
+ finally:
796
+ database.close()
797
+ if len(artists) < len(identifiers):
798
+ raise ValueError("Not enough artists match the post minimum and blacklist")
799
+ selected = secrets.SystemRandom().sample(artists, len(identifiers))
800
+ replacements = dict(zip(identifiers, selected))
801
+
802
+ def replace(match):
803
+ return replacements[match.group(1).lstrip("0") or "0"]
804
+
805
+ request.prompt = ARTIST_PLACEHOLDER.sub(replace, request.prompt)
806
+ request.second_prompt = ARTIST_PLACEHOLDER.sub(replace, request.second_prompt)
807
+ request.selected_artists = list(dict.fromkeys(selected))
808
 
809
 
810
  class ModelRequest(BaseModel):
 
2122
 
2123
 
2124
  def generate_images(request, from_api=True):
2125
+ resolve_artist_prompts(request)
2126
  if (
2127
  request.width % 8
2128
  or request.height % 8
 
2439
  database.execute(
2440
  "CREATE TABLE IF NOT EXISTS stars (path TEXT PRIMARY KEY)"
2441
  )
2442
+ database.execute(
2443
+ """CREATE TABLE IF NOT EXISTS image_prompts (
2444
+ path TEXT PRIMARY KEY,
2445
+ modified INTEGER NOT NULL,
2446
+ size INTEGER NOT NULL,
2447
+ prompt TEXT NOT NULL,
2448
+ second_prompt TEXT NOT NULL,
2449
+ artists TEXT NOT NULL
2450
+ )"""
2451
+ )
2452
  return database
2453
 
2454
 
2455
+ def stored_prompt(path, relative, database):
2456
+ stat = path.stat()
2457
+ cached = database.execute(
2458
+ """SELECT prompt, second_prompt, artists
2459
+ FROM image_prompts
2460
+ WHERE path = ? AND modified = ? AND size = ?""",
2461
+ (relative, stat.st_mtime_ns, stat.st_size),
2462
+ ).fetchone()
2463
+ if cached is not None:
2464
+ return cached[0], cached[1], json.loads(cached[2])
2465
+ prompt = ""
2466
+ second_prompt = ""
2467
+ artists = []
2468
+ try:
2469
+ with Image.open(BytesIO(stored_bytes(path))) as image:
2470
+ parameters = json.loads(image.info.get("parameters", "{}"))
2471
+ prompt = str(parameters.get("prompt", ""))
2472
+ second_prompt = str(parameters.get("second_prompt") or prompt)
2473
+ selected = parameters.get("selected_artists", [])
2474
+ if isinstance(selected, list):
2475
+ artists = list(dict.fromkeys(
2476
+ artist for artist in selected if isinstance(artist, str)
2477
+ ))
2478
+ except (json.JSONDecodeError, OSError, TypeError, ValueError):
2479
+ pass
2480
+ database.execute(
2481
+ """INSERT OR REPLACE INTO image_prompts
2482
+ (path, modified, size, prompt, second_prompt, artists)
2483
+ VALUES (?, ?, ?, ?, ?, ?)""",
2484
+ (
2485
+ relative,
2486
+ stat.st_mtime_ns,
2487
+ stat.st_size,
2488
+ prompt,
2489
+ second_prompt,
2490
+ json.dumps(artists, separators=(",", ":")),
2491
+ ),
2492
+ )
2493
+ return prompt, second_prompt, artists
2494
+
2495
+
2496
  def starred_paths():
2497
  database = star_database()
2498
  try:
 
3882
  path = (IMAGE_DIR / folder).resolve()
3883
  if path.parent != IMAGE_DIR.resolve() or not path.is_dir():
3884
  raise HTTPException(404, "folder not found")
3885
+ database = star_database()
3886
+ images = []
3887
+ try:
3888
+ with os.scandir(path) as entries:
3889
+ files = [
3890
+ item
3891
+ for item in sorted(entries, key=natural_key, reverse=True)
3892
+ if Path(item.name).suffix.casefold() in IMAGE_SUFFIXES
3893
+ and item.is_file()
3894
+ ]
3895
+ for item in files:
3896
+ relative = (Path(folder) / item.name).as_posix()
3897
+ prompt, second_prompt, artists = stored_prompt(
3898
+ Path(item.path), relative, database
3899
+ )
3900
+ images.append({
3901
  "name": Path(item.name).with_suffix(".png").name,
3902
+ "path": relative,
3903
+ "starred": relative in starred,
3904
+ "prompt": prompt,
3905
+ "second_prompt": second_prompt,
3906
+ "artists": artists,
3907
+ })
3908
+ database.commit()
3909
+ finally:
3910
+ database.close()
3911
+ return images
3912
 
3913
 
3914
  @api.get("/api/images", dependencies=[Depends(require_pass)])
 
4004
  )
4005
  def image_delete(body: DownloadRequest):
4006
  paths = selected_paths(body.items)
4007
+ relatives = [
4008
+ path.relative_to(IMAGE_DIR.resolve()).as_posix()
4009
+ for path in paths.values()
4010
+ ]
4011
+ for path, relative in zip(paths.values(), relatives):
4012
+ set_star(relative, False)
4013
  path.unlink()
4014
+ database = star_database()
4015
+ try:
4016
+ database.executemany(
4017
+ "DELETE FROM image_prompts WHERE path = ?",
4018
+ ((relative,) for relative in relatives),
4019
+ )
4020
+ database.commit()
4021
+ finally:
4022
+ database.close()
4023
  for value in body.items:
4024
  path = (IMAGE_DIR / value).resolve()
4025
  if path.is_dir() and not any(path.iterdir()):
explorer.css CHANGED
@@ -254,6 +254,23 @@ button:disabled {
254
  z-index: 1;
255
  }
256
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
257
  .viewer {
258
  cursor: grab;
259
  height: 100%;
@@ -290,4 +307,9 @@ button:disabled {
290
  height: 100dvh;
291
  width: 100%;
292
  }
 
 
 
 
 
293
  }
 
254
  z-index: 1;
255
  }
256
 
257
+ .prompt {
258
+ background: var(--bg);
259
+ border: 1px solid var(--border);
260
+ bottom: .75rem;
261
+ color: var(--text);
262
+ font: inherit;
263
+ left: .75rem;
264
+ margin: 0;
265
+ max-height: 30%;
266
+ max-width: 40%;
267
+ overflow: auto;
268
+ padding: .65rem .8rem;
269
+ position: absolute;
270
+ white-space: pre-wrap;
271
+ z-index: 1;
272
+ }
273
+
274
  .viewer {
275
  cursor: grab;
276
  height: 100%;
 
307
  height: 100dvh;
308
  width: 100%;
309
  }
310
+
311
+ .prompt {
312
+ bottom: 4rem;
313
+ max-width: calc(100% - 1.5rem);
314
+ }
315
  }
explorer.js CHANGED
@@ -44,6 +44,7 @@ class ImageExplorer extends HTMLElement {
44
  <button class="reset" type="button">Reset</button>
45
  <button class="zoom-in" type="button" aria-label="Zoom in">+</button>
46
  </div>
 
47
  <div class="viewer"><img alt="" draggable="false"></div>
48
  </dialog>`
49
  this.cache = new Map()
@@ -93,7 +94,7 @@ class ImageExplorer extends HTMLElement {
93
  this.updateDateNav()
94
  const search = $("input[type=search]", this)
95
  search.value = ""
96
- search.placeholder = `Filter ${folder ? "images" : "folders"}`
97
  search.setAttribute("aria-label", search.placeholder)
98
  if (folder === INFINITE) this.addGroups(data.groups)
99
  else if (folder) this.addImages(data.images)
@@ -203,6 +204,7 @@ class ImageExplorer extends HTMLElement {
203
  card.className = "image entry"
204
  card.classList.toggle("favorite", image.starred)
205
  card.dataset.name = image.name.toLowerCase()
 
206
  card.dataset.path = image.path
207
  const open = document.createElement("button")
208
  open.className = "preview"
@@ -303,6 +305,7 @@ class ImageExplorer extends HTMLElement {
303
  const query = value.trim().toLowerCase()
304
  for (const entry of $$(".entry", this)) {
305
  const nameMatch = !query || entry.dataset.name.includes(query)
 
306
  const favoriteMatch = !this.favoritesOnly || entry.classList.contains("favorite")
307
  entry.hidden = !nameMatch || !favoriteMatch
308
  }
@@ -423,6 +426,7 @@ class ImageExplorer extends HTMLElement {
423
  const dialog = $(".lightbox", this)
424
  $("img", dialog).src = original(image.path)
425
  $("img", dialog).alt = image.name
 
426
  $(".upscale-status", dialog).textContent = ""
427
  const star = $(".expanded-star", dialog)
428
  star.dataset.path = image.path
@@ -435,6 +439,16 @@ class ImageExplorer extends HTMLElement {
435
  this.showImage(this.images[this.imageIndex])
436
  }
437
 
 
 
 
 
 
 
 
 
 
 
438
  resetView() {
439
  const viewer = $(".viewer", this)
440
  const image = $("img", viewer)
 
44
  <button class="reset" type="button">Reset</button>
45
  <button class="zoom-in" type="button" aria-label="Zoom in">+</button>
46
  </div>
47
+ <pre class="prompt"></pre>
48
  <div class="viewer"><img alt="" draggable="false"></div>
49
  </dialog>`
50
  this.cache = new Map()
 
94
  this.updateDateNav()
95
  const search = $("input[type=search]", this)
96
  search.value = ""
97
+ search.placeholder = folder ? "Search positive prompts" : "Filter folders"
98
  search.setAttribute("aria-label", search.placeholder)
99
  if (folder === INFINITE) this.addGroups(data.groups)
100
  else if (folder) this.addImages(data.images)
 
204
  card.className = "image entry"
205
  card.classList.toggle("favorite", image.starred)
206
  card.dataset.name = image.name.toLowerCase()
207
+ card.dataset.prompt = image.prompt.toLowerCase()
208
  card.dataset.path = image.path
209
  const open = document.createElement("button")
210
  open.className = "preview"
 
305
  const query = value.trim().toLowerCase()
306
  for (const entry of $$(".entry", this)) {
307
  const nameMatch = !query || entry.dataset.name.includes(query)
308
+ || entry.dataset.prompt?.includes(query)
309
  const favoriteMatch = !this.favoritesOnly || entry.classList.contains("favorite")
310
  entry.hidden = !nameMatch || !favoriteMatch
311
  }
 
426
  const dialog = $(".lightbox", this)
427
  $("img", dialog).src = original(image.path)
428
  $("img", dialog).alt = image.name
429
+ $(".prompt", dialog).textContent = this.formatPrompt(image)
430
  $(".upscale-status", dialog).textContent = ""
431
  const star = $(".expanded-star", dialog)
432
  star.dataset.path = image.path
 
439
  this.showImage(this.images[this.imageIndex])
440
  }
441
 
442
+ formatPrompt(image) {
443
+ if (!image.prompt) return "Prompt unavailable"
444
+ const lines = image.artists.length ? [`1:${[...new Set(image.artists)].join(",")}`] : []
445
+ lines.push(`2:${image.prompt}`)
446
+ if (image.second_prompt && image.second_prompt !== image.prompt) {
447
+ lines.push(`3:${image.second_prompt}`)
448
+ }
449
+ return lines.join("\n")
450
+ }
451
+
452
  resetView() {
453
  const viewer = $(".viewer", this)
454
  const image = $("img", viewer)