File size: 10,735 Bytes
1246043
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3bbf2e8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
"""BFS Video Studio: LTX-2.3 + BFS V3 rank-64 on Hugging Face ZeroGPU."""
from __future__ import annotations

import os
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
os.environ.setdefault("TORCH_COMPILE_DISABLE", "1")
os.environ.setdefault("TORCHDYNAMO_DISABLE", "1")

import spaces  # Must precede torch and all CUDA-aware imports.
import sys
import json
import logging
import secrets
import tempfile
import time
from contextlib import nullcontext
from pathlib import Path

ROOT = Path(__file__).parent
for package in ("ltx-core", "ltx-pipelines"):
    sys.path.insert(0, str(ROOT / "packages" / package / "src"))

import torch
import gradio as gr
from huggingface_hub import hf_hub_download, snapshot_download
from ltx_core.loader import LTXV_LORA_COMFY_RENAMING_MAP, LoraPathStrengthAndSDOps
from ltx_core.model.video_vae import TilingConfig, get_video_chunks_number
from ltx_core.quantization.fp8_cast import build_policy
from ltx_pipelines.ic_lora import ICLoraPipeline
from ltx_pipelines.utils.constants import DISTILLED_SIGMAS
from ltx_pipelines.utils.media_io import encode_video
from media import FPS, prepare_guide, restore_audio, probe, geometry

logging.basicConfig(level=logging.INFO)
LOG = logging.getLogger("bfs-video-studio")
MODEL = "Alissonerdx/BFS-Best-Face-Swap-Video"
LORA = "ltx-2.3/head_swap_v3_rank_64.safetensors"
BASE = "Lightricks/LTX-2.3"
GEMMA = "google/gemma-3-12b-it-qat-q4_0-unquantized"
LOCK = json.loads((ROOT / "model-lock.json").read_text())

# Use native SDPA on Blackwell. Do not load hardware-specific compiled graphs.
from ltx_core.model.transformer import attention as attention_module
attention_module.memory_efficient_attention = None
attention_module.flash_attn_interface = None
attention_module.flash_attn_4_func = None

LOG.info("Downloading pinned base, BFS adapter, and authorized Gemma text encoder.")
checkpoint = hf_hub_download(BASE, "ltx-2.3-22b-distilled.safetensors", revision=LOCK[BASE])
upsampler = hf_hub_download(BASE, "ltx-2.3-spatial-upscaler-x2-1.1.safetensors", revision=LOCK[BASE])
lora_path = hf_hub_download(MODEL, LORA, revision=LOCK[MODEL])
gemma_path = snapshot_download(
    GEMMA, revision=LOCK[GEMMA],
    allow_patterns=["*.safetensors", "*.json", "tokenizer.model"],
)
PIPELINE = ICLoraPipeline(
    distilled_checkpoint_path=checkpoint, spatial_upsampler_path=upsampler,
    gemma_root=gemma_path,
    loras=[LoraPathStrengthAndSDOps(lora_path, 1.0, LTXV_LORA_COMFY_RENAMING_MAP)],
    device=torch.device("cuda"), quantization=build_policy(checkpoint),
)
for block in (PIPELINE.prompt_encoder, PIPELINE.image_conditioner, PIPELINE.stage_1,
              PIPELINE.video_decoder, PIPELINE.audio_decoder):
    block.warmup()
# Register the text encoder with ZeroGPU at startup as well as the transformer.
PIPELINE.prompt_encoder._cached_text_encoder = PIPELINE.prompt_encoder._build_text_encoder()
PIPELINE.prompt_encoder._text_encoder_ctx = lambda: nullcontext(PIPELINE.prompt_encoder._cached_text_encoder)
LOG.info("BFS_MODEL_READY: weights registered for ZeroGPU streaming.")

FACE_DEFAULT = "Use the face, hair, and identity of the reference portrait. Preserve natural skin texture."
ACTION_DEFAULT = "A person performs the motion in the guide video. Preserve clothing, body movement, camera framing, and environment."


def validate(video: str | None, face: str | None, consent: bool, duration: float, resolution: int) -> None:
    """Validate a guide video and reference photo before requesting a GPU."""
    if not consent:
        raise gr.Error("Confirm you have permission to use the people and media in your inputs.")
    if not face or not Path(face).is_file():
        raise gr.Error("Upload a reference photo.")
    try:
        geometry(probe(video), float(duration), int(resolution))
    except (ValueError, TypeError) as error:
        raise gr.Error(str(error)) from error


