Spaces:
Running on Zero

File size: 16,528 Bytes
b41065f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
import os

os.environ.setdefault("HF_XET_CHUNK_CACHE_SIZE_BYTES", "0")  # weights are read once and deleted, so skip the chunk cache
os.environ.setdefault("DIFFSYNTH_SKIP_DOWNLOAD", "True")  # every file is fetched below at a pinned revision

import gc
import json
import shutil
import subprocess
import tempfile
import threading
import time
from pathlib import Path

import gradio as gr
import spaces
import numpy as np
import torch

import mfn_hf  # shared look + usage analytics; import before @spaces.GPU

import imageio.v2 as imageio
from PIL import Image
from huggingface_hub import hf_hub_download
from safetensors.torch import load as load_safetensors_bytes, load_file

from diffsynth.core.vram.initialization import skip_model_initialization
from diffsynth.models.minimax_h3_controlnet import MiniMaxH3ControlNet
from diffsynth.models.minimax_h3_dit import MiniMaxH3DiT
from diffsynth.pipelines.minimax_h3_audio_video import MiniMaxH3MultiControlNet, MiniMaxH3Pipeline, ModelConfig
from diffsynth.utils.controlnet.annotator import Annotator
from diffsynth.utils.diffutoon import video_to_blur

# ----------------------------------------------------------------------------------------- pinned sources

MODEL_ID = "ml-resources/Diffutoon-2"
DT_REV = "3f3571f3d13a2612651b0fd9586fb6552075f020"
H3, H3_REV = "MiniMaxAI/MiniMax-H3", "12253298adb81e36757eabebb81d2ba1c0cc70cc"
ASSETS, ASSETS_REV = "mrfakename/diffutoon-2-assets", "2f035c46aa048401a1c08a82fce78276a35d4121"
AN, AN_REV = "lllyasviel/Annotators", "982e7edaec38759d914a963c48c4726685de7d96"

ROOT = Path(__file__).resolve().parent
DL = Path(tempfile.gettempdir()) / "diffutoon2-weights"
FPS = 24
OVERLAP = 5  # frames shared by neighbouring windows, as in the official long-video script
STEPS = 4  # Turbo LoRA (merged into the transformer)

# Per resolution: short side, longest allowed long side, frames per window, default and maximum seconds.
# Measured on an H200 with the weights below; see the README.
RESOLUTIONS = {
    "480p": {"short": 480, "long": 864, "window": 124, "default_s": 8, "max_s": 30},
    "720p": {"short": 736, "long": 1280, "window": 124, "default_s": 5, "max_s": 15},
}
# Seconds of GPU time per output second (generation + line art), with headroom, plus a fixed allowance.
GPU_S_PER_S = {"480p": 8.0, "720p": 18.0}
GPU_FIXED_S = 30

STYLES = {"General": "general", "People": "people", "Animals": "animals", "Scenery": "scenery", "City": "city"}

# ----------------------------------------------------------------------------------------- weights


class Int8Linear(torch.nn.Module):
    """Weight-only int8 linear (one symmetric scale per output channel), dequantized to bf16 on use."""

    def __init__(self, in_features, out_features, bias=True):
        super().__init__()
        self.in_features, self.out_features = in_features, out_features
        self.register_buffer("weight_int8", torch.empty(out_features, in_features, dtype=torch.int8, device="meta"))
        self.register_buffer("weight_scale", torch.empty(out_features, dtype=torch.float32, device="meta"))
        if bias:
            self.bias = torch.nn.Parameter(torch.empty(out_features, dtype=torch.bfloat16, device="meta"), requires_grad=False)
        else:
            self.bias = None

    def forward(self, x):
        w = self.weight_int8.to(x.dtype) * self.weight_scale.to(x.dtype)[:, None]
        return torch.nn.functional.linear(x, w, None if self.bias is None else self.bias.to(x.dtype))


def build_int8(model_cls, kwargs, sd):
    with skip_model_initialization():
        model = model_cls(**kwargs)
    for name in {k[: -len(".weight_int8")] for k in sd if k.endswith(".weight_int8")}:
        parent_name, child = name.rsplit(".", 1) if "." in name else ("", name)
        parent = model.get_submodule(parent_name) if parent_name else model
        old = getattr(parent, child)
        setattr(parent, child, Int8Linear(old.in_features, old.out_features, bias=old.bias is not None))
    missing, unexpected = model.load_state_dict(sd, assign=True, strict=False)
    if missing or unexpected:
        raise RuntimeError(f"weight mismatch: missing={missing[:5]} unexpected={unexpected[:5]}")
    return model.eval().requires_grad_(False)


