degen69 commited on
Commit
169bbff
·
verified ·
1 Parent(s): 7f16607

Upload folder using huggingface_hub

Browse files
README.md CHANGED
@@ -1,13 +1,17 @@
1
  ---
2
- title: BFS Video
3
- emoji: ⚡
4
  colorFrom: purple
5
- colorTo: purple
6
  sdk: gradio
7
- sdk_version: 6.31.0
8
- python_version: '3.12'
9
  app_file: app.py
10
- pinned: false
 
 
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
1
  ---
2
+ title: BFS Video — Best Face Swap
3
+ emoji: 🎭
4
  colorFrom: purple
5
+ colorTo: pink
6
  sdk: gradio
7
+ sdk_version: 5.50.0
 
8
  app_file: app.py
9
+ short_description: Swap the identity in any video (LTX-2.3 + BFS LoRA)
10
+ python_version: "3.12"
11
+ startup_duration_timeout: 60m
12
  ---
13
 
14
+ # BFS — Best Face Swap Video
15
+
16
+ Face/head-swap for video via LTX-2.3 and the BFS persistent-template LoRA.
17
+ Upload a guide video + a reference face, describe the shot, get a swapped video back.
__pycache__/app.cpython-312.pyc ADDED
Binary file (8.7 kB). View file
 
__pycache__/composer.cpython-312.pyc ADDED
Binary file (9.24 kB). View file
 
__pycache__/pipeline.cpython-312.pyc ADDED
Binary file (7.75 kB). View file
 
__pycache__/video_utils.cpython-312.pyc ADDED
Binary file (7.3 kB). View file
 