@spaces.GPU(duration=180, size="xlarge")
@torch.inference_mode()
def generate(
    video: str, face: str, consent: bool = False, duration: float = 2,
    resolution: int = 512, face_description: str = FACE_DEFAULT,
    action_description: str = ACTION_DEFAULT, seed: int = 42,
    randomize_seed: bool = True, progress=gr.Progress(track_tqdm=True),
) -> tuple[str, str, int]:
    """Swap a consenting person's identity using BFS V3 and preserve the guide audio.

    Upload a guide video and reference face, confirm permission, then choose a
    short duration and 512/640/768 canvas resolution. Returns MP4, run details,
    and the actual random seed. Uses an eight-step distilled LTX-2.3 schedule.
    """
    validate(video, face, consent, duration, resolution)
    started = time.perf_counter()
    seed = secrets.randbelow(2**31) if randomize_seed else int(seed)
    if not 0 <= seed < 2**31:
        raise gr.Error("Seed must be between 0 and 2147483647.")
    face_description = (face_description or FACE_DEFAULT).strip()[:1500]
    action_description = (action_description or ACTION_DEFAULT).strip()[:1500]
    prompt = f"head_swap:\nFACE:\n{face_description}\n\nACTION:\n{action_description}"
    result = Path(tempfile.mkdtemp(prefix="bfs-result-")) / "bfs-head-swap.mp4"
    try:
        with tempfile.TemporaryDirectory(prefix="bfs-work-") as tmp:
            directory = Path(tmp)
            progress(0.05, desc="Preparing your reference and guide")
            info = prepare_guide(video, face, float(duration), int(resolution), directory)
            progress(0.15, desc="Generating the new performance")
            tiling = TilingConfig.default()
            frames, _ = PIPELINE(
                prompt=prompt, seed=seed, height=info["height"] * 2, width=info["width"] * 2,
                num_frames=info["frames"], frame_rate=FPS, images=[],
                video_conditioning=[(info["guide"], 1.0)], skip_stage_2=True,
                tiling_config=tiling, stage_1_sigmas=DISTILLED_SIGMAS,
            )
            # The pipeline's first stage is half of the requested dimensions;
            # passing 2x above makes the selected resolution the real output.
            silent = directory / "generated.mp4"
            encode_video(video=frames, fps=FPS, audio=None, output_path=str(silent),
                         video_chunks_number=get_video_chunks_number(info["frames"], tiling))
            progress(0.95, desc="Restoring the original audio")
            restore_audio(str(silent), video, str(result), info["frames"] / FPS)
        elapsed = time.perf_counter() - started
        LOG.info("BFS_RUN_OK: %dx%d %d frames, %.1fs elapsed, seed=%d",
                 info["width"], info["height"], info["frames"], elapsed, seed)
        return str(result), (f"{info['width']} × {info['height']} · {info['frames'] / FPS:.2f}s · "
                             f"{FPS} fps · Seed {seed} · Generated in {elapsed:.1f}s"), seed
    except Exception:
        result.unlink(missing_ok=True)
        LOG.exception("BFS generation failed")
        raise


CSS = """
.gradio-container { max-width: 1160px !important; margin: auto !important; }
.dark .gradio-container { color: var(--body-text-color); }
#hero { padding: 26px 0 18px; } #hero h1 { font-size: 42px; letter-spacing: -1.5px; }
#run { min-height: 52px; } .hint { color: #777; font-size: 13px; }
"""
with gr.Blocks(title="BFS Video Studio", delete_cache=(3600, 86400)) as demo:
    gr.Markdown("**BFS / VIDEO STUDIO**\n# A new face. The same performance.\n"
                "Turn a reference portrait and a short guide video into a new performance. "
                "Powered by [BFS V3](https://huggingface.co/Alissonerdx/BFS-Best-Face-Swap-Video).", elem_id="hero")
    with gr.Row():
        with gr.Column(scale=1):
            with gr.Row():
                face = gr.Image(label="01 / Reference face", type="filepath", sources=["upload"], height=260)
                video = gr.Video(label="02 / Guide performance", sources=["upload"], height=260)
            with gr.Row():
                duration = gr.Slider(0.5, 3, value=2, step=0.5, label="Length in seconds")
                resolution = gr.Dropdown([512, 640, 768], value=512, label="Canvas resolution")
            with gr.Accordion("Describe the scene & tune the result", open=False):
                face_description = gr.Textbox(value=FACE_DEFAULT, label="Reference identity", lines=3)
                action_description = gr.Textbox(value=ACTION_DEFAULT, label="Performance and scene", lines=3)
                with gr.Row():
                    seed = gr.Number(value=42, precision=0, label="Seed")
                    randomize = gr.Checkbox(value=True, label="Randomize seed")
                gr.Markdown("8 distilled steps · BFS LoRA strength 1.0 · Original guide audio")
            consent = gr.Checkbox(value=False, label="I have permission to use every person and media file in these inputs.")
            run = gr.Button("Generate video →", variant="primary", elem_id="run")
        with gr.Column(scale=1):
            output = gr.Video(label="03 / Your result", interactive=False, height=430)
            status = gr.Markdown("Your generated video will appear here. Start with a clear portrait and a short close-up clip.")
    gr.Markdown("**A good first take:** one visible face, steady lighting, and no scene cuts. "
                "The model can change details of the scene and may struggle with hair, occlusion, and fast motion.")
    check = run.click(validate, [video, face, consent, duration, resolution], [], queue=False, api_name=False)
    check.success(generate, [video, face, consent, duration, resolution, face_description,
                            action_description, seed, randomize], [output, status, seed],
                  api_name="generate", concurrency_limit=1)
    with gr.Accordion("About the model", open=False):
        gr.Markdown("This demo runs **BFS V3 rank-64 on LTX-2.3**. The reference portrait remains "
                    "in a green side panel throughout conditioning. The model learns to return the "
                    "performance without that panel; the output is not manually cropped.\n\n"
                    "[Model & examples](https://huggingface.co/Alissonerdx/BFS-Best-Face-Swap-Video) · "
                    "[Author’s workflow](https://github.com/alisson-anjos/ComfyUI-BFSNodes) · "
                    "[LTX-2.3](https://huggingface.co/Lightricks/LTX-2.3)")

if __name__ == "__main__":
    demo.queue(max_size=8).launch(theme=gr.themes.Soft(primary_hue="emerald"), css=CSS,
                                 mcp_server=True, max_file_size="150mb", show_error=False,
                                 auth=("bfs", os.environ.get("APP_PASSWORD", "simzy2026")))