Skip to content

Free, open-source AI video generator for Mac. Run LTX-2.5 and MiniMax H3 (Hailuo) locally on Apple Silicon: text-to-video and image-to-video with sound, lip-sync, character LoRA training, songs from lyrics (YuE2) and image editing (Qwen-Image-Edit). One-click install via Pinokio. Offline: no cloud, no API key, no NVIDIA GPU.

release(v3.2.5): image-to-image + Ideogram reference bridge, robust first-run downloads

mrbizarrofbc6335a988c
diff --git a/VERSION b/VERSION
index 351227f..5ae69bd 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-3.2.4
+3.2.5
diff --git a/caption_reference_vision.py b/caption_reference_vision.py
new file mode 100644
index 0000000..8b608ec
--- /dev/null
+++ b/caption_reference_vision.py
@@ -0,0 +1,211 @@
+"""Vision-caption a reference image with the local Gemma 3 12B multimodal
+model, for the Ideogram 4 "reference bridge".
+
+Why this exists:
+ Ideogram 4 (mflux-generate-ideogram4) is TEXT-TO-IMAGE only — it has
+ no image input. To give it pseudo image-to-image, we describe the
+ user's reference image in words with the local Gemma 3 vision tower,
+ then splice that description into Ideogram's text prompt so Ideogram
+ redraws the look. It is a re-interpretation of the reference, never a
+ pixel copy.
+
+Why a standalone subprocess (and not the warm helper / caption_with_gemma):
+ 1. RAM. The Ideogram fp8 DiT render needs ~24 GB. Gemma loaded for
+ captioning is ~6 GB RSS. Running the caption in a short-lived
+ subprocess means Gemma's memory is fully reclaimed by the OS the
+ moment this process exits — BEFORE the heavy Ideogram render
+ starts. image_engine._generate_mflux spawns us, reads our caption
+ off stdout, and only then launches the Ideogram subprocess.
+ 2. Lightricks' Gemma wrapper (used by the LTX helper for prompt
+ enhancement) and `caption_with_gemma.py` are TEXT-ONLY — they do
+ not pass images through the vision tower. We need `mlx_vlm`, which
+ drives the `Gemma3ForConditionalGeneration` multimodal path on the
+ same Gemma 3 weights.
+
+Output contract (read by image_engine._generate_mflux):
+ On success we print a single-line machine-readable marker plus the
+ bare caption as the LAST line, e.g.:
+ CAPTION_JSON: {"caption": "A weathered ..."}
+ A weathered brass diving helmet on a dark studio backdrop, ...
+ The caller prefers the CAPTION_JSON line; if that is missing it falls
+ back to the last non-empty stdout line. On any failure we write a
+ one-line message to stderr and exit non-zero — the caller treats that
+ as "caption unavailable" and renders text-only (never crashes).
+
+CLI:
+ python caption_reference_vision.py \
+ --image <path> [--image <path> ...] # 1-3 images; first is described
+ [--model <mlx_models/gemma-3-12b-it-4bit>]
+ [--max-tokens 160]
+"""
+from __future__ import annotations
+
+import argparse
+import glob
+import json
+import os
+import pathlib
+import sys
+
+
+# The instruction Gemma sees. We want a tight, plain-prose description an
+# artist (here: Ideogram) can use to recreate the LOOK — subject,
+# composition, palette, lighting, style — with no chat preamble.
+_PROMPT = (
+ "Describe this image so an artist can recreate its look. In 2-3 "
+ "plain-prose sentences, cover: the main subject, the composition and "
+ "framing, the color palette, the lighting, and the overall visual "
+ "style (e.g. photographic, painterly, 3D render, illustration). "
+ "Do NOT add any preamble, list, markdown, or quotes — just the "
+ "description."
+)
+
+
+def _resolve_model(override: str | None) -> pathlib.Path | None:
+ """Resolve the Gemma 3 model dir the same way the panel does.
+
+ Order, mirroring mlx_ltx_panel.py's GEMMA resolution:
+ 1. explicit --model arg,
+ 2. env LTX_GEMMA_PATH,
+ 3. <script-dir>/mlx_models/gemma-3-12b-it-4bit,
+ 4. the HuggingFace cache snapshot glob under HF_HOME (or the
+ default cache root) — `cache/HF_HOME` is the in-repo location
+ the panel's preflight downloads into.
+ Returns the first directory that exists, else None.
+ """
+ if override:
+ p = pathlib.Path(override).expanduser()
+ return p if p.is_dir() else None
+
+ env_path = os.environ.get("LTX_GEMMA_PATH")
+ if env_path:
+ p = pathlib.Path(env_path).expanduser()
+ if p.is_dir():
+ return p
+
+ here = pathlib.Path(__file__).resolve().parent
+ local = here / "mlx_models" / "gemma-3-12b-it-4bit"
+ if local.is_dir():
+ return local
+
+ # HF cache snapshot fallback. HF_HOME may point at the in-repo
+ # cache/HF_HOME dir; otherwise fall back to the standard ~/.cache root.
+ hf_home = os.environ.get("HF_HOME") or str(here / "cache" / "HF_HOME")
+ candidates: list[str] = []
+ for root in (hf_home, str(pathlib.Path.home() / ".cache" / "huggingface")):
+ candidates.extend(glob.glob(os.path.join(
+ root, "hub",
+ "models--mlx-community--gemma-3-12b-it-4bit",
+ "snapshots", "*")))
+ for snap in candidates:
+ p = pathlib.Path(snap)
+ # A usable snapshot has the config + at least one weight shard.
+ if p.is_dir() and (p / "config.json").is_file():
+ return p
+ return None
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser(
+ description="Vision-caption a reference image with local Gemma 3 "
+ "for the Ideogram 4 reference bridge. Prints the "
+ "caption as the last stdout line plus a "
+ "CAPTION_JSON: {...} marker line; exits non-zero on "
+ "failure.")
+ ap.add_argument("--image", action="append", required=True, metavar="PATH",
+ help="Reference image path. Repeat for up to 3; the "
+ "first image is described, the rest are noted.")
+ ap.add_argument("--model", default=None,
+ help="Override Gemma 3 model dir (default: resolve via "
+ "LTX_GEMMA_PATH, then mlx_models/gemma-3-12b-it-4bit, "
+ "then the HF_HOME cache snapshot).")
+ ap.add_argument("--max-tokens", type=int, default=160,
+ help="Caption length cap (default 160).")
+ args = ap.parse_args()
+
+ # Accept 1-3 images; the bridge only ever sends up to 3. Take the
+ # first as the one to describe and keep the resolved existing paths.
+ raw = [pathlib.Path(p).expanduser() for p in (args.image or [])]
+ images = [p for p in raw if p.is_file()]
+ if not images:
+ sys.stderr.write(
+ "caption_reference_vision: no readable image among "
+ f"{[str(p) for p in raw]}\n")
+ return 1
+ images = images[:3]
+
+ gemma_path = _resolve_model(args.model)
+ if gemma_path is None:
+ sys.stderr.write(
+ "caption_reference_vision: Gemma model dir not found — set "
+ "LTX_GEMMA_PATH or pass --model (looked for "
+ "mlx_models/gemma-3-12b-it-4bit and the HF cache snapshot).\n")
+ return 1
+
+ # Import here (not module top) so --help and the arg parsing above
+ # never pay the import cost, and a missing package yields a clean
+ # stderr message instead of a traceback at import time.
+ try:
+ from mlx_vlm import load, generate
+ from mlx_vlm.prompt_utils import apply_chat_template
+ except ImportError as e:
+ sys.stderr.write(
+ f"caption_reference_vision: mlx_vlm not installed: {e}. "
+ "Run: pip install --no-deps 'mlx-vlm==0.4.4'\n")
+ return 1
+
+ try:
+ model, processor = load(str(gemma_path))
+ except Exception as e: # noqa: BLE001
+ sys.stderr.write(
+ f"caption_reference_vision: failed to load Gemma: "
+ f"{type(e).__name__}: {e}\n")
+ return 1
+
+ # Single-image caption is the robust path. If the user dropped more
+ # than one reference, describe the first and mention how many others
+ # accompany it so Ideogram knows it's part of a set — but we do NOT
+ # try to fuse multiple images (Gemma's multi-image grounding is weak
+ # and the extra tokens/RAM aren't worth it for a prompt hint).
+ described = images[0]
+ user_text = _PROMPT
+ if len(images) > 1:
+ user_text += (f" (This is the primary of {len(images)} reference "
+ "images provided together; describe this one.)")
+ messages = [{"role": "user", "content": user_text}]
+
+ try:
+ formatted = apply_chat_template(
+ processor, model.config, messages, num_images=1)
+ out = generate(
+ model, processor, formatted, image=[str(described)],
+ max_tokens=args.max_tokens, verbose=False,
+ )
+ except Exception as e: # noqa: BLE001
+ sys.stderr.write(
+ f"caption_reference_vision: caption failed for "
+ f"{described.name}: {type(e).__name__}: {e}\n")
+ return 1
+
+ text = (getattr(out, "text", out) or "")
+ # Collapse whitespace/newlines into a single clean line — the caller
+ # splices this into a one-line prompt fragment and also relies on the
+ # caption being the LAST stdout line.
+ caption = " ".join(str(text).split()).strip()
+ if not caption:
+ sys.stderr.write(
+ "caption_reference_vision: model returned an empty caption.\n")
+ return 1
+
+ # Machine-readable marker first (preferred by the caller), then the
+ # bare caption as the final line (fallback parse).
+ sys.stdout.write(
+ "CAPTION_JSON: "
+ + json.dumps({"caption": caption}, ensure_ascii=False) + "\n")
+ sys.stdout.write(caption + "\n")
+ sys.stdout.flush()
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/image_engine.py b/image_engine.py
index 1d68647..46a7cdc 100644
--- a/image_engine.py
+++ b/image_engine.py
@@ -205,6 +205,13 @@ class ImageEngineConfig:
# None → the ideogram argv branch falls back to "V4_DEFAULT_20" (20
# steps). Valid values: "V4_TURBO_12" | "V4_DEFAULT_20" | "V4_QUALITY_48".
mflux_preset: str | None = None
+ # Ideogram 4 "reference bridge". Ideogram is TEXT-TO-IMAGE only (no
+ # --image-paths), so when this is on AND refs are present we vision-
+ # caption the first ref(s) with local Gemma 3 and splice the caption
+ # into the Ideogram prompt — a re-interpretation of the look, not a
+ # pixel copy. Ignored by every non-ideogram family (they consume refs
+ # directly via --image-paths). See the bridge block in _generate_mflux.
+ ideogram_reference_bridge: bool = False
mflux_python_path: str = "" # optional override for the mflux CLI location
# Optional Lightning / acceleration LoRAs. With qwen_edit + a 4-step
# Lightning LoRA, generation drops from ~5 min to ~10-15 sec per
@@ -758,11 +765,86 @@ def _generate_mflux(prompt: str, n: int, width: int, height: int,
ideogram_prompt_file: str | None = None
if fam == "ideogram":
import tempfile
+ # Reference bridge: Ideogram has no image input, so when the user
+ # enabled it AND dropped reference image(s), vision-caption the
+ # first ref(s) with local Gemma 3 in a SEPARATE subprocess and
+ # splice the caption into the prompt. The subprocess (not an
+ # in-process load) matters here: Gemma's ~6 GB RSS is reclaimed by
+ # the OS the moment it exits — BEFORE we launch the ~24 GB Ideogram
+ # render below — so the two never coexist. The whole block is
+ # best-effort: any failure/timeout falls back to plain text-to-
+ # image with a warning and NEVER breaks the render.
+ eff_prompt = prompt
+ if config.ideogram_reference_bridge and refs and prompt.lstrip().startswith("{"):
+ # Layout-mode prompts are a serialized Ideogram JSON caption (the
+ # on-canvas editor). Appending a plain-text reference description
+ # would corrupt the JSON and mflux would silently drop the whole
+ # structured layout. Skip the bridge — the UI also hides the toggle
+ # in Layout mode, so this is a belt-and-suspenders guard.
+ if on_log is not None:
+ try: on_log("reference bridge skipped — Layout caption uses the canvas, not a reference")
+ except Exception: # noqa: BLE001
+ pass
+ elif config.ideogram_reference_bridge and refs:
+ try:
+ # Same interpreter that runs mflux (the venv python sits
+ # next to bin_path), mirroring the TeaCache wrap fallback.
+ bin_dir = Path(bin_path).parent
+ cap_py = bin_dir / "python3"
+ if not cap_py.is_file():
+ cap_py = bin_dir / "python"
+ if not cap_py.is_file():
+ cap_py = Path(sys.executable)
+ cap_helper = (Path(__file__).resolve().parent
+ / "caption_reference_vision.py")
+ cap_cmd = [str(cap_py), str(cap_helper)]
+ for r in refs[:3]: # first 3 refs only
+ cap_cmd += ["--image", str(Path(r).resolve())]
+ if on_log is not None:
+ try: on_log("captioning reference with Gemma 3 vision…")
+ except Exception: # noqa: BLE001
+ pass
+ cap_res = subprocess.run(
+ cap_cmd, capture_output=True, text=True,
+ env=_clean_subprocess_env(), timeout=180,
+ )
+ if cap_res.returncode != 0:
+ raise RuntimeError(
+ (cap_res.stderr or "captioner exited non-zero").strip())
+ # Prefer the CAPTION_JSON marker line; fall back to the
+ # last non-empty stdout line.
+ caption = ""
+ for ln in cap_res.stdout.splitlines():
+ if ln.startswith("CAPTION_JSON:"):
+ try:
+ caption = json.loads(
+ ln.split("CAPTION_JSON:", 1)[1].strip()
+ ).get("caption", "")
+ except Exception: # noqa: BLE001
+ caption = ""
+ if not caption:
+ tail = [ln for ln in cap_res.stdout.splitlines() if ln.strip()]
+ caption = tail[-1].strip() if tail else ""
+ if not caption:
+ raise RuntimeError("captioner returned no caption")
+ eff_prompt = (
+ f"{prompt}\n\nVisual reference to echo (subject, "
+ f"composition, palette, lighting, style): {caption}")
+ if on_log is not None:
+ try: on_log(f"reference caption: {caption[:120]}…")
+ except Exception: # noqa: BLE001
+ pass
+ except Exception as e: # noqa: BLE001 — never break the render
+ if on_log is not None:
+ try: on_log(f"reference caption failed ({e}); rendering text-only")
+ except Exception: # noqa: BLE001
+ pass
+ eff_prompt = prompt
_fd, ideogram_prompt_file = tempfile.mkstemp(
suffix=".json", prefix="ideogram_prompt_",
)
with os.fdopen(_fd, "w", encoding="utf-8") as _pf:
- _pf.write(prompt)
+ _pf.write(eff_prompt)
cmd = [
bin_path,
"--model", config.mflux_model,
@@ -998,7 +1080,67 @@ def _generate_mflux(prompt: str, n: int, width: int, height: int,
# Register before the wait loop so /stop can find this proc.
_register_active_proc(proc)
try:
- deadline = time.time() + timeout_s
+ # Activity-based (stall) timeout, NOT a fixed total deadline: the model
+ # download runs INSIDE this subprocess, and on a slow connection a
+ # 20-34 GB first-run pull can exceed any fixed render budget. The old
+ # fixed deadline killed a slow-but-progressing download mid-fetch — so a
+ # brand-new user's first generation just "failed" with a partial model.
+ # Reset the deadline on every output line (download "Fetching i/N" lines
+ # stream per file; render emits step lines every few seconds), so we
+ # only abort on a genuine STALL — no output for `stall_budget`. A
+ # generous absolute cap is the runaway backstop.
+ stall_budget = 1800.0 # 30 min of silence = stuck
+ hard_cap = time.time() + max(timeout_s, 14400.0) # 4 h absolute backstop
+ # The download writes to disk for many minutes while its stdout is
+ # silent OR floods \r-progress that readline() blocks on — either way
+ # the read loop below can't tick a stall clock during the pull. So
+ # liveness is owned by a DAEMON THREAD (a separate thread can't be
+ # starved by readline blocking — the GIL releases during blocking I/O):
+ # it polls the model's cache dir (growth = download alive) while the
+ # read loop stamps `_alive` on each render line (render alive). It kills
+ # the subprocess only on a GENUINE stall — neither disk nor stdout for
+ # stall_budget — and emits a GB readout. (HiDream uses the same idea.)
+ _hf_home = env.get("HF_HOME") or os.path.expanduser("~/.cache/huggingface")
+ dl_dir = ((Path(_hf_home) / "hub"
+ / ("models--" + config.mflux_model.replace("/", "--")))
+ if getattr(config, "mflux_model", None) else None)
+ def _dl_gb() -> float:
+ try:
+ if not dl_dir or not dl_dir.exists():
+ return -1.0
+ total = 0
+ for _root, _dirs, _files in os.walk(dl_dir):
+ for _f in _files:
+ _fp = os.path.join(_root, _f)
+ try:
+ if not os.path.islink(_fp): # skip snapshot symlinks → no double count
+ total += os.path.getsize(_fp)
+ except OSError:
+ pass
+ return total / 1e9
+ except Exception: # noqa: BLE001
+ return -1.0
+ _alive = [time.time()]
+ _wd_stop = threading.Event()
+ _wd_killed = [False]
+ def _watchdog() -> None:
+ _last = _dl_gb()
+ while not _wd_stop.wait(15.0):
+ _sz = _dl_gb()
+ if _sz > _last + 0.001: # >1 MB on disk → download alive
+ _alive[0] = time.time()
+ if _last >= 0.0 and on_log is not None:
+ try: on_log(f"[download] model weights: {_sz:.1f} GB")
+ except Exception: # noqa: BLE001
+ pass
+ _last = max(_last, _sz)
+ if (time.time() - _alive[0] > stall_budget) or (time.time() > hard_cap):
+ _wd_killed[0] = True
+ try: os.killpg(os.getpgid(proc.pid), 15) # SIGTERM tree → readline EOFs
+ except (OSError, ProcessLookupError):
+ pass
+ return
+ threading.Thread(target=_watchdog, name="mflux-dl-watchdog", daemon=True).start()
poll_interval = 0.5
if proc.stdout is not None:
while True:
@@ -1021,6 +1163,7 @@ def _generate_mflux(prompt: str, n: int, width: int, height: int,
break
line = raw.rstrip("\n")
if line:
+ _alive[0] = time.time() # render/output activity → alive
last_lines.append(line)
if on_log is not None:
try:
@@ -1028,11 +1171,8 @@ def _generate_mflux(prompt: str, n: int, width: int, height: int,
except Exception: # noqa: BLE001
# A buggy logger callback must not break the gen.
pass
- # Deadline check — runs every iteration whether or not
- # the child wrote a line, so a silent stall still trips.
- if time.time() > deadline:
- timed_out = True
- break
+ # Stall timeout is owned by the watchdog thread (it sees disk
+ # growth even while readline() above is blocked on \r-output).
# Child exited but we haven't seen EOF yet — flush any
# remaining buffered output on the next select cycle.
# Don't break here: select+readline above will drain
@@ -1040,6 +1180,9 @@ def _generate_mflux(prompt: str, n: int, width: int, height: int,
if proc.poll() is not None and not ready:
# No data in this slice + child gone → drain done.
break
+ if _wd_killed[0]: # watchdog SIGTERM'd a genuine stall
+ timed_out = True
+ _wd_stop.set() # stop the watchdog promptly
if timed_out:
# SIGTERM the whole process group, give it 2s to clean up,
# then SIGKILL if still alive. The except subprocess.TimeoutExpired
@@ -1061,21 +1204,23 @@ def _generate_mflux(prompt: str, n: int, width: int, height: int,
except subprocess.TimeoutExpired:
pass
raise RuntimeError(
- f"{bin_name} timed out after {timeout_s}s on a batch of "
- f"{n} seeds. First run downloads weights — qwen_edit Q8 "
- f"weights are ~34 GB; give it longer or pre-pull."
+ f"{bin_name} stalled: no output for {int(stall_budget)}s "
+ f"(a hung download or a Metal deadlock). First-run weight pulls "
+ f"stream progress and keep this alive — a genuine stall tripped it."
)
- rc = proc.wait(timeout=max(1, deadline - time.time()))
+ rc = proc.wait(timeout=30)
except subprocess.TimeoutExpired as e:
try:
proc.kill()
except OSError:
pass
raise RuntimeError(
- f"{bin_name} timed out after {timeout_s}s on a batch of {n} seeds. "
- f"First run downloads weights; give it longer next time."
+ f"{bin_name} did not exit after its output ended "
+ f"(possible zombie / stuck cleanup)."
) from e
finally:
+ try: _wd_stop.set() # belt: stop watchdog even on early error
+ except NameError: pass
if proc.stdout is not None:
try:
proc.stdout.close()
@@ -1169,6 +1314,21 @@ def _generate_mflux(prompt: str, n: int, width: int, height: int,
# no per-image metadata to show / reproduce / debug. The candidates
# below are still ordered by `seeds` so n=4 batches map to consistent
# indices in the UI.
+ def _is_safety_placeholder(png: Path) -> bool:
+ # Ideogram's safety head returns a flat gray "Image blocked by safety
+ # filter" placeholder on some benign prompts (no mflux signal — it's
+ # baked into the model weights). A real render has high colour variance;
+ # the placeholder is uniform mid-gray. Detect it so the job fails
+ # honestly instead of reporting a gray box as a successful render.
+ try:
+ from PIL import Image, ImageStat
+ st = ImageStat.Stat(Image.open(png).convert("RGB"))
+ mean_std = sum(st.stddev) / 3.0
+ spread = max(st.mean) - min(st.mean) # gray = channels ~equal
+ return mean_std < 15.0 and spread < 25.0
+ except Exception: # noqa: BLE001 — detection must never break a render
+ return False
+
results: list[dict] = []
for i, seed in enumerate(seeds):
# Try the templated path first (old mflux behavior + the n=1 case).
@@ -1212,8 +1372,18 @@ def _generate_mflux(prompt: str, n: int, width: int, height: int,
# (Code-review P3, 2026-05-09.)
"refs_ignored": (bool(refs) and not refs_used),
"lora_paths": list(config.mflux_lora_paths or []),
+ "safety_blocked": (fam == "ideogram" and _is_safety_placeholder(path)),
})
+ if fam == "ideogram" and results and all(r.get("safety_blocked") for r in results):
+ raise RuntimeError(
+ "Ideogram's safety filter blocked this prompt — it returned a gray "
+ "placeholder instead of a render. This is a known false-positive in "
+ "the Ideogram model itself (baked into the weights, not Phosphene) on "
+ "some perfectly benign prompts. Try rephrasing the prompt, or switch "
+ "to a Reference Edit engine."
+ )
+
if not results:
raise RuntimeError(
f"{bin_name} exited 0 but produced no files for any of {n} seeds "
diff --git a/mlx_ltx_panel.py b/mlx_ltx_panel.py
index 37c81c2..92f6d04 100644
--- a/mlx_ltx_panel.py
+++ b/mlx_ltx_panel.py
@@ -5401,6 +5401,15 @@ def make_job(form: dict[str, list[str]] | dict[str, str], *,
# engine; ignored by every other engine. _build_image_engine_config
# reads it off these params to set ImageEngineConfig.mflux_preset.
"ideo_preset": f("ideo_preset", "V4_DEFAULT_20") or "V4_DEFAULT_20",
+ # These two are read back off the params by the worker's
+ # _build_image_engine_config(form=p) call, so they MUST be
+ # carried here — anything not in this dict is silently dropped
+ # on the /queue/add path (the path the panel UI posts to).
+ # ideo_quantize = Fast-mode Q4; ideo_reference_bridge = the
+ # Ideogram vision-caption reference bridge. Both no-op'd before
+ # this line was added.
+ "ideo_quantize": f("ideo_quantize", ""),
+ "ideo_reference_bridge": f("ideo_reference_bridge", ""),
"aspect": aspect,
"n": n,
"seed": str(seed),
@@ -7982,6 +7991,16 @@ def _build_image_engine_config(
# smaller/faster kernels + ~half the RAM for ≤16 GB Macs.
_ideo_q = str(form.get("ideo_quantize") or "").strip()
_ideo_quantize = int(_ideo_q) if _ideo_q in ("3", "4", "5", "6", "8") else 6
+ # Reference bridge (panel checkbox "Use reference"): when ON, the
+ # worker vision-captions a loaded reference image and folds that
+ # description into the Ideogram prompt — a re-interpretation, NOT a
+ # pixel copy (Ideogram's CLI has no --image-paths). Off/absent = the
+ # historical text-only behaviour. The dataclass field is added by the
+ # image_engine.py side of this contract; we only set it here.
+ # Accept "1"/1/true from both the form path (always a string "1") and
+ # the JSON /image/agent path (a real bool True -> str(True) == "True").
+ _ideo_ref_bridge = (str(form.get("ideo_reference_bridge") or "").strip().lower()
+ in ("1", "true", "yes", "on"))
return agent_image_engine.ImageEngineConfig(
kind="mflux",
mflux_model=_resolve_ideogram_repo(), # un-gated mirror unless official already cached
@@ -7990,6 +8009,7 @@ def _build_image_engine_config(
mflux_quantize=_ideo_quantize, # 6 → M1-safe default; 4 → fast mode
mflux_lora_paths=[],
mflux_lora_scales=[],
+ ideogram_reference_bridge=_ideo_ref_bridge,
)
# ===== Qwen-Image-Edit-2511 — Fast / Medium / Quality ====================
# All three share the same ~24 GB Qwen-Image-Edit-2511 model on disk
@@ -12629,6 +12649,17 @@ _PER_IT_RE = re.compile(r"(\d+(?:\.\d+)?)\s*s/it")
# or `[image] model.safetensors: 45%|...` — so download progress is never
# mistaken for denoise steps.
_IMAGE_STEP_RE = re.compile(r"\[image\]\s+\d+%\|[^|]*\|\s*(\d+)\s*/\s*(\d+)")
+# First-run model download. huggingface_hub prints an aggregate
+# "Fetching N files: …| i/N" tqdm bar to the mflux/helper subprocess stdout,
+# which streams into the job log. Surfacing it stops the Now card from sitting
+# on "Loading pipeline" for the ~10 min a cold 20-30 GB model takes (which
+# reads as a hang). Matches with or without the "[image] " prefix.
+_DL_FETCH_RE = re.compile(r"Fetching\s+\d+\s+files:[^|]*\|[^|]*\|\s*(\d+)\s*/\s*(\d+)")
+# image_engine emits a disk-based "[download] model weights: X.X GB" line every
+# ~15 s while a model downloads — more reliable than the per-file Fetching bar
+# on big shards (which is silent for minutes). Prefer it: a climbing GB count is
+# honest and never sticks at 90% like the elapsed-creep fallback.
+_DL_GB_RE = re.compile(r"\[download\]\s*model weights:\s*([\d.]+)\s*GB")
def _parse_progress_signals(log_lines: list[str]) -> dict:
@@ -12648,6 +12679,9 @@ def _parse_progress_signals(log_lines: list[str]) -> dict:
stage1_step = stage1_total = None # latest seen for stage 1
stage2_step = stage2_total = None # latest seen for stage 2
image_step = image_total = None # latest seen for an mflux image job
+ download_seen = False # a first-run model download is in flight
+ download_files = download_total = None
+ download_gb = None # disk-based GB downloaded (preferred signal)
last_per_it = None
decode_started = decode_done = generate_done = upscale_done = pipe_loaded = False
for ln in reversed(log_lines or []):
@@ -12686,6 +12720,18 @@ def _parse_progress_signals(log_lines: list[str]) -> dict:
pit = _PER_IT_RE.search(ln)
if pit:
last_per_it = float(pit.group(1))
+ # First-run model download progress (huggingface_hub aggregate bar).
+ mg = _DL_GB_RE.search(ln)
+ if mg and download_gb is None:
+ try: download_gb = float(mg.group(1))
+ except ValueError: download_gb = None
+ download_seen = True
+ md = _DL_FETCH_RE.search(ln)
+ if md and download_files is None:
+ download_files, download_total = int(md.group(1)), int(md.group(2))
+ download_seen = True
+ elif not download_seen and "Downloading model from HuggingFace" in ln:
+ download_seen = True
if not decode_started and "step:decode_and_save start" in ln:
decode_started = True
if not decode_done and "step:decode_and_save done" in ln:
@@ -12733,6 +12779,10 @@ def _parse_progress_signals(log_lines: list[str]) -> dict:
"generate_done": generate_done,
"upscale_done": upscale_done,
"pipe_loaded": pipe_loaded,
+ "download_seen": download_seen,
+ "download_files": download_files,
+ "download_total": download_total,
+ "download_gb": download_gb,
}
@@ -12810,6 +12860,7 @@ def _compute_progress(current: dict | None, log_lines: list[str]) -> dict | None
eta = _bucket_eta(p)
signals = _parse_progress_signals(log_lines[-200:] if log_lines else [])
weights = _phase_weights(p)
+ download_frac = 0.0
# Phase pick — newest-first markers win. Order: post > decode > denoise > setup.
if signals["upscale_done"]:
@@ -12839,6 +12890,23 @@ def _compute_progress(current: dict | None, log_lines: list[str]) -> dict | None
if param_total > dt:
dt = param_total
phase_label = f"Denoising · step {ds} / {dt}"
+ elif signals["download_seen"] and not signals["pipe_loaded"]:
+ # Cold first-run model download — show it (with a moving bar) instead
+ # of sitting on "Loading pipeline" for ~10 min, which reads as a hang.
+ phase = "download"
+ df, dft, dgb = signals["download_files"], signals["download_total"], signals.get("download_gb")
+ if dgb is not None:
+ # Disk-based GB — the honest signal; bar creeps on elapsed but the
+ # GB count is what tells the user it's progressing, not frozen.
+ download_frac = min(0.95, elapsed / 900.0)
+ phase_label = f"Downloading model · first run · {dgb:.1f} GB"
+ elif df is not None and dft:
+ download_frac = max(0.0, min(0.99, df / dft))
+ phase_label = f"Downloading model · first run · {df}/{dft} files"
+ else:
+ # No signal yet — creep on elapsed so the bar still moves.
+ download_frac = min(0.95, elapsed / 600.0)
+ phase_label = "Downloading model · first run · this can take several minutes…"
else:
phase = "setup"
phase_label = "Loading pipeline" if not signals["pipe_loaded"] else "Preparing"
@@ -12852,6 +12920,11 @@ def _compute_progress(current: dict | None, log_lines: list[str]) -> dict | None
setup_budget = 60.0 if not signals["pipe_loaded"] else 10.0
within = min(0.92, elapsed / setup_budget) if setup_budget else 0
pct = within * setup_w
+ elif phase == "download":
+ # Its own 0→95% bar — the cold download dominates first-run wall time
+ # and we can't predict it. When generation starts the phase flips to
+ # "Denoising"; a clear two-phase progress beats a frozen bar.
+ pct = download_frac * 95
elif phase == "denoise":
ds = signals["denoise_step"] or 0
dt = signals["denoise_total"] or 1
@@ -12901,7 +12974,7 @@ def _compute_progress(current: dict | None, log_lines: list[str]) -> dict | None
else:
tail = 30.0
remaining = denoise_left + tail
- elif eta:
+ elif eta and phase != "download":
remaining = max(0.0, eta - elapsed)
return {
@@ -20181,8 +20254,8 @@ HTML = r"""<!doctype html>
<div class="composer-card">
<div class="composer-refs">
<div class="show">
- <h2>Reference images
- <span class="h2-hint">2-3 subjects: Qwen Edit (reliable) · HiDream Dev (fragile)</span>
+ <h2>Reference image(s) &mdash; for image-to-image (Reference Edit)
+ <span class="h2-hint">Drop a photo to edit/transform it · 2-3 subjects: Qwen Edit (reliable) · HiDream Dev (fragile)</span>
</h2>
<div class="studio-ref-grid" id="imgStudioRefs">
<div class="studio-ref-slot" data-slot="0">
@@ -20390,6 +20463,17 @@ HTML = r"""<!doctype html>
<span><strong style="color:var(--text)">⚡ Fast mode</strong> &mdash; 4-bit, for M1/M2 or low-RAM Macs <em>(slightly lower quality)</em></span>
</label>
+ <!-- Reference bridge: Ideogram is text-only and can't copy pixels.
+ When a reference image IS loaded, this opt-in vision-captions it
+ and folds the description into the prompt so Ideogram REDRAWS the
+ idea (a re-interpretation, not a pixel copy). Sends
+ ideo_reference_bridge=1. Hidden until a ref is present — see
+ ideoSyncRefBridge(). -->
+ <label class="ideo-refbridge" id="ideoRefBridgeRow" title="Ideogram is text-only — it cannot copy your reference pixel-for-pixel. With this on, the reference is described and that description is added to your prompt, so Ideogram redraws the idea in its own style. For a faithful copy, use a Reference Edit engine instead." style="display:none;align-items:center;gap:8px;margin-top:10px;padding:8px 11px;border:1px solid var(--border);border-radius:var(--r-sm);background:var(--panel-2);font-size:12.5px;color:var(--muted,#9aa6bd);cursor:pointer">
+ <input type="checkbox" id="ideoRefBridge" onchange="ideoState.refBridge=this.checked;if(typeof imgStudioUpdateValidity==='function')imgStudioUpdateValidity();if(typeof imgStudioUpdateRefWarning==='function')imgStudioUpdateRefWarning()" style="accent-color:var(--accent);cursor:pointer;flex:0 0 auto;width:16px;height:16px;margin:0">
+ <span><strong style="color:var(--text)">Use reference</strong> &mdash; Ideogram redraws it from a description <em>(not a pixel copy)</em></span>
+ </label>
+
<!-- Image-level palette (collapsible). ≤16 colors. -->
<details class="ideo-details" id="ideoPaletteDetails">
<summary>Image palette <span class="ideo-summary-meta" id="ideoPaletteCount"></span></summary>
@@ -20438,10 +20522,10 @@ HTML = r"""<!doctype html>
<div class="studio-engine-row">
<select id="imgStudioEngine" onchange="if(typeof ideoSyncVisibility==='function')ideoSyncVisibility();imgStudioUpdateValidity();imgStudioRefreshEngineStatus();imgStudioUpdateEstimate();imgStudioUpdateRefWarning();if(typeof renderLorasList==='function')renderLorasList()">
<option value="auto">Auto (use Settings)</option>
- <option value="qwen_edit_lightning_inline" selected>Fast &mdash; Lightning 4-step (~1:20, default, multi-ref)</option>
- <option value="qwen_edit_inline">Standard &mdash; 8-step Q6 (~2:05, no LoRA)</option>
- <option value="qwen_edit_high_inline">Quality &mdash; 40-step Q8 + CFG (~3:50, final renders)</option>
- <option value="ideogram4_inline">Ideogram 4 &mdash; typography &amp; layout (text-in-image)</option>
+ <option value="qwen_edit_lightning_inline" selected>Reference Edit &mdash; Fast (image-to-image, Lightning 4-step, ~1:20, default, multi-ref)</option>
+ <option value="qwen_edit_inline">Reference Edit &mdash; Standard (image-to-image, 8-step Q6, ~2:05, no LoRA)</option>
+ <option value="qwen_edit_high_inline">Reference Edit &mdash; Quality (image-to-image, 40-step Q8 + CFG, ~3:50, final renders)</option>
+ <option value="ideogram4_inline">Ideogram 4 &mdash; typography &amp; layout (text-in-image; optional reference bridge)</option>
<!-- HiDream-O1 hidden 2026-05-28 (issue #15): the engine expects a
standalone lab-repo clone at ~/HIDREAM-O1-MLX-LAB-active/.venv
which hasn't been made public yet, so selecting any of these
@@ -22573,6 +22657,18 @@ function imgStudioUpdateValidity() {
} else if (needsRefs && refsCount === 0) {
invalidReason = 'Pick at least 1 reference image (drop a file into one of the 3 slots above) — Qwen-Image-Edit composes against an image, it cannot run text-only. Use the Lightning preset only after picking a ref.';
}
+ // Non-blocking notice (does NOT disable Generate): Ideogram is text-only,
+ // so a loaded reference is silently dropped unless the reference bridge is
+ // on. Surface that trap with a way out (turn on the bridge, or switch to a
+ // Reference Edit engine for a faithful pixel copy). Closes the silent-drop
+ // trap flagged in the spec.
+ let softNotice = '';
+ if (!invalidReason
+ && eng.value === 'ideogram4_inline'
+ && refsCount >= 1
+ && !(typeof ideoState === 'object' && ideoState.refBridge)) {
+ softNotice = 'Heads up: Ideogram is text-only, so your reference image will be IGNORED. Turn on "Use reference" above to have Ideogram redraw it from a description, or switch to a Reference Edit engine for a faithful copy.';
+ }
// Don't override the busy state — imgStudioGenerate manages disabled
// during in-flight gens.
if (!IMG_STUDIO.busy) {
@@ -22581,6 +22677,8 @@ function imgStudioUpdateValidity() {
if (status && !status.textContent.startsWith('Generating')) {
if (invalidReason) {
status.innerHTML = '<svg class="ph" aria-hidden="true" style="margin-right:4px;vertical-align:-2px"><use href="#ph-warning-fill"/></svg>' + escapeHtml(invalidReason);
+ } else if (softNotice) {
+ status.innerHTML = '<svg class="ph" aria-hidden="true" style="margin-right:4px;vertical-align:-2px"><use href="#ph-warning-fill"/></svg>' + escapeHtml(softNotice);
} else {
status.textContent = '';
}
@@ -22696,6 +22794,9 @@ function imgStudioRenderSlot(idx) {
}
imgStudioUpdateValidity();
imgStudioUpdateRefWarning();
+ // The Ideogram reference-bridge checkbox only appears once a ref exists —
+ // re-evaluate its visibility whenever a slot fills or clears.
+ if (typeof ideoSyncRefBridge === 'function') ideoSyncRefBridge();
// Recent strip's "in-use" highlight depends on which paths are bound to
// slots — re-render the strip so freshly-cleared slots release their
// selection ring.
@@ -23018,6 +23119,7 @@ const ideoState = {
_editing: false, // a text input is focused (don't steal keys)
_editId: null, // box currently being edited inline on the canvas
fast: false, // Fast mode → 4-bit quantize (slower-GPU / low-RAM)
+ refBridge: false, // Reference bridge → caption a loaded ref into the prompt (ideogram only)
_seq: 1,
};
@@ -23138,8 +23240,13 @@ function ideoApplyComposerChrome(){
const prompt = document.getElementById('imgStudioPrompt');
const layout = ideoInLayout();
const active = ideoIsActive();
- // Refs: hidden whenever Ideogram is the engine (it never takes refs).
- if (refsWrap) refsWrap.style.display = active ? 'none' : '';
+ // Refs stay visible for Ideogram so the user can drop one for the
+ // reference bridge (vision-caption → prompt). Ideogram still can't copy
+ // pixels — the bridge checkbox + ref-warning explain that. (Previously
+ // the refs were force-hidden whenever Ideogram was active.)
+ if (refsWrap) refsWrap.style.display = '';
+ // Show/hide the bridge checkbox based on engine + whether a ref is loaded.
+ if (typeof ideoSyncRefBridge === 'function') ideoSyncRefBridge();
if (promptLabel){
if (layout){
promptLabel.hidden = false;
@@ -23159,6 +23266,24 @@ function ideoApplyComposerChrome(){
}
}
+// Show the Ideogram reference-bridge checkbox only when Ideogram is the
+// engine AND at least one reference image is loaded. Keep the checkbox and
+// ideoState.refBridge in sync. Called from ideoApplyComposerChrome (engine
+// change) and imgStudioRenderSlot (refs added/removed).
+function ideoSyncRefBridge(){
+ const row = document.getElementById('ideoRefBridgeRow');
+ const cb = document.getElementById('ideoRefBridge');
+ if (!row) return;
+ const active = (typeof ideoIsActive === 'function') && ideoIsActive();
+ const refsCount = ((typeof IMG_STUDIO === 'object' && IMG_STUDIO.refs) || []).filter(r => r && r.path).length;
+ // Bridge is simple-mode only: in Layout the prompt is a serialized JSON
+ // caption, and the backend skips the bridge to avoid corrupting it.
+ const show = active && refsCount >= 1
+ && !((typeof ideoInLayout === 'function') && ideoInLayout());
+ row.style.display = show ? 'flex' : 'none';
+ if (cb) cb.checked = !!ideoState.refBridge;
+}
+
function ideoSetMode(mode){
ideoState.mode = (mode === 'layout') ? 'layout' : 'simple';
document.querySelectorAll('#ideoPanel [data-ideo-mode]').forEach(b => {
@@ -24174,6 +24299,11 @@ async function imgStudioGenerate() {
// Fast mode → 4-bit quantize (Ideogram only). Null otherwise so the
// server applies its M1-safe q6 default.
ideo_quantize: (engineVal === 'ideogram4_inline' && typeof ideoState === 'object' && ideoState.fast) ? 4 : null,
+ // Reference bridge → caption a loaded ref into the Ideogram prompt. Only
+ // meaningful for ideogram4_inline AND when at least one ref is present.
+ ideo_reference_bridge: (engineVal === 'ideogram4_inline'
+ && typeof ideoState === 'object' && ideoState.refBridge
+ && IMG_STUDIO.refs.filter(r => r && r.path).length >= 1) ? 1 : null,
refs,
};
// Submit through the same /queue/add endpoint video jobs use, with
@@ -24198,6 +24328,9 @@ async function imgStudioGenerate() {
// _build_image_engine_config reads it into ImageEngineConfig.mflux_preset.
if (body.ideo_preset) fd.set('ideo_preset', body.ideo_preset);
if (body.ideo_quantize) fd.set('ideo_quantize', String(body.ideo_quantize));
+ // Reference bridge flag — _build_image_engine_config reads it into
+ // ImageEngineConfig.ideogram_reference_bridge (ideogram branch).
+ if (body.ideo_reference_bridge) fd.set('ideo_reference_bridge', '1');
fd.set('aspect', body.aspect || '16:9');
fd.set('n', String(body.n || 1));
fd.set('seed', String(body.seed != null ? body.seed : -1));