raubatz Oz commited on
Commit
2a69036
Β·
1 Parent(s): 64ee632

Track undownloaded outputs and open PNG/WebP in new tabs

Browse files

- Status line for gallery images not yet downloaded
- Warn on Generate if pending downloads would be replaced
- Mark downloaded via PNG/WebP buttons and gallery down icon
- PNG and WebP both open their file URL in a new tab

Co-Authored-By: Oz <oz-agent@warp.dev>

Files changed (1) hide show
  1. app.py +273 -13
app.py CHANGED
@@ -183,6 +183,136 @@ def resolve_download_bundle(selected_path, gallery_value, last_prompt_text, proj
183
  webp = save_webp_from_path(png_src, basename=base) if png_src else None
184
  prompt_file = save_prompt_txt(last_prompt_text, basename=base)
185
  return png, webp, prompt_file
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186
 
187
  # ── Model load ──────────────────────────────────────────────────────────────
188
  # Pipeline class depends on MODEL_VARIANT and is the only thing here that
@@ -558,6 +688,13 @@ with gr.Blocks() as demo:
558
  dynamic_loras_state = gr.State({})
559
  selected_output_state = gr.State(None)
560
  last_prompt_state = gr.State("")
 
 
 
 
 
 
 
561
  # Remember per-title LoRA weights / prompts across add/remove so existing
562
  # values don't snap back to catalog defaults when the selection changes.
563
  lora_weight_memory_state = gr.State({})
@@ -710,11 +847,17 @@ with gr.Blocks() as demo:
710
  with gr.Row():
711
  send_out_to_base_btn = gr.Button("↩ Send β†’ Base", size="sm")
712
  send_out_to_ref_btn = gr.Button("↩ Send β†’ Reference", size="sm")
 
 
 
 
713
  gr.Markdown(
714
  "*Downloads: `project` + `yymmddhhmmss` + `.png/.webp/.txt` "
715
  f"(default project `{DEFAULT_PROJECT_NAME}`). "
716
  "Click a gallery thumbnail before Download / Sendβ†’; otherwise latest. "
717
- "Prompt file = last run's combined user + LoRA + custom text.*"
 
 
718
  )
719
 
720
  with gr.Row():
@@ -1116,6 +1259,64 @@ with gr.Blocks() as demo:
1116
  )
1117
  # Must be registered inside the Blocks context (Gradio rejects load outside).
1118
  demo.load(fn=None, js=_TEXTBOX_NEWLINE_JS)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1119
  reload_catalog_btn.click(
1120
  fn=_on_page_load,
1121
  inputs=[dynamic_loras_state, lora_selector],
@@ -1224,28 +1425,82 @@ with gr.Blocks() as demo:
1224
  outputs=[download_png_btn, download_webp_btn, download_prompt_btn],
1225
  show_progress="hidden",
1226
  )
 
 
 
 
 
 
 
1227
  project_name.change(
1228
  fn=resolve_download_bundle,
1229
  inputs=[selected_output_state, output_gallery, last_prompt_state, project_name],
1230
  outputs=[download_png_btn, download_webp_btn, download_prompt_btn],
1231
  show_progress="hidden",
1232
  )
1233
- # PNG download also opens the image in a new tab when possible.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1234
  download_png_btn.click(
1235
  fn=None,
1236
- js="""() => {
1237
- const root = document.getElementById('download_png_btn');
1238
- if (!root) return;
1239
- const a = root.querySelector('a.download-link, a[href]');
1240
- const href = a && a.href;
1241
- if (href) {
1242
- window.open(href, '_blank', 'noopener,noreferrer');
1243
- }
1244
- }""",
 
 
 
 
 
 
 
 
 
1245
  )
 
 
 
 
 
 
 
 
 
 
1246
  # Reset any stale gallery selection before a new run starts, so Sendβ†’Base
1247
  # / Sendβ†’Ref after this run can't accidentally reuse a path from the
