mo7ammad2012 commited on
Commit
895b861
·
verified ·
1 Parent(s): 3ecbd93

Fix final image generation

Browse files
Files changed (1) hide show
  1. index.html +34 -78
index.html CHANGED
@@ -180,8 +180,7 @@
180
  </main>
181
 
182
  <script type="module">
183
- import { Client } from "https://cdn.jsdelivr.net/npm/@gradio/client/dist/index.min.js";
184
-
185
  /*
186
  Static frontend only.
187
  Change this single constant if you later choose another compatible
@@ -189,14 +188,12 @@ import { Client } from "https://cdn.jsdelivr.net/npm/@gradio/client/dist/index.m
189
  */
190
  const BACKEND_SPACE = "multimodalart/flux-lora-the-explorer";
191
  const BACKEND_ORIGIN = "https://multimodalart-flux-lora-the-explorer.hf.space";
192
-
193
  const $ = id => document.getElementById(id);
194
  const localQueue = [];
195
  let processing = false;
196
  let client = null;
197
  let api = null;
198
  let jobCounter = 0;
199
-
200
  const STYLES = [
201
  "No extra style","Photorealistic","Ultra realistic photography","Cinematic",
202
  "Hollywood blockbuster","IMAX film still","35mm analog film","70mm epic cinema",
@@ -243,7 +240,6 @@ const STYLES = [
243
  "Clean commercial","Hyper-detailed","Ethereal","Whimsical","Moody","Haunting",
244
  "Cozy","Playful","Epic"
245
  ];
246
-
247
  const STYLE_DETAIL = {
248
  "No extra style":"",
249
  "Photorealistic":"photorealistic, realistic materials, physically accurate lighting, natural texture",
@@ -303,34 +299,28 @@ const STYLE_DETAIL = {
303
  "Cozy":"cozy atmosphere, warm practical light, tactile materials, inviting detail",
304
  "Epic":"epic scale, heroic composition, monumental depth, dramatic visual impact"
305
  };
306
-
307
  const PROMPT_BOOST =
308
  "masterful composition, coherent anatomy, accurate hands and facial structure, " +
309
  "clear subject separation, refined color harmony, realistic material response, " +
310
  "controlled detail, intentional lighting, professional visual storytelling";
311
-
312
  for (const style of STYLES) {
313
  const option = document.createElement("option");
314
  option.value = style;
315
  $("styles").appendChild(option);
316
  }
317
-
318
  function normalise(value) {
319
  return String(value || "").toLowerCase().replace(/[^a-z0-9]+/g, "");
320
  }
321
-
322
  function updateQueueUI() {
323
  $("queuedChip").textContent = `Queued: ${localQueue.length}`;
324
  $("activeChip").textContent = processing ? "Active: generating" : "Active: none";
325
  }
326
-
327
  function setViewer(mode, message = "") {
328
  $("empty").style.display = mode === "empty" ? "block" : "none";
329
  $("loading").style.display = mode === "loading" ? "block" : "none";
330
  $("image").style.display = mode === "image" ? "block" : "none";
331
  if (message) $("status").textContent = message;
332
  }
333
-
334
  function endpointInfo(names) {
335
  const named = api?.named_endpoints || {};
336
  const entries = Object.entries(named);
@@ -344,24 +334,19 @@ function endpointInfo(names) {
344
  }
345
  return { endpoint: names[0], spec: null };
346
  }
347
-
348
  function buildPayload(spec, values, fallback) {
349
  const params = spec?.parameters;
350
  if (!Array.isArray(params) || !params.length) return fallback;
351
-
352
  return params.map(param => {
353
  const name = normalise(param.parameter_name || param.label || param.name || param.component);
354
  if (Object.prototype.hasOwnProperty.call(values, name)) return values[name];
355
-
356
  for (const [alias, value] of Object.entries(values)) {
357
  if (alias && name && (name.includes(alias) || alias.includes(name))) return value;
358
  }
359
-
360
  if ("parameter_default" in param) return param.parameter_default;
361
  return null;
362
  });
363
  }
364
-
365
  async function connectBackend() {
366
  if (client) return client;
367
  $("loadingTitle").textContent = "Connecting to the remote AIDMA engine…";
@@ -376,20 +361,16 @@ async function connectBackend() {
376
  api = await client.view_api();
377
  return client;
378
  }
379
-
380
  function snapshotJob() {
381
  const prompt = $("prompt").value.trim();
382
  if (!prompt) throw new Error("Write a prompt first.");
383
-
384
  const modelOption = $("model").selectedOptions[0];
385
  const [width, height] = $("ratio").value.split("x").map(Number);
386
  const styleName = $("style").value.trim();
387
  const styleText = STYLE_DETAIL[styleName] ?? styleName;
388
-
389
  const parts = [prompt];
390
  if (styleText && normalise(styleName) !== normalise("No extra style")) parts.push(styleText);
391
  if ($("boost").checked) parts.push(PROMPT_BOOST);
392
-
393
  return {
394
  id: ++jobCounter,
395
  repo: modelOption.value,
@@ -404,19 +385,15 @@ function snapshotJob() {
404
  loraScale: 0.95
405
  };
406
  }
407
-
408
  function remoteFileUrl(value) {
409
  if (typeof value !== "string") return null;
410
  const text = value.trim();
411
  if (!text) return null;
412
-
413
  // Already usable in the browser.
414
  if (/^(https?:\/\/|blob:|data:image\/)/i.test(text)) return text;
415
-
416
  // Modern Gradio may return a relative file route.
417
  if (text.startsWith("/gradio_api/")) return `${BACKEND_ORIGIN}${text}`;
418
  if (text.startsWith("gradio_api/")) return `${BACKEND_ORIGIN}/${text}`;
419
-
420
  // Some Gradio versions return only the server-side temporary path.
421
  if (
422
  text.startsWith("/tmp/") ||
@@ -425,25 +402,27 @@ function remoteFileUrl(value) {
425
  ) {
426
  return `${BACKEND_ORIGIN}/gradio_api/file=${encodeURI(text)}`;
427
  }
428
-
429
  return null;
430
  }
431
-
432
  function extractImageUrl(value, seen = new Set()) {
433
  if (value == null) return null;
434
-
435
  if (typeof Blob !== "undefined" && value instanceof Blob) {
436
  return URL.createObjectURL(value);
437
  }
438
-
 
 
439
  if (typeof value === "string") {
440
- return remoteFileUrl(value);
 
 
 
 
 
441
  }
442
-
443
  if (typeof value !== "object") return null;
444
  if (seen.has(value)) return null;
445
  seen.add(value);
446
-
447
  if (Array.isArray(value)) {
448
  // The first output of /run_lora is the generated image.
449
  for (const item of value) {
@@ -452,7 +431,6 @@ function extractImageUrl(value, seen = new Set()) {
452
  }
453
  return null;
454
  }
455
-
456
  // Gradio FileData commonly uses url/path/orig_name/name.
457
  for (const key of ["url", "path", "orig_name", "name", "image", "data"]) {
458
  if (Object.prototype.hasOwnProperty.call(value, key)) {
@@ -460,15 +438,12 @@ function extractImageUrl(value, seen = new Set()) {
460
  if (found) return found;
461
  }
462
  }
463
-
464
  for (const item of Object.values(value)) {
465
  const found = extractImageUrl(item, seen);
466
  if (found) return found;
467
  }
468
-
469
  return null;
470
  }
471
-
472
  function showImage(url, job) {
473
  $("image").src = url;
474
  $("download").href = url;
@@ -476,7 +451,6 @@ function showImage(url, job) {
476
  $("download").style.display = "inline-flex";
477
  setViewer("image", `${job.modelLabel} · seed ${job.seed}`);
478
  }
479
-
480
  async function loadSelectedLora(job) {
481
  const { endpoint, spec } = endpointInfo(["/add_custom_lora", "add_custom_lora"]);
482
  const payload = buildPayload(
@@ -488,20 +462,17 @@ async function loadSelectedLora(job) {
488
  },
489
  [job.repo]
490
  );
491
-
492
  const result = await client.predict(endpoint, payload);
493
  const data = result?.data || [];
494
  const selectedIndex = Number.isFinite(Number(data[4])) ? Number(data[4]) : null;
495
  const trigger = typeof data[5] === "string" && data[5].trim() ? data[5].trim() : job.trigger;
496
  return { selectedIndex, trigger };
497
  }
498
-
499
  async function runGeneration(job, selectedIndex, trigger) {
500
  const { endpoint, spec } = endpointInfo(["/run_lora", "run_lora"]);
501
  const finalPrompt = normalise(job.prompt).includes(normalise(trigger))
502
  ? job.prompt
503
  : `${trigger}, ${job.prompt}`;
504
-
505
  const values = {
506
  prompt: finalPrompt,
507
  prompttext: finalPrompt,
@@ -522,51 +493,42 @@ async function runGeneration(job, selectedIndex, trigger) {
522
  lorascale: job.loraScale,
523
  adapterstrength: job.loraScale
524
  };
525
-
526
- // Current explorer API normally keeps the selected LoRA in session State,
527
- // so selectedIndex is omitted from the common fallback payload.
528
- const fallback = [
 
 
 
529
  finalPrompt, null, 0.75, job.cfg, job.steps, false,
530
  job.seed, job.width, job.height, job.loraScale
531
  ];
532
- const payload = buildPayload(spec, values, fallback);
533
- const submission = client.submit(endpoint, payload);
534
- let finalUrl = null;
535
- let lastData = null;
536
-
537
- for await (const message of submission) {
538
- if (message.type === "status") {
539
- const stage = message.stage || message.status || "pending";
540
- const pos = Number.isFinite(message.position) ? ` · remote position ${message.position + 1}` : "";
541
- const eta = Number.isFinite(message.eta) ? ` · ETA ${Math.ceil(message.eta)}s` : "";
542
- $("queueStatus").textContent = `${stage}${pos}${eta}`;
543
- }
544
-
545
- if (message.type === "data") {
546
- lastData = message.data;
547
- const url = extractImageUrl(message.data);
548
- if (url) {
549
- finalUrl = url;
550
- showImage(url, job);
551
- }
552
- }
553
- }
554
-
555
  if (!finalUrl) {
556
- console.error("Unrecognized Gradio image payload:", lastData);
557
  throw new Error(
558
- "The remote engine returned an unsupported file payload. " +
559
- "Open the browser console and copy the logged payload if this appears again."
560
  );
561
  }
 
 
562
  return finalUrl;
563
  }
564
-
565
  async function processQueue() {
566
  if (processing || !localQueue.length) return;
567
  processing = true;
568
  updateQueueUI();
569
-
570
  while (localQueue.length) {
571
  const job = localQueue.shift();
572
  updateQueueUI();
@@ -575,11 +537,10 @@ async function processQueue() {
575
  $("queueStatus").textContent = "Preparing AIDMA LoRA";
576
  $("status").className = "";
577
  setViewer("loading", `Job #${job.id} is running.`);
578
-
579
  try {
580
  await connectBackend();
581
  const loaded = await loadSelectedLora(job);
582
- $("queueStatus").textContent = "Submitting to remote GPU";
583
  await runGeneration(job, loaded.selectedIndex, loaded.trigger);
584
  } catch (error) {
585
  console.error(error);
@@ -594,17 +555,14 @@ async function processQueue() {
594
  api = null;
595
  }
596
  }
597
-
598
  processing = false;
599
  updateQueueUI();
600
  }
601
-
602
  function escapeHtml(value) {
603
  return String(value).replace(/[&<>"']/g, char => ({
604
  "&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#039;"
605
  })[char]);
606
  }
607
-
608
  $("generate").addEventListener("click", () => {
609
  try {
610
  const job = snapshotJob();
@@ -619,14 +577,12 @@ $("generate").addEventListener("click", () => {
619
  $("prompt").focus();
620
  }
621
  });
622
-
623
  $("prompt").addEventListener("keydown", event => {
624
  if ((event.ctrlKey || event.metaKey) && event.key === "Enter") {
625
  event.preventDefault();
626
  $("generate").click();
627
  }
628
  });
629
-
630
  updateQueueUI();
631
  </script>
632
  </body>
 
180
  </main>
181
 
182
  <script type="module">
183
+ import { Client } from "https://cdn.jsdelivr.net/npm/@gradio/client/+esm";
 
184
  /*
185
  Static frontend only.
186
  Change this single constant if you later choose another compatible
 
188
  */
189
  const BACKEND_SPACE = "multimodalart/flux-lora-the-explorer";
190
  const BACKEND_ORIGIN = "https://multimodalart-flux-lora-the-explorer.hf.space";
 
191
  const $ = id => document.getElementById(id);
192
  const localQueue = [];
193
  let processing = false;
194
  let client = null;
195
  let api = null;
196
  let jobCounter = 0;
 
197
  const STYLES = [
198
  "No extra style","Photorealistic","Ultra realistic photography","Cinematic",
199
  "Hollywood blockbuster","IMAX film still","35mm analog film","70mm epic cinema",
 
240
  "Clean commercial","Hyper-detailed","Ethereal","Whimsical","Moody","Haunting",
241
  "Cozy","Playful","Epic"
242
  ];
 
243
  const STYLE_DETAIL = {
244
  "No extra style":"",
245
  "Photorealistic":"photorealistic, realistic materials, physically accurate lighting, natural texture",
 
299
  "Cozy":"cozy atmosphere, warm practical light, tactile materials, inviting detail",
300
  "Epic":"epic scale, heroic composition, monumental depth, dramatic visual impact"
301
  };
 
302
  const PROMPT_BOOST =
303
  "masterful composition, coherent anatomy, accurate hands and facial structure, " +
304
  "clear subject separation, refined color harmony, realistic material response, " +
305
  "controlled detail, intentional lighting, professional visual storytelling";
 
306
  for (const style of STYLES) {
307
  const option = document.createElement("option");
308
  option.value = style;
309
  $("styles").appendChild(option);
310
  }
 
311
  function normalise(value) {
312
  return String(value || "").toLowerCase().replace(/[^a-z0-9]+/g, "");
313
  }
 
314
  function updateQueueUI() {
315
  $("queuedChip").textContent = `Queued: ${localQueue.length}`;
316
  $("activeChip").textContent = processing ? "Active: generating" : "Active: none";
317
  }
 
318
  function setViewer(mode, message = "") {
319
  $("empty").style.display = mode === "empty" ? "block" : "none";
320
  $("loading").style.display = mode === "loading" ? "block" : "none";
321
  $("image").style.display = mode === "image" ? "block" : "none";
322
  if (message) $("status").textContent = message;
323
  }
 
324
  function endpointInfo(names) {
325
  const named = api?.named_endpoints || {};
326
  const entries = Object.entries(named);
 
334
  }
335
  return { endpoint: names[0], spec: null };
336
  }
 
337
  function buildPayload(spec, values, fallback) {
338
  const params = spec?.parameters;
339
  if (!Array.isArray(params) || !params.length) return fallback;
 
340
  return params.map(param => {
341
  const name = normalise(param.parameter_name || param.label || param.name || param.component);
342
  if (Object.prototype.hasOwnProperty.call(values, name)) return values[name];
 
343
  for (const [alias, value] of Object.entries(values)) {
344
  if (alias && name && (name.includes(alias) || alias.includes(name))) return value;
345
  }
 
346
  if ("parameter_default" in param) return param.parameter_default;
347
  return null;
348
  });
349
  }
 
350
  async function connectBackend() {
351
  if (client) return client;
352
  $("loadingTitle").textContent = "Connecting to the remote AIDMA engine…";
 
361
  api = await client.view_api();
362
  return client;
363
  }
 
364
  function snapshotJob() {
365
  const prompt = $("prompt").value.trim();
366
  if (!prompt) throw new Error("Write a prompt first.");
 
367
  const modelOption = $("model").selectedOptions[0];
368
  const [width, height] = $("ratio").value.split("x").map(Number);
369
  const styleName = $("style").value.trim();
370
  const styleText = STYLE_DETAIL[styleName] ?? styleName;
 
371
  const parts = [prompt];
372
  if (styleText && normalise(styleName) !== normalise("No extra style")) parts.push(styleText);
373
  if ($("boost").checked) parts.push(PROMPT_BOOST);
 
374
  return {
375
  id: ++jobCounter,
376
  repo: modelOption.value,
 
385
  loraScale: 0.95
386
  };
387
  }
 
388
  function remoteFileUrl(value) {
389
  if (typeof value !== "string") return null;
390
  const text = value.trim();
391
  if (!text) return null;
 
392
  // Already usable in the browser.
393
  if (/^(https?:\/\/|blob:|data:image\/)/i.test(text)) return text;
 
394
  // Modern Gradio may return a relative file route.
395
  if (text.startsWith("/gradio_api/")) return `${BACKEND_ORIGIN}${text}`;
396
  if (text.startsWith("gradio_api/")) return `${BACKEND_ORIGIN}/${text}`;
 
397
  // Some Gradio versions return only the server-side temporary path.
398
  if (
399
  text.startsWith("/tmp/") ||
 
402
  ) {
403
  return `${BACKEND_ORIGIN}/gradio_api/file=${encodeURI(text)}`;
404
  }
 
405
  return null;
406
  }
 
407
  function extractImageUrl(value, seen = new Set()) {
408
  if (value == null) return null;
 
409
  if (typeof Blob !== "undefined" && value instanceof Blob) {
410
  return URL.createObjectURL(value);
411
  }
412
+ if (typeof File !== "undefined" && value instanceof File) {
413
+ return URL.createObjectURL(value);
414
+ }
415
  if (typeof value === "string") {
416
+ const trimmed = value.trim();
417
+ // Some component serializers return raw base64 rather than a FileData URL.
418
+ if (/^[A-Za-z0-9+/=\s]{1000,}$/.test(trimmed)) {
419
+ return `data:image/png;base64,${trimmed.replace(/\s+/g, "")}`;
420
+ }
421
+ return remoteFileUrl(trimmed);
422
  }
 
423
  if (typeof value !== "object") return null;
424
  if (seen.has(value)) return null;
425
  seen.add(value);
 
426
  if (Array.isArray(value)) {
427
  // The first output of /run_lora is the generated image.
428
  for (const item of value) {
 
431
  }
432
  return null;
433
  }
 
434
  // Gradio FileData commonly uses url/path/orig_name/name.
435
  for (const key of ["url", "path", "orig_name", "name", "image", "data"]) {
436
  if (Object.prototype.hasOwnProperty.call(value, key)) {
 
438
  if (found) return found;
439
  }
440
  }
 
441
  for (const item of Object.values(value)) {
442
  const found = extractImageUrl(item, seen);
443
  if (found) return found;
444
  }
 
445
  return null;
446
  }
 
447
  function showImage(url, job) {
448
  $("image").src = url;
449
  $("download").href = url;
 
451
  $("download").style.display = "inline-flex";
452
  setViewer("image", `${job.modelLabel} · seed ${job.seed}`);
453
  }
 
454
  async function loadSelectedLora(job) {
455
  const { endpoint, spec } = endpointInfo(["/add_custom_lora", "add_custom_lora"]);
456
  const payload = buildPayload(
 
462
  },
463
  [job.repo]
464
  );
 
465
  const result = await client.predict(endpoint, payload);
466
  const data = result?.data || [];
467
  const selectedIndex = Number.isFinite(Number(data[4])) ? Number(data[4]) : null;
468
  const trigger = typeof data[5] === "string" && data[5].trim() ? data[5].trim() : job.trigger;
469
  return { selectedIndex, trigger };
470
  }
 
471
  async function runGeneration(job, selectedIndex, trigger) {
472
  const { endpoint, spec } = endpointInfo(["/run_lora", "run_lora"]);
473
  const finalPrompt = normalise(job.prompt).includes(normalise(trigger))
474
  ? job.prompt
475
  : `${trigger}, ${job.prompt}`;
 
476
  const values = {
477
  prompt: finalPrompt,
478
  prompttext: finalPrompt,
 
493
  lorascale: job.loraScale,
494
  adapterstrength: job.loraScale
495
  };
496
+ /*
497
+ The explorer's generation function is a Python generator that emits preview
498
+ frames. Using submit() here can leave a Static frontend holding only a
499
+ progress event. predict() waits until the generator completes and returns
500
+ the final three outputs: [image, seed, progress].
501
+ */
502
+ const fallbackWithoutState = [
503
  finalPrompt, null, 0.75, job.cfg, job.steps, false,
504
  job.seed, job.width, job.height, job.loraScale
505
  ];
506
+ const payload = buildPayload(spec, values, fallbackWithoutState);
507
+ $("queueStatus").textContent = "Waiting for the remote GPU and final image";
508
+ const response = await client.predict(endpoint, payload);
509
+ // @gradio/client normally returns { type: "data", data: [...] }.
510
+ // Keep compatibility with clients that return the output array directly.
511
+ const outputs = response?.data ?? response;
512
+ console.log("AIDMA final Gradio outputs:", outputs);
513
+ // /run_lora outputs: [generated image, final seed, progress component].
514
+ const imageOutput = Array.isArray(outputs) ? outputs[0] : outputs;
515
+ const returnedSeed = Array.isArray(outputs) ? Number(outputs[1]) : NaN;
516
+ const finalUrl = extractImageUrl(imageOutput) || extractImageUrl(outputs);
 
 
 
 
 
 
 
 
 
 
 
 
517
  if (!finalUrl) {
518
+ console.error("Unrecognized final Gradio image payload:", outputs);
519
  throw new Error(
520
+ "The remote Space did not provide a usable final image. " +
521
+ "It may have rejected this LoRA or changed its API."
522
  );
523
  }
524
+ if (Number.isFinite(returnedSeed)) job.seed = returnedSeed;
525
+ showImage(finalUrl, job);
526
  return finalUrl;
527
  }
 
528
  async function processQueue() {
529
  if (processing || !localQueue.length) return;
530
  processing = true;
531
  updateQueueUI();
 
532
  while (localQueue.length) {
533
  const job = localQueue.shift();
534
  updateQueueUI();
 
537
  $("queueStatus").textContent = "Preparing AIDMA LoRA";
538
  $("status").className = "";
539
  setViewer("loading", `Job #${job.id} is running.`);
 
540
  try {
541
  await connectBackend();
542
  const loaded = await loadSelectedLora(job);
543
+ $("queueStatus").textContent = "Submitting to remote GPU and waiting for final output";
544
  await runGeneration(job, loaded.selectedIndex, loaded.trigger);
545
  } catch (error) {
546
  console.error(error);
 
555
  api = null;
556
  }
557
  }
 
558
  processing = false;
559
  updateQueueUI();
560
  }
 
561
  function escapeHtml(value) {
562
  return String(value).replace(/[&<>"']/g, char => ({
563
  "&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#039;"
564
  })[char]);
565
  }
 
566
  $("generate").addEventListener("click", () => {
567
  try {
568
  const job = snapshotJob();
 
577
  $("prompt").focus();
578
  }
579
  });
 
580
  $("prompt").addEventListener("keydown", event => {
581
  if ((event.ctrlKey || event.metaKey) && event.key === "Enter") {
582
  event.preventDefault();
583
  $("generate").click();
584
  }
585
  });
 
586
  updateQueueUI();
587
  </script>
588
  </body>