Spaces:
Running on Zero
Running on Zero
Video: Wan2.2 TI2V 5B (FastWan, 3 steps, Apache 2.0) replaces LTX-Video in the Video and Edit tabs
Browse files
README.md
CHANGED
|
@@ -47,7 +47,8 @@ models:
|
|
| 47 |
- black-forest-labs/flux-3-image-klein-pup
|
| 48 |
- ACE-Step/acestep-v15-xl-turbo-diffusers
|
| 49 |
- ACE-Step/acestep-v15-xl-sft-diffusers
|
| 50 |
-
-
|
|
|
|
| 51 |
- facebook/musicgen-medium
|
| 52 |
- hexgrad/Kokoro-82M
|
| 53 |
- openai/whisper-large-v3-turbo
|
|
@@ -62,7 +63,7 @@ models:
|
|
| 62 |
**Edit tab (image editing, video editing, music editing):** change what you already have.
|
| 63 |
|
| 64 |
- **Edit image (image and text to image):** Black Forest Labs' caption model (flux-3-image-klein-pup) looks at your picture and writes a full caption of the edited scene, then **FLUX.3 Image klein** edits the picture itself in 16 steps.
|
| 65 |
-
- **Edit video (video and text to video):** **
|
| 66 |
- **Edit music (audio to audio):** **ACE-Step 1.5 XL turbo** (MIT) restyles a whole song while keeping its structure, redoes one part, adds an instrument, or pulls one out (vocals, drums, bass...).
|
| 67 |
|
| 68 |
**Image tab (text to image, image generation):** **Qwen3 4B** first turns your prompt into a full scene caption, using Black Forest Labs' own caption instructions, then **FLUX.3 Image klein** (black-forest-labs, 5.6B) draws a 1152×768 picture in 16 steps. The caption it was given is shown under the picture.
|
|
@@ -83,12 +84,12 @@ models:
|
|
| 83 |
|
| 84 |
1. **Qwen3 4B** (Qwen) improves your scene and motion prompts (prompt enhancement): it adds lighting, colour and texture, and keeps your subjects and directions as you wrote them. Untick the box to use your exact words.
|
| 85 |
2. **FLUX.3 Image klein** (black-forest-labs) draws the scene from a full caption Qwen3 4B writes (or you supply a start image).
|
| 86 |
-
3. **
|
| 87 |
4. **MusicGen medium** (facebook) adds a soundtrack if you describe one.
|
| 88 |
5. **Qwen3 4B** plans the narration (what to say and when) and **Kokoro** (hexgrad) speaks it, if narration is ticked.
|
| 89 |
|
| 90 |
-
**How it stays light on ZeroGPU quota:** each model is kept in its own pack, and a button copies only the models it needs onto the GPU, one after another where a job uses several. An image copies only the image model, and a video loads FLUX, then
|
| 91 |
|
| 92 |
-
**Licences:**
|
| 93 |
|
| 94 |
Runs on ZeroGPU: set the Space hardware to **ZeroGPU** in Settings.
|
|
|
|
| 47 |
- black-forest-labs/flux-3-image-klein-pup
|
| 48 |
- ACE-Step/acestep-v15-xl-turbo-diffusers
|
| 49 |
- ACE-Step/acestep-v15-xl-sft-diffusers
|
| 50 |
+
- FastVideo/FastWan2.2-TI2V-5B-FullAttn-Diffusers
|
| 51 |
+
- Wan-AI/Wan2.2-TI2V-5B-Diffusers
|
| 52 |
- facebook/musicgen-medium
|
| 53 |
- hexgrad/Kokoro-82M
|
| 54 |
- openai/whisper-large-v3-turbo
|
|
|
|
| 63 |
**Edit tab (image editing, video editing, music editing):** change what you already have.
|
| 64 |
|
| 65 |
- **Edit image (image and text to image):** Black Forest Labs' caption model (flux-3-image-klein-pup) looks at your picture and writes a full caption of the edited scene, then **FLUX.3 Image klein** edits the picture itself in 16 steps.
|
| 66 |
+
- **Edit video (video and text to video):** **Wan2.2 TI2V 5B** (FastWan, 3 steps) re-draws the first 2 seconds of your clip from a noisy copy of it, so its motion and layout stay while the look changes (colours, clothes, weather, style); Florence-2 and Qwen3 4B first write a description of the finished video.
|
| 67 |
- **Edit music (audio to audio):** **ACE-Step 1.5 XL turbo** (MIT) restyles a whole song while keeping its structure, redoes one part, adds an instrument, or pulls one out (vocals, drums, bass...).
|
| 68 |
|
| 69 |
**Image tab (text to image, image generation):** **Qwen3 4B** first turns your prompt into a full scene caption, using Black Forest Labs' own caption instructions, then **FLUX.3 Image klein** (black-forest-labs, 5.6B) draws a 1152×768 picture in 16 steps. The caption it was given is shown under the picture.
|
|
|
|
| 84 |
|
| 85 |
1. **Qwen3 4B** (Qwen) improves your scene and motion prompts (prompt enhancement): it adds lighting, colour and texture, and keeps your subjects and directions as you wrote them. Untick the box to use your exact words.
|
| 86 |
2. **FLUX.3 Image klein** (black-forest-labs) draws the scene from a full caption Qwen3 4B writes (or you supply a start image).
|
| 87 |
+
3. **Wan2.2 TI2V 5B** (Wan-AI), in FastVideo's 3-step **FastWan** version, animates it: 2 to 5 seconds, 1152×768, 24 fps.
|
| 88 |
4. **MusicGen medium** (facebook) adds a soundtrack if you describe one.
|
| 89 |
5. **Qwen3 4B** plans the narration (what to say and when) and **Kokoro** (hexgrad) speaks it, if narration is ticked.
|
| 90 |
|
| 91 |
+
**How it stays light on ZeroGPU quota:** each model is kept in its own pack, and a button copies only the models it needs onto the GPU, one after another where a job uses several. An image copies only the image model, and a video loads FLUX, then Wan2.2, then MusicGen in turn, so every job fits the default half-card slice.
|
| 92 |
|
| 93 |
+
**Licences:** Wan2.2 and FastWan (Apache 2.0), Kokoro, Whisper, CLAP, Qwen3 4B, Florence-2 large and SmolVLM2 2.2B are openly licensed. **FLUX.3 Image klein is under the FLUX Kommunity License** (non-commercial use) and **MusicGen medium is CC-BY-NC 4.0**; ACE-Step 1.5 is MIT, so images, videos and music made here are for non-commercial use.
|
| 94 |
|
| 95 |
Runs on ZeroGPU: set the Space hardware to **ZeroGPU** in Settings.
|
app.py
CHANGED
|
@@ -15,12 +15,12 @@ Describe tab: three sub-tabs for the describing jobs the Space does.
|
|
| 15 |
CLAP picks a genre, mood, tempo and instruments for a piece of music and writes them as one short
|
| 16 |
sentence.
|
| 17 |
Edit tab: change what you already have. Image (FLUX.3 Image klein edits the picture itself, with a caption
|
| 18 |
-
its own caption model writes from the picture), Video (
|
| 19 |
it, so the motion and layout stay and the look changes), Music (ACE-Step 1.5: restyle a song, redo a part, add an
|
| 20 |
instrument or pull one out).
|
| 21 |
Video tab (text to video, image to video, video generation): one button makes a whole clip. A small
|
| 22 |
text model (Qwen3 4B) first improves the scene and motion prompts if that is ticked, FLUX draws
|
| 23 |
-
the scene,
|
| 24 |
and if narration is ticked Qwen3 4B writes the lines and their timing and Kokoro speaks them.
|
| 25 |
|
| 26 |
Each model has its own ZeroGPU pack (see zero_packs.py), and each button copies only the packs it
|
|
@@ -65,8 +65,7 @@ import scipy.io.wavfile
|
|
| 65 |
import spaces
|
| 66 |
import torch
|
| 67 |
import zero_packs as packs
|
| 68 |
-
from diffusers import FluxPipeline,
|
| 69 |
-
from diffusers.pipelines.ltx.pipeline_ltx_condition import LTXVideoCondition
|
| 70 |
from diffusers.utils import export_to_video
|
| 71 |
from PIL import Image
|
| 72 |
from transformers import (AutoModelForCausalLM, AutoModelForImageTextToText, AutoProcessor,
|
|
@@ -80,7 +79,7 @@ IMAGE_MODEL = "black-forest-labs/flux-3-image-klein" # Gated, FLUX Kommunity l
|
|
| 80 |
IMAGE_KLEIN2 = "black-forest-labs/FLUX.2-klein-9B" # Used if FLUX.3 cannot be loaded (FLUX non-commercial)
|
| 81 |
IMAGE_FALLBACK = "black-forest-labs/FLUX.1-schnell" # Used if neither klein can be loaded (Apache 2.0)
|
| 82 |
CAPTION_RULES_REPO = "black-forest-labs/flux-3-image-klein-pup" # Apache 2.0: FLUX.3's caption instructions
|
| 83 |
-
VIDEO_MODEL = "
|
| 84 |
MUSIC_MODEL = "facebook/musicgen-medium" # Non-commercial licence (CC-BY-NC 4.0)
|
| 85 |
TEXT_MODEL = "Qwen/Qwen3-4B" # Narration planner and prompt rewriter
|
| 86 |
IMAGE_CAPTION_MODEL = "florence-community/Florence-2-large" # Picture to caption
|
|
@@ -110,8 +109,10 @@ WORDS_PER_SECOND = 2.5
|
|
| 110 |
IMAGE_WIDTH, IMAGE_HEIGHT = 1152, 768 # 3:2, multiples of 16 for FLUX
|
| 111 |
VIDEO_WIDTH, VIDEO_HEIGHT = 1152, 768 # Same size as the image, so nothing is shrunk (multiples of 32)
|
| 112 |
VIDEO_QUALITY = 9 # 0 to 10. Low values make the saved file blurry
|
| 113 |
-
FPS =
|
| 114 |
-
|
|
|
|
|
|
|
| 115 |
MAX_SEED = 2**31 - 1
|
| 116 |
|
| 117 |
NEGATIVE_PROMPT = ("worst quality, inconsistent motion, blurry, blurry motion, motion blur, "
|
|
@@ -165,14 +166,19 @@ if IMAGE_KIND == "flux3":
|
|
| 165 |
EDIT_RULES = _rules.get("i2i")
|
| 166 |
except Exception as e:
|
| 167 |
print(f"[load] FLUX.3 caption instructions not found ({type(e).__name__}); using a short version", flush=True)
|
| 168 |
-
print("[load]
|
| 169 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
video_pipe.vae.enable_tiling() # Decode the video in tiles to keep memory low
|
| 171 |
-
video_pipe.text_encoder.
|
| 172 |
-
packs.seal("t5")
|
| 173 |
-
for part in (video_pipe.transformer, video_pipe.vae):
|
| 174 |
part.to("cuda")
|
| 175 |
-
packs.seal("
|
| 176 |
print("[load] MusicGen...", flush=True)
|
| 177 |
music_processor = AutoProcessor.from_pretrained(MUSIC_MODEL)
|
| 178 |
music_model = MusicgenForConditionalGeneration.from_pretrained(
|
|
@@ -220,7 +226,7 @@ packs.seal("whisper", SPEECH_MODEL)
|
|
| 220 |
# ---- Editing models. Each can fail on its own: the Space still starts, and that edit tab says it is unavailable.
|
| 221 |
# Edit captions: Florence-2 describes the picture and Qwen3 4B writes the caption of the edited scene with
|
| 222 |
# Black Forest Labs' edit instructions. (FLUX.3's own 18.8 GB caption model was dropped: the disk is limited to 150 GB.)
|
| 223 |
-
# Video editing uses
|
| 224 |
# 90 GB that ZeroGPU copies to the GPU from, and the other models already fill 73 GB of it.
|
| 225 |
print("[load] ACE-Step 1.5 (music editing)...", flush=True)
|
| 226 |
music_edit_pipe = None
|
|
@@ -338,6 +344,69 @@ def draw_image(prompt, seed):
|
|
| 338 |
generator=generator, **options).images[0], prompt
|
| 339 |
|
| 340 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 341 |
def animate(image, scene, motion, seconds, seed):
|
| 342 |
"""Returns the path of a silent clip and its length in seconds."""
|
| 343 |
num_frames = clip_frames(seconds)
|
|
@@ -345,24 +414,8 @@ def animate(image, scene, motion, seconds, seed):
|
|
| 345 |
wants_slow = re.search(r"slow[\s-]?mo", motion.lower()) is not None
|
| 346 |
style = STYLE_SUFFIX + ("" if wants_slow else SPEED_SUFFIX) + "."
|
| 347 |
prompt = f"{motion}. {scene.strip()}. {style}" if scene.strip() else f"{motion}. {style}"
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
conditions=[start],
|
| 351 |
-
prompt=prompt,
|
| 352 |
-
negative_prompt=NEGATIVE_PROMPT + ("" if wants_slow else NEGATIVE_SLOW),
|
| 353 |
-
image_cond_noise_scale=0.0,
|
| 354 |
-
decode_timestep=0.05,
|
| 355 |
-
decode_noise_scale=0.025,
|
| 356 |
-
width=VIDEO_WIDTH,
|
| 357 |
-
height=VIDEO_HEIGHT,
|
| 358 |
-
num_frames=num_frames,
|
| 359 |
-
frame_rate=FPS,
|
| 360 |
-
timesteps=[1000, 993, 987, 981, 975, 909, 725, 0.03],
|
| 361 |
-
guidance_scale=1.0,
|
| 362 |
-
guidance_rescale=0.7,
|
| 363 |
-
generator=torch.Generator("cpu").manual_seed(seed),
|
| 364 |
-
).frames[0]
|
| 365 |
-
frames = frames[TRIM_FRAMES:]
|
| 366 |
path = f"/tmp/video_{seed}_{random.randint(0, 99999)}.mp4"
|
| 367 |
export_to_video(frames, path, fps=FPS, quality=VIDEO_QUALITY)
|
| 368 |
return path, len(frames) / FPS
|
|
@@ -722,13 +775,13 @@ def improve_prompts(scene, motion):
|
|
| 722 |
|
| 723 |
|
| 724 |
def clip_frames(seconds):
|
| 725 |
-
"""Frames
|
| 726 |
-
return
|
| 727 |
|
| 728 |
|
| 729 |
def film(image, scene, motion, music_prompt, want_narration, improve, seconds, seed):
|
| 730 |
-
"""A clip made one model at a time, so FLUX and
|
| 731 |
-
the text model (prompts and narration plan), FLUX draws,
|
| 732 |
plan = None
|
| 733 |
improve = improve and bool(scene.strip() or motion.strip())
|
| 734 |
if improve or want_narration:
|
|
@@ -737,11 +790,11 @@ def film(image, scene, motion, music_prompt, want_narration, improve, seconds, s
|
|
| 737 |
if improve:
|
| 738 |
scene, motion = improve_prompts(scene, motion)
|
| 739 |
if want_narration:
|
| 740 |
-
plan = plan_narration(scene, motion,
|
| 741 |
if image is None:
|
| 742 |
with timed(" draw"):
|
| 743 |
image, _ = draw_image(scene, seed)
|
| 744 |
-
packs.load("
|
| 745 |
with timed(" animate"):
|
| 746 |
video, length = animate(image, scene, motion, seconds, seed)
|
| 747 |
music_wav = None
|
|
@@ -753,7 +806,7 @@ def film(image, scene, motion, music_prompt, want_narration, improve, seconds, s
|
|
| 753 |
|
| 754 |
|
| 755 |
def studio_duration(image, scene, motion, music_prompt, want_narration, improve, seconds, seed):
|
| 756 |
-
total =
|
| 757 |
if image is None:
|
| 758 |
total += IMAGE_SECONDS - 2 # FLUX draws the scene first (FLUX.3: caption + 16 steps)
|
| 759 |
if music_prompt.strip():
|
|
@@ -785,10 +838,11 @@ def make_video(image, scene, motion, music_prompt, want_narration, improve, seco
|
|
| 785 |
# ---------------------------------------------------------------- Edit tab
|
| 786 |
|
| 787 |
EDIT_IMAGE_PIXELS = 1024 * 1024 # Edited pictures keep their shape and are about this many pixels
|
| 788 |
-
EDIT_VIDEO_PIXELS = 1152 * 768 # The size
|
| 789 |
-
EDIT_VIDEO_FRAMES = 49 # About 2 seconds at 24 frames a second (
|
| 790 |
-
|
| 791 |
-
|
|
|
|
| 792 |
EDIT_VIDEO_FPS = 24
|
| 793 |
MUSIC_EDIT_RATE = 48000 # ACE-Step works with 48 kHz stereo
|
| 794 |
MUSIC_EDIT_LIMIT = 60 # Songs are cut to their first 60 seconds
|
|
@@ -869,12 +923,12 @@ def read_clip(path):
|
|
| 869 |
if len(frames) >= EDIT_VIDEO_FRAMES:
|
| 870 |
break
|
| 871 |
reader.close()
|
| 872 |
-
count = (len(frames) - 1) //
|
| 873 |
return frames[:count], source_fps / step
|
| 874 |
|
| 875 |
|
| 876 |
def edit_video_prompt(frame, instruction, improve):
|
| 877 |
-
"""
|
| 878 |
then Qwen3 4B writes how the clip looks after the change. Both must already be on the GPU."""
|
| 879 |
seen = caption_image(frame)
|
| 880 |
if not improve:
|
|
@@ -889,41 +943,26 @@ def edit_video_prompt(frame, instruction, improve):
|
|
| 889 |
|
| 890 |
|
| 891 |
def edit_video_seconds(frames, fps, instruction, change, seed, improve):
|
| 892 |
-
return gpu_seconds(
|
| 893 |
|
| 894 |
|
| 895 |
@spaces.GPU(duration=edit_video_seconds, size=VIDEO_GPU_SIZE)
|
| 896 |
def edit_video_gpu(frames, fps, instruction, change, seed, improve):
|
| 897 |
-
"""
|
| 898 |
the prompt, so the motion and layout of the original stay."""
|
| 899 |
with timed("edit video"):
|
| 900 |
packs.load("florence", "qwen")
|
| 901 |
prompt = edit_video_prompt(frames[0], instruction, improve)
|
| 902 |
-
packs.load("
|
| 903 |
width, height = fit(frames[0].width, frames[0].height, EDIT_VIDEO_PIXELS, 32)
|
| 904 |
video = [f.resize((width, height), Image.LANCZOS) for f in frames]
|
| 905 |
-
steps = EDIT_VIDEO_CHANGE.get(change,
|
| 906 |
-
|
| 907 |
-
|
|
|
|
| 908 |
pixels = video_pipe.video_processor.preprocess_video(video, height, width)
|
| 909 |
-
|
| 910 |
-
|
| 911 |
-
latents = video_pipe._normalize_latents(latents, video_pipe.vae.latents_mean, video_pipe.vae.latents_std)
|
| 912 |
-
result = video_pipe(
|
| 913 |
-
prompt=prompt,
|
| 914 |
-
negative_prompt=NEGATIVE_PROMPT,
|
| 915 |
-
latents=latents.to(torch.bfloat16),
|
| 916 |
-
denoise_strength=steps / len(EDIT_VIDEO_STEPS),
|
| 917 |
-
timesteps=EDIT_VIDEO_STEPS,
|
| 918 |
-
decode_timestep=0.05,
|
| 919 |
-
decode_noise_scale=0.025,
|
| 920 |
-
width=width,
|
| 921 |
-
height=height,
|
| 922 |
-
num_frames=len(video),
|
| 923 |
-
frame_rate=round(fps),
|
| 924 |
-
guidance_scale=1.0,
|
| 925 |
-
generator=generator,
|
| 926 |
-
).frames[0]
|
| 927 |
path = f"/tmp/edit_video_{seed}_{random.randint(0, 99999)}.mp4"
|
| 928 |
export_to_video(result, path, fps=fps, quality=VIDEO_QUALITY)
|
| 929 |
return path, prompt
|
|
@@ -1066,11 +1105,11 @@ def on_open():
|
|
| 1066 |
# ---------------------------------------------------------------- UI
|
| 1067 |
|
| 1068 |
with gr.Blocks(title="Graphics Studio") as demo:
|
| 1069 |
-
gr.Markdown("# Graphics Studio\n**FLUX.3 Image klein** images, **
|
| 1070 |
"**Qwen3** + **Kokoro** narration, **Whisper** transcription, "
|
| 1071 |
"**Florence-2** image captions, **SmolVLM2** video descriptions, **CLAP** music classification.")
|
| 1072 |
gr.Markdown("Already have an image, a video or some music and want to change it? Use the **Edit** tab: "
|
| 1073 |
-
"**FLUX.3 Image klein** edits pictures, **
|
| 1074 |
counter = gr.Markdown(counts_text())
|
| 1075 |
|
| 1076 |
with gr.Tab("Image"):
|
|
@@ -1165,7 +1204,7 @@ with gr.Blocks(title="Graphics Studio") as demo:
|
|
| 1165 |
improve_prompt = gr.Checkbox(value=True, label="Improve my prompts first (Qwen3 4B adds visual "
|
| 1166 |
"detail; untick to use your exact words)")
|
| 1167 |
want_narration = gr.Checkbox(value=False, label="Add narration")
|
| 1168 |
-
seconds = gr.Slider(2,
|
| 1169 |
with gr.Accordion("More options", open=False):
|
| 1170 |
start_image = gr.Image(label="Start image (optional; otherwise FLUX draws the scene)", type="pil")
|
| 1171 |
with gr.Row():
|
|
@@ -1212,7 +1251,7 @@ with gr.Blocks(title="Graphics Studio") as demo:
|
|
| 1212 |
edit_vid_button = gr.Button("Change video", variant="primary")
|
| 1213 |
with gr.Column():
|
| 1214 |
edit_vid_out = gr.Video(label="New video", autoplay=False, loop=True)
|
| 1215 |
-
edit_vid_prompt = gr.Textbox(label="Prompt
|
| 1216 |
gr.Markdown("Works best for changing the look: colours, clothes, the weather, the time of day or the "
|
| 1217 |
"style (cartoon, painting, snow). Adding or removing whole objects works less well.")
|
| 1218 |
with gr.Tab("Edit music"):
|
|
|
|
| 15 |
CLAP picks a genre, mood, tempo and instruments for a piece of music and writes them as one short
|
| 16 |
sentence.
|
| 17 |
Edit tab: change what you already have. Image (FLUX.3 Image klein edits the picture itself, with a caption
|
| 18 |
+
its own caption model writes from the picture), Video (Wan2.2 TI2V 5B re-draws your clip from a noisy copy of
|
| 19 |
it, so the motion and layout stay and the look changes), Music (ACE-Step 1.5: restyle a song, redo a part, add an
|
| 20 |
instrument or pull one out).
|
| 21 |
Video tab (text to video, image to video, video generation): one button makes a whole clip. A small
|
| 22 |
text model (Qwen3 4B) first improves the scene and motion prompts if that is ticked, FLUX draws
|
| 23 |
+
the scene, Wan2.2 TI2V 5B (FastWan, 3 steps) animates it, MusicGen medium adds a soundtrack if you describe one,
|
| 24 |
and if narration is ticked Qwen3 4B writes the lines and their timing and Kokoro speaks them.
|
| 25 |
|
| 26 |
Each model has its own ZeroGPU pack (see zero_packs.py), and each button copies only the packs it
|
|
|
|
| 65 |
import spaces
|
| 66 |
import torch
|
| 67 |
import zero_packs as packs
|
| 68 |
+
from diffusers import FluxPipeline, WanPipeline
|
|
|
|
| 69 |
from diffusers.utils import export_to_video
|
| 70 |
from PIL import Image
|
| 71 |
from transformers import (AutoModelForCausalLM, AutoModelForImageTextToText, AutoProcessor,
|
|
|
|
| 79 |
IMAGE_KLEIN2 = "black-forest-labs/FLUX.2-klein-9B" # Used if FLUX.3 cannot be loaded (FLUX non-commercial)
|
| 80 |
IMAGE_FALLBACK = "black-forest-labs/FLUX.1-schnell" # Used if neither klein can be loaded (Apache 2.0)
|
| 81 |
CAPTION_RULES_REPO = "black-forest-labs/flux-3-image-klein-pup" # Apache 2.0: FLUX.3's caption instructions
|
| 82 |
+
VIDEO_MODEL = "FastVideo/FastWan2.2-TI2V-5B-FullAttn-Diffusers" # Apache 2.0: Wan2.2 TI2V 5B, 3-step distilled
|
| 83 |
MUSIC_MODEL = "facebook/musicgen-medium" # Non-commercial licence (CC-BY-NC 4.0)
|
| 84 |
TEXT_MODEL = "Qwen/Qwen3-4B" # Narration planner and prompt rewriter
|
| 85 |
IMAGE_CAPTION_MODEL = "florence-community/Florence-2-large" # Picture to caption
|
|
|
|
| 109 |
IMAGE_WIDTH, IMAGE_HEIGHT = 1152, 768 # 3:2, multiples of 16 for FLUX
|
| 110 |
VIDEO_WIDTH, VIDEO_HEIGHT = 1152, 768 # Same size as the image, so nothing is shrunk (multiples of 32)
|
| 111 |
VIDEO_QUALITY = 9 # 0 to 10. Low values make the saved file blurry
|
| 112 |
+
FPS = 24 # Wan2.2 TI2V 5B makes 24 frames a second
|
| 113 |
+
MAX_VIDEO_FRAMES = 121 # What it was trained on (5 seconds); it needs 4k + 1 frames
|
| 114 |
+
# FastWan's 3 steps (FastVideo's own list). Noise level of a step = timestep / 1000 (their scheduler, shift 8).
|
| 115 |
+
WAN_STEPS = [1000, 757, 522]
|
| 116 |
MAX_SEED = 2**31 - 1
|
| 117 |
|
| 118 |
NEGATIVE_PROMPT = ("worst quality, inconsistent motion, blurry, blurry motion, motion blur, "
|
|
|
|
| 166 |
EDIT_RULES = _rules.get("i2i")
|
| 167 |
except Exception as e:
|
| 168 |
print(f"[load] FLUX.3 caption instructions not found ({type(e).__name__}); using a short version", flush=True)
|
| 169 |
+
print("[load] Wan2.2 TI2V 5B (FastWan, 3 steps)...", flush=True)
|
| 170 |
+
# The repo says "WanDMDPipeline" (FastVideo's own class); diffusers' WanPipeline loads the same parts, and the
|
| 171 |
+
# 3-step sampling is done by wan_sample() below. About 25 GB in all (umT5 11.4 + transformer 10 + VAE 2.8),
|
| 172 |
+
# which replaces LTX-Video's 36 GB (T5 + 13B transformer), so the packs get smaller.
|
| 173 |
+
# The VAE stays in float32, as in Wan's own diffusers example (bf16 can spoil the colours).
|
| 174 |
+
from diffusers import AutoencoderKLWan
|
| 175 |
+
video_pipe = WanPipeline.from_pretrained(
|
| 176 |
+
VIDEO_MODEL, torch_dtype=torch.bfloat16,
|
| 177 |
+
vae=AutoencoderKLWan.from_pretrained(VIDEO_MODEL, subfolder="vae", torch_dtype=torch.float32))
|
| 178 |
video_pipe.vae.enable_tiling() # Decode the video in tiles to keep memory low
|
| 179 |
+
for part in (video_pipe.text_encoder, video_pipe.transformer, video_pipe.vae):
|
|
|
|
|
|
|
| 180 |
part.to("cuda")
|
| 181 |
+
packs.seal("wan", VIDEO_MODEL)
|
| 182 |
print("[load] MusicGen...", flush=True)
|
| 183 |
music_processor = AutoProcessor.from_pretrained(MUSIC_MODEL)
|
| 184 |
music_model = MusicgenForConditionalGeneration.from_pretrained(
|
|
|
|
| 226 |
# ---- Editing models. Each can fail on its own: the Space still starts, and that edit tab says it is unavailable.
|
| 227 |
# Edit captions: Florence-2 describes the picture and Qwen3 4B writes the caption of the edited scene with
|
| 228 |
# Black Forest Labs' edit instructions. (FLUX.3's own 18.8 GB caption model was dropped: the disk is limited to 150 GB.)
|
| 229 |
+
# Video editing uses Wan (already loaded; it replaced LTX-Video on 2026-11-04). Lucy Edit was tried on 2026-10-28: the packs live in a space of about
|
| 230 |
# 90 GB that ZeroGPU copies to the GPU from, and the other models already fill 73 GB of it.
|
| 231 |
print("[load] ACE-Step 1.5 (music editing)...", flush=True)
|
| 232 |
music_edit_pipe = None
|
|
|
|
| 344 |
generator=generator, **options).images[0], prompt
|
| 345 |
|
| 346 |
|
| 347 |
+
def wan_encode(pixels):
|
| 348 |
+
"""Pixels [1, 3, frames, H, W] in -1..1 -> normalised Wan latents [1, 48, frames', H/16, W/16]."""
|
| 349 |
+
vae = video_pipe.vae
|
| 350 |
+
with torch.no_grad():
|
| 351 |
+
latents = vae.encode(pixels.to("cuda", dtype=vae.dtype)).latent_dist.mode()
|
| 352 |
+
mean = torch.tensor(vae.config.latents_mean).view(1, -1, 1, 1, 1).to(latents)
|
| 353 |
+
std = torch.tensor(vae.config.latents_std).view(1, -1, 1, 1, 1).to(latents)
|
| 354 |
+
return ((latents - mean) / std).float()
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
def wan_decode(latents):
|
| 358 |
+
"""Normalised Wan latents -> a list of PIL frames."""
|
| 359 |
+
vae = video_pipe.vae
|
| 360 |
+
mean = torch.tensor(vae.config.latents_mean).view(1, -1, 1, 1, 1).to("cuda", vae.dtype)
|
| 361 |
+
std = torch.tensor(vae.config.latents_std).view(1, -1, 1, 1, 1).to("cuda", vae.dtype)
|
| 362 |
+
with torch.no_grad():
|
| 363 |
+
video = vae.decode(latents.to("cuda", vae.dtype) * std + mean, return_dict=False)[0]
|
| 364 |
+
return video_pipe.video_processor.postprocess_video(video, output_type="pil")[0]
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def wan_sample(prompt, num_frames, width, height, seed, first_frame=None, start_latents=None, steps=WAN_STEPS):
|
| 368 |
+
"""FastWan's few-step sampling (DMD), as in FastVideo's sampler: at each step the model's prediction gives the
|
| 369 |
+
clean video, which is noised again to the next step's level with fresh noise. No negative prompt (no CFG).
|
| 370 |
+
first_frame: a PIL picture the clip starts from (Wan2.2 TI2V's own way: frame 0 is held clean with timestep 0).
|
| 371 |
+
start_latents: latents of an existing clip, for editing; they are noised to the first step's level."""
|
| 372 |
+
generator = torch.Generator("cuda").manual_seed(seed)
|
| 373 |
+
transformer = video_pipe.transformer
|
| 374 |
+
with torch.no_grad():
|
| 375 |
+
prompt_embeds, _ = video_pipe.encode_prompt(prompt, do_classifier_free_guidance=False,
|
| 376 |
+
max_sequence_length=512, device="cuda")
|
| 377 |
+
prompt_embeds = prompt_embeds.to(transformer.dtype)
|
| 378 |
+
frames_latent = (num_frames - 1) // 4 + 1
|
| 379 |
+
shape = (1, 48, frames_latent, height // 16, width // 16)
|
| 380 |
+
condition = mask = None
|
| 381 |
+
if first_frame is not None:
|
| 382 |
+
pixels = video_pipe.video_processor.preprocess(first_frame.convert("RGB"), height, width).unsqueeze(2)
|
| 383 |
+
condition = wan_encode(pixels) # [1, 48, 1, h, w]
|
| 384 |
+
mask = torch.ones(1, 1, frames_latent, shape[3], shape[4], device="cuda")
|
| 385 |
+
mask[:, :, 0] = 0 # 0 = keep the given first frame
|
| 386 |
+
noise = torch.randn(shape, generator=generator, device="cuda", dtype=torch.float32)
|
| 387 |
+
sigma = steps[0] / 1000
|
| 388 |
+
latents = noise if start_latents is None else (1 - sigma) * start_latents + sigma * noise
|
| 389 |
+
clean = latents
|
| 390 |
+
for i, t in enumerate(steps):
|
| 391 |
+
sigma = t / 1000
|
| 392 |
+
model_input = latents if mask is None else (1 - mask) * condition + mask * latents
|
| 393 |
+
if mask is None:
|
| 394 |
+
timestep = torch.tensor([t], device="cuda")
|
| 395 |
+
else: # One timestep per token: 0 for the first frame's tokens (patch 1x2x2), t for the rest
|
| 396 |
+
timestep = (mask[0][0][:, ::2, ::2] * t).flatten().unsqueeze(0)
|
| 397 |
+
with torch.no_grad():
|
| 398 |
+
noise_pred = transformer(hidden_states=model_input.to(transformer.dtype), timestep=timestep,
|
| 399 |
+
encoder_hidden_states=prompt_embeds, return_dict=False)[0].float()
|
| 400 |
+
clean = latents - sigma * noise_pred
|
| 401 |
+
if i < len(steps) - 1:
|
| 402 |
+
next_sigma = steps[i + 1] / 1000
|
| 403 |
+
fresh = torch.randn(shape, generator=generator, device="cuda", dtype=torch.float32)
|
| 404 |
+
latents = (1 - next_sigma) * clean + next_sigma * fresh
|
| 405 |
+
if mask is not None:
|
| 406 |
+
clean = (1 - mask) * condition + mask * clean
|
| 407 |
+
return wan_decode(clean)
|
| 408 |
+
|
| 409 |
+
|
| 410 |
def animate(image, scene, motion, seconds, seed):
|
| 411 |
"""Returns the path of a silent clip and its length in seconds."""
|
| 412 |
num_frames = clip_frames(seconds)
|
|
|
|
| 414 |
wants_slow = re.search(r"slow[\s-]?mo", motion.lower()) is not None
|
| 415 |
style = STYLE_SUFFIX + ("" if wants_slow else SPEED_SUFFIX) + "."
|
| 416 |
prompt = f"{motion}. {scene.strip()}. {style}" if scene.strip() else f"{motion}. {style}"
|
| 417 |
+
frames = wan_sample(prompt, num_frames, VIDEO_WIDTH, VIDEO_HEIGHT, seed,
|
| 418 |
+
first_frame=image.convert("RGB").resize((VIDEO_WIDTH, VIDEO_HEIGHT), Image.LANCZOS))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 419 |
path = f"/tmp/video_{seed}_{random.randint(0, 99999)}.mp4"
|
| 420 |
export_to_video(frames, path, fps=FPS, quality=VIDEO_QUALITY)
|
| 421 |
return path, len(frames) / FPS
|
|
|
|
| 775 |
|
| 776 |
|
| 777 |
def clip_frames(seconds):
|
| 778 |
+
"""Frames Wan is asked for: a multiple of 4 plus 1, at most 121 (5 seconds at 24 frames a second)."""
|
| 779 |
+
return min(MAX_VIDEO_FRAMES, -(-int(seconds * FPS) // 4) * 4 + 1)
|
| 780 |
|
| 781 |
|
| 782 |
def film(image, scene, motion, music_prompt, want_narration, improve, seconds, seed):
|
| 783 |
+
"""A clip made one model at a time, so FLUX and Wan are never on the GPU together:
|
| 784 |
+
the text model (prompts and narration plan), FLUX draws, Wan2.2 animates, then MusicGen."""
|
| 785 |
plan = None
|
| 786 |
improve = improve and bool(scene.strip() or motion.strip())
|
| 787 |
if improve or want_narration:
|
|
|
|
| 790 |
if improve:
|
| 791 |
scene, motion = improve_prompts(scene, motion)
|
| 792 |
if want_narration:
|
| 793 |
+
plan = plan_narration(scene, motion, clip_frames(seconds) / FPS)
|
| 794 |
if image is None:
|
| 795 |
with timed(" draw"):
|
| 796 |
image, _ = draw_image(scene, seed)
|
| 797 |
+
packs.load("wan")
|
| 798 |
with timed(" animate"):
|
| 799 |
video, length = animate(image, scene, motion, seconds, seed)
|
| 800 |
music_wav = None
|
|
|
|
| 806 |
|
| 807 |
|
| 808 |
def studio_duration(image, scene, motion, music_prompt, want_narration, improve, seconds, seed):
|
| 809 |
+
total = 25 + min(seconds, 5) * 5.0 # Animation (Wan, 3 steps). ESTIMATE: check the logs and tighten
|
| 810 |
if image is None:
|
| 811 |
total += IMAGE_SECONDS - 2 # FLUX draws the scene first (FLUX.3: caption + 16 steps)
|
| 812 |
if music_prompt.strip():
|
|
|
|
| 838 |
# ---------------------------------------------------------------- Edit tab
|
| 839 |
|
| 840 |
EDIT_IMAGE_PIXELS = 1024 * 1024 # Edited pictures keep their shape and are about this many pixels
|
| 841 |
+
EDIT_VIDEO_PIXELS = 1152 * 768 # The size Wan makes clips at
|
| 842 |
+
EDIT_VIDEO_FRAMES = 49 # About 2 seconds at 24 frames a second (Wan needs 4k + 1 frames)
|
| 843 |
+
# Which of FastWan's steps re-draw the clip: the first step's noise level sets how much changes.
|
| 844 |
+
# "A lot" starts from pure noise but keeps the clip's first frame, so the scene stays and the motion is new.
|
| 845 |
+
EDIT_VIDEO_CHANGE = {"A little": [522], "Quite a lot": [757, 522], "A lot": [1000, 757, 522]}
|
| 846 |
EDIT_VIDEO_FPS = 24
|
| 847 |
MUSIC_EDIT_RATE = 48000 # ACE-Step works with 48 kHz stereo
|
| 848 |
MUSIC_EDIT_LIMIT = 60 # Songs are cut to their first 60 seconds
|
|
|
|
| 923 |
if len(frames) >= EDIT_VIDEO_FRAMES:
|
| 924 |
break
|
| 925 |
reader.close()
|
| 926 |
+
count = (len(frames) - 1) // 4 * 4 + 1 # Wan needs 4k + 1 frames
|
| 927 |
return frames[:count], source_fps / step
|
| 928 |
|
| 929 |
|
| 930 |
def edit_video_prompt(frame, instruction, improve):
|
| 931 |
+
"""Wan needs a description of the finished clip, not an instruction. Florence-2 describes the first frame,
|
| 932 |
then Qwen3 4B writes how the clip looks after the change. Both must already be on the GPU."""
|
| 933 |
seen = caption_image(frame)
|
| 934 |
if not improve:
|
|
|
|
| 943 |
|
| 944 |
|
| 945 |
def edit_video_seconds(frames, fps, instruction, change, seed, improve):
|
| 946 |
+
return gpu_seconds(25 + 0.1 * len(frames) * len(EDIT_VIDEO_CHANGE.get(change, [757, 522]))) # ESTIMATE: check logs
|
| 947 |
|
| 948 |
|
| 949 |
@spaces.GPU(duration=edit_video_seconds, size=VIDEO_GPU_SIZE)
|
| 950 |
def edit_video_gpu(frames, fps, instruction, change, seed, improve):
|
| 951 |
+
"""Wan video to video: the clip is encoded, noise is added, and FastWan's last steps re-draw it to match
|
| 952 |
the prompt, so the motion and layout of the original stay."""
|
| 953 |
with timed("edit video"):
|
| 954 |
packs.load("florence", "qwen")
|
| 955 |
prompt = edit_video_prompt(frames[0], instruction, improve)
|
| 956 |
+
packs.load("wan")
|
| 957 |
width, height = fit(frames[0].width, frames[0].height, EDIT_VIDEO_PIXELS, 32)
|
| 958 |
video = [f.resize((width, height), Image.LANCZOS) for f in frames]
|
| 959 |
+
steps = EDIT_VIDEO_CHANGE.get(change, [757, 522])
|
| 960 |
+
if steps[0] >= 1000: # Full re-draw: keep only the first frame
|
| 961 |
+
result = wan_sample(prompt, len(video), width, height, seed, first_frame=video[0], steps=steps)
|
| 962 |
+
else:
|
| 963 |
pixels = video_pipe.video_processor.preprocess_video(video, height, width)
|
| 964 |
+
result = wan_sample(prompt, len(video), width, height, seed, start_latents=wan_encode(pixels),
|
| 965 |
+
steps=steps)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 966 |
path = f"/tmp/edit_video_{seed}_{random.randint(0, 99999)}.mp4"
|
| 967 |
export_to_video(result, path, fps=fps, quality=VIDEO_QUALITY)
|
| 968 |
return path, prompt
|
|
|
|
| 1105 |
# ---------------------------------------------------------------- UI
|
| 1106 |
|
| 1107 |
with gr.Blocks(title="Graphics Studio") as demo:
|
| 1108 |
+
gr.Markdown("# Graphics Studio\n**FLUX.3 Image klein** images, **Wan2.2** animation, **MusicGen** music, "
|
| 1109 |
"**Qwen3** + **Kokoro** narration, **Whisper** transcription, "
|
| 1110 |
"**Florence-2** image captions, **SmolVLM2** video descriptions, **CLAP** music classification.")
|
| 1111 |
gr.Markdown("Already have an image, a video or some music and want to change it? Use the **Edit** tab: "
|
| 1112 |
+
"**FLUX.3 Image klein** edits pictures, **Wan2.2** re-draws videos, **ACE-Step 1.5** edits songs.")
|
| 1113 |
counter = gr.Markdown(counts_text())
|
| 1114 |
|
| 1115 |
with gr.Tab("Image"):
|
|
|
|
| 1204 |
improve_prompt = gr.Checkbox(value=True, label="Improve my prompts first (Qwen3 4B adds visual "
|
| 1205 |
"detail; untick to use your exact words)")
|
| 1206 |
want_narration = gr.Checkbox(value=False, label="Add narration")
|
| 1207 |
+
seconds = gr.Slider(2, 5, value=5, step=1, label="Length (seconds)")
|
| 1208 |
with gr.Accordion("More options", open=False):
|
| 1209 |
start_image = gr.Image(label="Start image (optional; otherwise FLUX draws the scene)", type="pil")
|
| 1210 |
with gr.Row():
|
|
|
|
| 1251 |
edit_vid_button = gr.Button("Change video", variant="primary")
|
| 1252 |
with gr.Column():
|
| 1253 |
edit_vid_out = gr.Video(label="New video", autoplay=False, loop=True)
|
| 1254 |
+
edit_vid_prompt = gr.Textbox(label="Prompt Wan2.2 was given", lines=3, interactive=False)
|
| 1255 |
gr.Markdown("Works best for changing the look: colours, clothes, the weather, the time of day or the "
|
| 1256 |
"style (cartoon, painting, snow). Adding or removing whole objects works less well.")
|
| 1257 |
with gr.Tab("Edit music"):
|