1248
- # previous run's gallery contents.
1249
  _infer_inputs = [
1250
  base_image, ref1, ref2, ref3, prompt, lora_prompt_display, custom_prompt_display,
1251
  lora_selector, seed, randomize_seed, guidance_scale, steps, upscale_factor,
@@ -1259,7 +1514,12 @@ with gr.Blocks() as demo:
1259
  last_prompt_state,
1260
  ]
1261
  for _run_btn in (run_button, run_button_top):
1262
- _run_btn.click(fn=lambda: None, outputs=[selected_output_state])
 
 
 
 
 
1263
 
1264
  run_event = run_button.click(
1265
  fn=infer,
 
183
  webp = save_webp_from_path(png_src, basename=base) if png_src else None
184
  prompt_file = save_prompt_txt(last_prompt_text, basename=base)
185
  return png, webp, prompt_file
186
+
187
+
188
+ # ── Download tracking (warn before overwriting undownloaded outputs) ─────────
189
+
190
+ def _norm_img_path(item) -> str | None:
191
+ from image_utils import _gallery_item_path
192
+ p = _gallery_item_path(item)
193
+ if p:
194
+ return os.path.abspath(p)
195
+ if isinstance(item, str) and item.strip():
196
+ return os.path.abspath(item) if os.path.isabs(item) else item.strip()
197
+ return None
198
+
199
+
200
+ def gallery_image_paths(gallery_value) -> list[str]:
201
+ paths: list[str] = []
202
+ seen: set[str] = set()
203
+ for item in gallery_value or []:
204
+ p = _norm_img_path(item)
205
+ if p and p not in seen:
206
+ seen.add(p)
207
+ paths.append(p)
208
+ return paths
209
+
210
+
211
+ def format_download_status(pending_list, gallery_value) -> str:
212
+ paths = gallery_image_paths(gallery_value)
213
+ pending = set(pending_list or [])
214
+ undownloaded = [p for p in paths if p in pending]
215
+ if not paths:
216
+ return "*No generated images yet.*"
217
+ if not undownloaded:
218
+ return f"βœ… All **{len(paths)}** gallery image(s) marked downloaded."
219
+ names = ", ".join(f"`{os.path.basename(p)}`" for p in undownloaded[:4])
220
+ extra = f" +{len(undownloaded) - 4} more" if len(undownloaded) > 4 else ""
221
+ return (
222
+ f"⚠️ **{len(undownloaded)}/{len(paths)}** not downloaded yet: {names}{extra}. "
223
+ f"Use ⬇️ PNG/WebP or the gallery ↓ icon."
224
+ )
225
+
226
+
227
+ def sync_download_tracking(gallery_value, pending_list, downloaded_list):
228
+ """Keep pending in sync with gallery contents.
229
+
230
+ New gallery paths not yet marked downloaded become pending.
231
+ Paths that left the gallery drop out of pending.
232
+ """
233
+ pending = set(pending_list or [])
234
+ downloaded = set(downloaded_list or [])
235
+ paths = gallery_image_paths(gallery_value)
236
+ path_set = set(paths)
237
+ pending = {p for p in pending if p in path_set}
238
+ for p in paths:
239
+ if p not in downloaded:
240
+ pending.add(p)
241
+ pending_out = [p for p in paths if p in pending] # stable order
242
+ downloaded_out = sorted(downloaded)
243
+ return pending_out, downloaded_out, format_download_status(pending_out, gallery_value)
244
+
245
+
246
+ def _mark_paths_downloaded(paths_to_mark, gallery_value, pending_list, downloaded_list):
247
+ pending = set(pending_list or [])
248
+ downloaded = set(downloaded_list or [])
249
+ marked = []
250
+ for raw in paths_to_mark or []:
251
+ p = _norm_img_path(raw)
252
+ if not p:
253
+ # bare filename / URL fragment from gallery JS
254
+ s = str(raw or "").strip()
255
+ if not s:
256
+ continue
257
+ base = os.path.basename(s.split("?")[0].split("#")[0])
258
+ for gp in gallery_image_paths(gallery_value):
259
+ if os.path.basename(gp) == base or base in gp or gp.endswith(base):
260
+ p = gp
261
+ break
262
+ if not p and base:
263
+ # still record basename key so status can clear if paths match later
264
+ p = base
265
+ if not p:
266
+ continue
267
+ downloaded.add(p)
268
+ pending.discard(p)
269
+ # also clear any gallery path sharing basename
270
+ base = os.path.basename(p)
271
+ for gp in list(pending):
272
+ if os.path.basename(gp) == base:
273
+ pending.discard(gp)
274
+ downloaded.add(gp)
275
+ marked.append(p)
276
+ paths = gallery_image_paths(gallery_value)
277
+ pending_out = [p for p in paths if p in pending]
278
+ return pending_out, sorted(downloaded), format_download_status(pending_out, gallery_value)
279
+
280
+
281
+ def mark_current_output_downloaded(selected_path, gallery_value, pending_list, downloaded_list):
282
+ """Mark the selected (or latest) gallery image as downloaded."""
283
+ p = resolve_output_download_path(selected_path, gallery_value)
284
+ return _mark_paths_downloaded([p] if p else [], gallery_value, pending_list, downloaded_list)
285
+
286
+
287
+ def mark_from_gallery_signal(signal, gallery_value, pending_list, downloaded_list):
288
+ """Mark download from gallery ↓ icon (JS writes URL/filename into signal)."""
289
+ raw = (signal or "").strip()
290
+ if not raw:
291
+ return (
292
+ list(pending_list or []),
293
+ list(downloaded_list or []),
294
+ format_download_status(pending_list, gallery_value),
295
+ gr.update(value=""),
296
+ )
297
+ # JS appends "|timestamp" so repeated clicks still fire .change
298
+ token = raw.split("|", 1)[0].strip()
299
+ pending, downloaded, status = _mark_paths_downloaded(
300
+ [token], gallery_value, pending_list, downloaded_list,
301
+ )
302
+ return pending, downloaded, status, gr.update(value="")
303
+
304
+
305
+ def warn_undownloaded_before_generate(pending_list, gallery_value):
306
+ """Toast if the current gallery still has undownloaded images."""
307
+ paths = gallery_image_paths(gallery_value)
308
+ pending = set(pending_list or [])
309
+ still = [p for p in paths if p in pending]
310
+ if still:
311
+ gr.Warning(
312
+ f"{len(still)} generated image(s) not downloaded yet β€” "
313
+ "this run will replace the output gallery."
314
+ )
315
+ return None # also clears selected_output_state when chained
316
 
317
  # ── Model load ──────────────────────────────────────────────────────────────
318
  # Pipeline class depends on MODEL_VARIANT and is the only thing here that
 
688
  dynamic_loras_state = gr.State({})
689
  selected_output_state = gr.State(None)
690
  last_prompt_state = gr.State("")
691
+ # Paths still in the gallery that have not been marked downloaded this session.
692
+ pending_download_state = gr.State([])
693
+ downloaded_images_state = gr.State([])
694
+ # Filled by JS when the gallery's built-in ↓ icon is clicked.
695
+ gallery_dl_signal = gr.Textbox(
696
+ value="", visible=False, elem_id="gallery_dl_signal",
697
+ )
698
  # Remember per-title LoRA weights / prompts across add/remove so existing
699
  # values don't snap back to catalog defaults when the selection changes.
700
  lora_weight_memory_state = gr.State({})
 
847
  with gr.Row():
848
  send_out_to_base_btn = gr.Button("↩ Send β†’ Base", size="sm")
849
  send_out_to_ref_btn = gr.Button("↩ Send β†’ Reference", size="sm")
850
+ download_status = gr.Markdown(
851
+ "*No generated images yet.*",
852
+ elem_id="download_status",
853
+ )
854
  gr.Markdown(
855
  "*Downloads: `project` + `yymmddhhmmss` + `.png/.webp/.txt` "
856
  f"(default project `{DEFAULT_PROJECT_NAME}`). "
857
  "Click a gallery thumbnail before Download / Sendβ†’; otherwise latest. "
858
+ "Prompt file = last run's combined user + LoRA + custom text. "
859
+ "PNG/WebP or the gallery ↓ icon marks an image downloaded; "
860
+ "Generate warns if undownloaded images would be replaced.*"
861
  )
862
 
863
  with gr.Row():
 
1259
  )
