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(v4.10.5): LoRAs stack on Hailuo H3, kohya LoRAs convert, LoRA browser toolbar + Characters filter

mrbizarro033ec58764bf
diff --git a/README.md b/README.md
index cf37089..f18734b 100644
--- a/README.md
+++ b/README.md
@@ -19,7 +19,7 @@
</p>
-> **Current release: v4.10.4.** The LoRA browser searches **Hugging Face** too, the way it searches CivitAI: a name, an author (`author:someone`) or an `owner/repo`, for Hailuo H3 or LTX; each card plays the repo's own example when it has one, and Install works as before. No API key. Includes 4.10.2 (Macs with 24 GB or less stream the video model from disk) and 4.10.1 (continuity for one-takes). Full notes on the [releases page](https://github.com/mrbizarro/Phosphene/releases).
+> **Current release: v4.10.5.** **LoRAs stack on Hailuo H3**: pick a character LoRA and keep Turbo on, or combine several LoRAs, each with its own strength (the Update brings the engine change with it). LoRAs in the kohya trainer format install and render now instead of being refused. The LoRA browser has one compact toolbar with a **Characters / Styles / Motion / Speed** filter, searches Hugging Face deeper, and no longer asks for a CivitAI key on the Hugging Face source. The panel no longer opens with the last clip already playing. Full notes on the [releases page](https://github.com/mrbizarro/Phosphene/releases).
## Overview
diff --git a/VERSION b/VERSION
index 4513d23..40f38aa 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-4.10.4
+4.10.5
diff --git a/docs/API.md b/docs/API.md
index 96d1a91..0b3cc13 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -62,7 +62,7 @@ Add a job to the panel's queue. Returns immediately; the helper renders it async
| `window_invariants` | What must not change between windows (who, where, light, lens). Re-injected into every later window. |
| `loras` | JSON-encoded array | See LoRA payload below. |
-**LoRA payload:** the `loras` field is a JSON-encoded array of `{path, strength}` objects. Stack as many as needed:
+**LoRA payload:** the `loras` field is a JSON-encoded array of `{path, strength}` objects. Stack as many as needed: On Hailuo H3, stacking needs the engine's repeatable `--lora` (`/status.h3.loras.max_stack` > 1); an older pack takes one adapter and the `h3_lora_slot` field decides whether it goes to Turbo or to the LoRA.
```json
[
diff --git a/docs/H3_ENGINE.md b/docs/H3_ENGINE.md
index 3489b24..09d9198 100644
--- a/docs/H3_ENGINE.md
+++ b/docs/H3_ENGINE.md
@@ -311,6 +311,21 @@ the conflict; setting it to `user` is the explicit opt-out — Turbo is released
the step count goes back to the tier's, and both facts are logged. Stacking two
LoRAs is refused the same way.
+**Stacking (runner with the repeatable `--lora`, 2026-09-06+).** The runtime
+adapter keeps every delta out of the base weight, so N adapters are a sum:
+`y = base(x) + Σ scale_i · (x @ A_iᵀ) @ B_iᵀ`. `generate_staged.py` takes
+`--lora PATH[:SCALE]` any number of times, Turbo first, and the panel posts
+Turbo plus up to four user LoRAs on a runner whose `--lora` help carries
+"Repeat the flag to stack adapters" (`h3_supports_lora_stack`, probed from the
+script text like every other capability). `/status.h3.loras.max_stack` reports
+the live limit, so the slot control disappears on a stacking runner and stays
+for an old pack. The community rule the panel repeats in its advisory: keep
+the strengths' total near 1.5 or under, and never stack two LoRAs that pull
+the same axis (two faces, two styles). A second `apply_lora` appends to the
+existing wrapper rather than nesting one — nesting hid the quantized base's
+`scales` from `plan()` and skipped every module (`tests/test_lora_stack.py`
+in the engine tree pins this).
+
**Key layouts.** Three exist in the wild and only two work:
| Layout | Keys | What happens |
diff --git a/docs/STATE.md b/docs/STATE.md
index 05d6148..676bfdd 100644
--- a/docs/STATE.md
+++ b/docs/STATE.md
@@ -1,5 +1,32 @@
# Phosphene — project state, history, open work
+> **🚀 2026-09-06 — v4.10.5 ships.** H3 LoRA stacking (engine `codex/h3-engine-v2`
+> at 21e8824 = live-preview merged: repeatable `--lora`, the qkv-permute fix),
+> kohya conversion, the LoRA browser toolbar + kind filter + deeper search +
+> no key prompt on Hugging Face, the autoplay fix. Proof render: Turbo v4 +
+> a character LoRA, native 1344×768×73f, both adapters on 208 modules,
+> 20.8 min wall (6 forwards × 177 s + 166 s VAE decode; the tier's Turbo
+> chip must price SIX forwards — see `_h3_retune_turbo_estimates`).
+
+> **🧩 2026-09-06 — H3 LoRAs stack (on dev, rides the next release).** The
+> H3 runner took ONE `--lora`; Turbo and a character LoRA could not both
+> run. Engine (`mrbizarro/minimax-h3-mlx`, commit on `codex/live-preview`,
+> to be merged to the shipped `codex/h3-engine-v2`): `LoRALinear` holds N
+> adapters, `apply_lora` appends to an existing wrapper instead of nesting
+> (nesting hid the quantized base's `scales` from `plan()` → applied=0),
+> `--lora` is `action="append"` in generate_staged and serve_staged, the
+> draft-cache key carries the sorted set, adaLN deltas accumulate;
+> `tests/test_lora_stack.py`. Panel: `h3_supports_lora_stack()` probes the
+> runner's help text ("Repeat the flag to stack adapters"), `max_stack`
+> is 4 on a stacking runner and 1 on an old pack, the argv posts Turbo
+> then every user LoRA as its own `--lora PATH:SCALE`, the Turbo-or-LoRA
+> slot control only renders for a single-slot pack, and a combined
+> strength above 1.5 logs the community's motion-coherence warning.
+> `test_h3_lora_stack.py`. **Also found:** the shipped `codex/h3-engine-v2`
+> lacks 9c0f0bf (2026-08-15: the unconditional qkv permute measured
+> ORTHOGONAL to the adapter, cosine +0.012, running on every LoRA incl.
+> Turbo) — the merge that ships stacking ships that fix too.
+
> **🪶 2026-09-06 — low-RAM block streaming for ≤24 GB Macs (on dev, rides the next release).**
> The vendored engine already had `low_ram_streaming` (BlockStreamer); the
> helper never used it. Now `LTX_LOW_RAM_STREAM` (panel sets it when
@@ -55,6 +82,13 @@
> the same sidecar and layout probe as a CivitAI install. 22 H3 characters
> at the time of writing. `test_hf_loras` pins lane detection, names, the
> catalog shape and the install.
+> **Then the browser itself.** Results carry a `kind` (character / style /
+> motion / speed / other, from the repo's name and tags; actions count as
+> motion) and the modal filters in place with counts and a "with example"
+> toggle. The controls are one toolbar — Source and Engine as segmented
+> controls, NSFW at the right, the search line, the kind chips — instead of
+> three stacked rows of full-width pills. An empty query runs the model's
+> three spellings and merges (87 H3 results, 16 characters, vs 50 and 1).
> **🎬 2026-09-05 — Editor v2 on dev/beta, UNRELEASED: speed, titles, transitions, the Director, sliding windows.**
> From the long-form editing brief (the measured gaps only, built our way).
diff --git a/mlx_ltx_panel.py b/mlx_ltx_panel.py
index 183cd7e..1631450 100644
--- a/mlx_ltx_panel.py
+++ b/mlx_ltx_panel.py
@@ -6585,6 +6585,11 @@ _hf_lora_catalog_cache: dict[str, tuple[float, list]] = {}
_HF_H3_RE = re.compile(r"minima[xc][_ -]?h3|hailuo[_ -]?h3", re.I)
_HF_LTX_RE = re.compile(r"ltx[_ -]?2\.?[35]|ltx[_ -]?video|ltxv", re.I)
HF_LORA_DEFAULT_QUERY = {"h3": "MiniMax H3 LoRA", "ltx": "LTX-2.3 LoRA"}
+# The HF search matches repo ids, and people spell the model three ways; an
+# empty query runs all three and merges, so a character repo named
+# `Minimax_H3-Someone` shows beside `minimax-h3-turbo-lora`.
+HF_LORA_DEFAULT_SEARCHES = {"h3": ("Minimax_H3", "MiniMax-H3", "MiniMax H3 LoRA", "Hailuo H3 LoRA"),
+ "ltx": ("LTX-2.3", "LTX-2.5", "LTXV LoRA", "LTX-Video LoRA")}
def hf_lora_lane_of_repo(repo_id: str, tags=None) -> str | None:
@@ -6600,6 +6605,45 @@ def hf_lora_lane_of_repo(repo_id: str, tags=None) -> str | None:
return None
+# WHAT KIND OF LoRA. Read from the repo name and its tags — the only things the
+# listing carries. A character is a name (two capitalised words, or the word
+# itself); speed is the distilled / accelerator family; style and motion by
+# their words; everything else is "other". Used by the browser's filter row.
+HF_LORA_KINDS = ("character", "style", "motion", "speed", "other")
+_HF_KIND_WORDS = {
+ "speed": r"turbo|lightx2v|distill|accel|acc[_ -]?lora|step|fast|pdd|speed",
+ "motion": r"motion|camera|transition|dance|danc|dolly|orbit|zoom|action|walk|run|jump|fight|drift|move|pose|drop|shake|twerk|kiss|lick|suck|blow|strip|undress|helper|slider",
+ "style": r"style|realism|realistic|anime|cartoon|toon|cinematic|film|noir|vintage|painterly|pixar|ghibli|aesthetic|look|lighting|grade|vhs|retro|detail|enhanc|texture",
+}
+_HF_CHAR_WORDS = r"character|person|celebrit|actor|actress|face|identity|likeness|portrait"
+# Words that mean "not a person": model names, precisions, tools, packs.
+_HF_TECH_WORDS = r"minimax|hailuo|h3|ltx|ltxv|int[48]|fp[48]|fp16|bf16|nvfp|gguf|convrot|controlnet|control|union|clipproj|proj|vae|encoder|decoder|qwen|vl|heretic|quant|q[48]|pruned|dit|transformer|model|weights|comfy|comfyui|workflow|lora|loras|text|embeddings|embedding|ref|patch|showcase|tests|test|acc|omni|bridge|semantic|upscaler|latent|i2v|t2v|r2v|ref2v|fl2v|a2v|v\d+"
+# Anything bigger than this is a checkpoint, not a LoRA (the largest adapter
+# in the wild, the LightX2V repack, is 1.96 GB).
+HF_LORA_MAX_BYTES = 2_500_000_000
+
+
+def hf_lora_kind(repo_id: str, tags=None) -> str:
+ tail = (repo_id or "").split("/")[-1]
+ stripped = hf_lora_pretty_name(repo_id)
+ text = (tail + " " + " ".join(str(t) for t in (tags or []))).lower()
+ for kind in ("speed", "motion", "style"):
+ if re.search(_HF_KIND_WORDS[kind], text):
+ return kind
+ if re.search(_HF_CHAR_WORDS, text):
+ return "character"
+ # "Megan Fox", "The Dude — Jeff Bridges", "Sydney Sweeney": two to four
+ # capitalised alphabetic words and not one of them model jargon.
+ words = [w for w in re.split(r"[ \-—_]+", stripped) if w]
+ particles = {"de", "da", "del", "della", "di", "van", "von", "der", "den", "la", "le", "du", "y", "e", "the", "of", "and", "al", "bin"}
+ caps = [w for w in words if w.isalpha() and w[:1].isupper()]
+ if 2 <= len(words) <= 5 and len(caps) >= 2 \
+ and all(w.isalpha() and (w[:1].isupper() or w.lower() in particles) for w in words) \
+ and not any(re.fullmatch(_HF_TECH_WORDS, w.lower()) for w in words):
+ return "character"
+ return "other"
+
+
def hf_lora_pretty_name(repo_id: str) -> str:
tail = (repo_id or "").split("/")[-1]
tail = re.sub(r"^(minima[xc][_ -]?h3|hailuo[_ -]?h3|ltx[_ -]?2\.?[35]|ltxv?)([_ -]?(dev(_and_sulphur)?|sulphur|lora))?[_ -]*", "", tail, flags=re.I)
@@ -6646,7 +6690,16 @@ def hf_lora_catalog(lane: str = "h3", q: str = "", force: bool = False) -> list[
elif kind == "author":
repos = _hf_api_get(f"/api/models?author={urllib.parse.quote(value)}&limit=200&sort=likes&direction=-1")
else:
- repos = _hf_api_get(f"/api/models?search={urllib.parse.quote(value)}&limit=60&sort=likes&direction=-1")
+ searches = HF_LORA_DEFAULT_SEARCHES.get(lane, (value,)) if not (q or "").strip() else (value,)
+ seen: dict[str, dict] = {}
+ for term in searches:
+ try:
+ for m in (_hf_api_get(f"/api/models?search={urllib.parse.quote(term)}&limit=200&sort=likes&direction=-1") or []):
+ if isinstance(m, dict) and m.get("id") and m["id"] not in seen:
+ seen[m["id"]] = m
+ except Exception: # noqa: BLE001
+ continue
+ repos = list(seen.values())[:320] # the lane filter and the size filter below do the real narrowing
wanted = [m for m in (repos or []) if isinstance(m, dict) and m.get("id")
and (kind == "repo" or hf_lora_lane_of_repo(m["id"], m.get("tags")) == lane)]
import concurrent.futures as _cf
@@ -6657,9 +6710,10 @@ def hf_lora_catalog(lane: str = "h3", q: str = "", force: bool = False) -> list[
except Exception: # noqa: BLE001
return None
sib = info.get("siblings") or []
- weights = [s for s in sib if str(s.get("rfilename", "")).lower().endswith(".safetensors")]
+ weights = [s for s in sib if str(s.get("rfilename", "")).lower().endswith(".safetensors")
+ and 0 < int(s.get("size") or 0) <= HF_LORA_MAX_BYTES]
if not weights:
- return None
+ return None # no LoRA-sized weights: a checkpoint or a pack
w = max(weights, key=lambda s: int(s.get("size") or 0))
prev = next((s for s in sib if str(s.get("rfilename", "")).lower().endswith((".mp4", ".webm", ".mov"))), None)
if prev is None:
@@ -6679,6 +6733,7 @@ def hf_lora_catalog(lane: str = "h3", q: str = "", force: bool = False) -> list[
"base_model": "MiniMax H3" if lane == "h3" else "LTXV 2.3",
"lane": lane, "hf_url": "https://huggingface.co/" + rid, "civitai_url": None,
"trigger_words": [], "description": "", "nsfw": False,
+ "kind": hf_lora_kind(rid, list(info.get("tags") or m.get("tags") or [])),
}
items: list[dict] = []
with _cf.ThreadPoolExecutor(max_workers=8) as ex:
@@ -6879,7 +6934,8 @@ def _civitai_download(download_url: str, meta: dict) -> dict:
sidecar_data = {
"name": meta.get("name") or target.stem,
"description": meta.get("description") or "",
- "trigger_words": list(meta.get("trigger_words") or []),
+ "trigger_words": (list(meta.get("trigger_words") or [])
+ or list(layout_info.get("trigger_words") or [])),
"recommended_strength": float(meta.get("recommended_strength") or 1.0),
"preview_url": meta.get("preview_url"),
"base_model": (meta.get("base_model")
@@ -9854,6 +9910,34 @@ def h3_supports_first_frame() -> bool:
return _h3_runner_has_flag("--first-frame")
+# The phrase the stackable runner's `--lora` help carries. Probing the help
+# text rather than the flag is what tells a repeatable `--lora` from the
+# single-slot one: both spell the flag identically.
+H3_LORA_STACK_MARKER = "Repeat the flag to stack adapters"
+H3_LORA_STACK_LIMIT = 4
+
+
+def h3_supports_lora_stack() -> bool:
+ """Whether the INSTALLED runner takes `--lora` more than once.
+
+ Stacking landed on the engine after Turbo did, so a pack that predates it
+ has exactly one adapter slot and a second `--lora` is an argparse error
+ 30 s into the render. Same probe as every other capability: the script
+ text, cached per runner mtime."""
+ return h3_supports_lora() and _h3_runner_has_flag(H3_LORA_STACK_MARKER)
+
+
+def h3_lora_max_stack() -> int:
+ """How many user adapters a render may carry on the installed runner."""
+ return H3_LORA_STACK_LIMIT if h3_supports_lora_stack() else H3_LORA_MAX_STACK
+
+
+def h3_lora_stack_note() -> str:
+ if h3_supports_lora_stack():
+ return H3_LORA_STACK_OK_NOTE
+ return H3_LORA_STACK_NOTE
+
+
def h3_supports_lora() -> bool:
"""Whether the INSTALLED runner accepts the shared `--lora PATH:SCALE`.
@@ -10084,6 +10168,14 @@ H3_LORA_IMPORT_LOCK = threading.Lock()
H3_LORA_STACK_NOTE = (
"H3's runner has ONE adapter slot (`--lora` takes a single path), so a "
"LoRA and Turbo can't both run. Pick which one this render uses.")
+# The sentence for a runner that stacks (h3_supports_lora_stack). The 1.5
+# figure is the community's working rule for H3, not a measurement of ours:
+# above it the combined update starts to break motion coherence.
+H3_LORA_STACK_OK_NOTE = (
+ "LoRAs stack on H3: each keeps its own strength and Turbo rides along. "
+ "Keep the strengths' total near 1.5 or under, and avoid two LoRAs that "
+ "pull the same thing (two faces, two styles).")
+H3_LORA_STACK_STRENGTH_ADVISORY = 1.5
# Namespaces other runtimes wrap the DiT in. Longest-first so
# "model.diffusion_model." wins over "diffusion_model." on a file that has
@@ -10703,14 +10795,20 @@ def _h3_lora_layout(path: Path) -> dict:
"LIGHTX2V_LORA_FIX.md."),
}
if not a_names and any(k.endswith(_H3_LORA_KOHYA_SUFFIX) for k in keys):
+ # Convertible, not refused (2026-09-06): the character LoRAs people
+ # actually train for H3 come out of kohya-style trainers in exactly
+ # this shape, and the two things the runner cannot read — the naming
+ # and the `.alpha` scalar — are both mechanical. `_h3_lora_convert_kohya`
+ # renames the keys onto the runner's modules and folds alpha/rank into
+ # lora_B, so strength 1.0 means "as trained", same as every other file.
+ n_down = len([k for k in keys if k.endswith(_H3_LORA_KOHYA_SUFFIX)])
return {
- "layout": "kohya", "prefix": "", "pairs": 0,
- "ok": False, "convertible": False,
+ "layout": "kohya", "prefix": "", "pairs": n_down,
+ "ok": False, "convertible": True,
"reason": (
- "this LoRA uses kohya `lora_down` / `lora_up` naming and ships "
- "its own `.alpha` scalars. The H3 loader reads lora_A / lora_B "
- "and applies no alpha, so a plain rename would run it at the "
- "wrong strength — it needs manual conversion."),
+ "this LoRA uses kohya `lora_down` / `lora_up` naming with "
+ "`.alpha` scalars; it is rewritten onto the runner's lora_A / "
+ "lora_B names with alpha/rank folded into lora_B."),
}
if not pairs:
return {
@@ -10807,6 +10905,94 @@ def _h3_lora_strip_prefix(path: Path, prefix: str) -> int:
return n_renamed
+# kohya module names → the runner's checkpoint names. Underscores are the
+# trainer's separator AND part of the module names (`out_proj`, `qkv_proj`),
+# so the map is by known target, never by a blind `_`→`.` rewrite.
+_H3_KOHYA_MODULE_RE = re.compile(
+ r"^lora_unet_(?:(token_refiner)_)?blocks_(\d+)_(attn_qkv_proj|attn_out_proj|mlp_fc1|mlp_fc2)$")
+_H3_KOHYA_TAILS = {"attn_qkv_proj": "attn.qkv_proj", "attn_out_proj": "attn.out_proj",
+ "mlp_fc1": "mlp.fc1", "mlp_fc2": "mlp.fc2"}
+
+
+def _h3_kohya_module_name(name: str) -> str | None:
+ m = _H3_KOHYA_MODULE_RE.match(name)
+ if not m:
+ return None
+ refiner, idx, tail = m.groups()
+ return f"{'token_refiner.' if refiner else ''}blocks.{int(idx)}.{_H3_KOHYA_TAILS[tail]}"
+
+
+def _h3_lora_convert_kohya(path: Path) -> dict:
+ """Rewrite a kohya-format H3 adapter in place into the runner's layout.
+
+ `lora_down` is A, `lora_up` is B, and kohya applies the update as
+ (alpha / rank) · B @ A. The runner applies no alpha, so the quotient is
+ folded into B in float32 and cast back — the file then reads at strength
+ 1.0 exactly as it trained. Original metadata is kept and extended with
+ `converted_from`, so the operation is visible afterwards; modules the
+ runner has no target for are dropped and counted. The temp file must
+ classify as bare with the same pair count before it replaces the original."""
+ import mlx.core as mx
+ header, _ = _safetensors_header(path)
+ meta = {str(k): str(v) for k, v in (header.get("__metadata__") or {}).items()}
+ tensors = mx.load(str(path))
+ out: dict = {}
+ folded: dict[str, float] = {}
+ dropped: list[str] = []
+ names = sorted({k[: -len(_H3_LORA_KOHYA_SUFFIX)] for k in tensors
+ if k.endswith(_H3_LORA_KOHYA_SUFFIX)})
+ for name in names:
+ down = tensors.get(f"{name}.lora_down.weight")
+ up = tensors.get(f"{name}.lora_up.weight")
+ target = _h3_kohya_module_name(name)
+ if down is None or up is None or target is None:
+ dropped.append(name)
+ continue
+ rank = int(down.shape[0])
+ alpha_t = tensors.get(f"{name}.alpha")
+ alpha = float(alpha_t.item()) if alpha_t is not None else float(rank)
+ q = alpha / rank if rank else 1.0
+ b = up
+ if abs(q - 1.0) > 1e-6:
+ b = (up.astype(mx.float32) * q).astype(up.dtype)
+ out[f"{target}{_H3_LORA_A_SUFFIX}"] = down
+ out[f"{target}{_H3_LORA_B_SUFFIX}"] = b
+ folded[target] = q
+ if not out:
+ raise RuntimeError(f"{path.name}: kohya file has no module the H3 runner can take "
+ f"({len(dropped)} unknown module names, e.g. {dropped[:2]})")
+ quotients = sorted(set(round(v, 6) for v in folded.values()))
+ meta.update({
+ "converted_from": "kohya",
+ "converted_by": "phosphene",
+ "alpha_over_rank": ",".join(f"{v:g}" for v in quotients),
+ "converted_modules": str(len(out) // 2),
+ "dropped_modules": str(len(dropped)),
+ })
+ # mx.save_safetensors appends ".safetensors" to any other name, so the
+ # temp file keeps the suffix and carries its marker in the stem.
+ tmp = path.with_name(path.stem + ".kohya-tmp.safetensors")
+ try:
+ mx.save_safetensors(str(tmp), out, metadata=meta)
+ check = _h3_lora_layout(tmp)
+ if check["layout"] != "bare" or check["pairs"] != len(out) // 2:
+ raise RuntimeError(
+ f"post-conversion check failed (layout={check['layout']}, "
+ f"pairs={check['pairs']}) — leaving the original untouched.")
+ os.replace(tmp, path)
+ except Exception:
+ try:
+ tmp.unlink()
+ except OSError:
+ pass
+ raise
+ finally:
+ del tensors, out
+ trigger = (meta.get("modelspec.trigger_phrase") or "").strip()
+ return {"pairs": len(folded), "dropped": len(dropped), "alpha_over_rank": quotients,
+ "trigger_words": [trigger] if trigger else []}
+
+
def _h3_lora_prepare(path: Path) -> dict:
"""Make `path` loadable by the H3 runner, or raise saying why it can't be.
@@ -10821,6 +11007,26 @@ def _h3_lora_prepare(path: Path) -> dict:
"pairs": info["pairs"]}
if not info["convertible"]:
raise RuntimeError(f"{path.name}: {info['reason']}")
+ if info["layout"] == "kohya":
+ done = _h3_lora_convert_kohya(path)
+ push(f"[h3:lora] {path.name}: kohya → runner layout, {done['pairs']} modules, "
+ f"alpha/rank {', '.join(f'{q:g}' for q in done['alpha_over_rank'])} folded into lora_B"
+ + (f", {done['dropped']} module(s) without a target dropped" if done['dropped'] else ""))
+ # A sidecar that already sits next to the file (a download that was
+ # refused at render time by an older build) learns the trigger phrase
+ # the trainer wrote into the file, if it has none of its own.
+ try:
+ sc = path.with_suffix(".json")
+ if done["trigger_words"] and sc.is_file():
+ data = json.loads(sc.read_text(encoding="utf-8"))
+ if not data.get("trigger_words"):
+ data["trigger_words"] = done["trigger_words"]
+ data["lora_layout"] = "kohya"
+ atomic_write_text(sc, json.dumps(data, indent=2))
+ except Exception: # noqa: BLE001
+ pass
+ return {"layout": "kohya", "converted": True, "prefix": "",
+ "pairs": done["pairs"], "trigger_words": done["trigger_words"]}
n = _h3_lora_strip_prefix(path, info["prefix"])
push(f"[h3:lora] {path.name}: stripped `{info['prefix']}` from {n} keys "
f"(ComfyUI repack → bare layout; tensors untouched)")
@@ -10944,10 +11150,10 @@ def h3_loras_status() -> dict:
"dir": str(_h3_loras_dir()),
"count": len(entries),
"usable": len(usable),
- "max_stack": H3_LORA_MAX_STACK,
+ "max_stack": h3_lora_max_stack(),
"slots": list(H3_LORA_SLOTS),
"default_slot": H3_LORA_SLOT_DEFAULT,
- "note": H3_LORA_STACK_NOTE,
+ "note": h3_lora_stack_note(),
"base_model": _CIVITAI_VIDEO_FAMILIES["h3"][0],
}
@@ -20641,7 +20847,7 @@ def make_job(form: dict[str, list[str]] | dict[str, str], *,
# the render) would carry Turbo's pinned 4 sigma points on a render
# that is not using the 4-step distillation adapter. Announced, never
# silent — the whole reason h3_lora_slot is an explicit field.
- if (_h3_turbo and _h3_lora_slot == "user"
+ if (_h3_turbo and _h3_lora_slot == "user" and not h3_supports_lora_stack()
and any(_lora_is_h3_lane((e or {}).get("path"))
for e in (job["params"].get("loras") or []))):
_h3_turbo = False
@@ -22487,6 +22693,7 @@ def run_h3_job_inner(job: dict) -> None:
lora_slot = H3_LORA_SLOT_DEFAULT
user_lora: Path | None = None
user_lora_strength = 1.0
+ user_lora_stack: list[tuple[Path, float]] = []
_h3_lora_root = _h3_loras_dir()
_picked: list[tuple[Path, float]] = []
_foreign: list[str] = []
@@ -22525,32 +22732,52 @@ def run_h3_job_inner(job: dict) -> None:
"This render picks a LoRA, and "
+ _h3_runner_behind("--lora", paths["runner"],
"Or un-pick the LoRA and render again."))
- if len(_picked) > H3_LORA_MAX_STACK:
+ _stack_ok = h3_supports_lora_stack()
+ _max_stack = h3_lora_max_stack()
+ if len(_picked) > _max_stack:
+ if _stack_ok:
+ raise RenderRefused(
+ "h3_lora_slots",
+ f"H3 stacks up to {_max_stack} LoRAs per render and "
+ f"{len(_picked)} are picked "
+ f"({', '.join(pp.name for pp, _ in _picked)}). Un-pick some.")
raise RenderRefused(
"h3_lora_slots",
f"H3's runner has {H3_LORA_MAX_STACK} adapter slot — `--lora` "
f"takes a single path — and {len(_picked)} LoRAs are picked "
f"({', '.join(pp.name for pp, _ in _picked)}). Stacking is an "
f"LTX capability; on H3, pick one.")
+ # Layout gate, per file. Idempotent — a file already in bare layout is
+ # inspected and returned untouched; a ComfyUI repack is renamed in
+ # place here if it wasn't already renamed at install time (hand-copied
+ # files never went through the download path); a diffusers-namespace
+ # file raises with the sentence naming the alpha problem.
+ _stack_layouts = []
+ for _pp, _ps in _picked:
+ _stack_layouts.append(_h3_lora_prepare(_pp).get("layout"))
user_lora, user_lora_strength = _picked[0]
- # Layout gate. Idempotent — a file already in bare layout is inspected
- # and returned untouched; a ComfyUI repack is renamed in place here if
- # it wasn't already renamed at install time (hand-copied files never
- # went through the download path); a diffusers-namespace file raises
- # with the sentence naming the alpha problem.
- _layout = _h3_lora_prepare(user_lora)
+ user_lora_stack = list(_picked)
p["h3_lora_path"] = str(user_lora)
p["h3_lora_strength"] = user_lora_strength
- p["h3_lora_layout"] = _layout.get("layout")
+ p["h3_lora_layout"] = _stack_layouts[0]
+ if len(_picked) > 1:
+ p["h3_lora_stack"] = [{"path": str(pp), "strength": ps, "layout": ly}
+ for (pp, ps), ly in zip(_picked, _stack_layouts)]
+ _total = sum(abs(ps) for _, ps in _picked)
+ if _total > H3_LORA_STACK_STRENGTH_ADVISORY:
+ push(f"[h3] {len(_picked)} LoRAs stacked at a combined strength of "
+ f"{_total:.2f} — above {H3_LORA_STACK_STRENGTH_ADVISORY:g} the "
+ f"stack tends to break motion. Lower one if the clip judders.")
# ---- Turbo: the 4-step distillation LoRA -----------------------------
# make_job already gated this and pinned `steps`, but re-resolve the adapter
# HERE: the queue can sit for an hour and a job must not reach the runner
# with a --lora path that stopped resolving in the meantime.
turbo = bool(p.get("h3_turbo"))
- if turbo and user_lora is not None:
- # ONE slot, two claimants. Both outcomes are stated out loud; neither
- # is chosen for the user behind their back.
+ if turbo and user_lora is not None and not h3_supports_lora_stack():
+ # ONE slot, two claimants (a runner that predates stacking). Both
+ # outcomes are stated out loud; neither is chosen for the user behind
+ # their back. A stacking runner takes both — see the argv below.
if lora_slot == "user":
turbo = False
p["h3_turbo"] = False
@@ -22774,14 +23001,17 @@ def run_h3_job_inner(job: dict) -> None:
# CLI still requires PATH:SCALE; 1.0 means "as repacked". Never pass
# the raw v0.1 file here — its missing alpha/rank fold renders noise.
cmd += h3_turbo_argv(turbo_paths)
- elif user_lora is not None:
- # The SAME flag Turbo rides — one slot, and this render spent it here.
+ if user_lora is not None and (not turbo or h3_supports_lora_stack()):
+ # The SAME flag Turbo rides. On a stacking runner every `--lora` is one
+ # more adapter on the same base layers, Turbo first; on the single-slot
+ # runner this branch only runs when Turbo did not spend the slot.
# `PATH:SCALE` is the runner's own spelling (lora.parse_spec), and the
# scale is the picker's strength: 1.0 means "as trained" for a
# checkpoint that ships alpha == rank, which is the only namespace this
# lane accepts (the diffusers/PEFT one, whose alpha is NOT in the file,
# is refused upstream in _h3_lora_prepare).
- cmd += ["--lora", f"{user_lora}:{user_lora_strength:g}"]
+ for _pp, _ps in (user_lora_stack if h3_supports_lora_stack() else [(user_lora, user_lora_strength)]):
+ cmd += ["--lora", f"{_pp}:{_ps:g}"]
env = os.environ.copy()
# The runner pipes raw RGB into `ffmpeg` from PATH (minimax_h3_mlx.media);
diff --git a/test_h3_lora_file_import.py b/test_h3_lora_file_import.py
index ecb7e61..71cb63a 100644
--- a/test_h3_lora_file_import.py
+++ b/test_h3_lora_file_import.py
@@ -99,6 +99,16 @@ def _kohya_header() -> bytes:
return len(encoded).to_bytes(8, "little") + encoded
+def _diffusers_header() -> bytes:
+ """The one layout the lane still refuses: split to_q/to_k/to_v with no alpha in the file."""
+ header = {
+ "transformer.blocks.0.attn.to_q.lora_A.weight": {"dtype": "F32", "shape": [1, 1], "data_offsets": [0, 4]},
+ "transformer.blocks.0.attn.to_q.lora_B.weight": {"dtype": "F32", "shape": [1, 1], "data_offsets": [4, 8]},
+ }
+ encoded = json.dumps(header).encode("utf-8")
+ return len(encoded).to_bytes(8, "little") + encoded + b"\0" * 8
+
+
class TestH3LoraFileImport(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory(prefix="phos-h3-lora-import-")
@@ -120,13 +130,15 @@ class TestH3LoraFileImport(unittest.TestCase):
self.assertEqual(result["layout"], "bare")
self.assertFalse(result["converted"])
- def test_refuses_raw_kohya_and_leaves_no_file(self):
- payload = _kohya_header()
-
- with self.assertRaisesRegex(RuntimeError, "kohya.*alpha"):
- P.import_h3_lora_file("raw-kohya.safetensors", payload)
-
- self.assertEqual(list(self.dir.iterdir()), [])
+ def test_a_kohya_file_is_converted_on_import(self):
+ """kohya is CONVERTED now, not refused (test_h3_lora_kohya.py pins the
+ arithmetic). The import lands a bare-layout file plus its sidecar."""
+ result = P.import_h3_lora_file("raw-kohya.safetensors", _kohya_header())
+ self.assertEqual(result["layout"], "kohya")
+ self.assertTrue(result["converted"])
+ names = sorted(p.name for p in self.dir.iterdir())
+ self.assertEqual(names, ["raw-kohya.json", "raw-kohya.safetensors"])
+ self.assertEqual(P._h3_lora_layout(self.dir / "raw-kohya.safetensors")["layout"], "bare")
def test_refuses_non_safetensors_uploads(self):
with self.assertRaisesRegex(ValueError, "\.safetensors"):
@@ -253,8 +265,8 @@ class TestH3LoraFileImport(unittest.TestCase):
self.assertNotIn(str(os.getpid()), message)
def test_a_refusal_leaves_no_staging_directory_behind(self):
- with self.assertRaises(RuntimeError):
- P.import_h3_lora_file("doomed.safetensors", _kohya_header())
+ with self.assertRaises(Exception):
+ P.import_h3_lora_file("doomed.safetensors", _diffusers_header())
self.assertEqual(list(self.dir.iterdir()), [])
def test_a_successful_import_writes_a_sidecar_like_the_civitai_path(self):
diff --git a/test_h3_lora_kohya.py b/test_h3_lora_kohya.py
new file mode 100644
index 0000000..844a715
--- /dev/null
+++ b/test_h3_lora_kohya.py
@@ -0,0 +1,109 @@
+"""kohya-format H3 adapters are converted, not refused.
+
+The character LoRAs people train for H3 come out of kohya-style trainers:
+`lora_unet_blocks_N_attn_qkv_proj.lora_down.weight` / `.lora_up.weight` and a
+`.alpha` scalar per module, applied as (alpha/rank)·B@A. The runner reads
+lora_A / lora_B and applies no alpha, so the panel renames the modules onto
+the runner's tree and folds alpha/rank into lora_B — strength 1.0 then means
+"as trained", the same contract as every other file in the lane.
+"""
+import json, struct, tempfile, unittest
+from pathlib import Path
+
+import mlx.core as mx
+
+import mlx_ltx_panel as P
+
+
+def _kohya_file(path: Path, alpha: float, rank: int = 4, extra_unknown: bool = False, meta=None):
+ t = {}
+ for name in ("lora_unet_blocks_3_attn_qkv_proj", "lora_unet_blocks_3_attn_out_proj",
+ "lora_unet_token_refiner_blocks_0_mlp_fc1"):
+ t[f"{name}.lora_down.weight"] = mx.random.normal((rank, 8)).astype(mx.bfloat16)
+ t[f"{name}.lora_up.weight"] = mx.random.normal((12, rank)).astype(mx.bfloat16)
+ t[f"{name}.alpha"] = mx.array(alpha, dtype=mx.bfloat16)
+ if extra_unknown:
+ t["lora_unet_blocks_3_adaln_proj.lora_down.weight"] = mx.zeros((rank, 8))
+ t["lora_unet_blocks_3_adaln_proj.lora_up.weight"] = mx.zeros((12, rank))
+ mx.save_safetensors(str(path), t, metadata=meta or {"modelspec.trigger_phrase": "Some Person", "ss_network_alpha": str(alpha)})
+ return t
+
+
+def _header(path: Path) -> dict:
+ with open(path, "rb") as f:
+ n = struct.unpack("<Q", f.read(8))[0]
+ return json.loads(f.read(n))
+
+
+class KohyaConversion(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory(prefix="phos-kohya-")
+ self.path = Path(self.tmp.name) / "Person.safetensors"
+
+ def tearDown(self):
+ self.tmp.cleanup()
+
+ def test_layout_names_kohya_as_convertible(self):
+ _kohya_file(self.path, alpha=4.0)
+ info = P._h3_lora_layout(self.path)
+ self.assertEqual(info["layout"], "kohya")
+ self.assertTrue(info["convertible"])
+ self.assertEqual(info["pairs"], 3)
+
+ def test_keys_map_onto_the_runner_modules(self):
+ _kohya_file(self.path, alpha=4.0)
+ P._h3_lora_prepare(self.path)
+ keys = sorted(k for k in _header(self.path) if k != "__metadata__")
+ self.assertIn("blocks.3.attn.qkv_proj.lora_A.weight", keys)
+ self.assertIn("blocks.3.attn.out_proj.lora_B.weight", keys)
+ self.assertIn("token_refiner.blocks.0.mlp.fc1.lora_A.weight", keys)
+ self.assertFalse(any("lora_down" in k or ".alpha" in k for k in keys))
+ self.assertEqual(P._h3_lora_layout(self.path)["layout"], "bare")
+
+ def test_alpha_over_rank_is_folded_into_b(self):
+ src = _kohya_file(self.path, alpha=2.0, rank=4) # quotient 0.5
+ P._h3_lora_prepare(self.path)
+ out = mx.load(str(self.path))
+ want = (src["lora_unet_blocks_3_attn_qkv_proj.lora_up.weight"].astype(mx.float32) * 0.5)
+ got = out["blocks.3.attn.qkv_proj.lora_B.weight"].astype(mx.float32)
+ self.assertTrue(mx.allclose(got, want, atol=2e-2, rtol=2e-2).item())
+ a_same = mx.array_equal(out["blocks.3.attn.qkv_proj.lora_A.weight"],
+ src["lora_unet_blocks_3_attn_qkv_proj.lora_down.weight"])
+ self.assertTrue(a_same.item())
+ self.assertEqual(_header(self.path)["__metadata__"]["alpha_over_rank"], "0.5")
+
+ def test_alpha_equal_rank_leaves_b_untouched(self):
+ src = _kohya_file(self.path, alpha=4.0, rank=4)
+ P._h3_lora_prepare(self.path)
+ out = mx.load(str(self.path))
+ self.assertTrue(mx.array_equal(out["blocks.3.attn.qkv_proj.lora_B.weight"],
+ src["lora_unet_blocks_3_attn_qkv_proj.lora_up.weight"]).item())
+
+ def test_metadata_and_trigger_phrase_survive_and_reach_the_sidecar(self):
+ _kohya_file(self.path, alpha=4.0)
+ sc = self.path.with_suffix(".json")
+ sc.write_text(json.dumps({"name": "Person", "trigger_words": []}))
+ done = P._h3_lora_prepare(self.path)
+ self.assertEqual(done["trigger_words"], ["Some Person"])
+ meta = _header(self.path)["__metadata__"]
+ self.assertEqual(meta["converted_from"], "kohya")
+ self.assertEqual(meta["modelspec.trigger_phrase"], "Some Person")
+ self.assertEqual(json.loads(sc.read_text())["trigger_words"], ["Some Person"])
+
+ def test_unknown_modules_are_dropped_and_counted(self):
+ _kohya_file(self.path, alpha=4.0, extra_unknown=True)
+ done = P._h3_lora_prepare(self.path)
+ self.assertEqual(done["pairs"], 3)
+ self.assertEqual(_header(self.path)["__metadata__"]["dropped_modules"], "1")
+
+ def test_conversion_is_idempotent(self):
+ _kohya_file(self.path, alpha=2.0)
+ P._h3_lora_prepare(self.path)
+ first = self.path.read_bytes()
+ again = P._h3_lora_prepare(self.path)
+ self.assertEqual(again["layout"], "bare")
+ self.assertEqual(self.path.read_bytes(), first)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/test_h3_lora_stack.py b/test_h3_lora_stack.py
new file mode 100644
index 0000000..d9870cc
--- /dev/null
+++ b/test_h3_lora_stack.py
@@ -0,0 +1,50 @@
+"""H3 LoRA stacking is a RUNNER capability, reported, never assumed.
+
+A pack that predates the repeatable `--lora` has one adapter slot and the
+panel keeps its Turbo-or-LoRA arbitration for it; a pack that carries the
+stack marker in its `--lora` help takes Turbo and up to four user adapters in
+one render. Both answers come from the installed script's text, so an old
+install never posts a second `--lora` into an argparse error.
+"""
+import unittest
+from unittest import mock
+
+import mlx_ltx_panel as p
+
+
+def _flags(*present):
+ def probe(flag):
+ return any(flag == f or flag in f for f in present)
+ return probe
+
+
+class StackCapability(unittest.TestCase):
+ def test_single_slot_runner_keeps_the_old_contract(self):
+ with mock.patch.object(p, "_h3_runner_has_flag", _flags("--lora")):
+ self.assertTrue(p.h3_supports_lora())
+ self.assertFalse(p.h3_supports_lora_stack())
+ self.assertEqual(p.h3_lora_max_stack(), 1)
+ self.assertIn("ONE adapter slot", p.h3_lora_stack_note())
+
+ def test_stacking_runner_reports_the_limit_and_the_advice(self):
+ with mock.patch.object(p, "_h3_runner_has_flag", _flags("--lora", p.H3_LORA_STACK_MARKER)):
+ self.assertTrue(p.h3_supports_lora_stack())
+ self.assertEqual(p.h3_lora_max_stack(), p.H3_LORA_STACK_LIMIT)
+ self.assertGreater(p.H3_LORA_STACK_LIMIT, 1)
+ self.assertIn("stack", p.h3_lora_stack_note())
+ self.assertIn("1.5", p.h3_lora_stack_note())
+
+ def test_marker_is_the_runner_help_text(self):
+ """The marker must be the sentence the stackable runner prints, not a flag."""
+ self.assertTrue(p.H3_LORA_STACK_MARKER.startswith("Repeat the flag"))
+
+ def test_status_block_carries_the_live_limit(self):
+ with mock.patch.object(p, "_h3_runner_has_flag", _flags("--lora", p.H3_LORA_STACK_MARKER)), \
+ mock.patch.object(p, "list_h3_user_loras", lambda: []):
+ st = p.h3_loras_status()
+ self.assertEqual(st["max_stack"], p.H3_LORA_STACK_LIMIT)
+ self.assertEqual(st["note"], p.H3_LORA_STACK_OK_NOTE)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/test_hf_loras.py b/test_hf_loras.py
index 900effa..2a1d613 100644
--- a/test_hf_loras.py
+++ b/test_hf_loras.py
@@ -79,3 +79,36 @@ def test_routes_registered():
from panel import routes_loras # noqa: F401
from panel.routes import GET_ROUTES, POST_ROUTES
assert "/hf/loras" in GET_ROUTES and "/hf/loras/download" in POST_ROUTES
+
+
+def test_kind_from_name_and_tags():
+ k = p.hf_lora_kind
+ assert k("Someone/Minimax_H3-Megan_Fox") == "character"
+ assert k("Someone/Minimax_H3-The_Dude-Jeff_Bridges") == "character"
+ assert k("larryvrh/MiniMax-H3-Turbo-Lora") == "speed"
+ assert k("x/minimax-h3-lightx2v-4step") == "speed"
+ assert k("x/LTX-2.3-Latin_dance") == "motion"
+ assert k("x/valiantcat-LTX-2.3-Transition-LORA") == "motion"
+ assert k("x/Realism-People-LoRA") == "style"
+ assert k("x/Minimax_H3-Titty_Drop") == "motion" # an action, not a person
+ assert k("x/some-repo", ["character"]) == "character"
+ # base models, precisions and tools are never "characters"
+ assert k("MiniMaxAI/MiniMax-H3") == "other"
+ assert k("x/nvfp4-INT4-INT8-Convrot") == "other"
+ assert k("x/PinkCherry_MiniMax-H3") == "other"
+ assert k("x/Fun-ControlNet-Union") == "other"
+ assert k("x/ClipProj-MiniMax-H3") == "other"
+ assert k("x/Minimax_H3-Ana_de_Armas") == "character"
+
+
+def test_catalog_skips_checkpoint_sized_repos(monkeypatch):
+ def fake_get(path, timeout=20.0):
+ if "/api/models?" in path:
+ return [{"id": "MiniMaxAI/MiniMax-H3", "likes": 6949}, {"id": "Someone/Minimax_H3-Megan_Fox", "likes": 3}]
+ if "MiniMaxAI" in path:
+ return {"siblings": [{"rfilename": "transformer.safetensors", "size": 40_000_000_000}, {"rfilename": "clip.mp4", "size": 5}]}
+ return {"siblings": [{"rfilename": "lora.safetensors", "size": 155_000_000}]}
+ monkeypatch.setattr(p, "_hf_api_get", fake_get)
+ p._hf_lora_catalog_cache.clear()
+ items = p.hf_lora_catalog("h3", "", force=True)
+ assert [i["id"] for i in items] == ["Someone/Minimax_H3-Megan_Fox"]
diff --git a/webapp/index.html b/webapp/index.html
index 0abc0c5..abfcb09 100644
--- a/webapp/index.html
+++ b/webapp/index.html
@@ -4166,9 +4166,8 @@
<button class="ghost-btn" onclick="closeCivitaiModal()">Close</button>
</div>
<div class="models-hint">
- LoRAs land in <code id="civitaiTargetDir">mlx_models/loras/</code>
- with a sidecar JSON that carries the trigger words and recommended
- strength. The CivitAI page link stays in the sidecar for attribution.
+ Pick a source and an engine, search, Install. Installed LoRAs land in
+ <code id="civitaiTargetDir">mlx_models/loras/</code> with their notes and show up in the picker.
</div>
<!-- Inline API-key banner. CivitAI requires a token to download LoRAs
(even SFW ones). Three states, all rendered in the same slot by
@@ -4182,25 +4181,33 @@
<!-- Family pill row (image context only). Click a pill to scope the
result set to a specific engine family (Qwen / HiDream / All).
Shown / hidden by civitaiRenderFamilyPills() on each open. -->
- <div class="civitai-family-row" id="civitaiFamilyRow" style="display:none;
- margin: 4px 0 8px; display:flex; gap:6px; flex-wrap:wrap;">
+ <div class="civitai-toolbar">
+ <div class="civitai-seg" id="civitaiSourceRow" style="display:none" aria-label="Source">
+ <button type="button" class="pill-btn active" data-civitai-source="civitai" onclick="civitaiSetSource('civitai')">CivitAI</button>
+ <button type="button" class="pill-btn" data-civitai-source="huggingface" onclick="civitaiSetSource('huggingface')" title="Search Hugging Face — a name, an author (author:someone) or an owner/repo">Hugging Face</button>
+ </div>
+ <div class="civitai-seg" id="civitaiFamilyRow" style="display:none" aria-label="Engine"></div>
+ <label class="toggle-pill" id="civitaiNsfwPill" data-spicy-only hidden>
+ <input type="checkbox" id="civitaiNsfw">
+ <span class="toggle-dot"></span>
+ <span>Show NSFW</span>
+ </label>
</div>
- <!-- WHERE THE LoRAs COME FROM. CivitAI, or Hugging Face searched the same
- way — a name, an author, or an owner/repo. Phosphene names no org and
- endorses nothing; what shows is what matches. Video context only. -->
- <div class="civitai-family-row" id="civitaiSourceRow" style="display:none; margin: 4px 0 8px; gap:6px; flex-wrap:wrap;">
- <button type="button" class="pill-btn active" data-civitai-source="civitai" onclick="civitaiSetSource('civitai')">CivitAI</button>
- <button type="button" class="pill-btn" data-civitai-source="huggingface" onclick="civitaiSetSource('huggingface')" title="Search Hugging Face for LoRAs — a name, an author (author:someone) or an owner/repo">Hugging Face</button>
+ <!-- WHAT KIND, for the Hugging Face source: read from each repo's name and
+ tags on the server; filtered here without another fetch. -->
+ <div class="civitai-chips" id="civitaiKindRow" style="display:none">
+ <button type="button" class="pill-btn active" data-civitai-kind="all" onclick="civitaiSetKind('all')">All</button>
+ <button type="button" class="pill-btn" data-civitai-kind="character" onclick="civitaiSetKind('character')">Characters</button>
+ <button type="button" class="pill-btn" data-civitai-kind="style" onclick="civitaiSetKind('style')">Styles</button>
+ <button type="button" class="pill-btn" data-civitai-kind="motion" onclick="civitaiSetKind('motion')">Motion</button>
+ <button type="button" class="pill-btn" data-civitai-kind="speed" onclick="civitaiSetKind('speed')">Speed</button>
+ <button type="button" class="pill-btn" data-civitai-kind="other" onclick="civitaiSetKind('other')">Other</button>
+ <label class="toggle-pill" title="Only repos that ship an example clip or image"><input type="checkbox" id="civitaiWithExample" onchange="civitaiSetKind()"><span class="toggle-dot"></span><span>With example</span></label>
</div>
<div class="civitai-search-bar">
<input type="text" id="civitaiQuery" placeholder="Search by name, style, creator…"
oninput="if(this._t) clearTimeout(this._t); this._t = setTimeout(civitaiSearch, 350)"
onkeydown="if(event.key==='Enter'){ event.preventDefault(); civitaiSearch(); }">
- <label class="toggle-pill" id="civitaiNsfwPill" data-spicy-only hidden>
- <input type="checkbox" id="civitaiNsfw">
- <span class="toggle-dot"></span>
- <span>Show NSFW</span>
- </label>
</div>
<div class="civitai-grid" id="civitaiGrid">
<div class="hint">Loading…</div>
diff --git a/webapp/js/boot.js b/webapp/js/boot.js
index f5a6137..eca8593 100644
--- a/webapp/js/boot.js
+++ b/webapp/js/boot.js
@@ -421,7 +421,7 @@ function _maybeAutoLoadAllForEmptyFilter(mode) {
outputsLoadAll().then(() => {
const visible = filteredMainOutputs();
if (visible.length && !visible.some(o => o.path === activePath)) {
- selectOutput(visible[0].path);
+ selectOutput(visible[0].path, { autoplay: false }); // not a click
}
});
return true;
@@ -447,7 +447,7 @@ function setMainOutputsFilter(mode) {
const visible = filteredMainOutputs();
// If the active selection was filtered out, switch to the first match.
if (visible.length && !visible.some(o => o.path === activePath)) {
- selectOutput(visible[0].path);
+ selectOutput(visible[0].path, { autoplay: false }); // not a click
}
renderCarousel();
// Reset scroll position on filter change so the user lands at the
@@ -499,7 +499,7 @@ function _autoMainOutputsFilterForMode(mode) {
// off-filter (e.g. mode=image but the viewer is showing a video).
const visible = filteredMainOutputs();
if (visible.length && !visible.some(o => o.path === activePath)) {
- selectOutput(visible[0].path);
+ selectOutput(visible[0].path, { autoplay: false }); // not a click
}
}
diff --git a/webapp/js/loras.js b/webapp/js/loras.js
index d5d9279..f3501f9 100644
--- a/webapp/js/loras.js
+++ b/webapp/js/loras.js
@@ -199,7 +199,9 @@ function renderH3LoraSlot() {
const lora = _h3ActiveUserLora();
const turboOn = (document.getElementById('h3_turbo') || {}).value === '1';
const onH3 = (typeof currentEngine === 'function') && currentEngine() === 'h3';
- const conflict = !!(onH3 && lora && turboOn);
+ // A runner that stacks takes Turbo AND the LoRA — no slot to choose.
+ const stacks = !!(H3 && H3.loras && Number(H3.loras.max_stack || 1) > 1);
+ const conflict = !!(onH3 && lora && turboOn && !stacks);
row.hidden = !conflict;
if (!conflict) {
// No conflict = no choice to remember. Reset so a later render can't
diff --git a/webapp/js/preview.js b/webapp/js/preview.js
index 457bb70..fefea12 100644
--- a/webapp/js/preview.js
+++ b/webapp/js/preview.js
@@ -1300,6 +1300,9 @@ async function refreshCivitaiAccessUI() {
function renderCivitaiAuthBanner(haveKey, mode) {
const box = document.getElementById('civitaiAuthBanner');
if (!box) return;
+ // The key is CivitAI's; on the Hugging Face source the banner stays hidden
+ // even when the access probe answers after the source switch.
+ if (typeof _civitaiSource !== 'undefined' && _civitaiSource === 'huggingface') { box.style.display = 'none'; return; }
// Three visual modes: 'view' (default), 'edit' (showing input), 'err' (last save failed).
const m = mode || (haveKey ? 'view' : 'edit');
box.style.display = '';
@@ -1385,6 +1388,8 @@ function civitaiSetSource(src) {
// needs neither.
const title = document.getElementById('civitaiModalTitle');
const banner = document.getElementById('civitaiAuthBanner');
+ const kr = document.getElementById('civitaiKindRow');
+ if (kr) kr.style.display = (_civitaiSource === 'huggingface') ? 'flex' : 'none';
if (_civitaiSource === 'huggingface') {
if (title) title.textContent = `Browse Hugging Face for ${_civitaiFamily === 'h3' ? 'Hailuo H3' : 'LTX'} LoRAs`;
if (banner) banner.style.display = 'none';
@@ -1395,12 +1400,43 @@ function civitaiSetSource(src) {
if (_civitaiSearching) { _civitaiRerun = true; return; }
civitaiSearch();
}
+// ---- kind filter (Hugging Face source only) -------------------------------------
+let _civitaiKind = 'all';
+let _hfLoraItems = [];
+function civitaiSetKind(kind) {
+ if (kind) _civitaiKind = kind;
+ document.querySelectorAll('#civitaiKindRow [data-civitai-kind]').forEach(b =>
+ b.classList.toggle('active', b.dataset.civitaiKind === _civitaiKind));
+ _hfLoraPaint();
+}
+function _hfLoraPaint() {
+ const grid = document.getElementById('civitaiGrid');
+ const status = document.getElementById('civitaiStatus');
+ const withEx = !!(document.getElementById('civitaiWithExample') || {}).checked;
+ const items = _hfLoraItems.filter(it => (_civitaiKind === 'all' || (it.kind || 'other') === _civitaiKind) && (!withEx || it.preview_url));
+ renderCivitaiGrid(items, false);
+ const counts = {};
+ _hfLoraItems.forEach(it => { const k = it.kind || 'other'; counts[k] = (counts[k] || 0) + 1; });
+ document.querySelectorAll('#civitaiKindRow [data-civitai-kind]').forEach(b => {
+ const k = b.dataset.civitaiKind; const n = k === 'all' ? _hfLoraItems.length : (counts[k] || 0);
+ b.textContent = { all: 'All', character: 'Characters', style: 'Styles', motion: 'Motion', speed: 'Speed', other: 'Other' }[k] + (n ? ` · ${n}` : '');
+ });
+ if (_hfLoraItems.length && !items.length) {
+ grid.innerHTML = `<div class="hint">Nothing of that kind in these results${withEx ? ' with an example' : ''}. Try another filter or a different search.</div>`;
+ }
+ if (status) {
+ status.textContent = `${items.length} of ${_hfLoraItems.length} LoRAs on Hugging Face — a card plays the repo's own example when it has one. Read the repo before you install; Phosphene lists what matches, nothing more.`;
+ status.className = 'civitai-status-line';
+ }
+}
function civitaiSourceRowSync() {
const row = document.getElementById('civitaiSourceRow');
if (!row) return;
const show = _civitaiContext === 'video';
row.style.display = show ? 'flex' : 'none';
if (!show) _civitaiSource = 'civitai';
+ const kr = document.getElementById('civitaiKindRow');
+ if (kr) kr.style.display = (show && _civitaiSource === 'huggingface') ? 'flex' : 'none';
}
// Hugging Face source: the whole catalog for the lane comes at once (no
// paging), filtered by the query on the server.
@@ -1417,13 +1453,14 @@ async function _hfLoraSearch(grid, status, loadMore) {
status.className = 'civitai-status-line err';
return;
}
- renderCivitaiGrid(data.items, false);
+ _hfLoraItems = data.items || [];
loadMore.style.display = 'none';
- if ((data.items || []).length === 0) {
+ if (_hfLoraItems.length === 0) {
+ renderCivitaiGrid([], false);
grid.innerHTML = `<div class="hint">Nothing on Hugging Face for ${_civitaiFamily === 'h3' ? 'Hailuo H3' : 'LTX'}${q ? ` matching "${escapeHtml(q)}"` : ''}. Try a name, <code>author:someone</code>, or <code>owner/repo</code>.</div>`;
+ status.textContent = '';
} else {
- status.textContent = `${data.items.length} LoRA${data.items.length === 1 ? '' : 's'} on Hugging Face — a card plays the repo's own example when it has one. Read the repo before you install; Phosphene lists what matches, nothing more.`;
- status.className = 'civitai-status-line';
+ civitaiSetKind();
}
}
@@ -1867,7 +1904,7 @@ async function cancelDownload() {
// Inline handlers in the markup and the other files resolve these through
// the global scope; everything NOT listed here is private to this module.
Object.assign(globalThis, {
- civitaiSetSource, civitaiSourceRowSync,
+ civitaiSetSource, civitaiSourceRowSync, civitaiSetKind,
normalizeLivePreview, _liveStageMediaHeld, _showLiveReturnChip, _hideLiveStageChrome,
_restoreSelectedOutputAfterLive, _handoffLiveStageToOutput, returnToLiveRender, _renderLiveStageFrame,
renderLiveStage, renderNowPreview, stopEarly, markNoVoiceTouched,
diff --git a/webapp/js/queue.js b/webapp/js/queue.js
index 97d6975..8ff8ba1 100644
--- a/webapp/js/queue.js
+++ b/webapp/js/queue.js
@@ -2407,7 +2407,7 @@ async function poll() {
// destroy the last estimate one line before the seamless swap can use it.
if (stageMayAutoSelectOutput()) {
const visible = filteredMainOutputs();
- if (visible.length) selectOutput(visible[0].path);
+ if (visible.length) selectOutput(visible[0].path, { autoplay: false });
}
// If the saved filter (from localStorage) selects a kind that's not
// in /status's top-60, the carousel is empty on boot and the user
@@ -3059,6 +3059,12 @@ function stageMayAutoSelectOutput() {
}
function selectOutput(path, options) {
options = options || {};
+ // AUTOPLAY IS FOR A CLICK, NOT FOR BOOT. The stage selects the newest
+ // output on load and after every refresh or filter change; those used to
+ // build the player with `autoplay`, so the panel opened already playing
+ // the last clip, sound and all. A selection the person did not make shows
+ // the clip paused on its first frame; a click plays.
+ const autoplay = options.autoplay !== false;
activePath = path;
const _uev = (typeof window !== 'undefined') ? window.event : null;
const userSelected = !!(_uev && _uev.isTrusted);
@@ -3120,7 +3126,7 @@ function selectOutput(path, options) {
} else if (liveBackdrop) {
wrap.innerHTML =
`<img class="player-handoff-backdrop" src="${escapeHtml(liveBackdrop)}" alt="">` +
- `<video class="player-handoff-media" controls autoplay src="${escapeHtml(playerSrc)}"></video>`;
+ `<video class="player-handoff-media" controls${autoplay ? ' autoplay' : ''} src="${escapeHtml(playerSrc)}"></video>`;
const handoffVideo = wrap.querySelector('.player-handoff-media');
_wireStageMutePersistence(handoffVideo);
const revealFinished = () => {
@@ -3139,7 +3145,7 @@ function selectOutput(path, options) {
// settles; controls must never stay transparent forever.
setTimeout(revealFinished, 4000);
} else {
- wrap.innerHTML = `<video controls autoplay src="${escapeHtml(playerSrc)}"></video>`;
+ wrap.innerHTML = `<video controls${autoplay ? ' autoplay' : ''} src="${escapeHtml(playerSrc)}"></video>`;
_wireStageMutePersistence(wrap.querySelector('video'));
}
// Surface aspect adapts to actual media dimensions so vertical clips
diff --git a/webapp/style/panel.css b/webapp/style/panel.css
index ab0cf01..0a41e17 100644
--- a/webapp/style/panel.css
+++ b/webapp/style/panel.css
@@ -9989,3 +9989,14 @@
.sbe-track.is-ripple .sbe-clip.is-drag { box-shadow: 0 0 0 2px var(--warning), var(--shadow-2); }
.sbe-track.is-ripple::after { content: 'ripple · everything after slides'; position: absolute; right: 8px; top: 4px;
font-size: var(--fs-sm, 12px); color: var(--warning); pointer-events: none; z-index: 30; }
+
+/* ---- LoRA browser: one toolbar, compact controls ------------------------------- */
+.civitai-toolbar { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; margin: 6px 0 8px; }
+.civitai-seg { display: inline-flex; border: 1px solid var(--border-strong); border-radius: 999px; overflow: hidden; background: var(--panel); }
+.civitai-seg .pill-btn { border: 0; border-radius: 0; padding: 5px 12px; width: auto; flex: 0 0 auto; font-size: 12px; margin: 0; }
+.civitai-seg .pill-btn + .pill-btn { border-left: 1px solid var(--border); }
+.civitai-seg .pill-btn.active { background: var(--accent); color: #fff; }
+.civitai-chips { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; margin: 0 0 8px; }
+.civitai-chips .pill-btn { width: auto; flex: 0 0 auto; padding: 3px 9px; font-size: 11px; border-radius: 999px; margin: 0; }
+.civitai-chips .toggle-pill { margin-left: auto; }
+.civitai-toolbar .toggle-pill { margin-left: auto; }