Spaces:
Running on Zero

diffutoon-2 / app.py
mfn
Initial Space demo
b41065f
Raw History Blame Contribute Delete
16.5 kB
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