1260
  # Must be registered inside the Blocks context (Gradio rejects load outside).
1261
  demo.load(fn=None, js=_TEXTBOX_NEWLINE_JS)
1262
+ # Capture clicks on Gradio Gallery's built-in download (↓) control.
1263
+ demo.load(
1264
+ fn=None,
1265
+ js="""
1266
+ () => {
1267
+ if (window.__fluxGalleryDlHook) return;
1268
+ window.__fluxGalleryDlHook = true;
1269
+ const setSignal = (val) => {
1270
+ const root = document.getElementById('gallery_dl_signal');
1271
+ if (!root) return;
1272
+ const ta = root.querySelector('textarea, input');
1273
+ if (!ta) return;
1274
+ ta.value = val || '';
1275
+ ta.dispatchEvent(new Event('input', { bubbles: true }));
1276
+ };
1277
+ document.addEventListener('click', (e) => {
1278
+ const t = e.target;
1279
+ if (!t || !t.closest) return;
1280
+ const gal = t.closest('#output_gallery');
1281
+ if (!gal) return;
1282
+ // Gradio download control: anchor with download attr, or button near download icon.
1283
+ const a = t.closest('a[download], a.download-link, a[href*="file="]');
1284
+ const btn = t.closest('button');
1285
+ let href = '';
1286
+ if (a && a.href) {
1287
+ href = a.getAttribute('download') || a.href;
1288
+ } else if (btn) {
1289
+ const label = (btn.getAttribute('aria-label') || btn.title || btn.textContent || '').toLowerCase();
1290
+ if (!(label.includes('download') || label.includes('save') || btn.innerHTML.includes('download'))) {
1291
+ // still allow if nested svg title looks like download
1292
+ const svgTitle = (btn.querySelector('title')?.textContent || '').toLowerCase();
1293
+ if (!svgTitle.includes('download') && !btn.querySelector('[data-testid*="download"]')) {
1294
+ return;
1295
+ }
1296
+ }
1297
+ const nearA = btn.closest('a') || btn.querySelector('a') || gal.querySelector('a[download]');
1298
+ href = (nearA && (nearA.getAttribute('download') || nearA.href)) || '';
1299
+ if (!href) {
1300
+ // fallback: selected/preview image src basename
1301
+ const img = gal.querySelector('.preview img, .thumbnail-lg img, img');
1302
+ href = (img && (img.currentSrc || img.src)) || 'gallery-download';
1303
+ }
1304
+ } else {
1305
+ return;
1306
+ }
1307
+ if (!href) return;
1308
+ try {
1309
+ const u = href.startsWith('http') || href.startsWith('blob:') || href.startsWith('/')
1310
+ ? href : href;
1311
+ const base = (u.split('/').pop() || u).split('?')[0];
1312
+ setSignal(base + '|' + Date.now());
1313
+ } catch (_) {
1314
+ setSignal(String(href) + '|' + Date.now());
1315
+ }
1316
+ }, true);
1317
+ }
1318
+ """,
1319
+ )
1320
  reload_catalog_btn.click(
1321
  fn=_on_page_load,
1322
  inputs=[dynamic_loras_state, lora_selector],
 
1425
  outputs=[download_png_btn, download_webp_btn, download_prompt_btn],
1426
  show_progress="hidden",
1427
  )
