Spaces:
Running on Zero
Running on Zero
Switch backend to native LTX-2 (ICLoraPipeline)
#2
by linoyts HF Staff - opened
- README.md +2 -2
- app.py +210 -95
- requirements.txt +9 -7
README.md
CHANGED
|
@@ -11,10 +11,10 @@ pinned: false
|
|
| 11 |
hardware: zero-a10g
|
| 12 |
short_description: Remove beards from video with an LTX-2.3 IC-LoRA
|
| 13 |
models:
|
| 14 |
-
-
|
| 15 |
- Lightricks/LTX-2.3-22b-IC-LoRA-Instant-Shave
|
| 16 |
---
|
| 17 |
|
| 18 |
# πͺ LTX-2.3 Beard Removal (Instant Shave)
|
| 19 |
Removes beard, mustache and stubble from a person in a video while preserving identity, expression and motion.
|
| 20 |
-
IC-LoRA on LTX-2.3 (
|
|
|
|
| 11 |
hardware: zero-a10g
|
| 12 |
short_description: Remove beards from video with an LTX-2.3 IC-LoRA
|
| 13 |
models:
|
| 14 |
+
- Lightricks/LTX-2.3
|
| 15 |
- Lightricks/LTX-2.3-22b-IC-LoRA-Instant-Shave
|
| 16 |
---
|
| 17 |
|
| 18 |
# πͺ LTX-2.3 Beard Removal (Instant Shave)
|
| 19 |
Removes beard, mustache and stubble from a person in a video while preserving identity, expression and motion.
|
| 20 |
+
IC-LoRA on LTX-2.3 (the native LTX-2 pipeline, 30 steps, guidance 4.0, STG, 25fps, `REMOVEBEARD` trigger).
|
app.py
CHANGED
|
@@ -1,50 +1,136 @@
|
|
| 1 |
import os
|
|
|
|
|
|
|
| 2 |
|
| 3 |
-
|
| 4 |
-
os.environ
|
|
|
|
| 5 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
import random
|
| 7 |
import tempfile
|
| 8 |
-
import threading
|
| 9 |
-
import time
|
| 10 |
|
| 11 |
import numpy as np
|
| 12 |
import imageio.v3 as iio
|
| 13 |
-
import
|
|
|
|
| 14 |
import torch
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
import gradio as gr
|
| 16 |
-
from
|
| 17 |
-
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
LORA_REPO = "Lightricks/LTX-2.3-22b-IC-LoRA-Instant-Shave"
|
| 28 |
LORA_FILE = "ltx-2.3-22b-ic-lora-instant-shave-0.9.safetensors"
|
| 29 |
LORA_SCALE = 1.0
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
GUIDANCE = 4.0
|
| 33 |
-
STG_BLOCKS = [29]
|
| 34 |
-
NEGATIVE = ("beard, mustache, facial hair, stubble, worst quality, "
|
| 35 |
-
"inconsistent motion, blurry, jittery, distorted")
|
| 36 |
-
MAX_SEED = np.iinfo(np.int32).max
|
| 37 |
-
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 38 |
-
|
| 39 |
RES_PRESETS = {"960Γ544 (recommended)": (960, 544), "768Γ448 (fast)": (768, 448)}
|
|
|
|
| 40 |
FRAME_CHOICES = [33, 49, 73, 97, 121]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
pipe.set_adapters("shave", LORA_SCALE)
|
| 48 |
|
| 49 |
|
| 50 |
def _src_fps(path, default=FPS):
|
|
@@ -54,85 +140,121 @@ def _src_fps(path, default=FPS):
|
|
| 54 |
return default
|
| 55 |
|
| 56 |
|
| 57 |
-
def
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
out = []
|
| 63 |
for i in range(num_frames):
|
| 64 |
-
idx = min(int(round(i / FPS *
|
| 65 |
-
|
| 66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
|
| 69 |
-
def _pick_resolution(
|
| 70 |
w, h = RES_PRESETS[preset]
|
| 71 |
-
|
| 72 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
return w, h
|
| 74 |
|
| 75 |
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
|
|
|
|
|
|
| 80 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
if
|
| 85 |
-
|
| 86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
|
| 88 |
|
| 89 |
def _duration(*args, **kwargs):
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
w, h = RES_PRESETS.get(preset, (960, 544))
|
| 93 |
-
per_frame = max(3.0, 3.0 * (w * h) / (768 * 448)) # 30 steps + CFG + STG (dev path)
|
| 94 |
-
return int(120 + int(num_frames) * per_frame)
|
| 95 |
|
| 96 |
|
| 97 |
@spaces.GPU(duration=_duration)
|
| 98 |
-
|
| 99 |
-
|
| 100 |
if video is None:
|
| 101 |
-
raise gr.Error("Please upload a video
|
| 102 |
-
if
|
| 103 |
-
|
| 104 |
-
seed = int(seed)
|
| 105 |
num_frames = int(num_frames)
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
width, height
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
spatio_temporal_guidance_blocks=STG_BLOCKS,
|
| 122 |
-
generator=torch.Generator(device="cuda").manual_seed(seed),
|
| 123 |
-
output_type="np", return_dict=False,
|
| 124 |
-
)
|
| 125 |
-
out_path = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False).name
|
| 126 |
-
_export(video_out[0], audio_out, out_path)
|
| 127 |
return out_path, seed
|
| 128 |
|
| 129 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
with gr.Blocks(title="LTX-2.3 Beard Removal") as demo:
|
| 131 |
gr.Markdown(
|
| 132 |
"# πͺ LTX-2.3 Beard Removal (Instant Shave)\n"
|
| 133 |
"Remove beard, mustache and stubble from a person in a video while preserving identity, expression and "
|
| 134 |
-
"motion. Using [LTX 2.3 Dev](https://huggingface.co/
|
| 135 |
-
"[Beard-Removal IC-LoRA](https://huggingface.co/Lightricks/LTX-2.3-22b-IC-LoRA-Instant-Shave)
|
| 136 |
)
|
| 137 |
with gr.Row():
|
| 138 |
with gr.Column():
|
|
@@ -144,29 +266,22 @@ with gr.Blocks(title="LTX-2.3 Beard Removal") as demo:
|
|
| 144 |
with gr.Accordion("Settings", open=False):
|
| 145 |
preset = gr.Dropdown(list(RES_PRESETS), value="960Γ544 (recommended)", label="Resolution")
|
| 146 |
num_frames = gr.Dropdown(FRAME_CHOICES, value=49, label="Frames (25fps)")
|
| 147 |
-
negative = gr.Textbox(NEGATIVE, label="Negative prompt", lines=2)
|
| 148 |
randomize = gr.Checkbox(True, label="Randomize seed")
|
| 149 |
seed = gr.Slider(0, MAX_SEED, value=42, step=1, label="Seed")
|
| 150 |
run = gr.Button("Remove beard", variant="primary")
|
| 151 |
with gr.Column():
|
| 152 |
video_out = gr.Video(label="Clean-shaven result")
|
| 153 |
|
| 154 |
-
run.click(shave, inputs=[video_in, prompt, preset, num_frames,
|
| 155 |
outputs=[video_out, seed])
|
| 156 |
|
| 157 |
gr.Examples(
|
| 158 |
examples=[
|
| 159 |
-
[
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
["examples/beard_2.mp4",
|
| 163 |
-
"the same man in a hooded jacket with a completely smooth, clean-shaven face β no beard, no stubble, bare skin along his jaw β standing outdoors at night, cool city lights and soft bokeh glowing behind him, the light catching the clean planes of his face; a cool night-time ambience with distant traffic and a soft breeze",
|
| 164 |
-
"960Γ544 (recommended)", 49, NEGATIVE, 42, False],
|
| 165 |
-
["examples/beard_3.mp4",
|
| 166 |
-
"the same man seen in profile with a completely smooth, clean-shaven face β no beard, no stubble, clean bare cheeks and jaw β smoking a pipe outdoors in a red jacket, a thin curl of smoke drifting past him; a gentle outdoor ambience, a soft breeze and faint distant birdsong",
|
| 167 |
-
"960Γ544 (recommended)", 49, NEGATIVE, 42, False],
|
| 168 |
],
|
| 169 |
-
inputs=[video_in, prompt, preset, num_frames,
|
| 170 |
outputs=[video_out, seed], fn=shave, cache_examples=True, cache_mode="lazy",
|
| 171 |
)
|
| 172 |
|
|
|
|
| 1 |
import os
|
| 2 |
+
import subprocess
|
| 3 |
+
import sys
|
| 4 |
|
| 5 |
+
# ZeroGPU: torch.compile / dynamo unsupported β disable before any torch import.
|
| 6 |
+
os.environ["TORCH_COMPILE_DISABLE"] = "1"
|
| 7 |
+
os.environ["TORCHDYNAMO_DISABLE"] = "1"
|
| 8 |
|
| 9 |
+
# memory-efficient attention
|
| 10 |
+
subprocess.run([sys.executable, "-m", "pip", "install", "xformers==0.0.32.post2", "--no-build-isolation"], check=False)
|
| 11 |
+
|
| 12 |
+
# --- clone + install the NATIVE LTX-2 codebase at the pinned commit the working ZeroGPU spaces use ---
|
| 13 |
+
LTX_REPO_URL = "https://github.com/Lightricks/LTX-2.git"
|
| 14 |
+
LTX_REPO_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "LTX-2")
|
| 15 |
+
LTX_COMMIT = "ae855f8538843825f9015a419cf4ba5edaf5eec2"
|
| 16 |
+
if not os.path.exists(LTX_REPO_DIR):
|
| 17 |
+
subprocess.run(["git", "clone", LTX_REPO_URL, LTX_REPO_DIR], check=True)
|
| 18 |
+
subprocess.run(["git", "-C", LTX_REPO_DIR, "checkout", LTX_COMMIT], check=True)
|
| 19 |
+
subprocess.run([sys.executable, "-m", "pip", "install", "--force-reinstall", "--no-deps",
|
| 20 |
+
"-e", os.path.join(LTX_REPO_DIR, "packages", "ltx-core"),
|
| 21 |
+
"-e", os.path.join(LTX_REPO_DIR, "packages", "ltx-pipelines")], check=True)
|
| 22 |
+
sys.path.insert(0, os.path.join(LTX_REPO_DIR, "packages", "ltx-pipelines", "src"))
|
| 23 |
+
sys.path.insert(0, os.path.join(LTX_REPO_DIR, "packages", "ltx-core", "src"))
|
| 24 |
+
|
| 25 |
+
import logging
|
| 26 |
import random
|
| 27 |
import tempfile
|
|
|
|
|
|
|
| 28 |
|
| 29 |
import numpy as np
|
| 30 |
import imageio.v3 as iio
|
| 31 |
+
from PIL import Image, ImageOps
|
| 32 |
+
|
| 33 |
import torch
|
| 34 |
+
torch._dynamo.config.suppress_errors = True
|
| 35 |
+
torch._dynamo.config.disable = True
|
| 36 |
+
|
| 37 |
+
import spaces
|
| 38 |
import gradio as gr
|
| 39 |
+
from huggingface_hub import hf_hub_download, snapshot_download
|
| 40 |
+
|
| 41 |
+
# Import LTX modules in the proven order β importing ltx_core.quantization/loader FIRST hits a
|
| 42 |
+
# circular import (fp8_cast <-> loader.fuse_loras). Importing the model modules first forces the
|
| 43 |
+
# correct init order (mirrors the working reference Space).
|
| 44 |
+
from ltx_core.model.video_vae import TilingConfig, get_video_chunks_number, decode_video as _vae_decode_video # noqa: F401
|
| 45 |
+
from ltx_core.model.upsampler import upsample_video as _upsample_video # noqa: F401
|
| 46 |
+
from ltx_core.model.audio_vae import encode_audio as _vae_encode_audio # noqa: F401
|
| 47 |
+
from ltx_core.quantization import QuantizationPolicy
|
| 48 |
+
from ltx_core.loader import LoraPathStrengthAndSDOps, LTXV_LORA_COMFY_RENAMING_MAP
|
| 49 |
+
from ltx_pipelines.ic_lora import ICLoraPipeline
|
| 50 |
+
from ltx_pipelines.utils.media_io import encode_video
|
| 51 |
|
| 52 |
+
# --- ZeroGPU loader patch -------------------------------------------------------------
|
| 53 |
+
# The native loader opens safetensors directly on the CUDA device
|
| 54 |
+
# (safe_open(path, device="cuda")), doing the host->device copy in safetensors' own C++
|
| 55 |
+
# (cudaMemcpy) β bypassing torch.Tensor.to, the call ZeroGPU patches to virtualise + pack
|
| 56 |
+
# weights at module scope. Result: "No CUDA GPUs are available" at startup, nothing packs.
|
| 57 |
+
# Patch it to open on CPU then move via torch.Tensor.to (ZeroGPU-virtualisable).
|
| 58 |
+
import safetensors as _safetensors
|
| 59 |
+
import ltx_core.loader.sft_loader as _sft
|
| 60 |
+
from ltx_core.loader.primitives import StateDict as _StateDict
|
| 61 |
|
| 62 |
+
def _zerogpu_safe_load(self, path, sd_ops, device=None):
|
| 63 |
+
device = device or torch.device("cpu")
|
| 64 |
+
sd, size, dtype = {}, 0, set()
|
| 65 |
+
model_paths = path if isinstance(path, list) else [path]
|
| 66 |
+
for shard_path in model_paths:
|
| 67 |
+
with _safetensors.safe_open(shard_path, framework="pt", device="cpu") as f:
|
| 68 |
+
for name in f.keys():
|
| 69 |
+
expected = name if sd_ops is None else sd_ops.apply_to_key(name)
|
| 70 |
+
if expected is None:
|
| 71 |
+
continue
|
| 72 |
+
value = f.get_tensor(name).to(device=device) # torch path -> ZeroGPU-virtualised
|
| 73 |
+
kvs = ((expected, value),)
|
| 74 |
+
if sd_ops is not None:
|
| 75 |
+
kvs = sd_ops.apply_to_key_value(expected, value)
|
| 76 |
+
for k, v in kvs:
|
| 77 |
+
size += v.nbytes
|
| 78 |
+
dtype.add(v.dtype)
|
| 79 |
+
sd[k] = v
|
| 80 |
+
return _StateDict(sd=sd, device=device, size=size, dtype=dtype)
|
| 81 |
+
|
| 82 |
+
_sft.SafetensorsStateDictLoader.load = _zerogpu_safe_load
|
| 83 |
+
print("[PATCH] safetensors loader -> CPU-open + torch.to (ZeroGPU-virtualisable)")
|
| 84 |
+
# --------------------------------------------------------------------------------------
|
| 85 |
+
|
| 86 |
+
# --- attention backend patch (FA3 crashes on Blackwell ZeroGPU; use xformers/SDPA) ---
|
| 87 |
+
import torch.nn.functional as F
|
| 88 |
+
from ltx_core.model.transformer import attention as _attn_mod
|
| 89 |
+
|
| 90 |
+
def _sdpa_as_mea(query, key, value, attn_bias=None, scale=None, **kwargs):
|
| 91 |
+
q, k, v = query.transpose(1, 2), key.transpose(1, 2), value.transpose(1, 2)
|
| 92 |
+
return F.scaled_dot_product_attention(q, k, v, scale=scale).transpose(1, 2)
|
| 93 |
+
|
| 94 |
+
# IMPORTANT (ZeroGPU): never query CUDA at module scope. SDPA works on every GPU (incl.
|
| 95 |
+
# Blackwell ZeroGPU, where FA3 crashes), so patch it unconditionally.
|
| 96 |
+
_attn_mod.memory_efficient_attention = _sdpa_as_mea
|
| 97 |
+
print("[ATTN] SDPA (patched at module scope, no CUDA query)")
|
| 98 |
+
|
| 99 |
+
logging.getLogger().setLevel(logging.INFO)
|
| 100 |
+
|
| 101 |
+
# =========================== PER-LORA CONFIG (colorize) ===========================
|
| 102 |
+
TITLE = "LTX-2.3 Beard Removal (native LTX-2)"
|
| 103 |
LORA_REPO = "Lightricks/LTX-2.3-22b-IC-LoRA-Instant-Shave"
|
| 104 |
LORA_FILE = "ltx-2.3-22b-ic-lora-instant-shave-0.9.safetensors"
|
| 105 |
LORA_SCALE = 1.0
|
| 106 |
+
SKIP_STAGE_2 = True
|
| 107 |
+
GRAYSCALE_REF = False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
RES_PRESETS = {"960Γ544 (recommended)": (960, 544), "768Γ448 (fast)": (768, 448)}
|
| 109 |
+
DEFAULT_PRESET = "960Γ544 (recommended)"
|
| 110 |
FRAME_CHOICES = [33, 49, 73, 97, 121]
|
| 111 |
+
DEFAULT_FRAMES = 49
|
| 112 |
+
|
| 113 |
+
def build_prompt(p):
|
| 114 |
+
return (
|
| 115 |
+
f"REMOVEBEARD {p.strip()}, completely smooth and clean-shaven face, bare skin, "
|
| 116 |
+
"no beard, no stubble, no facial hair; identity, expression, motion, lighting and scene unchanged."
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
EXAMPLES = [
|
| 120 |
+
["examples/beard_1.mp4",
|
| 121 |
+
"the same man with a completely smooth clean-shaven face, no beard or stubble, bare skin, relaxed expression in soft indoor light; a quiet room ambience",
|
| 122 |
+
"960Γ544 (recommended)", 49, 42, False],
|
| 123 |
+
["examples/beard_2.mp4",
|
| 124 |
+
"the same man in a hooded jacket with a completely smooth clean-shaven face, no beard or stubble, outdoors at night with city lights behind him; cool night ambience",
|
| 125 |
+
"960Γ544 (recommended)", 49, 42, False],
|
| 126 |
+
]
|
| 127 |
+
# =================================================================================
|
| 128 |
|
| 129 |
+
FPS = 25.0
|
| 130 |
+
MAX_SEED = np.iinfo(np.int32).max
|
| 131 |
+
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 132 |
+
LTX_MODEL_REPO = "Lightricks/LTX-2.3"
|
| 133 |
+
GEMMA_REPO = "google/gemma-3-12b-it-qat-q4_0-unquantized"
|
|
|
|
| 134 |
|
| 135 |
|
| 136 |
def _src_fps(path, default=FPS):
|
|
|
|
| 140 |
return default
|
| 141 |
|
| 142 |
|
| 143 |
+
def _prep_reference(path, width, height, num_frames):
|
| 144 |
+
"""Resample to 24fps, aspect-fit/crop to WxH, NF frames; (optionally grayscale); write temp mp4."""
|
| 145 |
+
vid = iio.imread(path, plugin="pyav")
|
| 146 |
+
src_fps = _src_fps(path)
|
| 147 |
+
n = len(vid)
|
| 148 |
out = []
|
| 149 |
for i in range(num_frames):
|
| 150 |
+
idx = min(int(round(i / FPS * src_fps)), n - 1)
|
| 151 |
+
im = Image.fromarray(vid[idx]).convert("RGB")
|
| 152 |
+
im = ImageOps.fit(im, (width, height), Image.LANCZOS)
|
| 153 |
+
if GRAYSCALE_REF:
|
| 154 |
+
im = im.convert("L").convert("RGB")
|
| 155 |
+
out.append(np.array(im))
|
| 156 |
+
tmp = tempfile.mktemp(suffix=".mp4")
|
| 157 |
+
iio.imwrite(tmp, np.stack(out), fps=FPS, plugin="pyav", codec="libx264")
|
| 158 |
+
return tmp
|
| 159 |
|
| 160 |
|
| 161 |
+
def _pick_resolution(path, preset):
|
| 162 |
w, h = RES_PRESETS[preset]
|
| 163 |
+
try:
|
| 164 |
+
f0 = iio.imread(path, plugin="pyav", index=0)
|
| 165 |
+
if f0.shape[0] > f0.shape[1]: # portrait
|
| 166 |
+
w, h = h, w
|
| 167 |
+
except Exception:
|
| 168 |
+
pass
|
| 169 |
return w, h
|
| 170 |
|
| 171 |
|
| 172 |
+
# --- Load native pipeline + IC-LoRA once at module scope (ZeroGPU packs weights here) ---
|
| 173 |
+
print("Downloading checkpointsβ¦")
|
| 174 |
+
checkpoint_path = hf_hub_download(LTX_MODEL_REPO, "ltx-2.3-22b-distilled-1.1.safetensors", token=HF_TOKEN)
|
| 175 |
+
spatial_upsampler_path = hf_hub_download(LTX_MODEL_REPO, "ltx-2.3-spatial-upscaler-x2-1.1.safetensors", token=HF_TOKEN)
|
| 176 |
+
gemma_root = snapshot_download(GEMMA_REPO, token=HF_TOKEN)
|
| 177 |
+
lora_path = hf_hub_download(LORA_REPO, LORA_FILE, token=HF_TOKEN)
|
| 178 |
|
| 179 |
+
print("Building ICLoraPipelineβ¦")
|
| 180 |
+
pipeline = ICLoraPipeline(
|
| 181 |
+
distilled_checkpoint_path=checkpoint_path,
|
| 182 |
+
spatial_upsampler_path=spatial_upsampler_path,
|
| 183 |
+
gemma_root=gemma_root,
|
| 184 |
+
loras=[LoraPathStrengthAndSDOps(lora_path, LORA_SCALE, LTXV_LORA_COMFY_RENAMING_MAP)],
|
| 185 |
+
# bf16 (NOT fp8): the IC-LoRA is fused into the transformer at MODULE SCOPE (the GPU
|
| 186 |
+
# worker can't re-open the checkpoint file). fp8_cast()'s fusion runs a custom CUDA kernel
|
| 187 |
+
# that can't be ZeroGPU-virtualised; the bf16 fuse rule is pure torch -> virtualisable.
|
| 188 |
+
quantization=None,
|
| 189 |
+
)
|
| 190 |
|
| 191 |
+
|
| 192 |
+
def _preload_pin(ledger, tag):
|
| 193 |
+
if ledger is None:
|
| 194 |
+
return
|
| 195 |
+
for name in ["transformer", "video_encoder", "video_decoder", "audio_encoder",
|
| 196 |
+
"audio_decoder", "vocoder", "spatial_upsampler", "text_encoder",
|
| 197 |
+
"gemma_embeddings_processor"]:
|
| 198 |
+
fn = getattr(ledger, name, None)
|
| 199 |
+
if callable(fn):
|
| 200 |
+
try:
|
| 201 |
+
obj = fn()
|
| 202 |
+
setattr(ledger, name, (lambda o=obj: o))
|
| 203 |
+
print(f"[preload {tag}] {name} β")
|
| 204 |
+
except Exception as e:
|
| 205 |
+
print(f"[preload {tag}] {name} skipped: {e}")
|
| 206 |
+
|
| 207 |
+
# Preload stage 1 always; preload stage 2 only when two-stage is used (skip_stage_2=False).
|
| 208 |
+
# Eagerly pinning both ledgers materializes TWO ~46GB transformers β too big for the ZeroGPU pack.
|
| 209 |
+
_preload_pin(getattr(pipeline, "stage_1_model_ledger", None), "stage1")
|
| 210 |
+
if not SKIP_STAGE_2:
|
| 211 |
+
_preload_pin(getattr(pipeline, "stage_2_model_ledger", None), "stage2")
|
| 212 |
+
print("Pipeline ready.")
|
| 213 |
|
| 214 |
|
| 215 |
def _duration(*args, **kwargs):
|
| 216 |
+
nf = next((a for a in args if isinstance(a, int) and a in FRAME_CHOICES), DEFAULT_FRAMES)
|
| 217 |
+
return int(60 + nf * 1.2)
|
|
|
|
|
|
|
|
|
|
| 218 |
|
| 219 |
|
| 220 |
@spaces.GPU(duration=_duration)
|
| 221 |
+
@torch.inference_mode()
|
| 222 |
+
def shave(video, prompt, preset, num_frames, seed, randomize, progress=gr.Progress(track_tqdm=True)):
|
| 223 |
if video is None:
|
| 224 |
+
raise gr.Error("Please upload a video.")
|
| 225 |
+
if not prompt.strip():
|
| 226 |
+
raise gr.Error("Describe the result (e.g. 'a brown rabbit on grey rocks, soft birdsong').")
|
| 227 |
+
seed = random.randint(0, MAX_SEED) if randomize else int(seed)
|
| 228 |
num_frames = int(num_frames)
|
| 229 |
+
width, height = _pick_resolution(video, preset)
|
| 230 |
+
ref_path = _prep_reference(video, width, height, num_frames)
|
| 231 |
+
tiling = TilingConfig.default()
|
| 232 |
+
# skip_stage_2 outputs at half the passed dims -> pass 2x so output matches the preset.
|
| 233 |
+
gen_w, gen_h = (width * 2, height * 2) if SKIP_STAGE_2 else (width, height)
|
| 234 |
+
video_out, audio_out = pipeline(
|
| 235 |
+
prompt=build_prompt(prompt),
|
| 236 |
+
seed=seed, height=gen_h, width=gen_w,
|
| 237 |
+
num_frames=num_frames, frame_rate=FPS,
|
| 238 |
+
images=[], video_conditioning=[(ref_path, 1.0)],
|
| 239 |
+
skip_stage_2=SKIP_STAGE_2, tiling_config=tiling,
|
| 240 |
+
)
|
| 241 |
+
out_path = tempfile.mktemp(suffix=".mp4")
|
| 242 |
+
encode_video(video=video_out, fps=FPS, audio=audio_out, output_path=out_path,
|
| 243 |
+
video_chunks_number=get_video_chunks_number(num_frames, tiling))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 244 |
return out_path, seed
|
| 245 |
|
| 246 |
|
| 247 |
+
# --- UI config (match the public Space exactly) ---
|
| 248 |
+
RES_PRESETS = {"960Γ544 (recommended)": (960, 544), "768Γ448 (fast)": (768, 448)}
|
| 249 |
+
FRAME_CHOICES = [33, 49, 73, 97, 121]
|
| 250 |
+
|
| 251 |
+
|
| 252 |
with gr.Blocks(title="LTX-2.3 Beard Removal") as demo:
|
| 253 |
gr.Markdown(
|
| 254 |
"# πͺ LTX-2.3 Beard Removal (Instant Shave)\n"
|
| 255 |
"Remove beard, mustache and stubble from a person in a video while preserving identity, expression and "
|
| 256 |
+
"motion. Using [LTX 2.3 Dev](https://huggingface.co/Lightricks/LTX-2.3) with the "
|
| 257 |
+
"[Beard-Removal IC-LoRA](https://huggingface.co/Lightricks/LTX-2.3-22b-IC-LoRA-Instant-Shave)."
|
| 258 |
)
|
| 259 |
with gr.Row():
|
| 260 |
with gr.Column():
|
|
|
|
| 266 |
with gr.Accordion("Settings", open=False):
|
| 267 |
preset = gr.Dropdown(list(RES_PRESETS), value="960Γ544 (recommended)", label="Resolution")
|
| 268 |
num_frames = gr.Dropdown(FRAME_CHOICES, value=49, label="Frames (25fps)")
|
|
|
|
| 269 |
randomize = gr.Checkbox(True, label="Randomize seed")
|
| 270 |
seed = gr.Slider(0, MAX_SEED, value=42, step=1, label="Seed")
|
| 271 |
run = gr.Button("Remove beard", variant="primary")
|
| 272 |
with gr.Column():
|
| 273 |
video_out = gr.Video(label="Clean-shaven result")
|
| 274 |
|
| 275 |
+
run.click(shave, inputs=[video_in, prompt, preset, num_frames, seed, randomize],
|
| 276 |
outputs=[video_out, seed])
|
| 277 |
|
| 278 |
gr.Examples(
|
| 279 |
examples=[
|
| 280 |
+
['examples/beard_1.mp4', 'the same man with a completely smooth, clean-shaven face β no beard, no mustache, no stubble, bare clear skin revealing his jawline and natural skin texture β a relaxed neutral expression in soft, even indoor light; a quiet, intimate room ambience', '960Γ544 (recommended)', 49, 42, False],
|
| 281 |
+
['examples/beard_2.mp4', 'the same man in a hooded jacket with a completely smooth, clean-shaven face β no beard, no stubble, bare skin along his jaw β standing outdoors at night, cool city lights and soft bokeh glowing behind him, the light catching the clean planes of his face; a cool night-time ambience with distant traffic and a soft breeze', '960Γ544 (recommended)', 49, 42, False],
|
| 282 |
+
['examples/beard_3.mp4', 'the same man seen in profile with a completely smooth, clean-shaven face β no beard, no stubble, clean bare cheeks and jaw β smoking a pipe outdoors in a red jacket, a thin curl of smoke drifting past him; a gentle outdoor ambience, a soft breeze and faint distant birdsong', '960Γ544 (recommended)', 49, 42, False],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 283 |
],
|
| 284 |
+
inputs=[video_in, prompt, preset, num_frames, seed, randomize],
|
| 285 |
outputs=[video_out, seed], fn=shave, cache_examples=True, cache_mode="lazy",
|
| 286 |
)
|
| 287 |
|
requirements.txt
CHANGED
|
@@ -1,9 +1,11 @@
|
|
| 1 |
-
|
| 2 |
-
transformers
|
| 3 |
accelerate
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
imageio-ffmpeg
|
| 9 |
av
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
transformers==4.57.6
|
|
|
|
| 2 |
accelerate
|
| 3 |
+
torch==2.8.0
|
| 4 |
+
torchaudio==2.8.0
|
| 5 |
+
einops
|
| 6 |
+
scipy
|
|
|
|
| 7 |
av
|
| 8 |
+
scikit-image>=0.25.2
|
| 9 |
+
flashpack==0.1.2
|
| 10 |
+
imageio[ffmpeg]
|
| 11 |
+
pillow
|