def fetch(repo, filename, revision):
    return hf_hub_download(repo, filename, revision=revision, local_dir=DL)


def fetch_state_dict(repo, filename, revision):
    """Download one safetensors file, read it into RAM and delete it, so the disk only ever holds one shard."""
    path = fetch(repo, filename, revision)
    with open(path, "rb") as f:
        sd = load_safetensors_bytes(f.read())
    os.remove(path)
    return sd


with open(fetch(ASSETS, "int8_format.json", ASSETS_REV)) as f:
    FORMAT = json.load(f)
EMBEDS = load_file(fetch(ASSETS, "prompt_embeds.safetensors", ASSETS_REV))

# The VAEs come straight from MiniMax H3; the text encoder is never loaded (prompt embeddings are precomputed).
vae_path = fetch(H3, "FL2VA/video_vae/source/model.safetensors", H3_REV)
audio_vae_path = fetch(H3, "FL2VA/audio_vae/model.safetensors", H3_REV)
pipe = MiniMaxH3Pipeline.from_pretrained(
    torch_dtype=torch.bfloat16, device="cpu",
    model_configs=[ModelConfig(path=vae_path), ModelConfig(path=audio_vae_path)],
    processor_config=None,
)
os.remove(vae_path)
os.remove(audio_vae_path)
gc.collect()

dit_sd = {}
for fn in FORMAT["dit"]["files"]:
    dit_sd.update(fetch_state_dict(ASSETS, fn, ASSETS_REV))
pipe.dit = build_int8(MiniMaxH3DiT, FORMAT["dit"]["kwargs"], dit_sd)
del dit_sd
pipe.controlnet = MiniMaxH3MultiControlNet([  # order: line art, then color
    build_int8(MiniMaxH3ControlNet, FORMAT["controlnets"]["kwargs"], fetch_state_dict(ASSETS, fn, ASSETS_REV))
    for fn in FORMAT["controlnets"]["files"]
])
gc.collect()
pipe.to("cuda")

for fn in ("sk_model.pth", "sk_model2.pth"):
    fetch(AN, fn, AN_REV)
LINEART = Annotator("lineart", model_path=str(DL), detect_resolution=512, device="cuda")

# ----------------------------------------------------------------------------------------- video helpers

FFMPEG = shutil.which("ffmpeg") or "ffmpeg"
FFPROBE = shutil.which("ffprobe") or "ffprobe"


def probe(path):
    out = subprocess.run(
        [FFPROBE, "-v", "error", "-select_streams", "v:0", "-show_entries",
         "stream=width,height:stream_side_data=rotation:format=duration", "-of", "json", path],
        capture_output=True, text=True, check=True,
    ).stdout
    info = json.loads(out)
    stream = info["streams"][0]
    w, h = int(stream["width"]), int(stream["height"])
    rotation = 0
    for sd in stream.get("side_data_list", []) or []:
        rotation = int(float(sd.get("rotation", 0) or 0))
    if abs(rotation) % 180 == 90:
        w, h = h, w
    return w, h, float(info.get("format", {}).get("duration", 0) or 0)


def target_size(w, h, res):
    cfg = RESOLUTIONS[res]
    short, long_max = cfg["short"], cfg["long"]
    ratio = max(w, h) / max(min(w, h), 1)
    long = int(min(max(round(short * ratio / 32) * 32, short), long_max))
    return (long, short) if w >= h else (short, long)


def prep_video(src, dst, w, h, n_frames):
    vf = f"fps={FPS},scale={w}:{h}:force_original_aspect_ratio=increase:flags=lanczos,crop={w}:{h}"
    subprocess.run(
        [FFMPEG, "-y", "-loglevel", "error", "-i", src, "-vf", vf, "-an", "-frames:v", str(n_frames),
         "-c:v", "libx264", "-crf", "12", "-pix_fmt", "yuv420p", dst],
        check=True, capture_output=True,
    )


def read_frames(path):
    reader = imageio.get_reader(path)
    frames = [Image.fromarray(f) for f in reader]
    reader.close()
    return frames


def write_frames(frames, path):
    writer = imageio.get_writer(path, fps=FPS, quality=8, macro_block_size=1)
    for f in frames:
        writer.append_data(np.asarray(f))
    writer.close()