1428
+ # Track which gallery images still need downloading.
1429
+ output_gallery.change(
1430
+ fn=sync_download_tracking,
1431
+ inputs=[output_gallery, pending_download_state, downloaded_images_state],
1432
+ outputs=[pending_download_state, downloaded_images_state, download_status],
1433
+ show_progress="hidden",
1434
+ )
1435
  project_name.change(
1436
  fn=resolve_download_bundle,
1437
  inputs=[selected_output_state, output_gallery, last_prompt_state, project_name],
1438
  outputs=[download_png_btn, download_webp_btn, download_prompt_btn],
1439
  show_progress="hidden",
1440
  )
1441
+ # Open PNG/WebP in a new tab (in addition to the browser download) and mark
1442
+ # the current gallery image as downloaded for the pending-status tracker.
1443
+ _OPEN_DL_TAB_JS = """
1444
+ (btnId) => {
1445
+ const openHref = (href) => {
1446
+ if (!href || href === '#' || href.endsWith('/')) return false;
1447
+ window.open(href, '_blank', 'noopener,noreferrer');
1448
+ return true;
1449
+ };
1450
+ const tryOpen = () => {
1451
+ const root = document.getElementById(btnId);
1452
+ if (!root) return false;
1453
+ const anchors = root.querySelectorAll('a.download-link, a[href], a[download]');
1454
+ for (const a of anchors) {
1455
+ const href = a.href || a.getAttribute('href') || '';
1456
+ if (openHref(href)) return true;
1457
+ }
1458
+ // Gradio sometimes nests the file link one tick later after value bind.
1459
+ return false;
1460
+ };
1461
+ if (tryOpen()) return;
1462
+ // Retry briefly β€” DownloadButton href can lag the click on first bind.
1463
+ let n = 0;
1464
+ const t = setInterval(() => {
1465
+ n += 1;
1466
+ if (tryOpen() || n >= 8) clearInterval(t);
1467
+ }, 50);
1468
+ }
1469
+ """
1470
  download_png_btn.click(
1471
  fn=None,
1472
+ # Concatenate (not f-string) so braces inside _OPEN_DL_TAB_JS stay literal JS.
1473
+ js="() => { (" + _OPEN_DL_TAB_JS + ")('download_png_btn'); }",
1474
+ ).then(
1475
+ fn=mark_current_output_downloaded,
1476
+ inputs=[selected_output_state, output_gallery,
1477
+ pending_download_state, downloaded_images_state],
1478
+ outputs=[pending_download_state, downloaded_images_state, download_status],
1479
+ show_progress="hidden",
1480
+ )
1481
+ download_webp_btn.click(
1482
+ fn=None,
1483
+ js="() => { (" + _OPEN_DL_TAB_JS + ")('download_webp_btn'); }",
1484
+ ).then(
1485
+ fn=mark_current_output_downloaded,
1486
+ inputs=[selected_output_state, output_gallery,
1487
+ pending_download_state, downloaded_images_state],
1488
+ outputs=[pending_download_state, downloaded_images_state, download_status],
1489
+ show_progress="hidden",
1490
  )
