Upload app.py
Browse files51 unmodified lines525354555657585556575859606162636465666768697071727374757677787980818283848586878889251 unmodified lines3413423433163443453463475 unmodified lines35335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942032842142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047133747247347447513 unmodified lines48949049149249349449549649749849950035750150250350462 unmodified lines56756856942642742842957057157257357457557657757857958058158258358458558658758858959029 unmodified lines620621622465623624625626265 unmodified lines89289389489589673773889789889990090151 unmodified lines)MOTION_LORA_SCALE = float(os.environ.get("H3_MOTION_LORA_SCALE", "1.0"))
HMCUMSHOT_REPO = os.environ.get("H3_HMCUMSHOT_REPO", "Hearmeman/minimax-h3-loras")HMCUMSHOT_FILE = os.environ.get("H3_HMCUMSHOT_FILE", "HMCumshot_V1.0.safetensors")HMCUMSHOT_SCALE = float(os.environ.get("H3_HMCUMSHOT_SCALE", "1.0"))HMCUMSHOT_TRIGGER = os.environ.get("H3_HMCUMSHOT_TRIGGER", "cumshot")# Realism / anatomy LoRAs. These are folded after FlashGen and the existing# Motion Enhancer, using the same extra-LoRA merge path below.REALISM_LORA_REPO = os.environ.get( "H3_REALISM_LORA_REPO", "fal/MiniMax-H3-Realism-People-LoRA",)REALISM_LORA_FILE = os.environ.get( "H3_REALISM_LORA_FILE", "h3-realism-people-t2v-i2v-r2v.safetensors",)REALISM_LORA_SCALE = float(os.environ.get("H3_REALISM_LORA_SCALE", "0.8"))REALISM_LORA_TRIGGER = "r34l1sm"
# Polyhedron: Perfect Eyes / Perfect Skin / Perfect Hands. The Civitai model# has multiple versions, so the loader resolves the current version/file at# startup instead of hard-coding a version ID that may become stale.DETAIL_LORA_REPO = os.environ.get("H3_DETAIL_LORA_REPO", "civitai-model://2899220")DETAIL_LORA_FILE = os.environ.get( "H3_DETAIL_LORA_FILE", "polyhedron_minimax_h3_image_lora_v2__perfe8ct.safetensors",)DETAIL_LORA_SCALE = float(os.environ.get("H3_DETAIL_LORA_SCALE", "0.7"))
BLOWJOB_LORA_REPO = os.environ.get( "H3_BLOWJOB_LORA_REPO", "iamgroot1212/minimax-h3-loras",)BLOWJOB_LORA_FILE = os.environ.get( "H3_BLOWJOB_LORA_FILE", "MMH3-Hybrid-BlowJob-lora.safetensors",)BLOWJOB_LORA_SCALE = float(os.environ.get("H3_BLOWJOB_LORA_SCALE", "1.0"))
CONDITIONER_SPACE = os.environ.get("H3_CONDITIONER", "multimodalart/qwen3vl-conditioner")# ``pack`` places the transformer at startup (66 GB on disk via the spaces pack); VAEs move on first GPU call.251 unmodified lines# These are folded after FlashGen, so the original 4-step FlashGen schedule and# all of its QKV/layout handling remain unchanged. The extra adapters use the# standard .lora_A.weight/.lora_B.weight export used by the motion-enhancer and# HMCumshot checkpoints.# additional H3 checkpoints.
def _apply_extra_lora( transformer,5 unmodified lines from huggingface_hub import hf_hub_download from safetensors.torch import load_file
if repo_id.startswith("civitai-model://"): # Resolve a Civitai model page to its newest model version, then use # the same streaming downloader as the explicit civitai://version-id # path. This keeps the Space independent of a hard-coded version ID. import requests model_id = repo_id.removeprefix("civitai-model://") api_url = f"https://civitai.com/api/v1/models/{model_id}" metadata = requests.get(api_url, timeout=30).json() versions = metadata.get("modelVersions") or [] if not versions: raise ValueError(f"{label}: Civitai model {model_id} has no model versions") version = versions[0] model_version_id = str(version["id"]) files = [f for f in (version.get("files") or []) if str(f.get("name", "")).lower().endswith(".safetensors")] if not files: raise ValueError(f"{label}: Civitai version {model_version_id} has no .safetensors file") # Prefer the requested filename when it exists; otherwise use the first # safetensors file exposed by the current version. selected = next((f for f in files if f.get("name") == filename), files[0]) filename = os.path.basename(selected["name"]) download_url = selected.get("downloadUrl") or f"https://civitai.com/api/download/models/{model_version_id}" cache_dir = os.path.join(tempfile.gettempdir(), "h3-lora-cache") os.makedirs(cache_dir, exist_ok=True) path = os.path.join(cache_dir, filename) if not os.path.isfile(path) or os.path.getsize(path) == 0: tmp_path = f"{path}.part" with requests.get(download_url, stream=True, timeout=120, allow_redirects=True) as response: response.raise_for_status() with open(tmp_path, "wb") as handle: for chunk in response.iter_content(chunk_size=8 * 1024 * 1024): if chunk: handle.write(chunk) os.replace(tmp_path, path) elif repo_id.startswith("civitai://"): import requests model_version_id = repo_id.removeprefix("civitai://") download_url = f"https://civitai.com/api/download/models/{model_version_id}" cache_dir = os.path.join(tempfile.gettempdir(), "h3-lora-cache") os.makedirs(cache_dir, exist_ok=True) path = os.path.join(cache_dir, filename) if not os.path.isfile(path) or os.path.getsize(path) == 0: tmp_path = f"{path}.part" with requests.get(download_url, stream=True, timeout=120, allow_redirects=True) as response: response.raise_for_status() with open(tmp_path, "wb") as handle: for chunk in response.iter_content(chunk_size=8 * 1024 * 1024): if chunk: handle.write(chunk) os.replace(tmp_path, path) elif repo_id == "aronzhan/H3-Loras-bucket": import requests bucket_url = f"https://huggingface.co/buckets/{repo_id}/resolve/{filename}" cache_dir = os.path.join(tempfile.gettempdir(), "h3-lora-cache") os.makedirs(cache_dir, exist_ok=True) path = os.path.join(cache_dir, filename) if not os.path.isfile(path) or os.path.getsize(path) == 0: tmp_path = f"{path}.part" with requests.get(bucket_url, stream=True, timeout=60, allow_redirects=True) as response: response.raise_for_status() with open(tmp_path, "wb") as handle: for chunk in response.iter_content(chunk_size=8 * 1024 * 1024): if chunk: handle.write(chunk) os.replace(tmp_path, path) else: path = hf_hub_download(repo_id, filename) path = hf_hub_download(repo_id, filename)
lora = load_file(path, device="cpu")
normalized = {} for key, tensor in lora.items(): k = key if k.startswith("lora_unet__"): k = k.replace("lora_unet__", "", 1) k = k.replace("_blocks_", ".blocks.") k = k.replace("_self_attn_", ".attn.") k = k.replace("_ffn_net_0_proj", ".mlp.fc1") k = k.replace("_ffn_net_2", ".mlp.fc2") k = k.replace("to_out_0", "out_proj") elif k.startswith("lora_unet_"): body = k[len("lora_unet_"):] parts = body.split(".") head = parts[0].split("_") out = [] i = 0 while i < len(head): if head[i] == "blocks" and i + 1 < len(head) and head[i + 1].isdigit(): out += ["blocks", head[i + 1]] i += 2 continue if head[i] == "self" and i + 1 < len(head) and head[i + 1] == "attn": out.append("attn") i += 2 continue out.append(head[i]) i += 1 k = ".".join(out + parts[1:]) for prefix in ("base_model.model.", "diffusion_model.", "transformer.", "pipe.dit."): if k.startswith(prefix): k = k[len(prefix):] k = k.replace(".self_attn.", ".attn.") k = k.replace(".ffn.0.", ".mlp.fc1.") k = k.replace(".ffn.2.", ".mlp.fc2.") k = k.replace(".lora_down.weight", ".lora_A.weight") k = k.replace(".lora_up.weight", ".lora_B.weight") k = k.replace(".lora_A.default.weight", ".lora_A.weight") k = k.replace(".lora_B.default.weight", ".lora_B.weight") normalized[k] = tensor lora = normalized suffix_a = ".lora_A.weight" suffix_b = ".lora_B.weight" bases = sorted( {key[: -len(suffix_a)] for key in lora if key.endswith(suffix_a)} ) if not bases: sample = list(lora.keys())[:5] raise ValueError(f"{label}: no lora_A/lora_B pairs found") raise ValueError(f"{label}: no lora_A/lora_B pairs found; keys: {sample}")
params = dict(transformer.named_parameters()) num_heads = transformer.config.num_attention_heads13 unmodified lines source_name = name.removeprefix("diffusion_model.") target_name = _lora_target_name(source_name)
# ComfyUI H3 LoRAs may store q/k/v as separate targets. The # diffusers H3 transformer used by this Space has separate to_q/k/v # parameters, so those can be folded directly. if target_name.endswith((".attn.q", ".attn.k", ".attn.v")): kind = target_name.rsplit(".", 1)[-1] target_parts = [( target_name.replace(f".attn.{kind}", f".attn.to_{kind}") + ".weight", b, )] if target_name.endswith(".attn.qkv_proj"): elif target_name.endswith(".attn.qkv_proj"): prefix = target_name.removesuffix("qkv_proj") rows = _reorder_interleaved_qkv(b, num_heads, head_dim) targets = zip(62 unmodified lines ), _apply_extra_lora( transformer, HMCUMSHOT_REPO, HMCUMSHOT_FILE, "HMCumshot LoRA", HMCUMSHOT_SCALE, REALISM_LORA_REPO, REALISM_LORA_FILE, "H3 Realism People LoRA", REALISM_LORA_SCALE, ), _apply_extra_lora( transformer, DETAIL_LORA_REPO, DETAIL_LORA_FILE, "Perfect Eyes / Skin / Hands LoRA", DETAIL_LORA_SCALE, ), _apply_extra_lora( transformer, BLOWJOB_LORA_REPO, BLOWJOB_LORA_FILE, "MiniMax H3 BlowJob LoRA", BLOWJOB_LORA_SCALE, ), ]
29 unmodified lines lora_status = load_and_apply_lora(pipe.transformer) print(f"[gen] {lora_status}", flush=True)
# Then fold the requested Motion Enhancer and HMCumshot LoRAs into the # Then fold the requested Motion Enhancer and BlowJob LoRA into the # same transformer. They add their deltas on top of FlashGen. for extra_status in load_and_apply_extra_loras(pipe.transformer): print(f"[gen] {extra_status}", flush=True)265 unmodified lines progress(0.0, desc="Enhancing the prompt, then encoding ..." if enhance_prompt else "Encoding prompt ...") conditioned = time.time() condition_prompt = prompt # Realism People was trained with the `r34l1sm` trigger. Keep it hidden # from the UI while ensuring the adapter receives its intended trigger. if HMCUMSHOT_TRIGGER.lower() not in condition_prompt.lower(): condition_prompt = f"{HMCUMSHOT_TRIGGER}. {condition_prompt}" if REALISM_LORA_TRIGGER.lower() not in condition_prompt.lower(): condition_prompt = f"{REALISM_LORA_TRIGGER}, {condition_prompt}"
prompt_embeds, text_token_tags, metadata, plan = encode_remote( condition_prompt,app.py+175-15