Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor(scripts): extract _runner_common.py — dedupe flux2/z-image shared helpers (#219)

[._.]/ Adam Eivy25563e9ddad3
diff --git a/DONE.md b/DONE.md
index 5c0c6a2a19..08137c81ce 100644
--- a/DONE.md
+++ b/DONE.md
@@ -4,6 +4,10 @@ Archive of completed work. For active roadmap, see [PLAN.md](./PLAN.md). For pro
---
+## 2026-05-12
+
+- **Extract `scripts/_runner_common.py`** — Pulled the byte-for-byte-duplicated `pick_device` / `make_generator` / `apply_memory_optimizations` / `write_sidecar` / `make_stepwise_callback` / `_emit_user_error` / `_repo_from_hf_error` / HF cause-chain walker (~200 LOC) out of `scripts/flux2_macos.py` + `scripts/z_image_turbo.py` into a shared module. `make_stepwise_callback` now takes an optional `unpack_latents` callable so the flux2 packed-transformer-latent path stays runner-specific while the rest of the decode is shared. `install_hf_error_handler` is a `@decorator` over `main()` that owns the gated/notfound/401 dispatch — `if __name__ == "__main__": main()` collapses to one line in both runners. Mirrors the `lora_utils.py` extraction pattern. Server tests 4012/4012 green; both runners' `--help` resolves cleanly.
+
## 2026-05-10
- **Pipeline — Story Arc Planning (Phases 1–4 shipped)** — Four-phase rebuild of the PipelineSeries page from a flat issue list into a structural Arc → Season → Episode tree.
diff --git a/PLAN.md b/PLAN.md
index 8cfe56e5c5..2f72701551 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -58,7 +58,6 @@ These were flagged by the post-merge code review pass on the Z-Image + Civitai L
- [ ] **Detect `_shippedDefaults` ↔ `image[]` drift in mediaModels.js.** A real-install case (2026-05-09) hit a state where `_shippedDefaults.image.list` recorded all default ids but the user's `image[]` array was missing several of them — possibly from a partial editor save or a write race. The deletion-survives-upgrade contract then permanently skipped re-adding those built-ins on every restart. Add a boot-time check in `loadMediaModels()`: for any id present in `_shippedDefaults.image.list` AND `DEFAULT_REGISTRY.image` but missing from the user's `image[]`, log a clear warning (`⚠️ media-models drift: built-in <id> was shipped but is missing from image[] — restore it manually or delete _shippedDefaults.image to re-bootstrap`). Don't auto-recover (would defeat real deletions), just make the drift loud. Same pattern applies to video.
-- [ ] **Extract `scripts/_runner_common.py`** — `scripts/flux2_macos.py` and `scripts/z_image_turbo.py` still duplicate `pick_device`, `make_generator`, `apply_memory_optimizations`, `write_sidecar`, `make_stepwise_callback` (~95% identical, only the latents-unpack branch differs), `_emit_user_error`, and the entire bottom-of-file HF cause-chain walker (`_repo_from_hf_error` + the gated/notfound/401 dispatch in `__main__`). Roughly 200 lines of byte-for-byte duplication. Extract into a shared module with `make_stepwise_callback(pipe, h, w, dir, *, unpack_latents=None)` and `install_hf_error_handler()` (decorator/context manager wrapping `main`). The `apply_loras` extraction already shipped via `scripts/lora_utils.py`; this is the same pattern, larger blast radius.
- [ ] **`RUNNER_FAMILIES` constants module** — runner ids `'mflux' | 'flux2' | 'z-image'` are bare strings in `server/lib/civitai.js`, `server/lib/mediaModels.js`, `client/src/pages/ImageGen.jsx`, and the `RUNNER_LABEL` / `RUNNER_BADGE_CLASS` maps in `client/src/pages/Loras.jsx`. Export `RUNNER_FAMILIES = { MFLUX, FLUX2, Z_IMAGE }` from `server/lib/runners.js` (mirror to a small client constant) so a typo can't silently break the LoRA picker's compat filter. `isFlux2()` / `isZImage()` already wrap the server-side comparisons; this is mostly client + civitai.js cleanup.
- [ ] **Two `listLoras` exports collision** — `server/services/imageGen/local.js#listLoras` returns minimal `{ filename, name }` (powers `/api/image-gen/loras`); `server/services/loras.js#listLoras` returns the rich Civitai-aware shape (powers `/api/loras`). Same name, two modules, two shapes — a future caller importing the wrong one gets `undefined` for `civitai` / `runnerFamily`. Rename the legacy one to `listLoraFilenames` (or have it project from the new list) to make the distinction explicit.
- [ ] **Generic `deepMerge` utility** — three call sites now do hand-rolled deep-merge: `server/services/voice/config.js`, `server/services/meatspacePost.js`, and the new `server/routes/loras.js#POST /auth/civitai`. Promote the cleanest impl (voice/config.js) into `server/lib/objects.js` and consolidate. Then loras.js, voice config, and meatspacePost all consume one helper — and `updateSettings()`-via-shallow-merge stops being a footgun for any future settings sub-object.
diff --git a/scripts/_runner_common.py b/scripts/_runner_common.py
new file mode 100644
index 0000000000..3c794a6c6d
--- /dev/null
+++ b/scripts/_runner_common.py
@@ -0,0 +1,310 @@
+"""
+Shared helpers for the PortOS local image-gen Python runners
+(`flux2_macos.py` and `z_image_turbo.py`).
+
+Both runners present the same CLI surface to `server/services/imageGen/local.js`
+— STAGE: markers, USER_ERROR: lines, stepwise PNG previews, sidecar JSON — and
+the bits that own that contract live here. Keeping these in one module means a
+fix to the HF error mapping or the stepwise decode lands in both runners at
+once, instead of drifting.
+
+The runner-specific bits each script still owns:
+ - argparse + which pipeline class / weight repo to load
+ - `load_pipeline_*` (sdnq / int8 / auto-pipeline / ERNIE)
+ - the txt2img-vs-i2i pipe swap (`to_i2i_pipeline` in z-image)
+
+Anything generic — device picking, RNG seeding, memory-saving knobs, sidecar
+writes, stepwise preview decode, USER_ERROR markers, and the cause-chain
+walker that turns a buried `GatedRepoError` into a friendly link — belongs here.
+"""
+
+import json
+import sys
+import threading
+from contextlib import contextmanager
+from functools import wraps
+from pathlib import Path
+
+import torch
+from PIL import Image
+
+
+@contextmanager
+def heartbeat(stage: str, interval: float = 20.0):
+ """Emit a periodic STAGE:<stage>:heartbeat:Ns marker so the JS idle
+ watchdog (default 5min) doesn't kill silent long pipeline loads.
+
+ Diffusers' from_pretrained on a fully-cached 10-25 GB model is silent
+ for several minutes (mmap + weight assignment, no tqdm), which trips
+ the JS-side idle watchdog. `handleLine()` in imageGen/local.js sees
+ the heartbeat line and resets lastActivityAt. True hangs (GIL-pinned
+ C extension, no I/O) still trip the watchdog because the heartbeat
+ thread can't print either.
+ """
+ stop = threading.Event()
+
+ def beat():
+ elapsed = 0
+ while not stop.wait(interval):
+ elapsed += int(interval)
+ print(f"STAGE:{stage}:heartbeat:{elapsed}s", file=sys.stderr, flush=True)
+
+ t = threading.Thread(target=beat, daemon=True)
+ t.start()
+ try:
+ yield
+ finally:
+ stop.set()
+ t.join(timeout=interval + 1)
+
+
+def pick_device(requested: str) -> str:
+ """Resolve `auto`/`mps`/`cuda`/`cpu` against what torch actually has.
+ Falls back to CPU with a warning when the requested accelerator isn't
+ available — never silently downgrades without telling the user."""
+ if requested == "auto":
+ if torch.backends.mps.is_available():
+ return "mps"
+ if torch.cuda.is_available():
+ return "cuda"
+ return "cpu"
+ if requested == "mps" and not torch.backends.mps.is_available():
+ print("⚠️ MPS requested but unavailable — falling back to CPU", file=sys.stderr)
+ return "cpu"
+ if requested == "cuda" and not torch.cuda.is_available():
+ print("⚠️ CUDA requested but unavailable — falling back to CPU", file=sys.stderr)
+ return "cpu"
+ return requested
+
+
+def make_generator(device: str, seed: int) -> torch.Generator:
+ """Seed a torch Generator on the right device. Accelerator generators
+ must be initialised with the device string; the CPU fallback uses the
+ no-arg form."""
+ if device in ("cuda", "mps"):
+ return torch.Generator(device).manual_seed(int(seed))
+ return torch.Generator().manual_seed(int(seed))
+
+
+def apply_memory_optimizations(pipe) -> None:
+ """Enable every memory-saving knob diffusers exposes on the loaded
+ pipeline. Best-effort: each call is gated on hasattr so older / smaller
+ pipelines that don't ship a given slice / tile path still work."""
+ if hasattr(pipe, "enable_attention_slicing"):
+ pipe.enable_attention_slicing()
+ if hasattr(pipe, "enable_vae_slicing"):
+ pipe.enable_vae_slicing()
+ vae = getattr(pipe, "vae", None)
+ if hasattr(pipe, "enable_vae_tiling"):
+ pipe.enable_vae_tiling()
+ elif vae is not None and hasattr(vae, "enable_tiling"):
+ vae.enable_tiling()
+
+
+def write_sidecar(output: str, payload: dict) -> None:
+ """Write `<output>.metadata.json` next to the generated image. The
+ server's gallery scanner picks this up to surface prompt/seed/model
+ in the lightbox without re-parsing the PNG."""
+ sidecar = Path(output).with_suffix(".metadata.json")
+ sidecar.write_text(json.dumps(payload, indent=2))
+
+
+def make_stepwise_callback(
+ stepwise_dir: str,
+ pipe,
+ height: int,
+ width: int,
+ *,
+ unpack_latents=None,
+):
+ """Return a `callback_on_step_end` that decodes the running latent into
+ a small preview PNG. `local.js#processLatestFrame` watches this dir and
+ streams the freshest frame to the SSE client.
+
+ The only per-runner difference is how packed latents are projected back
+ to `(B, C, H_lat, W_lat)` before the VAE decode:
+
+ - mflux / z-image: latents already arrive in `(B, C, H_lat, W_lat)`
+ layout. Pass `unpack_latents=None`; the callback simply skips the
+ step when latents are not 4-D (rather than guessing the shape).
+ - flux2: transformer-packed latents come back as
+ `(B, num_patches, C*p*p)`. Pass a callable that takes
+ `(latents, height, width)` and returns the unpacked tensor.
+ """
+ if not stepwise_dir:
+ return None
+ out = Path(stepwise_dir)
+ out.mkdir(parents=True, exist_ok=True)
+ vae = pipe.vae
+ scaling = getattr(vae.config, "scaling_factor", 1.0) or 1.0
+ shift = getattr(vae.config, "shift_factor", 0.0) or 0.0
+ # Capture the VAE's weight dtype + device so the callback can align the
+ # scaled latents before decode. Some pipelines (ERNIE, Flux2) keep latents
+ # in float32 even when the pipeline was loaded with torch_dtype=bfloat16,
+ # so `vae.decode(latents / scaling + shift)` would feed float32 into a
+ # bfloat16 VAE and error with "Input type (float) and bias type
+ # (c10::BFloat16) should be the same".
+ try:
+ vae_param = next(vae.parameters())
+ vae_dtype, vae_device = vae_param.dtype, vae_param.device
+ except StopIteration:
+ vae_dtype, vae_device = None, None
+
+ fired = {"count": 0, "saved": 0}
+
+ @torch.no_grad()
+ def cb(pipe, step_index, _timestep, callback_kwargs):
+ fired["count"] += 1
+ latents = callback_kwargs.get("latents")
+ if latents is None:
+ if step_index == 0:
+ print("⚠️ stepwise: latents missing from callback_kwargs", file=sys.stderr)
+ return callback_kwargs
+ if step_index == 0:
+ print(f"🖼️ stepwise: callback live, latents.shape={tuple(latents.shape)}", file=sys.stderr)
+ # Best-effort decode. Errors here must not abort generation — the
+ # final image is still produced after the last step.
+ try:
+ if latents.dim() == 3:
+ if unpack_latents is None:
+ # No unpack helper provided; skip preview rather than
+ # guess the shape. The final image still saves.
+ return callback_kwargs
+ latents = unpack_latents(latents, height, width)
+ elif latents.dim() != 4:
+ return callback_kwargs
+ scaled = latents / scaling + shift
+ if vae_dtype is not None and (scaled.dtype != vae_dtype or scaled.device != vae_device):
+ scaled = scaled.to(device=vae_device, dtype=vae_dtype)
+ decoded = vae.decode(scaled, return_dict=False)[0]
+ decoded = (decoded.clamp(-1, 1) + 1) / 2
+ arr = (decoded[0].float().cpu().permute(1, 2, 0).numpy() * 255).astype("uint8")
+ img = Image.fromarray(arr)
+ img.thumbnail((512, 512), Image.LANCZOS)
+ img.save(out / f"step_{step_index + 1}.png", "PNG", optimize=False)
+ fired["saved"] += 1
+ except Exception as err:
+ print(f"⚠️ stepwise preview failed at step {step_index}: {type(err).__name__}: {err}", file=sys.stderr)
+ return callback_kwargs
+
+ cb._stats = fired
+ return cb
+
+
+def _emit_user_error(kind: str, message: str, repo: str = "") -> None:
+ """Emit a structured single-line error the server's stderr parser picks up
+ for the SSE error event. `kind` is a stable identifier the UI maps to a
+ friendly heading; `message` is the human prose; `repo` (optional) is the
+ HF repo to deep-link the user to so they can request access / check token."""
+ line = f"USER_ERROR:{kind}"
+ if repo:
+ line += f":{repo}"
+ print(line, file=sys.stderr, flush=True)
+ print(f"❌ {message}", file=sys.stderr, flush=True)
+
+
+def _repo_from_hf_error(hf_err) -> str:
+ """huggingface_hub doesn't always populate `repo_id` on the error.
+ Fall back to parsing the failing URL — `/<owner>/<repo>/resolve/...`
+ for file downloads or `/api/models/<owner>/<repo>` for API hits."""
+ repo = getattr(hf_err, "repo_id", None) or ""
+ if repo:
+ return repo
+ url = (
+ getattr(getattr(hf_err, "response", None), "url", None)
+ or getattr(getattr(hf_err, "request", None), "url", None)
+ )
+ if url is None:
+ return ""
+ path = str(url).split("huggingface.co", 1)[-1].lstrip("/")
+ parts = path.split("/")
+ if parts[:1] == ["api"] and len(parts) >= 4 and parts[1] in {"models", "datasets", "spaces"}:
+ return f"{parts[2]}/{parts[3]}"
+ if len(parts) >= 2 and parts[0] not in {"api", "settings", "join"}:
+ return f"{parts[0]}/{parts[1]}"
+ return ""
+
+
+def install_hf_error_handler(main_fn):
+ """Decorator that wraps a runner's `main()` in the canonical HuggingFace
+ error-to-USER_ERROR-line translation.
+
+ Walks the exception cause chain so a buried `GatedRepoError` /
+ `RepositoryNotFoundError` / 401 `HfHubHTTPError` produces a friendly
+ `USER_ERROR:<kind>:<repo>` line + `❌ <message>` on stderr — even when
+ diffusers wraps the underlying HF error in OSError. Unknown failures
+ emit a generic `USER_ERROR:unknown` marker and re-raise so the original
+ traceback still surfaces.
+
+ Usage:
+
+ @install_hf_error_handler
+ def main():
+ ...
+
+ if __name__ == "__main__":
+ main()
+ """
+
+ @wraps(main_fn)
+ def wrapped(*args, **kwargs):
+ try:
+ return main_fn(*args, **kwargs)
+ except KeyboardInterrupt:
+ sys.exit(130)
+ except SystemExit:
+ raise
+ except Exception as err:
+ # Lazy-import so the module loads on systems without
+ # huggingface_hub installed (e.g. test environments).
+ from huggingface_hub.errors import (
+ GatedRepoError,
+ HfHubHTTPError,
+ RepositoryNotFoundError,
+ )
+ # Walk the cause chain — diffusers wraps HF errors in OSError, so
+ # the innermost exception is what tells us the real story.
+ chain = []
+ cur = err
+ while cur is not None:
+ chain.append(cur)
+ cur = cur.__cause__ or cur.__context__
+ gated = next((e for e in chain if isinstance(e, GatedRepoError)), None)
+ notfound = next(
+ (e for e in chain if isinstance(e, RepositoryNotFoundError)), None
+ )
+ http = next((e for e in chain if isinstance(e, HfHubHTTPError)), None)
+ if gated is not None:
+ repo = _repo_from_hf_error(gated)
+ url = f"https://huggingface.co/{repo}" if repo else "https://huggingface.co/"
+ _emit_user_error(
+ "gated_repo",
+ f"Access to {repo or 'the model repo'} is restricted. Visit {url} "
+ f"to request access, then make sure your HF token is set in PortOS.",
+ repo,
+ )
+ sys.exit(2)
+ status = (
+ getattr(getattr(http, "response", None), "status_code", None)
+ if http
+ else None
+ )
+ if status == 401:
+ _emit_user_error(
+ "hf_unauthorized",
+ "HuggingFace rejected the token (401). Check that the token is valid "
+ "and has read access, then re-paste it in PortOS.",
+ )
+ sys.exit(2)
+ if notfound is not None:
+ repo = _repo_from_hf_error(notfound)
+ _emit_user_error(
+ "repo_not_found", f"HF repo not found: {repo or '(unknown)'}", repo
+ )
+ sys.exit(2)
+ # Unknown failure — emit the original traceback (raised below) plus
+ # a generic structured marker so the UI shows something useful.
+ _emit_user_error("unknown", f"{type(err).__name__}: {err}")
+ raise
+
+ return wrapped
diff --git a/scripts/flux2_macos.py b/scripts/flux2_macos.py
index 40a04b24e6..264e4d2c3a 100755
--- a/scripts/flux2_macos.py
+++ b/scripts/flux2_macos.py
@@ -25,8 +25,6 @@ import inspect
import json
import os
import sys
-import threading
-from contextlib import contextmanager
from pathlib import Path
# Must precede `import torch` — enables the fast-math kernel path on MPS,
@@ -37,56 +35,18 @@ import torch
from PIL import Image
sys.path.insert(0, str(Path(__file__).resolve().parent))
+from _runner_common import ( # noqa: E402
+ apply_memory_optimizations,
+ heartbeat,
+ install_hf_error_handler,
+ make_generator,
+ make_stepwise_callback,
+ pick_device,
+ write_sidecar,
+)
from lora_utils import apply_loras # noqa: E402
-@contextmanager
-def heartbeat(stage: str, interval: float = 20.0):
- # Diffusers' from_pretrained on a fully-cached 10-25 GB model is silent
- # for several minutes (mmap + weight assignment, no tqdm), which trips the
- # JS-side idle watchdog (default 5min). Emit a non-noise stderr line every
- # `interval` seconds so handleLine() in imageGen/local.js sees activity
- # and resets lastActivityAt. True hangs (GIL-pinned C extension, no I/O)
- # still trip the watchdog because the heartbeat thread can't print either.
- stop = threading.Event()
-
- def beat():
- elapsed = 0
- while not stop.wait(interval):
- elapsed += int(interval)
- print(f"STAGE:{stage}:heartbeat:{elapsed}s", file=sys.stderr, flush=True)
-
- t = threading.Thread(target=beat, daemon=True)
- t.start()
- try:
- yield
- finally:
- stop.set()
- t.join(timeout=interval + 1)
-
-
-def pick_device(requested: str) -> str:
- if requested == "auto":
- if torch.backends.mps.is_available():
- return "mps"
- if torch.cuda.is_available():
- return "cuda"
- return "cpu"
- if requested == "mps" and not torch.backends.mps.is_available():
- print("⚠️ MPS requested but unavailable — falling back to CPU", file=sys.stderr)
- return "cpu"
- if requested == "cuda" and not torch.cuda.is_available():
- print("⚠️ CUDA requested but unavailable — falling back to CPU", file=sys.stderr)
- return "cpu"
- return requested
-
-
-def make_generator(device: str, seed: int) -> torch.Generator:
- if device in ("cuda", "mps"):
- return torch.Generator(device).manual_seed(int(seed))
- return torch.Generator().manual_seed(int(seed))
-
-
def probe_hf_auth(repo: str) -> None:
"""Fail early with a clear message when HF_TOKEN is missing or the
license hasn't been accepted. Without this probe, the user sees a vague
@@ -207,18 +167,6 @@ def load_pipeline_int8(repo: str, base_repo: str, device: str, dtype):
return pipe
-def apply_memory_optimizations(pipe) -> None:
- if hasattr(pipe, "enable_attention_slicing"):
- pipe.enable_attention_slicing()
- if hasattr(pipe, "enable_vae_slicing"):
- pipe.enable_vae_slicing()
- vae = getattr(pipe, "vae", None)
- if hasattr(pipe, "enable_vae_tiling"):
- pipe.enable_vae_tiling()
- elif vae is not None and hasattr(vae, "enable_tiling"):
- vae.enable_tiling()
-
-
def _unpack_flux2_latents(latents, height: int, width: int, vae_scale: int = 8, patch: int = 2):
"""Convert Flux2 transformer-packed latents `(B, num_patches, C*P*P)` back
to the VAE-friendly `(B, C, H_lat, W_lat)` layout.
@@ -242,74 +190,6 @@ def _unpack_flux2_latents(latents, height: int, width: int, vae_scale: int = 8,
return latents.reshape(bsz, c, h * patch, w * patch)
-def make_stepwise_callback(stepwise_dir: str, pipe, height: int, width: int):
- """Return a `callback_on_step_end` that decodes the running latent into a
- small preview PNG. local.js's `processLatestFrame` watches this dir and
- streams the freshest frame to the SSE client."""
-
- if not stepwise_dir:
- return None
- out = Path(stepwise_dir)
- out.mkdir(parents=True, exist_ok=True)
- vae = pipe.vae
- scaling = getattr(vae.config, "scaling_factor", None)
- if scaling is None:
- scaling = 1.0
- shift = getattr(vae.config, "shift_factor", None)
- if shift is None:
- shift = 0.0
- # Capture VAE weight dtype + device so the callback can align the scaled
- # latents before decode — pipelines sometimes keep latents in float32
- # while the VAE is bfloat16 (which errors with "Input type (float) and
- # bias type (c10::BFloat16) should be the same").
- try:
- vae_param = next(vae.parameters())
- vae_dtype, vae_device = vae_param.dtype, vae_param.device
- except StopIteration:
- vae_dtype, vae_device = None, None
-
- fired = {"count": 0, "saved": 0}
-
- @torch.no_grad()
- def cb(pipe, step_index, _timestep, callback_kwargs):
- fired["count"] += 1
- latents = callback_kwargs.get("latents")
- if latents is None:
- if step_index == 0:
- print("⚠️ stepwise: latents missing from callback_kwargs", file=sys.stderr)
- return callback_kwargs
- if step_index == 0:
- print(f"🖼️ stepwise: callback live, latents.shape={tuple(latents.shape)}", file=sys.stderr)
- # Best-effort decode. Errors here must not abort generation — the
- # final image is still produced after the last step.
- try:
- # Flux2 latents arrive packed (B, num_patches, C*p*p). VAE expects
- # (B, C, H, W). Skip unpack if it's already 4-D (future-proof).
- if latents.dim() == 3:
- latents = _unpack_flux2_latents(latents, height, width)
- scaled = latents / scaling + shift
- if vae_dtype is not None and (scaled.dtype != vae_dtype or scaled.device != vae_device):
- scaled = scaled.to(device=vae_device, dtype=vae_dtype)
- decoded = vae.decode(scaled, return_dict=False)[0]
- decoded = (decoded.clamp(-1, 1) + 1) / 2
- arr = (decoded[0].float().cpu().permute(1, 2, 0).numpy() * 255).astype("uint8")
- img = Image.fromarray(arr)
- img.thumbnail((512, 512), Image.LANCZOS)
- img.save(out / f"step_{step_index + 1}.png", "PNG", optimize=False)
- fired["saved"] += 1
- except Exception as err:
- print(f"⚠️ stepwise preview failed at step {step_index}: {type(err).__name__}: {err}", file=sys.stderr)
- return callback_kwargs
-
- cb._stats = fired
- return cb
-
-
-def write_sidecar(output: str, payload: dict) -> None:
- sidecar = Path(output).with_suffix(".metadata.json")
- sidecar.write_text(json.dumps(payload, indent=2))
-
-
def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(description="PortOS FLUX.2-klein runner")
p.add_argument("--model", required=True, help="model id (e.g. flux2-klein-4b)")
@@ -335,6 +215,7 @@ def parse_args() -> argparse.Namespace:
return p.parse_args()
+@install_hf_error_handler
def main() -> None:
args = parse_args()
@@ -369,7 +250,13 @@ def main() -> None:
(int(args.width), int(args.height)), Image.LANCZOS
)
- callback = make_stepwise_callback(args.stepwise_image_output_dir, pipe, int(args.height), int(args.width))
+ callback = make_stepwise_callback(
+ args.stepwise_image_output_dir,
+ pipe,
+ int(args.height),
+ int(args.width),
+ unpack_latents=_unpack_flux2_latents,
+ )
# Flux2KleinPipeline.__call__ doesn't always accept negative_prompt or
# strength — passing an unsupported kwarg raises TypeError. Filter to
# what the live signature actually accepts.
@@ -449,84 +336,5 @@ def main() -> None:
print(f"✅ flux2 saved {args.output} (seed={seed})", file=sys.stderr)
-def _emit_user_error(kind: str, message: str, repo: str = "") -> None:
- """Emit a structured single-line error the server's stderr parser picks up
- for the SSE error event. `kind` is a stable identifier the UI maps to a
- friendly heading; `message` is the human prose; `repo` (optional) is the
- HF repo to deep-link the user to so they can request access / check token."""
- line = f"USER_ERROR:{kind}"
- if repo:
- line += f":{repo}"
- print(line, file=sys.stderr, flush=True)
- print(f"❌ {message}", file=sys.stderr, flush=True)
-
-
if __name__ == "__main__":
- try:
- main()
- except KeyboardInterrupt:
- sys.exit(130)
- except SystemExit:
- raise
- except Exception as err:
- # Top-level safety net — every error type we recognise gets a friendly
- # USER_ERROR: line so the UI can surface "request access at <link>"
- # instead of bare "Exit code 1". Anything we don't recognise still
- # falls through to a printed traceback above + a generic USER_ERROR
- # below, so the user sees *something* actionable.
- from huggingface_hub.errors import GatedRepoError, RepositoryNotFoundError, HfHubHTTPError
- # Walk the cause chain — diffusers wraps HF errors in OSError, so the
- # innermost exception is what tells us the real story.
- chain = []
- cur = err
- while cur is not None:
- chain.append(cur)
- cur = cur.__cause__ or cur.__context__
- def _repo_from_hf_error(hf_err):
- """huggingface_hub doesn't always populate `repo_id` on the error.
- Fall back to parsing the failing URL — `/<owner>/<repo>/resolve/...`
- for file downloads or `/api/models/<owner>/<repo>` for API hits."""
- repo = getattr(hf_err, "repo_id", None) or ""
- if repo:
- return repo
- url = getattr(getattr(hf_err, "response", None), "url", None) or \
- getattr(getattr(hf_err, "request", None), "url", None)
- if url is None:
- return ""
- path = str(url).split("huggingface.co", 1)[-1].lstrip("/")
- parts = path.split("/")
- if parts[:1] == ["api"] and len(parts) >= 4 and parts[1] in {"models", "datasets", "spaces"}:
- return f"{parts[2]}/{parts[3]}"
- if len(parts) >= 2 and parts[0] not in {"api", "settings", "join"}:
- return f"{parts[0]}/{parts[1]}"
- return ""
-
- gated = next((e for e in chain if isinstance(e, GatedRepoError)), None)
- notfound = next((e for e in chain if isinstance(e, RepositoryNotFoundError)), None)
- http = next((e for e in chain if isinstance(e, HfHubHTTPError)), None)
- if gated is not None:
- repo = _repo_from_hf_error(gated)
- url = f"https://huggingface.co/{repo}" if repo else "https://huggingface.co/"
- _emit_user_error(
- "gated_repo",
- f"Access to {repo or 'the model repo'} is restricted. Visit {url} "
- f"to request access, then make sure your HF token is set in PortOS.",
- repo,
- )
- sys.exit(2)
- status = getattr(getattr(http, "response", None), "status_code", None) if http else None
- if status == 401:
- _emit_user_error(
- "hf_unauthorized",
- "HuggingFace rejected the token (401). Check that the token is valid "
- "and has read access, then re-paste it in PortOS.",
- )
- sys.exit(2)
- if notfound is not None:
- repo = _repo_from_hf_error(notfound)
- _emit_user_error("repo_not_found", f"HF repo not found: {repo or '(unknown)'}", repo)
- sys.exit(2)
- # Unknown failure — emit the original traceback (already printed above)
- # plus a generic structured marker so the UI shows something useful.
- _emit_user_error("unknown", f"{type(err).__name__}: {err}")
- raise
+ main()
diff --git a/scripts/z_image_turbo.py b/scripts/z_image_turbo.py
index d895d4acb4..51cfb3891d 100644
--- a/scripts/z_image_turbo.py
+++ b/scripts/z_image_turbo.py
@@ -15,11 +15,8 @@ venv at ~/.portos/venv-flux2 (already has diffusers from git HEAD + torch).
import argparse
import inspect
-import json
import os
import sys
-import threading
-from contextlib import contextmanager
from pathlib import Path
os.environ.setdefault("PYTORCH_MPS_FAST_MATH", "1")
@@ -28,56 +25,18 @@ import torch
from PIL import Image
sys.path.insert(0, str(Path(__file__).resolve().parent))
+from _runner_common import ( # noqa: E402
+ apply_memory_optimizations,
+ heartbeat,
+ install_hf_error_handler,
+ make_generator,
+ make_stepwise_callback,
+ pick_device,
+ write_sidecar,
+)
from lora_utils import apply_loras # noqa: E402
-@contextmanager
-def heartbeat(stage: str, interval: float = 20.0):
- # Diffusers' from_pretrained on a fully-cached 10-25 GB model is silent
- # for several minutes (mmap + weight assignment, no tqdm), which trips the
- # JS-side idle watchdog (default 5min). Emit a non-noise stderr line every
- # `interval` seconds so handleLine() in imageGen/local.js sees activity
- # and resets lastActivityAt. True hangs (GIL-pinned C extension, no I/O)
- # still trip the watchdog because the heartbeat thread can't print either.
- stop = threading.Event()
-
- def beat():
- elapsed = 0
- while not stop.wait(interval):
- elapsed += int(interval)
- print(f"STAGE:{stage}:heartbeat:{elapsed}s", file=sys.stderr, flush=True)
-
- t = threading.Thread(target=beat, daemon=True)
- t.start()
- try:
- yield
- finally:
- stop.set()
- t.join(timeout=interval + 1)
-
-
-def pick_device(requested: str) -> str:
- if requested == "auto":
- if torch.backends.mps.is_available():
- return "mps"
- if torch.cuda.is_available():
- return "cuda"
- return "cpu"
- if requested == "mps" and not torch.backends.mps.is_available():
- print("⚠️ MPS requested but unavailable — falling back to CPU", file=sys.stderr)
- return "cpu"
- if requested == "cuda" and not torch.cuda.is_available():
- print("⚠️ CUDA requested but unavailable — falling back to CPU", file=sys.stderr)
- return "cpu"
- return requested
-
-
-def make_generator(device: str, seed: int) -> torch.Generator:
- if device in ("cuda", "mps"):
- return torch.Generator(device).manual_seed(int(seed))
- return torch.Generator().manual_seed(int(seed))
-
-
def load_pipeline(repo: str, device: str, dtype, pipeline_class: str = ""):
# When the registry pins a pipeline class (e.g. ErnieImagePipeline,
# which isn't yet in AutoPipelineForText2Image's registry) load it
@@ -115,86 +74,6 @@ def to_i2i_pipeline(pipe):
return AutoPipelineForImage2Image.from_pipe(pipe)
-def apply_memory_optimizations(pipe) -> None:
- if hasattr(pipe, "enable_attention_slicing"):
- pipe.enable_attention_slicing()
- if hasattr(pipe, "enable_vae_slicing"):
- pipe.enable_vae_slicing()
- vae = getattr(pipe, "vae", None)
- if hasattr(pipe, "enable_vae_tiling"):
- pipe.enable_vae_tiling()
- elif vae is not None and hasattr(vae, "enable_tiling"):
- vae.enable_tiling()
-
-
-def make_stepwise_callback(stepwise_dir: str, pipe, height: int, width: int):
- """Return a `callback_on_step_end` that decodes the running latent into a
- small preview PNG. local.js's `processLatestFrame` watches this dir and
- streams the freshest frame to the SSE client.
-
- Z-Image latents come back in the standard `(B, C, H_lat, W_lat)` layout
- (unlike FLUX.2's packed transformer latents) so the decode path is a
- plain VAE call — no unpack helper needed.
- """
- if not stepwise_dir:
- return None
- out = Path(stepwise_dir)
- out.mkdir(parents=True, exist_ok=True)
- vae = pipe.vae
- scaling = getattr(vae.config, "scaling_factor", 1.0) or 1.0
- shift = getattr(vae.config, "shift_factor", 0.0) or 0.0
- # ERNIE keeps latents in float32 even when the pipeline was loaded with
- # torch_dtype=bfloat16, so `vae.decode(latents / scaling + shift)` feeds
- # float32 into a bfloat16 VAE and errors with "Input type (float) and
- # bias type (c10::BFloat16) should be the same". Capture the VAE's actual
- # weight dtype + device once so the callback can align the scaled latents
- # before decode.
- try:
- vae_param = next(vae.parameters())
- vae_dtype, vae_device = vae_param.dtype, vae_param.device
- except StopIteration:
- vae_dtype, vae_device = None, None
-
- fired = {"count": 0, "saved": 0}
-
- @torch.no_grad()
- def cb(pipe, step_index, _timestep, callback_kwargs):
- fired["count"] += 1
- latents = callback_kwargs.get("latents")
- if latents is None:
- if step_index == 0:
- print("⚠️ stepwise: latents missing from callback_kwargs", file=sys.stderr)
- return callback_kwargs
- if step_index == 0:
- print(f"🖼️ stepwise: callback live, latents.shape={tuple(latents.shape)}", file=sys.stderr)
- try:
- if latents.dim() != 4:
- # Some pipelines return packed latents. Skip preview rather
- # than guess the unpack shape — the final image still saves.
- return callback_kwargs
- scaled = latents / scaling + shift
- if vae_dtype is not None and (scaled.dtype != vae_dtype or scaled.device != vae_device):
- scaled = scaled.to(device=vae_device, dtype=vae_dtype)
- decoded = vae.decode(scaled, return_dict=False)[0]
- decoded = (decoded.clamp(-1, 1) + 1) / 2
- arr = (decoded[0].float().cpu().permute(1, 2, 0).numpy() * 255).astype("uint8")
- img = Image.fromarray(arr)
- img.thumbnail((512, 512), Image.LANCZOS)
- img.save(out / f"step_{step_index + 1}.png", "PNG", optimize=False)
- fired["saved"] += 1
- except Exception as err:
- print(f"⚠️ stepwise preview failed at step {step_index}: {type(err).__name__}: {err}", file=sys.stderr)
- return callback_kwargs
-
- cb._stats = fired
- return cb
-
-
-def write_sidecar(output: str, payload: dict) -> None:
- sidecar = Path(output).with_suffix(".metadata.json")
- sidecar.write_text(json.dumps(payload, indent=2))
-
-
def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(description="PortOS Z-Image-Turbo runner")
p.add_argument("--model", required=True, help="model id (e.g. z-image-turbo-bf16)")
@@ -219,6 +98,7 @@ def parse_args() -> argparse.Namespace:
return p.parse_args()
+@install_hf_error_handler
def main() -> None:
args = parse_args()
@@ -328,71 +208,5 @@ def main() -> None:
print(f"✅ z-image saved {args.output} (seed={seed})", file=sys.stderr)
-def _emit_user_error(kind: str, message: str, repo: str = "") -> None:
- line = f"USER_ERROR:{kind}"
- if repo:
- line += f":{repo}"
- print(line, file=sys.stderr, flush=True)
- print(f"❌ {message}", file=sys.stderr, flush=True)
-
-
if __name__ == "__main__":
- try:
- main()
- except KeyboardInterrupt:
- sys.exit(130)
- except SystemExit:
- raise
- except Exception as err:
- # Friendly USER_ERROR markers for common HF failure modes so the UI
- # surfaces actionable text instead of raw "Exit code 1".
- from huggingface_hub.errors import GatedRepoError, RepositoryNotFoundError, HfHubHTTPError
- chain = []
- cur = err
- while cur is not None:
- chain.append(cur)
- cur = cur.__cause__ or cur.__context__
-
- def _repo_from_hf_error(hf_err):
- repo = getattr(hf_err, "repo_id", None) or ""
- if repo:
- return repo
- url = getattr(getattr(hf_err, "response", None), "url", None) or \
- getattr(getattr(hf_err, "request", None), "url", None)
- if url is None:
- return ""
- path = str(url).split("huggingface.co", 1)[-1].lstrip("/")
- parts = path.split("/")
- if parts[:1] == ["api"] and len(parts) >= 4 and parts[1] in {"models", "datasets", "spaces"}:
- return f"{parts[2]}/{parts[3]}"
- if len(parts) >= 2 and parts[0] not in {"api", "settings", "join"}:
- return f"{parts[0]}/{parts[1]}"
- return ""
-
- gated = next((e for e in chain if isinstance(e, GatedRepoError)), None)
- notfound = next((e for e in chain if isinstance(e, RepositoryNotFoundError)), None)
- http = next((e for e in chain if isinstance(e, HfHubHTTPError)), None)
- if gated is not None:
- repo = _repo_from_hf_error(gated)
- url = f"https://huggingface.co/{repo}" if repo else "https://huggingface.co/"
- _emit_user_error(
- "gated_repo",
- f"Access to {repo or 'the model repo'} is restricted. Visit {url} "
- f"to request access, then make sure your HF token is set in PortOS.",
- repo,
- )
- sys.exit(2)
- status = getattr(getattr(http, "response", None), "status_code", None) if http else None
- if status == 401:
- _emit_user_error(
- "hf_unauthorized",
- "HuggingFace rejected the token (401). Check that the token is valid "
- "and has read access, then re-paste it in PortOS.",
- )
- sys.exit(2)
- if notfound is not None:
- repo = _repo_from_hf_error(notfound)
- _emit_user_error("repo_not_found", f"HF repo not found: {repo or '(unknown)'}", repo)
- sys.exit(2)
- _emit_user_error("unknown", f"{type(err).__name__}: {err}")
- raise
+ main()