1491
+ # Gallery built-in ↓ icon β†’ JS signal β†’ mark downloaded.
1492
+ gallery_dl_signal.change(
1493
+ fn=mark_from_gallery_signal,
1494
+ inputs=[gallery_dl_signal, output_gallery,
1495
+ pending_download_state, downloaded_images_state],
1496
+ outputs=[pending_download_state, downloaded_images_state,
1497
+ download_status, gallery_dl_signal],
1498
+ show_progress="hidden",
1499
+ )
1500
+
1501
  # Reset any stale gallery selection before a new run starts, so Sendβ†’Base
1502
  # / Sendβ†’Ref after this run can't accidentally reuse a path from the
1503
+ # previous run's gallery contents. Also warn if undownloaded images exist.
1504
  _infer_inputs = [
1505
  base_image, ref1, ref2, ref3, prompt, lora_prompt_display, custom_prompt_display,
1506
  lora_selector, seed, randomize_seed, guidance_scale, steps, upscale_factor,
 
1514
  last_prompt_state,
1515
  ]
1516
  for _run_btn in (run_button, run_button_top):
1517
+ _run_btn.click(
1518
+ fn=warn_undownloaded_before_generate,
1519
+ inputs=[pending_download_state, output_gallery],
1520
+ outputs=[selected_output_state],
1521
+ show_progress="hidden",
1522
+ )
1523
 
1524
  run_event = run_button.click(
1525
  fn=infer,