Update app.py
Browse files
app.py
CHANGED
|
@@ -66,6 +66,12 @@ from control_tools import (
|
|
| 66 |
OPENPOSE_KEYPOINT_NAMES,
|
| 67 |
)
|
| 68 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
# ββ Model load ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 70 |
# Pipeline class depends on MODEL_VARIANT and is the only thing here that
|
| 71 |
# can't live in config.py (config must stay torch/diffusers-free).
|
|
@@ -110,26 +116,8 @@ def on_gallery_select(evt: gr.SelectData, gallery_value):
|
|
| 110 |
return None
|
| 111 |
return item[0] if isinstance(item, (list, tuple)) else item
|
| 112 |
|
| 113 |
-
|
| 114 |
-
#
|
| 115 |
-
|
| 116 |
-
def _spawn_log(pil_images, result_image, prompt, seed, steps, guidance_scale,
|
| 117 |
-
width, height, duration, success, error="",
|
| 118 |
-
lora_titles=None, lora_weights=None, upscale_factor="None",
|
| 119 |
-
lora_prompt_text=""):
|
| 120 |
-
"""Fire-and-forget logger. ENABLE_LOGGING is read once at import time in
|
| 121 |
-
config.py β there's no per-call env lookup. Used by single, batch and
|
| 122 |
-
bulk inference paths."""
|
| 123 |
-
if not ENABLE_LOGGING:
|
| 124 |
-
return
|
| 125 |
-
threading.Thread(
|
| 126 |
-
target=log_inference,
|
| 127 |
-
args=(pil_images, result_image, prompt, seed, steps, guidance_scale,
|
| 128 |
-
width, height, duration, success, error),
|
| 129 |
-
kwargs={"lora_titles": lora_titles, "lora_weights": lora_weights,
|
| 130 |
-
"upscale_factor": upscale_factor, "lora_prompt_text": lora_prompt_text},
|
| 131 |
-
daemon=True,
|
| 132 |
-
).start()
|
| 133 |
|
| 134 |
|
| 135 |
# ββ GPU step (shared by single, batch, and bulk) βββββββββββββββββββββββββββββ
|
|
@@ -202,25 +190,8 @@ def _infer_gpu(
|
|
| 202 |
return image, seed, width, height
|
| 203 |
|
| 204 |
|
| 205 |
-
def _meta_for(prompt, seed, steps, guidance_scale, width, height, upscale_factor,
|
| 206 |
-
canvas_mode, canvas_fit_mode, lora_titles, lora_weights,
|
| 207 |
-
lora_prompt, custom_prompt, extra=None):
|
| 208 |
-
meta = {
|
| 209 |
-
"prompt": (prompt or "").strip(),
|
| 210 |
-
"seed": seed, "steps": steps,
|
| 211 |
-
"guidance_scale": guidance_scale if MODEL_VARIANT != "9B-KV" else None,
|
| 212 |
-
"width": width, "height": height,
|
| 213 |
-
"model": f"FLUX.2-Klein-{MODEL_VARIANT}",
|
| 214 |
-
"upscale_factor": upscale_factor,
|
| 215 |
-
"canvas_mode": canvas_mode, "canvas_fit_mode": canvas_fit_mode,
|
| 216 |
-
"loras": list(zip(lora_titles or [], lora_weights or [])),
|
| 217 |
-
"lora_prompt": (lora_prompt or "").strip(),
|
| 218 |
-
"custom_prompt": (custom_prompt or "").strip(),
|
| 219 |
-
}
|
| 220 |
-
if extra:
|
| 221 |
-
meta.update(extra)
|
| 222 |
-
return meta
|
| 223 |
|
|
|
|
| 224 |
|
| 225 |
# ββ Single / batch infer (generator β streams into gr.Gallery) βββββββββββββββ
|
| 226 |
|
|
@@ -231,10 +202,7 @@ def infer(
|
|
| 231 |
batch_count, batch_vary, sweep_min, sweep_max,
|
| 232 |
dynamic_loras, *slider_values, progress=gr.Progress(track_tqdm=True),
|
| 233 |
):
|
| 234 |
-
"""Generator. Streams a list of PNG paths into the output gallery
|
| 235 |
-
result at a time. Each iteration is its own @spaces.GPU call, so a
|
| 236 |
-
ZeroGPU quota wall mid-batch only loses the in-progress item β earlier
|
| 237 |
-
PNGs are already saved to disk and surfaced in the gallery."""
|
| 238 |
gc.collect(); torch.cuda.empty_cache()
|
| 239 |
if not isinstance(upscale_factor, str) or upscale_factor not in UPSCALE_MODELS:
|
| 240 |
upscale_factor = "None"
|
|
@@ -262,7 +230,6 @@ def infer(
|
|
| 262 |
active_styles = [get_style_by_title(t, dynamic_loras) for t in selected_titles
|
| 263 |
if get_style_by_title(t, dynamic_loras)
|
| 264 |
and get_style_by_title(t, dynamic_loras)["adapter_name"] is not None]
|
| 265 |
-
log_titles = [s["title"] for s in active_styles]
|
| 266 |
|
| 267 |
results = []
|
| 268 |
last_seed_text = ""
|
|
@@ -274,7 +241,6 @@ def infer(
|
|
| 274 |
sliders[slot] = val
|
| 275 |
|
| 276 |
cur_seed = seeds[i]
|
| 277 |
-
log_weights = [float(w) for w in sliders[:len(active_styles)]]
|
| 278 |
t0 = time.perf_counter()
|
| 279 |
try:
|
| 280 |
image, used_seed, w, h = _infer_gpu(
|
|
@@ -284,26 +250,13 @@ def infer(
|
|
| 284 |
canvas_fit_mode, pad_color, dynamic_loras,
|
| 285 |
*sliders, progress=progress,
|
| 286 |
)
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
lora_prompt_text, custom_prompt_text,
|
| 290 |
-
extra={"batch_index": i, "batch_total": batch_count,
|
| 291 |
-
"batch_vary": batch_vary})
|
| 292 |
-
results.append(save_with_metadata(image, meta))
|
| 293 |
last_seed_text = str(used_seed)
|
| 294 |
-
_spawn_log(pil_images, image, prompt, used_seed, steps, guidance_scale,
|
| 295 |
-
w, h, time.perf_counter() - t0, True,
|
| 296 |
-
lora_titles=log_titles, lora_weights=log_weights,
|
| 297 |
-
upscale_factor=upscale_factor, lora_prompt_text=lora_prompt_text or "")
|
| 298 |
yield results, last_seed_text
|
| 299 |
except Exception as e:
|
| 300 |
-
_spawn_log(pil_images, None, prompt, cur_seed, steps, guidance_scale,
|
| 301 |
-
0, 0, time.perf_counter() - t0, False, str(e),
|
| 302 |
-
lora_titles=log_titles, lora_weights=log_weights,
|
| 303 |
-
upscale_factor=upscale_factor, lora_prompt_text=lora_prompt_text or "")
|
| 304 |
yield results, f"Batch {i+1}/{batch_count} failed: {e}"
|
| 305 |
-
|
| 306 |
-
|
| 307 |
|
| 308 |
# ββ Bulk processing (one input image per iteration) βββββββββββββββββββββββββ
|
| 309 |
|
|
@@ -321,35 +274,18 @@ def bulk_infer(
|
|
| 321 |
canvas_mode, custom_width, custom_height, canvas_fit_mode, pad_color,
|
| 322 |
dynamic_loras, *slider_values, progress=gr.Progress(),
|
| 323 |
):
|
| 324 |
-
"""Process each uploaded image as its own GPU call
|
| 325 |
-
into the bulk output gallery as soon as they complete. Outputs and a CSV
|
| 326 |
-
manifest are written to /tmp/bulk_<sid>/ with stable filenames, so a
|
| 327 |
-
ZeroGPU quota wall mid-run still leaves earlier outputs grabbable from
|
| 328 |
-
the gallery and from disk.
|
| 329 |
-
|
| 330 |
-
Logging: each image is logged individually via _spawn_log on success or
|
| 331 |
-
failure β same code path as single/batch, so bulk shows up in the dataset
|
| 332 |
-
with the same schema, just with extra bulk_index / bulk_total fields
|
| 333 |
-
embedded in the PNG metadata."""
|
| 334 |
if not input_files:
|
| 335 |
raise gr.Error("Upload at least one image first.")
|
| 336 |
|
| 337 |
work_dir = _new_bulk_workdir()
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
"idx", "input_filename", "output_path", "seed",
|
| 342 |
-
"width", "height", "success", "error", "duration_sec",
|
| 343 |
-
])
|
| 344 |
|
| 345 |
active_styles = [get_style_by_title(t, dynamic_loras) for t in (selected_titles or [])
|
| 346 |
if get_style_by_title(t, dynamic_loras)
|
| 347 |
and get_style_by_title(t, dynamic_loras)["adapter_name"] is not None]
|
| 348 |
-
log_titles = [s["title"] for s in active_styles]
|
| 349 |
-
log_weights = [float(w) for w in slider_values[:len(active_styles)]]
|
| 350 |
-
|
| 351 |
-
results, succeeded, failed = [], 0, 0
|
| 352 |
-
total = len(input_files)
|
| 353 |
|
| 354 |
for i, path in enumerate(input_files):
|
| 355 |
progress(i / total, desc=f"Image {i+1}/{total}")
|
|
@@ -369,46 +305,13 @@ def bulk_infer(
|
|
| 369 |
|
| 370 |
stem = os.path.splitext(fname)[0]
|
| 371 |
out_path = os.path.join(work_dir, f"{i:03d}_{stem}.png")
|
| 372 |
-
|
| 373 |
-
canvas_mode, canvas_fit_mode, log_titles, log_weights,
|
| 374 |
-
lora_prompt_text, custom_prompt_text,
|
| 375 |
-
extra={"bulk_input": fname,
|
| 376 |
-
"bulk_index": i, "bulk_total": total})
|
| 377 |
-
image.save(out_path, format="PNG", pnginfo=build_pnginfo(meta))
|
| 378 |
results.append(out_path)
|
| 379 |
succeeded += 1
|
| 380 |
-
duration = time.perf_counter() - t0
|
| 381 |
-
|
| 382 |
-
with open(manifest_path, "a", newline="") as f:
|
| 383 |
-
csv.writer(f).writerow([i, fname, out_path, used_seed, w, h, True, "", f"{duration:.2f}"])
|
| 384 |
-
|
| 385 |
-
_spawn_log([img], image, prompt, used_seed, steps, guidance_scale,
|
| 386 |
-
w, h, duration, True,
|
| 387 |
-
lora_titles=log_titles, lora_weights=log_weights,
|
| 388 |
-
upscale_factor=upscale_factor, lora_prompt_text=lora_prompt_text or "")
|
| 389 |
-
|
| 390 |
-
status = f"β
{succeeded}/{total} done ({failed} failed)"
|
| 391 |
-
yield results, status, gr.update()
|
| 392 |
except Exception as e:
|
| 393 |
-
|
| 394 |
-
duration = time.perf_counter() - t0
|
| 395 |
-
with open(manifest_path, "a", newline="") as f:
|
| 396 |
-
csv.writer(f).writerow([i, fname, "", "", "", "", False, str(e)[:300], f"{duration:.2f}"])
|
| 397 |
-
_spawn_log([], None, prompt, 0, steps, guidance_scale,
|
| 398 |
-
0, 0, duration, False, str(e),
|
| 399 |
-
lora_titles=log_titles, lora_weights=log_weights,
|
| 400 |
-
upscale_factor=upscale_factor, lora_prompt_text=lora_prompt_text or "")
|
| 401 |
-
yield results, f"β οΈ Image {i+1} failed: {e} | {succeeded} ok, {failed} failed", gr.update()
|
| 402 |
-
continue
|
| 403 |
-
|
| 404 |
-
zip_path = os.path.join(work_dir, "outputs.zip")
|
| 405 |
-
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_STORED) as zf:
|
| 406 |
-
for p in results:
|
| 407 |
-
zf.write(p, arcname=os.path.basename(p))
|
| 408 |
-
zf.write(manifest_path, arcname="manifest.csv")
|
| 409 |
-
|
| 410 |
-
yield results, f"π Done β {succeeded}/{total} succeeded, {failed} failed", zip_path
|
| 411 |
|
|
|
|
| 412 |
|
| 413 |
# ββ Custom prompt manager (session-local) ββββββββββββββββββββββββββββββββββββ
|
| 414 |
|
|
@@ -466,6 +369,9 @@ with gr.Blocks() as demo:
|
|
| 466 |
dynamic_loras_state = gr.State({})
|
| 467 |
selected_output_state = gr.State(None)
|
| 468 |
|
|
|
|
|
|
|
|
|
|
| 469 |
with gr.Column(elem_id="col-container"):
|
| 470 |
_logging_badge = "π’ On" if ENABLE_LOGGING else "π΄ Off"
|
| 471 |
|
|
|
|
| 66 |
OPENPOSE_KEYPOINT_NAMES,
|
| 67 |
)
|
| 68 |
|
| 69 |
+
def save_simple_image(image: Image.Image) -> str:
|
| 70 |
+
"""Save image without any metadata for privacy."""
|
| 71 |
+
path = f"/tmp/gen_{uuid.uuid4().hex[:8]}.png"
|
| 72 |
+
image.save(path, format="PNG")
|
| 73 |
+
return path
|
| 74 |
+
|
| 75 |
# ββ Model load ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 76 |
# Pipeline class depends on MODEL_VARIANT and is the only thing here that
|
| 77 |
# can't live in config.py (config must stay torch/diffusers-free).
|
|
|
|
| 116 |
return None
|
| 117 |
return item[0] if isinstance(item, (list, tuple)) else item
|
| 118 |
|
| 119 |
+
# 2do
|
| 120 |
+
# remove logging completely
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
|
| 122 |
|
| 123 |
# ββ GPU step (shared by single, batch, and bulk) βββββββββββββββββββββββββββββ
|
|
|
|
| 190 |
return image, seed, width, height
|
| 191 |
|
| 192 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
|
| 194 |
+
# ββ Single / batch infer (generator β streams into gr.Gallery) βββββββββββββββ
|
| 195 |
|
| 196 |
# ββ Single / batch infer (generator β streams into gr.Gallery) βββββββββββββββ
|
| 197 |
|
|
|
|
| 202 |
batch_count, batch_vary, sweep_min, sweep_max,
|
| 203 |
dynamic_loras, *slider_values, progress=gr.Progress(track_tqdm=True),
|
| 204 |
):
|
| 205 |
+
"""Generator. Streams a list of PNG paths into the output gallery."""
|
|
|
|
|
|
|
|
|
|
| 206 |
gc.collect(); torch.cuda.empty_cache()
|
| 207 |
if not isinstance(upscale_factor, str) or upscale_factor not in UPSCALE_MODELS:
|
| 208 |
upscale_factor = "None"
|
|
|
|
| 230 |
active_styles = [get_style_by_title(t, dynamic_loras) for t in selected_titles
|
| 231 |
if get_style_by_title(t, dynamic_loras)
|
| 232 |
and get_style_by_title(t, dynamic_loras)["adapter_name"] is not None]
|
|
|
|
| 233 |
|
| 234 |
results = []
|
| 235 |
last_seed_text = ""
|
|
|
|
| 241 |
sliders[slot] = val
|
| 242 |
|
| 243 |
cur_seed = seeds[i]
|
|
|
|
| 244 |
t0 = time.perf_counter()
|
| 245 |
try:
|
| 246 |
image, used_seed, w, h = _infer_gpu(
|
|
|
|
| 250 |
canvas_fit_mode, pad_color, dynamic_loras,
|
| 251 |
*sliders, progress=progress,
|
| 252 |
)
|
| 253 |
+
# Simple save without metadata / logging
|
| 254 |
+
results.append(save_simple_image(image)) # β define this helper below
|
|
|
|
|
|
|
|
|
|
|
|
|
| 255 |
last_seed_text = str(used_seed)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 256 |
yield results, last_seed_text
|
| 257 |
except Exception as e:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 258 |
yield results, f"Batch {i+1}/{batch_count} failed: {e}"
|
| 259 |
+
|
|
|
|
| 260 |
|
| 261 |
# ββ Bulk processing (one input image per iteration) βββββββββββββββββββββββββ
|
| 262 |
|
|
|
|
| 274 |
canvas_mode, custom_width, custom_height, canvas_fit_mode, pad_color,
|
| 275 |
dynamic_loras, *slider_values, progress=gr.Progress(),
|
| 276 |
):
|
| 277 |
+
"""Process each uploaded image as its own GPU call."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 278 |
if not input_files:
|
| 279 |
raise gr.Error("Upload at least one image first.")
|
| 280 |
|
| 281 |
work_dir = _new_bulk_workdir()
|
| 282 |
+
results = []
|
| 283 |
+
succeeded = 0
|
| 284 |
+
total = len(input_files)
|
|
|
|
|
|
|
|
|
|
| 285 |
|
| 286 |
active_styles = [get_style_by_title(t, dynamic_loras) for t in (selected_titles or [])
|
| 287 |
if get_style_by_title(t, dynamic_loras)
|
| 288 |
and get_style_by_title(t, dynamic_loras)["adapter_name"] is not None]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 289 |
|
| 290 |
for i, path in enumerate(input_files):
|
| 291 |
progress(i / total, desc=f"Image {i+1}/{total}")
|
|
|
|
| 305 |
|
| 306 |
stem = os.path.splitext(fname)[0]
|
| 307 |
out_path = os.path.join(work_dir, f"{i:03d}_{stem}.png")
|
| 308 |
+
image.save(out_path, format="PNG") # plain save, no metadata
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 309 |
results.append(out_path)
|
| 310 |
succeeded += 1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 311 |
except Exception as e:
|
| 312 |
+
print(f"Bulk image {i+1} failed: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 313 |
|
| 314 |
+
return results
|
| 315 |
|
| 316 |
# ββ Custom prompt manager (session-local) ββββββββββββββββββββββββββββββββββββ
|
| 317 |
|
|
|
|
| 369 |
dynamic_loras_state = gr.State({})
|
| 370 |
selected_output_state = gr.State(None)
|
| 371 |
|
| 372 |
+
# 2do
|
| 373 |
+
# once logging is remove, adapt this
|
| 374 |
+
|
| 375 |
with gr.Column(elem_id="col-container"):
|
| 376 |
_logging_badge = "π’ On" if ENABLE_LOGGING else "π΄ Off"
|
| 377 |
|