def mux_audio(video, src, dst, seconds):
    """Put the input's soundtrack (if any) back under the stylized video."""
    subprocess.run(
        [FFMPEG, "-y", "-loglevel", "error", "-i", video, "-t", f"{seconds:.3f}", "-i", src,
         "-map", "0:v:0", "-map", "1:a:0?", "-c:v", "copy", "-c:a", "aac", "-b:a", "192k", "-shortest",
         "-movflags", "+faststart", dst],
        check=True, capture_output=True,
    )


def make_segments(n, window):
    """Windows of `window` frames sharing OVERLAP frames; the last one is padded up to a valid 17k+5 length."""
    segs, start = [], 0
    while True:
        end = start + window
        if end >= n:
            rest = n - start
            segs.append((start, start + max(22, -(-(rest - 5) // 17) * 17 + 5)))
            return segs
        segs.append((start, end))
        start = end - OVERLAP


def plan(video, res, seconds):
    w, h, dur = probe(video)
    n = int(min(seconds, dur if dur > 0 else seconds) * FPS)
    return w, h, max(n, 1)


# ----------------------------------------------------------------------------------------- inference


def gpu_duration(video, style, res, seconds, seed, line_strength, color_strength, progress=None):
    try:
        seconds = min(float(seconds), RESOLUTIONS[res]["max_s"])
    except Exception:
        seconds = 10
    return int(GPU_FIXED_S + GPU_S_PER_S.get(res, GPU_S_PER_S["720p"]) * seconds)


@spaces.GPU(size="xlarge", duration=gpu_duration)
def stylize(video, style, res, seconds, seed, line_strength, color_strength, progress=gr.Progress()):
    if not video:
        raise gr.Error("Upload a video first.")
    if res not in RESOLUTIONS:
        raise gr.Error("Pick a resolution.")
    t0 = time.time()
    seconds = float(min(max(float(seconds), 1.0), RESOLUTIONS[res]["max_s"]))
    try:
        src_w, src_h, n = plan(video, res, seconds)
    except Exception:
        raise gr.Error("Could not read this video. Try an mp4, mov or webm file.")
    w, h = target_size(src_w, src_h, res)
    work = Path(tempfile.mkdtemp(prefix="dt2-"))
    try:
        progress(0, desc="Reading the video")
        prep_video(video, str(work / "in.mp4"), w, h, n)

        blur_err = []

        def blur():
            try:
                video_to_blur(str(work / "in.mp4"), str(work / "color.mp4"))
            except Exception as e:  # noqa: BLE001
                blur_err.append(e)

        blur_thread = threading.Thread(target=blur)
        blur_thread.start()  # colour track on the CPU while the line art runs on the GPU

        frames = read_frames(str(work / "in.mp4"))
        n = len(frames)
        if n < 1:
            raise gr.Error("The video has no frames.")
        outline = []
        for i, f in enumerate(frames):
            if i % 24 == 0:
                progress(i / n * 0.1, desc="Drawing line art")
            outline.append(LINEART(f).convert("RGB"))
        del frames
        blur_thread.join()
        if blur_err:
            raise gr.Error("Could not process this video.")
        color = read_frames(str(work / "color.mp4"))[:n]
        color += [color[-1]] * (n - len(color))

        segs = make_segments(n, RESOLUTIONS[res]["window"])
        total = segs[-1][1]
        outline += [outline[-1]] * (total - len(outline))
        color += [color[-1]] * (total - len(color))
        emb = EMBEDS[STYLES.get(style, "general")]
        out, pin = [], None
        for i, (s, e) in enumerate(segs):
            def steps(timesteps, i=i):
                timesteps = list(timesteps)
                for k, t in enumerate(timesteps):
                    progress(0.1 + 0.9 * (i * STEPS + k) / (len(segs) * STEPS),
                             desc=f"Stylizing part {i + 1} of {len(segs)}")
                    yield t

            clip, _audio, pin = pipe(
                prompt=None, text_embedding=emb, height=h, width=w, num_frames=e - s,
                num_inference_steps=STEPS, seed=int(seed or 0) + i,
                control_video=[outline[s:e], color[s:e]], control_scale=[float(line_strength), float(color_strength)],
                pin_latents=pin, return_latents=True, progress_bar_cmd=steps,
            )
            pin = pin[:, :, -2:]
            ov = 0 if i == 0 else segs[i - 1][1] - s
            for j in range(ov):  # cross-fade the frames two windows share
                out[-ov + j] = Image.blend(out[-ov + j], clip[j], j / max(ov - 1, 1))
            out.extend(clip[ov:])
        out = out[:n]
        progress(1.0, desc="Writing the video")
        write_frames(out, str(work / "toon.mp4"))
        result = Path(tempfile.mkdtemp(prefix="dt2-out-")) / "diffutoon2.mp4"
        mux_audio(str(work / "toon.mp4"), video, str(result), n / FPS)
    finally:
        shutil.rmtree(work, ignore_errors=True)
    return str(result), f"Took {time.time() - t0:.1f} s for {n / FPS:.1f} s of video at {w}x{h}"


# ----------------------------------------------------------------------------------------- UI

EXAMPLE_DIR = ROOT / "examples"
EXAMPLE_DIR.mkdir(exist_ok=True)
EXAMPLES = []
for folder, name, style in [
    ("demo_people", "cat-girl", "People"), ("demo_people", "stroller", "People"),
    ("demo_animals", "koala", "Animals"), ("demo_animals", "libby", "Animals"),
    ("demo_scenery", "8", "Scenery"), ("demo_scenery", "46", "Scenery"),
]:
    dst = EXAMPLE_DIR / f"{folder.split('_')[1]}-{name}.mp4"
    if not dst.exists():
        shutil.copy(hf_hub_download(MODEL_ID, f"assets/{folder}/{name}/input.mp4", revision=DT_REV), dst)
    EXAMPLES.append([str(dst), style, "480p", RESOLUTIONS["480p"]["default_s"]])


def on_res(res):
    cfg = RESOLUTIONS[res]
    return gr.update(maximum=cfg["max_s"], value=min(cfg["default_s"], cfg["max_s"]))


with gr.Blocks(title="Diffutoon-2") as demo:
    mfn_hf.header(
        "Diffutoon-2",
        model=MODEL_ID,
        description="Turns a real video into an anime-style cartoon that follows its outlines, colours and motion.",
        flow_fn="/stylize",
    )
    with gr.Row():
        with gr.Column():
            inp = gr.Video(label="Input video", sources=["upload"])
            style = gr.Dropdown(list(STYLES), value="General", label="Scene type",
                                info="Pick what the video mostly shows.")
            with gr.Row():
                res = gr.Radio(list(RESOLUTIONS), value="480p", label="Resolution")
                seconds = gr.Slider(1, RESOLUTIONS["480p"]["max_s"], value=RESOLUTIONS["480p"]["default_s"], step=1,
                                    label="Length (seconds)", info="Taken from the start of the video.")
            with gr.Accordion("Settings", open=False):
                seed = gr.Number(43, label="Seed", precision=0)
                line_strength = gr.Slider(0, 1, value=0.4, step=0.05, label="Line-art strength",
                                          info="How closely the cartoon follows the outlines.")
                color_strength = gr.Slider(0, 1, value=0.4, step=0.05, label="Colour strength",
                                           info="How closely it follows the original colours.")
            btn = gr.Button("Make it anime", variant="primary")
        with gr.Column():
            out = gr.Video(label="Anime video (AI-generated)", interactive=False)
            took = mfn_hf.took()
            gr.Markdown("The result is AI-generated. It keeps the input's soundtrack.")
    gr.Examples(EXAMPLES, [inp, style, res, seconds], label="Examples (from the Diffutoon-2 demo)",
                cache_examples=False)
    res.change(on_res, res, seconds, api_name=False)
    btn.click(stylize, [inp, style, res, seconds, seed, line_strength, color_strength], [out, took], api_name="stylize")
    gr.Markdown(
        "**Powered by MiniMax H3.** [Diffutoon-2](https://huggingface.co/ml-resources/Diffutoon-2) by "
        "[DiffSynth-Studio](https://github.com/modelscope/DiffSynth-Studio) / ModelScope (Apache-2.0), on the "
        "[MiniMax H3](https://huggingface.co/MiniMaxAI/MiniMax-H3) FL2VA video model by MiniMax with the "
        "[lightx2v Turbo](https://huggingface.co/lightx2v/Minimax-h3-Turbo) 4-step LoRA. Weights are int8 versions "
        "([diffutoon-2-assets](https://huggingface.co/mrfakename/diffutoon-2-assets)). MiniMax H3 is licensed under "
        "the MiniMax H3 Community License Agreement, Copyright © 2026 MiniMax. All Rights Reserved.\n\n"
        "Only upload footage you own or have the rights to. Use must follow MiniMax's "
        "[Acceptable Use Policy](https://huggingface.co/MiniMaxAI/MiniMax-H3/blob/main/LICENSE) (Exhibit A of the licence)."
    )
    mfn_hf.footer()


if __name__ == "__main__":
    demo.launch()  # mfn_hf patches launch: theme, CSS, queue and analytics