app.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ BFS — Best Face Swap Video · Hugging Face Space (ZeroGPU)
3
+
4
+ Swap the identity in any video using the V3 persistent-template technique.
5
+ The reference face is placed in a green chroma side-strip that persists across
6
+ all frames, giving the model continuous identity conditioning throughout generation.
7
+
8
+ Model: LTX-2.3 (22B) + BFS head-swap LoRA from degen69/BFS-Best-Face-Swap-Video
9
+ Hardware: ZeroGPU xlarge (96 GB)
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ # `import spaces` MUST come before torch / diffusers / anything that touches CUDA.
15
+ # It patches torch.cuda so the 22B model can load at startup rather than on GPU time.
16
+ import spaces
17
+
18
+ import os
19
+ import tempfile
20
+ import time
21
+
22
+ import gradio as gr
23
+ import numpy as np
24
+ from PIL import Image
25
+
26
+ from composer import compose_frames, crop_reserved_region
27
+ from pipeline import load_pipeline, run_inference
28
+ from video_utils import (
29
+ compute_target_size,
30
+ extract_audio,
31
+ frames_for_duration,
32
+ load_video_frames,
33
+ resize_frames,
34
+ save_video,
35
+ )
36
+
37
+ REGION_SIZE = 256
38
+ DEFAULT_FPS = 24.0
39
+ DEFAULT_DURATION = 5.0
40
+ DEFAULT_RESOLUTION = 768
41
+
42
+ # ---------------------------------------------------------------------------
43
+ # Load models once at startup (module scope). `spaces` packs the weights to
44
+ # disk; the GPU worker streams them into VRAM on each request.
45
+ # ---------------------------------------------------------------------------
46
+
47
+ print("[bfs] Loading pipeline at startup…", flush=True)
48
+ _PIPELINE_STATE = load_pipeline(device="cuda")
49
+ print("[bfs] Pipeline ready.", flush=True)
50
+
51
+
52
+ # ---------------------------------------------------------------------------
53
+ # Core processing function
54
+ # ---------------------------------------------------------------------------
55
+
56
+ def _estimate_duration(guide_video_path, face_image, prompt, duration, fps, lora_strength, seed, *args, **kwargs) -> int:
57
+ """Scale the GPU reservation with the requested video length."""
58
+ try:
59
+ secs = float(duration)
60
+ except (TypeError, ValueError):
61
+ secs = DEFAULT_DURATION
62
+ # ~60s base + ~45s per second of video, capped at 600 (ZeroGPU max).
63
+ return min(600, int(90 + secs * 45))
64
+
65
+
66
+ @spaces.GPU(duration=_estimate_duration, size="xlarge")
67
+ def generate(
68
+ guide_video_path: str,
69
+ face_image: Image.Image,
70
+ prompt: str,
71
+ duration: float,
72
+ fps: float,
73
+ lora_strength: float,
74
+ seed: float,
75
+ progress: gr.Progress = gr.Progress(track_tqdm=True),
76
+ ) -> tuple[str, str]:
77
+ """
78
+ Full head-swap pipeline:
79
+ 1. Load + resize guide video frames
80
+ 2. Compose chroma face strip (ReservedRegionFrameComposer)
81
+ 3. Run LTX-2.3 diffusion
82
+ 4. Crop face strip from output
83
+ 5. Mux original audio back in
84
+
85
+ Returns (output_video_path, status_message).
86
+ """
87
+ started = time.perf_counter()
88
+
89
+ # ---- validate inputs early ----
90
+ if guide_video_path is None:
91
+ return "", "Please upload a guide video."
92
+ if face_image is None:
93
+ return "", "Please upload a reference face image."
94
+ if not prompt.strip():
95
+ return "", "Please enter a text prompt."
96
+
97
+ progress(0.05, desc="Loading guide video…")
98
+ frames, source_fps = load_video_frames(guide_video_path)
99
+ if len(frames) == 0:
100
+ return "", "Could not read frames from the guide video."
101
+
102
+ # ---- extract audio before we do anything else ----
103
+ audio_tmp = tempfile.mktemp(suffix=".wav")
104
+ has_audio = extract_audio(guide_video_path, audio_tmp)
105
+
106
+ # ---- resize frames ----
107
+ progress(0.10, desc="Resizing frames…")
108
+ orig_h, orig_w = frames.shape[1], frames.shape[2]
109
+ target_w, target_h = compute_target_size(orig_w, orig_h, DEFAULT_RESOLUTION)
110
+ frames = resize_frames(frames, target_w, target_h)
111
+
112
+ # ---- trim / pad to requested duration ----
113
+ n_frames = frames_for_duration(fps, duration)
114
+ if len(frames) >= n_frames:
115
+ frames = frames[:n_frames]
116
+ else:
117
+ # loop last frame
118
+ pad = np.stack([frames[-1]] * (n_frames - len(frames)))
119
+ frames = np.concatenate([frames, pad], axis=0)
120
+
121
+ # ---- compose chroma strip ----
122
+ progress(0.15, desc="Compositing reference face strip…")
123
+ composed = compose_frames(
124
+ frames,
125
+ face_image,
126
+ region_position="left",
127
+ region_size_px=REGION_SIZE,
128
+ )
129
+
130
+ # ---- run diffusion ----
131
+ progress(0.20, desc="Running LTX-2.3 diffusion…")
132
+ generated = run_inference(
133
+ _PIPELINE_STATE,
134
+ composed,
135
+ prompt=prompt,
136
+ fps=fps,
137
+ lora_strength=lora_strength,
138
+ seed=int(seed),
139
+ progress_cb=lambda msg: progress(0.20, desc=msg),
140
+ )
141
+
142
+ # ---- crop face strip from output ----
143
+ progress(0.90, desc="Cropping reserved region…")
144
+ cropped = crop_reserved_region(
145
+ generated,
146
+ region_position="left",
147
+ region_size_px=REGION_SIZE,
148
+ output_size=(target_w, target_h),
149
+ )
150
+
151
+ # ---- save output video with audio ----
152
+ progress(0.95, desc="Encoding output video…")
153
+ out_path = tempfile.mktemp(suffix=".mp4")
154
+ save_video(
155
+ cropped,
156
+ fps=fps,
157
+ output_path=out_path,
158
+ audio_path=audio_tmp if has_audio else None,
159
+ audio_duration=duration,
160
+ )
161
+
162
+ elapsed = time.perf_counter() - started
163
+ progress(1.0, desc="Done.")
164
+ return out_path, f"Generation complete in {elapsed:.0f}s."
165
+
166
+
167
+ # ---------------------------------------------------------------------------
168
+ # Gradio UI
169
+ # ---------------------------------------------------------------------------
170
+
171
+ DESCRIPTION = """
172
+ # BFS — Best Face Swap Video
173
+
174
+ Swap the identity in any video using the **V3 persistent-template** technique.
175
+ The reference face is placed in a green chroma side-strip that persists across
176
+ all frames, giving the model continuous identity conditioning throughout generation.
177
+
178
+ **Prompt format:**
179
+ ```
180
+ head_swap:
181
+ FACE: Female, fair skin, ~25 years old, long wavy auburn hair, green eyes…
182
+ ACTION: A person in a grey hoodie walks toward the camera indoors…
183
+ ```
184
+ """
185
+
186
+ with gr.Blocks(title="BFS — Best Face Swap Video") as demo:
187
+ gr.Markdown(DESCRIPTION)
188
+
189
+ with gr.Row():
190
+ with gr.Column(scale=1):
191
+ guide_video = gr.Video(label="Guide Video", sources=["upload"])
192
+ face_image = gr.Image(label="Reference Face", type="pil", sources=["upload"])
193
+ prompt = gr.Textbox(
194
+ label="Text Prompt",
195
+ placeholder="head_swap:\nFACE: ...\nACTION: ...",
196
+ lines=6,
197
+ )
198
+
199
+ with gr.Accordion("Parameters", open=False):
200
+ duration = gr.Slider(1, 15, value=DEFAULT_DURATION, step=0.5, label="Duration (seconds)")
201
+ fps = gr.Slider(8, 30, value=DEFAULT_FPS, step=1.0, label="FPS")
202
+ lora_strength = gr.Slider(0.5, 1.5, value=1.2, step=0.05, label="Face Swap Strength")
203
+ seed = gr.Number(value=42, label="Seed", precision=0)
204
+
205
+ run_btn = gr.Button("Generate", variant="primary")
206
+
207
+ with gr.Column(scale=1):
208
+ output_video = gr.Video(label="Result", interactive=False)
209
+ status_text = gr.Textbox(label="Status", interactive=False)
210
+
211
+ run_btn.click(
212
+ fn=generate,
213
+ inputs=[guide_video, face_image, prompt, duration, fps, lora_strength, seed],
214
+ outputs=[output_video, status_text],
215
+ api_name="/generate",
216
+ )
217
+
218
+ gr.Markdown("""
219
+ ---
220
+ **Hardware:** ZeroGPU xlarge (96 GB) — billed to the viewer's own HF quota.
221
+ **Model:** [degen69/BFS-Best-Face-Swap-Video](https://huggingface.co/degen69/BFS-Best-Face-Swap-Video) · Built on [LTX-2.3](https://huggingface.co/Lightricks/LTX-2.3)
222
+ **License:** For research and professional VFX use only. You must have explicit consent for any likeness you process.
223
+ """)
224
+
225
+
226
+ if __name__ == "__main__":
227
+ demo.launch(mcp_server=True)
composer.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ReservedRegionFrameComposer — pure-Python port of the ComfyUI-BFSNodes node.
3
+
4
+ Adds a chroma-key side strip to every frame, placing the reference face inside
5
+ it so the LTX-2.3 model can use it as a persistent identity template throughout
6
+ generation. After generation, call crop_reserved_region() to remove the strip.
7
+ """
8
+
9
+ import math
10
+ from typing import Literal
11
+
12
+ import numpy as np
13
+ from PIL import Image
14
+
15
+
16
+ # ---------------------------------------------------------------------------
17
+ # Low-level helpers (ported from ComfyUI-BFSNodes/util.py)
18
+ # ---------------------------------------------------------------------------
19
+
20
+ def _fit_inside(src_w: int, src_h: int, max_w: int, max_h: int) -> tuple[int, int]:
21
+ if src_w <= 0 or src_h <= 0:
22
+ return 1, 1
23
+ scale = min(max_w / src_w, max_h / src_h)
24
+ return max(1, int(round(src_w * scale))), max(1, int(round(src_h * scale)))
25
+
26
+
27
+ def _aligned_offset(container: int, content: int, align: str) -> int:
28
+ if align == "start":
29
+ return 0
30
+ if align == "end":
31
+ return max(0, container - content)
32
+ return max(0, (container - content) // 2)
33
+
34
+
35
+ def _paste_with_alpha(dst: Image.Image, src: Image.Image, xy: tuple[int, int]) -> None:
36
+ if src.mode == "RGBA":
37
+ dst.paste(src, xy, src.split()[-1])
38
+ else:
39
+ dst.paste(src, xy)
40
+
41
+
42
+ def _add_padding(img: Image.Image, pad: int = 16) -> Image.Image:
43
+ canvas = Image.new("RGBA", (img.width + pad * 2, img.height + pad * 2), (255, 255, 255, 255))
44
+ canvas.paste(img.convert("RGBA"), (pad, pad))
45
+ return canvas
46
+
47
+
48
+ # ---------------------------------------------------------------------------
49
+ # Face layout helpers
50
+ # ---------------------------------------------------------------------------
51
+
52
+ def _layout_faces(
53
+ faces: list[Image.Image],
54
+ region_w: int,
55
+ region_h: int,
56
+ scale_pct: float,
57
+ padding: int,
58
+ gap: int,
59
+ stack: str,
60
+ align_main: str,
61
+ align_cross: str,
62
+ ) -> Image.Image:
63
+ """Composite all faces into a single region_w x region_h RGBA tile."""
64
+ canvas = Image.new("RGBA", (region_w, region_h), (0, 0, 0, 0))
65
+ if not faces:
66
+ return canvas
67
+
68
+ n = len(faces)
69
+ avail_w = region_w - 2 * padding
70
+ avail_h = region_h - 2 * padding
71
+
72
+ # Determine grid shape
73
+ if stack == "horizontal" or (stack == "auto" and region_w >= region_h):
74
+ cols, rows = n, 1
75
+ elif stack == "vertical" or (stack == "auto" and region_h > region_w):
76
+ cols, rows = 1, n
77
+ else: # grid
78
+ cols = math.ceil(math.sqrt(n))
79
+ rows = math.ceil(n / cols)
80
+
81
+ cell_w = max(1, (avail_w - gap * (cols - 1)) // cols)
82
+ cell_h = max(1, (avail_h - gap * (rows - 1)) // rows)
83
+
84
+ for i, face in enumerate(faces):
85
+ col, row = i % cols, i // cols
86
+ fw, fh = _fit_inside(face.width, face.height, int(cell_w * scale_pct / 100), int(cell_h * scale_pct / 100))
87
+ resized = face.resize((fw, fh), Image.LANCZOS)
88
+
89
+ cx = padding + col * (cell_w + gap) + _aligned_offset(cell_w, fw, align_cross)
90
+ cy = padding + row * (cell_h + gap) + _aligned_offset(cell_h, fh, align_main)
91
+ _paste_with_alpha(canvas, resized, (cx, cy))
92
+
93
+ return canvas
94
+
95
+
96
+ # ---------------------------------------------------------------------------
97
+ # Public API
98
+ # ---------------------------------------------------------------------------
99
+
100
+ def compose_frames(
101
+ frames: np.ndarray,
102
+ face_image: Image.Image,
103
+ region_position: Literal["left", "right", "top", "bottom"] = "left",
104
+ region_size_px: int = 256,
105
+ face_scale_pct: float = 100.0,
106
+ face_padding_px: int = 12,
107
+ face_gap_px: int = 12,
108
+ face_align_main: str = "center",
109
+ face_align_cross: str = "center",
110
+ chroma_rgb: tuple[int, int, int] = (0, 255, 0),
111
+ ) -> np.ndarray:
112
+ """
113
+ Args:
114
+ frames: uint8 numpy array [N, H, W, 3]
115
+ face_image: PIL Image — the reference face
116
+ region_*: strip geometry and face placement
117
+ chroma_rgb: background colour of the reserved strip
118
+
119
+ Returns:
120
+ uint8 numpy array [N, H, W, 3] with the chroma strip composited in.
121
+ The original content is shrunk to fill the remaining area; total
122
+ resolution is unchanged (matches the input WxH).
123
+ """
124
+ N, H, W, C = frames.shape
125
+ face_pil = _add_padding(face_image.convert("RGBA"), 16)
126
+
127
+ vertical = region_position in ("top", "bottom")
128
+ if vertical:
129
+ content_h = H - region_size_px
130
+ content_w = W
131
+ region_w, region_h = W, region_size_px
132
+ else:
133
+ content_w = W - region_size_px
134
+ content_h = H
135
+ region_w, region_h = region_size_px, H
136
+
137
+ # Pre-render the face tile (same for every frame)
138
+ face_tile = _layout_faces(
139
+ [face_pil],
140
+ region_w, region_h,
141
+ face_scale_pct, face_padding_px, face_gap_px,
142
+ "auto", face_align_main, face_align_cross,
143
+ )
144
+ chroma_bg = Image.new("RGB", (region_w, region_h), chroma_rgb)
145
+ chroma_bg.paste(face_tile, (0, 0), face_tile) # alpha-composite face onto chroma
146
+
147
+ out = np.empty_like(frames)
148
+
149
+ for i in range(N):
150
+ frame_pil = Image.fromarray(frames[i], "RGB")
151
+
152
+ # Resize original content to fit the non-reserved area
153
+ content_pil = frame_pil.resize((content_w, content_h), Image.LANCZOS)
154
+
155
+ # Build full-size canvas
156
+ canvas = Image.new("RGB", (W, H))
157
+ if region_position == "left":
158
+ canvas.paste(chroma_bg, (0, 0))
159
+ canvas.paste(content_pil, (region_size_px, 0))
160
+ elif region_position == "right":
161
+ canvas.paste(content_pil, (0, 0))
162
+ canvas.paste(chroma_bg, (content_w, 0))
163
+ elif region_position == "top":
164
+ canvas.paste(chroma_bg, (0, 0))
165
+ canvas.paste(content_pil, (0, region_size_px))
166
+ else: # bottom
167
+ canvas.paste(content_pil, (0, 0))
168
+ canvas.paste(chroma_bg, (0, content_h))
169
+
170
+ out[i] = np.array(canvas)
171
+
172
+ return out
173
+
174
+
175
+ def crop_reserved_region(
176
+ frames: np.ndarray,
177
+ region_position: Literal["left", "right", "top", "bottom"] = "left",
178
+ region_size_px: int = 256,
179
+ output_size: tuple[int, int] | None = None,
180
+ ) -> np.ndarray:
181
+ """
182
+ Remove the reserved strip from generated frames and resize back to
183
+ output_size (W, H). If output_size is None, resize to fill the full
184
+ original frame dimensions.
185
+
186
+ Args:
187
+ frames: uint8 [N, H, W, 3]
188
+ output_size: (W, H) to resize to after cropping, or None for original size
189
+
190
+ Returns:
191
+ uint8 [N, out_H, out_W, 3]
192
+ """
193
+ N, H, W, _ = frames.shape
194
+ target_w = output_size[0] if output_size else W
195
+ target_h = output_size[1] if output_size else H
196
+
197
+ if region_position == "left":
198
+ crop = frames[:, :, region_size_px:, :]
199
+ elif region_position == "right":
200
+ crop = frames[:, :, :W - region_size_px, :]
201
+ elif region_position == "top":
202
+ crop = frames[:, region_size_px:, :, :]
203
+ else: # bottom
204
+ crop = frames[:, :H - region_size_px, :, :]
205
+
206
+ if crop.shape[2] == target_w and crop.shape[1] == target_h:
207
+ return crop
208
+
209
+ out = np.empty((N, target_h, target_w, 3), dtype=np.uint8)
210
+ for i in range(N):
211
+ out[i] = np.array(Image.fromarray(crop[i]).resize((target_w, target_h), Image.LANCZOS))
212
+ return out
pipeline.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ LTX-2.3 inference pipeline for BFS head-swap (ZeroGPU-adapted).
3
+
4
+ Model sources:
5
+ Transformer : SulphurAI/Sulphur-2-base — sulphur_dev_fp8mixed.safetensors
6
+ Video VAE : Kijai/LTX2.3_comfy — vae/LTX23_video_vae_bf16.safetensors
7
+ Pipeline cfg: Lightricks/LTX-Video (text encoder, scheduler, tokenizer via from_pretrained)
8
+ LoRA distill: SulphurAI/Sulphur-2-base — distill_loras/ltx-2.3-22b-distilled-lora-1.1_fro90_ceil72_condsafe.safetensors
9
+ LoRA BFS : degen69/BFS-Best-Face-Swap-Video — ltx-2.3/head_swap_v3_rank_adaptive_fro_098.safetensors
10
+
11
+ ZeroGPU notes:
12
+ - `import spaces` must come before torch (done in app.py).
13
+ - Models are loaded at MODULE SCOPE with `.to("cuda")` so the `spaces`
14
+ pack step captures them. Do NOT lazy-load inside the GPU function.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import gc
20
+ import os
21
+ import tempfile
22
+ from pathlib import Path
23
+ from typing import Callable
24
+
25
+ import numpy as np
26
+ import torch
27
+ from huggingface_hub import hf_hub_download
28
+ from PIL import Image
29
+
30
+ # ---------------------------------------------------------------------------
31
+ # Model file specs
32
+ # ---------------------------------------------------------------------------
33
+
34
+ _HF_CACHE = os.environ.get("HF_HOME", os.path.expanduser("~/.cache/huggingface"))
35
+
36
+ MODELS = {
37
+ "transformer": ("SulphurAI/Sulphur-2-base", "sulphur_dev_fp8mixed.safetensors"),
38
+ "video_vae": ("Kijai/LTX2.3_comfy", "vae/LTX23_video_vae_bf16.safetensors"),
39
+ "lora_motion": ("SulphurAI/Sulphur-2-base", "distill_loras/ltx-2.3-22b-distilled-lora-1.1_fro90_ceil72_condsafe.safetensors"),
40
+ "lora_bfs": ("degen69/BFS-Best-Face-Swap-Video", "ltx-2.3/head_swap_v3_rank_adaptive_fro_098.safetensors"),
41
+ }
42
+
43
+ # Distilled sigmas from the workflow (BasicScheduler bong_tangent, 8 steps)
44
+ DISTILLED_SIGMAS = [1.0, 0.99375, 0.9875, 0.98125, 0.975, 0.909375, 0.725, 0.421875, 0.0]
45
+
46
+ NEGATIVE_PROMPT = (
47
+ "pc game, console game, video game, cartoon, childish, ugly, "
48
+ "artifacts, low resolution, blurry, jagged edges"
49
+ )
50
+
51
+
52
+ # ---------------------------------------------------------------------------
53
+ # Model download helpers
54
+ # ---------------------------------------------------------------------------
55
+
56
+ def _download(key: str, token: str | None = None) -> str:
57
+ repo, filename = MODELS[key]
58
+ return hf_hub_download(repo_id=repo, filename=filename, token=token)
59
+
60
+
61
+ def _maybe_download_all(
62
+ token: str | None = None,
63
+ progress_cb: Callable[[str], None] | None = None,
64
+ ) -> dict[str, str]:
65
+ paths = {}
66
+ for key in MODELS:
67
+ if progress_cb:
68
+ progress_cb(f"Downloading {key}…")
69
+ paths[key] = _download(key, token=token)
70
+ return paths
71
+
72
+
73
+ # ---------------------------------------------------------------------------
74
+ # Pipeline construction (called once at module scope)
75
+ # ---------------------------------------------------------------------------
76
+
77
+ def load_pipeline(
78
+ device: str = "cuda",
79
+ token: str | None = None,
80
+ progress_cb: Callable[[str], None] | None = None,
81
+ ) -> dict:
82
+ """
83
+ Download (if needed) and load all model components.
84
+ Returns a dict of loaded objects cached for reuse.
85
+
86
+ LoRAs are loaded but NOT fused so that lora_strength can be adjusted
87
+ per-request in run_inference() via set_adapters().
88
+ """
89
+ from diffusers import (
90
+ AutoencoderKLLTXVideo,
91
+ LTXImageToVideoPipeline,
92
+ LTXVideoTransformer3DModel,
93
+ )
94
+
95
+ # All three model repos are public; only pass a token if the caller
96
+ # supplied one (e.g. via the HF_TOKEN Space secret).
97
+ effective_token = token or os.environ.get("HF_TOKEN") or None
98
+ paths = _maybe_download_all(token=effective_token, progress_cb=progress_cb)
99
+
100
+ if progress_cb:
101
+ progress_cb("Loading transformer…")
102
+ # fp8_e4m3fn weights are loaded into bfloat16 compute precision to maximise
103
+ # diffusers compatibility; the weight file on disk is fp8-quantised.
104
+ transformer = LTXVideoTransformer3DModel.from_single_file(
105
+ paths["transformer"],
106
+ torch_dtype=torch.bfloat16,
107
+ ).to(device)
108
+
109
+ if progress_cb:
110
+ progress_cb("Loading video VAE…")
111
+ video_vae = AutoencoderKLLTXVideo.from_single_file(
112
+ paths["video_vae"],
113
+ torch_dtype=torch.bfloat16,
114
+ ).to(device)
115
+
116
+ if progress_cb:
117
+ progress_cb("Building pipeline…")
118
+ pipe = LTXImageToVideoPipeline.from_pretrained(
119
+ "Lightricks/LTX-Video",
120
+ transformer=transformer,
121
+ vae=video_vae,
122
+ torch_dtype=torch.bfloat16,
123
+ token=effective_token,
124
+ ).to(device)
125
+
126
+ if progress_cb:
127
+ progress_cb("Loading LoRAs…")
128
+ pipe.load_lora_weights(paths["lora_motion"], adapter_name="motion")
129
+ pipe.load_lora_weights(paths["lora_bfs"], adapter_name="bfs")
130
+ # Default weights — overridden per-request in run_inference()
131
+ pipe.set_adapters(["motion", "bfs"], adapter_weights=[1.0, 1.0])
132
+
133
+ return {"pipe": pipe, "device": device}
134
+
135
+
136
+ # ---------------------------------------------------------------------------
137
+ # Inference
138
+ # ---------------------------------------------------------------------------
139
+
140
+ def run_inference(
141
+ state: dict,
142
+ composed_frames: np.ndarray,
143
+ prompt: str,
144
+ fps: float = 24.0,
145
+ lora_strength: float = 1.0,
146
+ seed: int = 42,
147
+ num_inference_steps: int = 8,
148
+ guidance_scale: float = 1.0,
149
+ region_size_px: int = 256,
150
+ progress_cb: Callable[[str], None] | None = None,
151
+ ) -> np.ndarray:
152
+ """
153
+ Run LTX-2.3 image-to-video inference on the composed frames.
154
+
155
+ Args:
156
+ state: dict returned by load_pipeline()
157
+ composed_frames: uint8 [N, H, W, 3] with chroma strip added
158
+ prompt: text prompt (head_swap: format)
159
+ fps: target frame rate
160
+ lora_strength: multiplier applied on top of default LoRA weights
161
+ seed: RNG seed
162
+ region_size_px: strip width to set guide frame crop
163
+
164
+ Returns:
165
+ uint8 [N, H, W, 3] — generated frames (strip still present, call
166
+ composer.crop_reserved_region() to remove it)
167
+ """
168
+ pipe = state["pipe"]
169
+ device = state["device"]
170
+
171
+ N, H, W, _ = composed_frames.shape
172
+ first_frame = Image.fromarray(composed_frames[0])
173
+
174
+ # Always set adapter weights — LoRAs are not fused, so strength is dynamic.
175
+ # motion LoRA is kept at 1.0; only the BFS identity LoRA is user-adjustable.
176
+ pipe.set_adapters(["motion", "bfs"], adapter_weights=[1.0, lora_strength])
177
+
178
+ generator = torch.Generator(device=device).manual_seed(seed)
179
+
180
+ if progress_cb:
181
+ progress_cb("Running diffusion…")
182
+
183
+ with torch.inference_mode():
184
+ result = pipe(
185
+ image=first_frame,
186
+ prompt=prompt,
187
+ negative_prompt=NEGATIVE_PROMPT,
188
+ width=W,
189
+ height=H,
190
+ num_frames=N,
191
+ frame_rate=fps,
192
+ guidance_scale=guidance_scale,
193
+ num_inference_steps=num_inference_steps,
194
+ generator=generator,
195
+ decode_timestep=0.05,
196
+ decode_noise_scale=0.025,
197
+ output_type="pt",
198
+ )
199
+
200
+ # result.frames is [1, N, C, H, W] float in [0,1]
201
+ frames_pt = result.frames[0] # [N, C, H, W]
202
+ frames_np = (frames_pt.permute(0, 2, 3, 1).cpu().float().numpy() * 255).clip(0, 255).astype(np.uint8)
203
+
204
+ gc.collect()
205
+ if torch.cuda.is_available():
206
+ torch.cuda.empty_cache()
207
+
208
+ return frames_np
requirements.txt ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ torch
2
+ torchvision
3
+ torchaudio
4
+ diffusers>=0.32.0
5
+ transformers>=4.50.0
6
+ accelerate>=1.0.0
7
+ safetensors>=0.4.0
8
+ opencv-python-headless
9
+ pillow>=10.0.0
10
+ numpy>=1.24.0
11
+ ffmpeg-python
12
+ imageio
13
+ imageio-ffmpeg
14
+ decord
15
+ einops
16
+ kornia
17
+ audioop-lts
video_utils.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Video I/O utilities: load frames + audio from a video file, save frames back
3
+ to video with audio, and trim audio to match video duration.
4
+ """
5
+
6
+ import os
7
+ import subprocess
8
+ import tempfile
9
+ from pathlib import Path
10
+
11
+ import numpy as np
12
+ from PIL import Image
13
+
14
+
15
+ # ---------------------------------------------------------------------------
16
+ # Loading
17
+ # ---------------------------------------------------------------------------
18
+
19
+ def load_video_frames(
20
+ path: str,
21
+ fps: float = 24.0,
22
+ max_frames: int | None = None,
23
+ ) -> tuple[np.ndarray, float]:
24
+ """
25
+ Decode video frames to a uint8 numpy array [N, H, W, 3].
26
+
27
+ Returns (frames, actual_fps).
28
+ Uses decord when available; falls back to opencv.
29
+ """
30
+ try:
31
+ import decord
32
+ decord.bridge.set_bridge("native")
33
+ vr = decord.VideoReader(path, ctx=decord.cpu(0))
34
+ actual_fps = float(vr.get_avg_fps())
35
+ total = len(vr)
36
+ if max_frames is not None:
37
+ total = min(total, max_frames)
38
+ indices = list(range(total))
39
+ frames = vr.get_batch(indices).asnumpy() # [N, H, W, 3]
40
+ return frames, actual_fps
41
+ except ImportError:
42
+ pass
43
+
44
+ import cv2
45
+ cap = cv2.VideoCapture(path)
46
+ actual_fps = cap.get(cv2.CAP_PROP_FPS) or fps
47
+ frames = []
48
+ while True:
49
+ ret, frame = cap.read()
50
+ if not ret:
51
+ break
52
+ frames.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
53
+ if max_frames is not None and len(frames) >= max_frames:
54
+ break
55
+ cap.release()
56
+ return np.stack(frames, axis=0), actual_fps
57
+
58
+
59
+ def extract_audio(video_path: str, output_path: str) -> bool:
60
+ """Extract audio track from video to a WAV file. Returns False if no audio."""
61
+ result = subprocess.run(
62
+ [
63
+ "ffprobe", "-v", "quiet", "-select_streams", "a",
64
+ "-show_entries", "stream=codec_type",
65
+ "-of", "csv=p=0", video_path,
66
+ ],
67
+ capture_output=True, text=True,
68
+ )
69
+ if "audio" not in result.stdout:
70
+ return False
71
+
72
+ subprocess.run(
73
+ [
74
+ "ffmpeg", "-y", "-i", video_path,
75
+ "-vn", "-acodec", "pcm_s16le",
76
+ "-ar", "44100", "-ac", "2", output_path,
77
+ ],
78
+ capture_output=True, check=True,
79
+ )
80
+ return True
81
+
82
+
83
+ # ---------------------------------------------------------------------------
84
+ # Saving
85
+ # ---------------------------------------------------------------------------
86
+
87
+ def save_video(
88
+ frames: np.ndarray,
89
+ fps: float,
90
+ output_path: str,
91
+ audio_path: str | None = None,
92
+ audio_duration: float | None = None,
93
+ crf: int = 19,
94
+ ) -> str:
95
+ """
96
+ Encode frames [N, H, W, 3] uint8 to an mp4 file.
97
+ Optionally mux audio_path (trimmed to audio_duration seconds if provided).
98
+
99
+ Returns the path to the written file.
100
+ """
101
+ N, H, W, _ = frames.shape
102
+ tmp_video = output_path + ".noaudio.mp4"
103
+
104
+ # Write raw video with ffmpeg via stdin pipe
105
+ cmd = [
106
+ "ffmpeg", "-y",
107
+ "-f", "rawvideo",
108
+ "-vcodec", "rawvideo",
109
+ "-s", f"{W}x{H}",
110
+ "-pix_fmt", "rgb24",
111
+ "-r", str(fps),
112
+ "-i", "pipe:0",
113
+ "-vcodec", "libx264",
114
+ "-pix_fmt", "yuv420p",
115
+ "-crf", str(crf),
116
+ "-preset", "fast",
117
+ tmp_video,
118
+ ]
119
+ proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
120
+ for frame in frames:
121
+ proc.stdin.write(frame.tobytes())
122
+ proc.stdin.close()
123
+ proc.wait()
124
+
125
+ if audio_path and os.path.exists(audio_path):
126
+ duration_flag = ["-t", str(audio_duration)] if audio_duration else []
127
+ subprocess.run(
128
+ [
129
+ "ffmpeg", "-y",
130
+ "-i", tmp_video,
131
+ "-i", audio_path,
132
+ *duration_flag,
133
+ "-c:v", "copy",
134
+ "-c:a", "aac", "-b:a", "192k",
135
+ "-shortest",
136
+ output_path,
137
+ ],
138
+ capture_output=True, check=True,
139
+ )
140
+ os.remove(tmp_video)
141
+ else:
142
+ os.rename(tmp_video, output_path)
143
+
144
+ return output_path
145
+
146
+
147
+ # ---------------------------------------------------------------------------
148
+ # Resolution helpers
149
+ # ---------------------------------------------------------------------------
150
+
151
+ def align_to(value: int, multiple: int = 32) -> int:
152
+ """Round value up to the nearest multiple."""
153
+ return ((value + multiple - 1) // multiple) * multiple
154
+
155
+
156
+ def compute_target_size(
157
+ orig_w: int,
158
+ orig_h: int,
159
+ base_resolution: int = 768,
160
+ multiple: int = 32,
161
+ ) -> tuple[int, int]:
162
+ """
163
+ Scale the longer edge to base_resolution, preserving aspect ratio,
164
+ then align both dimensions to `multiple`.
165
+ """
166
+ scale = base_resolution / max(orig_w, orig_h)
167
+ new_w = align_to(int(orig_w * scale), multiple)
168
+ new_h = align_to(int(orig_h * scale), multiple)
169
+ return new_w, new_h
170
+
171
+
172
+ def resize_frames(frames: np.ndarray, target_w: int, target_h: int) -> np.ndarray:
173
+ """Resize [N, H, W, 3] frames to target_w x target_h."""
174
+ if frames.shape[2] == target_w and frames.shape[1] == target_h:
175
+ return frames
176
+ out = np.empty((len(frames), target_h, target_w, 3), dtype=np.uint8)
177
+ for i, f in enumerate(frames):
178
+ out[i] = np.array(Image.fromarray(f).resize((target_w, target_h), Image.LANCZOS))
179
+ return out
180
+
181
+
182
+ def frames_for_duration(fps: float, duration: float) -> int:
183
+ """Return frame count aligned to LTX-2.3 requirements: ((n * fps) // 8) * 8 + 1."""
184
+ raw = int(duration * fps)
185
+ return ((raw // 8) * 8) + 1