rtgfreuui commited on
Commit
37e06dc
·
verified ·
1 Parent(s): e168a5c

Copy files from spaces/Viggle/viggle-animate

Browse files
.gitattributes CHANGED
@@ -33,3 +33,41 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ examples/costume_drive.mp4 filter=lfs diff=lfs merge=lfs -text
37
+ examples/costume_out.mp4 filter=lfs diff=lfs merge=lfs -text
38
+ examples/costume_ref.png filter=lfs diff=lfs merge=lfs -text
39
+ examples/prop_drive.mp4 filter=lfs diff=lfs merge=lfs -text
40
+ examples/prop_out.mp4 filter=lfs diff=lfs merge=lfs -text
41
+ examples/prop_ref.png filter=lfs diff=lfs merge=lfs -text
42
+ examples/style_drive.mp4 filter=lfs diff=lfs merge=lfs -text
43
+ examples/style_out.mp4 filter=lfs diff=lfs merge=lfs -text
44
+ examples/style_ref.png filter=lfs diff=lfs merge=lfs -text
45
+ examples/clay_out.mp4 filter=lfs diff=lfs merge=lfs -text
46
+ examples/clay_ref.png filter=lfs diff=lfs merge=lfs -text
47
+ examples/corgi_out.mp4 filter=lfs diff=lfs merge=lfs -text
48
+ examples/corgi_ref.png filter=lfs diff=lfs merge=lfs -text
49
+ examples/duo_anime_drive.mp4 filter=lfs diff=lfs merge=lfs -text
50
+ examples/duo_anime_out.mp4 filter=lfs diff=lfs merge=lfs -text
51
+ examples/duo_anime_ref.png filter=lfs diff=lfs merge=lfs -text
52
+ examples/duo_real_out.mp4 filter=lfs diff=lfs merge=lfs -text
53
+ examples/duo_real_ref.png filter=lfs diff=lfs merge=lfs -text
54
+ examples/panda_drive.mp4 filter=lfs diff=lfs merge=lfs -text
55
+ examples/panda_out.mp4 filter=lfs diff=lfs merge=lfs -text
56
+ examples/panda_ref.png filter=lfs diff=lfs merge=lfs -text
57
+ examples/penguin_drive.mp4 filter=lfs diff=lfs merge=lfs -text
58
+ examples/penguin_out.mp4 filter=lfs diff=lfs merge=lfs -text
59
+ examples/penguin_ref.png filter=lfs diff=lfs merge=lfs -text
60
+ examples/plane_drive.mp4 filter=lfs diff=lfs merge=lfs -text
61
+ examples/plane_out.mp4 filter=lfs diff=lfs merge=lfs -text
62
+ examples/plane_ref.png filter=lfs diff=lfs merge=lfs -text
63
+ examples/robot_drive.mp4 filter=lfs diff=lfs merge=lfs -text
64
+ examples/robot_out.mp4 filter=lfs diff=lfs merge=lfs -text
65
+ examples/robot_ref.png filter=lfs diff=lfs merge=lfs -text
66
+ examples/wushu_animals_drive.mp4 filter=lfs diff=lfs merge=lfs -text
67
+ examples/wushu_animals_out.mp4 filter=lfs diff=lfs merge=lfs -text
68
+ examples/wushu_animals_ref.png filter=lfs diff=lfs merge=lfs -text
69
+ examples/wushu_robots_out.mp4 filter=lfs diff=lfs merge=lfs -text
70
+ examples/wushu_robots_ref.png filter=lfs diff=lfs merge=lfs -text
71
+ examples/lipsync_drive.mp4 filter=lfs diff=lfs merge=lfs -text
72
+ examples/lipsync_out.mp4 filter=lfs diff=lfs merge=lfs -text
73
+ examples/lipsync_ref.png filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,12 +1,53 @@
1
  ---
2
- title: Rfihjref
3
- emoji: 🔥
4
- colorFrom: pink
5
- colorTo: green
6
- sdk: static
 
 
 
 
7
  pinned: false
8
- license: other
9
- short_description: iooiojkij
 
10
  ---
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Viggle-Animate
3
+ emoji: 🕺
4
+ colorFrom: indigo
5
+ colorTo: purple
6
+ sdk: gradio
7
+ sdk_version: 5.50.0
8
+ python_version: "3.10"
9
+ app_file: app.py
10
+ hf_oauth: true
11
  pinned: false
12
+ models:
13
+ - Viggle/Viggle-Animate
14
+ short_description: Put the person from a still into a driving video, in 4 steps
15
  ---
16
 
17
+ Upload a driving video and a character still. The clip's first frame is repainted with
18
+ gpt-image-2 so it shows your character in that exact pose and framing, and that repainted
19
+ frame is the only conditioning the model gets besides the clip itself — no pose estimation,
20
+ no segmentation, no masks.
21
+
22
+ Takes 4–10 s of driving video and renders it at 4 sampling steps; anything longer is cut to
23
+ 10.1 s. The model itself only renders frame counts of the form 17k+5 and never fewer than 124
24
+ (5.17 s), so shorter clips are held out to 124 frames with a frozen last frame and the render
25
+ is trimmed back — what comes out is exactly as long as what went in.
26
+
27
+ Weights: [`Viggle/Viggle-Animate`](https://huggingface.co/Viggle/Viggle-Animate).
28
+
29
+ **No sign-in.** The GPU comes out of your own ZeroGPU quota, and the render asks for more of
30
+ it than a free account's day holds — in practice rendering needs PRO. The repaint calls an
31
+ image model this Space pays for, on the CPU, before any GPU is involved, and is limited to
32
+ five a day per visitor. The finished examples at the bottom of the page need neither, and
33
+ are there so the model can be judged for free.
34
+
35
+ **Hardware.** The transformer is 62 GiB in bf16; with the VAEs that is 73.5 GiB on the card.
36
+ ZeroGPU `xlarge` (96 GB) is required — `large` is 48 GB and cannot hold it. `xlarge` bills at
37
+ 2× the normal quota rate, so a free account's day does not go far here; PRO gets 40 min.
38
+
39
+ The weights stay on the CPU at startup. Pre-staging them through ZeroGPU's tensor pack was
40
+ tried and cannot fit: the pack plus the source weights need ~159 GB on disk at once, and the
41
+ container enforces a write quota that `df` does not show — the pack's `fallocate` dies with
42
+ ENOSPC while the boot log prints over a terabyte free. The cost is one host-to-device copy on
43
+ the first render a cold worker handles (measured 14 s, from warm page cache); queued renders
44
+ after it skip the copy. What did land instead: the decode step quantizes to uint8 on the card
45
+ rather than walking the clip to fp32 numpy on the CPU (bit-identical frames, several seconds
46
+ of GPU time saved), the frame count rides along from `prepare` instead of being re-counted in
47
+ the billed window, and trimming plus watermarking run in the parent process after the GPU
48
+ window closes.
49
+
50
+ When AOT-compiled copies of the transformer's two repeated block classes exist in the weights
51
+ repo (`<ClassName>/package.pt2`, built once on this hardware from an owner-only maintenance
52
+ button), they are downloaded at boot and swapped in after the weights reach the card; without
53
+ them the Space renders the same model eagerly.
app.py ADDED
@@ -0,0 +1,1111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Viggle-Animate on ZeroGPU: put the person from a still into a driving video.
3
+
4
+ Two stages, deliberately split so the OpenAI call never burns GPU quota:
5
+
6
+ prepare (CPU) frame 0 of the driving clip is handed to gpt-image-2 together with the
7
+ character still, and comes back with the performer replaced. That
8
+ repainted frame is the model's reference -- the whole "no pose, no
9
+ segmentation, no mask" claim rests on this being the only preprocessing.
10
+ A frame painted elsewhere can be supplied directly instead, which is what
11
+ the bundled examples do: it costs nothing and it renders deterministically.
12
+ render (GPU) 4 sampling steps against the driving clip. ~62 GiB of weights, so this
13
+ needs ZeroGPU `xlarge` (the full 96 GB card); `large` is 48 GB and
14
+ cannot hold it.
15
+
16
+ Measured on this hardware: weights download at ~1.05 GiB/s and load in ~85 s, for 73.5 GiB
17
+ of parameters against a 95.0 GiB card.
18
+
19
+ The load is at MODULE level because `@spaces.GPU` bodies run in a worker process forked on
20
+ the first GPU request -- it inherits everything import time set up, and nothing a request
21
+ handler later assigns to a global. The weights stay on the CPU at startup; pre-staging them
22
+ through ZeroGPU's tensor pack was tried and does not fit here -- see the note at the bottom
23
+ of the load.
24
+ """
25
+
26
+ import base64
27
+ import contextlib
28
+ import inspect
29
+ import io
30
+ import json
31
+ import os
32
+ import shutil
33
+ import subprocess
34
+ import tempfile
35
+ import time
36
+ from pathlib import Path
37
+
38
+ # 243 frames peaks at 86.1 GiB allocated against a 95.0 GiB card. That margin only survives if
39
+ # the allocator can grow segments instead of stranding them, so this is set before torch loads.
40
+ # Both spellings: 2.9 renamed the variable and warns on the old one, 2.8 only knows the old one.
41
+ os.environ.setdefault("PYTORCH_ALLOC_CONF", "expandable_segments:True")
42
+ os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
43
+
44
+ import gradio as gr
45
+ import spaces
46
+ import torch
47
+ from huggingface_hub import HfApi, hf_hub_download, snapshot_download
48
+ from huggingface_hub.errors import EntryNotFoundError
49
+ from openai import OpenAI
50
+ from PIL import Image
51
+
52
+ # A private module: LazyAOTIModel and PACKAGE_FILENAME are not among the package's lazy
53
+ # top-level exports. The builder pins `spaces` itself (0.51.1 at this writing -- listing it in
54
+ # requirements.txt at any other version is a pip conflict); this module is byte-identical in
55
+ # 0.51.1 and 0.51.3, the versions the code was written against.
56
+ from spaces.zero.torch.aoti import (PACKAGE_FILENAME, LazyAOTIModel, aoti_capture,
57
+ aoti_compile_and_save, aoti_patch)
58
+
59
+ H3 = "/tmp/h3"
60
+ VA = "/tmp/viggle"
61
+ MODEL_CARD = "https://huggingface.co/Viggle/Viggle-Animate"
62
+ SITE = "https://viggle.ai/h3"
63
+ EX = Path(__file__).parent / "examples"
64
+ # Every case ships as driving clip + already-painted frame 0 + the render those two produce,
65
+ # so clicking one costs no GPU and no OpenAI call. Several share a driving clip, hence the
66
+ # name -> (drive file prefix, caption) shape: `corgi` and `clay` reuse `costume`'s clip, and
67
+ # the second take of each two-character pair reuses its partner's.
68
+ # Order is what a visitor reads top to bottom. `lipsync` is first because it is the only case
69
+ # whose driving clip carries a soundtrack, and therefore the only one where the mouth has
70
+ # anything to track: every other output's audio track is this finetune's digital silence
71
+ # (-105 dBFS, against -22 for this one). Then the swaps where the target is not a person -- one
72
+ # paint and one render each, no best-of-N -- and last the human cases the model card compares
73
+ # against Wan2.2-Animate. Within that, aspect ratio is grouped, because the output rows below
74
+ # are split on these indices.
75
+ CASES = {
76
+ "lipsync": ("lipsync", "the driving clip has sound, so the mouth has something to say "
77
+ "— turn the volume on"),
78
+ "corgi": ("costume", "a corgi"),
79
+ "panda": ("panda", "a giant panda"),
80
+ "penguin": ("penguin", "a penguin"),
81
+ "plane": ("plane", "an airliner — wings for arms, landing gear for legs"),
82
+ "robot": ("robot", "a walking robot"),
83
+ "clay": ("costume", "claymation"),
84
+ "duo_anime": ("duo_anime", "two characters at once — cel-shaded cat and corgi"),
85
+ "duo_real": ("duo_anime", "the same frame, painted photoreal over the anime set"),
86
+ "wushu_animals": ("wushu_animals", "a wide arena shot, both fighters replaced"),
87
+ "wushu_robots": ("wushu_animals", "the same shot, gold and chrome robots"),
88
+ "prop": ("prop", "a light-up toy, held in both hands"),
89
+ "costume": ("costume", "a bow headwrap and floral leggings, driven by a bearded man"),
90
+ "style": ("style", "a flat 2D anime character"),
91
+ }
92
+ FPS = 24
93
+ # The video VAE only encodes frame counts of the form 17n+5, and the pipeline refuses anything
94
+ # under 5.0 s, so 124 (5.167 s) is the shortest render that exists -- not a choice made here.
95
+ # Uploads are held out to the next such count and the render is cut back, so any length between
96
+ # MIN_UPLOAD_S and MAX_FRAMES/FPS comes back at its own length.
97
+ #
98
+ # The ceiling is VRAM, not the model, which allows up to 345. Measured peak allocated on one
99
+ # B200 at 480x832: 79.9 GiB at 124 frames, 82.5 at 175, 86.1 at 243, and 86.8 at 243 frames on a
100
+ # 480x864 canvas -- 414,720 px, wider than anything LADDER can now produce, so that 86.8 GiB is a
101
+ # true upper bound with 8.2 GiB of headroom against this card's 95.0 GiB. Hence 243, not 345.
102
+ CHUNK, TAIL = 17, 5
103
+ MIN_FRAMES, MAX_FRAMES = 124, 243 # 5.167 s .. 10.125 s
104
+ MIN_UPLOAD_S = 4.0
105
+ # The 480-class bucket ladder, copied from `ft/buckets.py`. These nine geometries are the only ones
106
+ # the model was ever trained or evaluated on. They are 32-aligned by construction and all spend the
107
+ # same ~390 rows per latent frame -- the ladder holds *area* constant, not the short edge.
108
+ LADDER = [(416, 960), (448, 896), (480, 832), (544, 736), (640, 640),
109
+ (736, 544), (832, 480), (896, 448), (960, 416)]
110
+ # Measured on this card (renders of 2026-09-01/05): the denoise loop runs 1.6x the B200 timings
111
+ # `budget` extrapolates from (42 s at 124 frames), and the host-to-device copy is 22 s from warm
112
+ # page cache, 75 s typical, 154 s cold -- and one 261 s outlier that overran the request and drew
113
+ # only a warning. Both are set high on purpose -- the padded request is what locks the free tier
114
+ # out at admission; see `budget`.
115
+ SLOWDOWN = float(os.environ.get("SLOWDOWN", "1.6")) # this card vs the B200 the timings came from
116
+ H2D = float(os.environ.get("H2D", "170")) # seconds to move the weights onto the card
117
+ # Measured good on this card: the first render logged no fallback, so sm_120 serves the shape.
118
+ ATTN = os.environ.get("ATTN", "_native_cudnn") # set to "" to stay on torch's default
119
+ DAILY = int(os.environ.get("DAILY_LIMIT", "5"))
120
+ # Who may press the AOTI build button, which holds a write token for the weights repo.
121
+ OWNERS = {u.strip().lower() for u in os.environ.get("OWNERS", "yycc").split(",") if u.strip()}
122
+ # The repaint is downscaled to a ladder canvas -- 480x832 at most -- before the model ever sees
123
+ # it, so the detail the higher tiers buy is resampled away. What has to survive that downscale is
124
+ # the pose and the identity, not the texture. "low", "medium", "high" or "auto".
125
+ QUALITY = os.environ.get("IMAGE_QUALITY", "low")
126
+ # There is no `input_fidelity` here on purpose. The openai SDK accepts the parameter, but
127
+ # gpt-image-2 rejects it -- `invalid_input_fidelity_model`, a 400 on every request, not a
128
+ # warning. It is a gpt-image-1 knob. Do not add it back.
129
+ FONT = "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"
130
+ # Fail at boot, not in `finish` -- which runs after the GPU money is already spent.
131
+ assert Path(FONT).exists(), f"watermark font missing: {FONT}"
132
+
133
+ t = time.time()
134
+ snapshot_download("MiniMaxAI/MiniMax-H3", local_dir=H3,
135
+ allow_patterns=["*.json", "vae/*", "audio_vae/*",
136
+ "scheduler/*", "audio_scheduler/*"])
137
+ snapshot_download("Viggle/Viggle-Animate", local_dir=VA,
138
+ allow_patterns=["transformer/*", "lora/*", "assets/*"])
139
+ print(f"[boot] weights in {time.time()-t:.0f}s", flush=True)
140
+
141
+ from diffusers import MiniMaxH3Transformer3DModel, ModularPipeline, attention_backend
142
+ from diffusers.modular_pipelines.minimax_h3 import (MiniMaxH3ImageReference,
143
+ MiniMaxH3VideoReference)
144
+ from diffusers.modular_pipelines.minimax_h3.before_denoise import MiniMaxH3SetTimestepsStep
145
+ from diffusers.modular_pipelines.minimax_h3.decoders import MiniMaxH3VideoDecodeStep
146
+ from diffusers.modular_pipelines.minimax_h3.denoise import MiniMaxH3LoopSchedulerStep
147
+ from diffusers.modular_pipelines.minimax_h3.encoders import MiniMaxH3Ref2VATextEncoderStep
148
+ from diffusers.modular_pipelines.minimax_h3.modular_pipeline import audio_latent_num_frames
149
+ from diffusers.utils.export_utils import encode_video
150
+
151
+ # The text encoder is never loaded: conditioning is a frozen 362x5120 tensor computed once
152
+ # from a fixed prompt, so Qwen3-VL (63 GB of the base repo) stays on disk. Nothing in the
153
+ # output comes from text anyone types here -- there is no prompt box for that reason.
154
+ FIXED = torch.load(f"{VA}/assets/fixed_embed_fwd_anyframe.pt", weights_only=False)
155
+
156
+
157
+ def use_fixed_embeds(self, components, state):
158
+ block_state = self.get_block_state(state)
159
+ block_state.prompt_embeds = FIXED["prompt_embeds"].to(components._execution_device,
160
+ torch.bfloat16)
161
+ block_state.text_token_tags = FIXED["text_token_tags"]
162
+ self.set_block_state(state, block_state)
163
+ return components, state
164
+
165
+
166
+ MiniMaxH3Ref2VATextEncoderStep.__call__ = use_fixed_embeds
167
+
168
+
169
+ @torch.no_grad() # stock has it too; the pipeline already runs under no_grad, so belt-and-braces
170
+ def decode_to_uint8(self, components, state):
171
+ """The stock step ends in `postprocess_video`, which walks the decoded clip to fp32 numpy on
172
+ the CPU -- measured 9.2 s at 243 frames against 0.03 s for quantizing on the card
173
+ (REALTIME_PIPELINE.md: "pure format conversion, buys nothing"). Everything through the fp32
174
+ denormalize below is the stock code, and fp32 round is round-half-to-even in numpy and torch
175
+ alike, so the u8 frames are bit-identical to what the old path fed x264 -- only the CPU round
176
+ trip is gone. `encode_video` takes the [T,H,W,C] uint8 tensor as-is. `output_type` is
177
+ ignored: this app is the only caller and it always wants frames.
178
+ """
179
+ block_state = self.get_block_state(state)
180
+ device = components._execution_device
181
+ latents_mean = torch.tensor(components.vae.config.latents_mean, device=device).view(1, -1, 1, 1, 1)
182
+ latents_std = torch.tensor(components.vae.config.latents_std, device=device).view(1, -1, 1, 1, 1)
183
+ latents = block_state.latents * latents_std + latents_mean
184
+ with torch.autocast(device_type=device.type, dtype=torch.float16, enabled=device.type == "cuda"):
185
+ video = components.vae.decode(latents, return_dict=False)[0]
186
+ pixel_mean = torch.tensor(components.pixel_mean, device=device).view(1, -1, 1, 1, 1)
187
+ pixel_std = torch.tensor(components.pixel_std, device=device).view(1, -1, 1, 1, 1)
188
+ video = (video.float() * pixel_std + pixel_mean).clamp(0, 1)
189
+ # In-place on purpose: `video` is a fresh tensor never read again, and the out-of-place
190
+ # spelling would hold two extra full-size fp32 temporaries at the peak.
191
+ block_state.videos = [v.mul_(255).round_().to(torch.uint8).permute(1, 2, 3, 0).contiguous().cpu()
192
+ for v in video]
193
+ self.set_block_state(state, block_state)
194
+ return components, state
195
+
196
+
197
+ MiniMaxH3VideoDecodeStep.__call__ = decode_to_uint8
198
+
199
+ # ---------------------------------------------------------------------------------------------
200
+ # The audio pin. When the upload has a soundtrack it is VAE-encoded and written into the render's
201
+ # *target* audio rows as a clean latent -- t=1, H3's flow being reversed -- and held there for the
202
+ # whole loop, instead of being denoised out of noise like every other target row. The video branch
203
+ # attends to those rows, so the picture is driven by the real speech. That is what improves
204
+ # lip-sync, and it is measurable rather than hoped for: against a control-vs-control floor of
205
+ # 50.4 dB, swapping the pinned track for encoded silence moves the video by 23.0-32.8 dB across
206
+ # four shot/canvas combinations. It costs nothing -- peak VRAM matched the control to 0.1 GiB and
207
+ # wall clock to within run-to-run noise. `AUDIO_PIN.md` in the repo has the falsification runs.
208
+ #
209
+ # Both patches are installed once, at import, and read PIN at call time. Installing them per
210
+ # request would leak across visitors: a class patch is process-global and one worker serves every
211
+ # request, so an upload that had audio would silently pin the next upload that did not.
212
+ PIN = False
213
+
214
+ _build_row_timesteps = MiniMaxH3SetTimestepsStep.build_row_timesteps
215
+
216
+
217
+ def pinned_row_timesteps(*a):
218
+ """Tell the transformer the target audio rows are already clean.
219
+
220
+ Positional arg 6 is `audio_timestep`, and `before_denoise.py` passes all nine positionally.
221
+ Without this the rows hold real audio while the model is told they are noise at the current
222
+ sigma, and it denoises against a premise that is false.
223
+ """
224
+ return _build_row_timesteps(*a[:6], 1.0, *a[7:]) if PIN else _build_row_timesteps(*a)
225
+
226
+
227
+ MiniMaxH3SetTimestepsStep.build_row_timesteps = staticmethod(pinned_row_timesteps)
228
+
229
+ _loop_step = MiniMaxH3LoopSchedulerStep.__call__
230
+
231
+
232
+ @torch.no_grad()
233
+ def video_only_step(self, components, block_state, i, t):
234
+ """Step the video rows only, so the pinned audio rows survive every step untouched.
235
+
236
+ The obvious alternative -- raising `num_condition_audio_rows` so the loop treats them as
237
+ conditioning -- does not work: it empties the decoder's slice
238
+ `audio_latents[num_condition_audio_rows:]` and trips the reference-count assert in
239
+ `MiniMaxH3PrepareLatentsStep`. That count stays 0.
240
+ """
241
+ if not PIN:
242
+ return _loop_step(self, components, block_state, i, t)
243
+ n = block_state.num_condition_video_rows
244
+ block_state.latents[n:] = components.scheduler.step(
245
+ block_state.noise_pred[0, n:].float(), t, block_state.latents[n:], return_dict=False)[0]
246
+ return components, block_state
247
+
248
+
249
+ MiniMaxH3LoopSchedulerStep.__call__ = video_only_step
250
+
251
+ t = time.time()
252
+ PIPE = ModularPipeline.from_pretrained(H3, workflow="ref2va")
253
+ PIPE.load_components(names=["vae", "audio_vae", "scheduler", "audio_scheduler"],
254
+ pretrained_model_name_or_path=H3, torch_dtype=torch.bfloat16)
255
+ PIPE.transformer_ref = MiniMaxH3Transformer3DModel.from_pretrained(
256
+ f"{VA}/transformer", torch_dtype=torch.bfloat16)
257
+ # `prefix=None` and the explicit `weight_name` are both required: the loader defaults to a
258
+ # `.bin` name (raises) and to filtering keys for a `transformer.` prefix these bare keys do
259
+ # not have -- that mismatch loads nothing and only warns, i.e. silently renders the
260
+ # un-distilled model at 4 steps, which looks like noise.
261
+ PIPE.transformer_ref.load_lora_adapter(f"{VA}/lora",
262
+ weight_name="pytorch_lora_weights.safetensors",
263
+ prefix=None)
264
+ PIPE.scheduler.set_shift(3.0) # the base default is 12; the few-step student wants 3
265
+ ASR = PIPE.audio_vae.config.sampling_rate # 32 kHz; the rate the pin has to be fed at
266
+
267
+ # AOT-compiled copies of the transformer's two repeated block classes, built ON THIS HARDWARE by
268
+ # the maintenance button below (a package compiled on another arch will not load) and stored in
269
+ # the weights repo as <ClassName>/package.pt2 -- code only, tens of MB: the weights come from
270
+ # each block's own state_dict at patch time. Missing packages mean an eager Space, not a broken
271
+ # one. Only the *download* happens here; the patching waits for the GPU worker, because
272
+ # `aoti_patch` snapshots `state_dict()` and until `PIPE.to("cuda")` in `render` those storages
273
+ # are the CPU ones the copy abandons -- patched at boot, the compiled blocks would read CPU
274
+ # weights forever. See `wire_aoti`.
275
+ AOTI_REPO = "Viggle/Viggle-Animate"
276
+
277
+
278
+ class _Cell:
279
+ # Stand-in for the ContextVars inside LazyAOTIModel. The worker runs every GPU task in a
280
+ # fresh copy_context(), so a ContextVar set during one render is invisible to the next --
281
+ # the dlopen'd package would be re-extracted and re-loaded inside every billed window, and
282
+ # each extraction is another copy charged against the container's hidden write quota. A
283
+ # plain attribute survives across tasks; the parent never calls these models, so the
284
+ # context isolation being discarded here protected nothing.
285
+ def __init__(self):
286
+ self.v = None
287
+
288
+ def get(self):
289
+ return self.v
290
+
291
+ def set(self, v):
292
+ self.v = v
293
+
294
+
295
+ AOTI_BLOCKS = {}
296
+ # `ATTN=""` must keep meaning "no cuDNN anywhere": the packages baked cuDNN in at build time
297
+ # and ignore `set_attention_backend`, so with the kill switch set they may not be wired at all.
298
+ if os.environ.get("AOTI", "1") == "1" and ATTN:
299
+ try:
300
+ AOTI_BLOCKS = {name: LazyAOTIModel(hf_hub_download(AOTI_REPO, PACKAGE_FILENAME,
301
+ subfolder=name))
302
+ for name in MiniMaxH3Transformer3DModel._repeated_blocks}
303
+ for lazy in AOTI_BLOCKS.values():
304
+ lazy.compiled_model, lazy.loaded_weights = _Cell(), _Cell()
305
+ print(f"[boot] aoti packages loaded: {', '.join(AOTI_BLOCKS)}", flush=True)
306
+ except EntryNotFoundError:
307
+ AOTI_BLOCKS = {}
308
+ print("[boot] no aoti packages on the hub -- rendering eager", flush=True)
309
+ # The weights stay on the CPU until `render`'s `PIPE.to("cuda")`. Pre-staging them through
310
+ # ZeroGPU's tensor pack (`PIPE.to("cuda")` here at import) was tried 2026-09-01 and cannot fit:
311
+ # the pack `posix_fallocate`s 78.6 GB while the 80 GB of sources still sit on the same disk, and
312
+ # the container has a hidden ~100 GB write quota that statvfs does not report -- the boot line
313
+ # below prints >1.3 TB free while the fallocate dies ENOSPC instantly. The prize was small
314
+ # anyway: the pack loads via O_DIRECT disk reads, the copy it replaces runs from warm page cache.
315
+ print(f"[boot] pipeline in {time.time()-t:.0f}s, "
316
+ f"disk free {shutil.disk_usage('/tmp').free/1e9:.0f} GB /tmp, "
317
+ f"{shutil.disk_usage(Path.home()).free/1e9:.0f} GB {Path.home()}", flush=True)
318
+
319
+
320
+ def run(*cmd):
321
+ # ffmpeg says why it failed on stderr, and `capture_output` swallows it -- a bare
322
+ # CalledProcessError names the exit code and nothing else, which is useless for a codec or
323
+ # container the uploader chose.
324
+ p = subprocess.run(cmd, capture_output=True, text=True, errors="replace")
325
+ if p.returncode:
326
+ raise gr.Error(f"{cmd[0]} failed: {p.stderr.strip().splitlines()[-1] if p.stderr.strip() else p.returncode}")
327
+
328
+
329
+ def sweep(hours=6):
330
+ """Drop working directories older than `hours`.
331
+
332
+ Each request leaves one behind holding a few hundred MB of intermediate video, and the
333
+ container runs for weeks. Pruning by age rather than tracking them is deliberate: a render
334
+ in flight still owns its directory, and age is the one property that cannot mistake a live
335
+ job for a dead one.
336
+ """
337
+ cutoff = time.time() - hours * 3600
338
+ for d in Path(tempfile.gettempdir()).glob("tmp*"):
339
+ # Two concurrent requests both sweep, so a directory can disappear between the glob and
340
+ # the stat. That is not a reason to fail somebody's render.
341
+ with contextlib.suppress(OSError):
342
+ if d.is_dir() and d.stat().st_mtime < cutoff:
343
+ shutil.rmtree(d, ignore_errors=True)
344
+
345
+
346
+ def probe(path):
347
+ out = subprocess.run(
348
+ ["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries",
349
+ "stream=width,height", "-of", "json", path],
350
+ check=True, capture_output=True, text=True).stdout
351
+ s = json.loads(out)["streams"][0]
352
+ return s["width"], s["height"]
353
+
354
+
355
+ def nframes(path):
356
+ return int(subprocess.run(
357
+ ["ffprobe", "-v", "error", "-select_streams", "v:0", "-count_frames",
358
+ "-show_entries", "stream=nb_read_frames", "-of", "csv=p=0", path],
359
+ check=True, capture_output=True, text=True).stdout.strip())
360
+
361
+
362
+ def has_audio(path):
363
+ """Whether the upload carries a soundtrack, which is what decides if the pin is used."""
364
+ return bool(subprocess.run(
365
+ ["ffprobe", "-v", "error", "-select_streams", "a:0", "-show_entries",
366
+ "stream=codec_type", "-of", "csv=p=0", path],
367
+ check=True, capture_output=True, text=True).stdout.strip())
368
+
369
+
370
+ def grid(n):
371
+ """Smallest frame count the video VAE accepts (17k+5) that still covers `n` frames.
372
+
373
+ Rounding *up* costs at most 16 frames of held-still tail, which gets trimmed off the render.
374
+ Rounding down would instead silently shorten every clip that is not already on the grid.
375
+ """
376
+ return min(MAX_FRAMES, max(MIN_FRAMES, -(-(n - TAIL) // CHUNK) * CHUNK + TAIL))
377
+
378
+
379
+ def canvas(w, h):
380
+ """The ladder geometry whose aspect is closest to the upload's.
381
+
382
+ Not "scale to a 480 short edge", which is the obvious rule and the wrong one. The ladder
383
+ holds area constant, not the short edge, so the two rules agree only near 480x832 and drift
384
+ apart everywhere else -- a square clip on a 480 short edge is 480x480, which is 225 rows per
385
+ latent frame against the ladder's 390. `ft/dataset_fwd.py:59` records training doing exactly
386
+ that and undoing it: "1:1 used to resize to 480x480 [...] 42% of the budget thrown away on
387
+ the one class that could most afford the pixels. Index 4 is 640x640."
388
+
389
+ Snapping to the ladder also removes two failure modes for free. Every entry is a multiple of
390
+ 32, so the patchify guard can no longer fire -- it is what the 16-grid 464 case used to trip.
391
+ And the aspects are bounded to 0.43..2.31, so a panorama or a column no longer produces a
392
+ canvas the model has never seen; it gets cover-cropped to the nearest one it has.
393
+ """
394
+ return min(LADDER, key=lambda b: abs(b[0] / b[1] - w / h))
395
+
396
+
397
+ def fit(img, w, h):
398
+ """Land a reference frame on exactly w x h without stretching it.
399
+
400
+ Stretching would be the quiet failure here: the reference is compared against the driving
401
+ clip frame by frame, so a horizontally squeezed body is a body that disagrees with every
402
+ frame of the motion. Off-aspect input is cover-cropped instead, losing edges rather than
403
+ proportions.
404
+ """
405
+ if abs(img.width / img.height - w / h) > 0.01:
406
+ s = max(w / img.width, h / img.height)
407
+ img = img.resize((round(img.width * s), round(img.height * s)), Image.LANCZOS)
408
+ img = img.crop(((img.width - w) // 2, (img.height - h) // 2,
409
+ (img.width - w) // 2 + w, (img.height - h) // 2 + h))
410
+ return img.resize((w, h), Image.LANCZOS)
411
+
412
+
413
+ # The repainted frame is a motion anchor before it is a picture. Whatever geometry it shows is
414
+ # what the video model tries to reconcile with the driving clip, and when the two disagree the
415
+ # driving clip wins -- an editor that quietly re-poses or re-centres the subject produces a
416
+ # reference that fights every frame. So the pose is stated as the constraint and the identity as
417
+ # the single edit, rather than both being items in one list.
418
+ REPAINT = (
419
+ "Edit the first image, which is one frame of a video. Change exactly one thing: who the "
420
+ "person is. Give them the face, hair, skin tone and clothing of the person in the second "
421
+ "image.\n"
422
+ "The body does not move. Keep the pose identical -- every limb, both hands, the head angle "
423
+ "and the direction of gaze stay exactly where they are, and the person keeps the same "
424
+ "position in the frame and the same size. Do not re-pose, straighten, re-centre or redraw "
425
+ "the body: repaint the person who is already standing there, do not draw a new one.\n"
426
+ "Nothing else changes. Same camera angle, same framing and crop, same background, same "
427
+ "lighting, shadows and colour grade. Anything the person is holding or touching stays "
428
+ "exactly as it is, in the same hand, at the same angle.\n"
429
+ "Do not zoom or crop, and do not add text, captions or watermarks."
430
+ )
431
+
432
+ SEEN = {}
433
+
434
+
435
+ def gate(request):
436
+ """One repaint counter per client IP per day.
437
+
438
+ This is a spend limit on the owner's image-model budget, not on the GPU. The gpt-image-2
439
+ repaint happens in `prepare`, on the CPU, before any `@spaces.GPU` call -- ZeroGPU's quota
440
+ never sees it, and only this counter stops it. The GPU needs no gate here at all: ZeroGPU's
441
+ own admission check turns visitors away by their Hub quota (see `budget`).
442
+
443
+ An IP is a weaker key than the Hub username this used to count -- a forwarded header can be
444
+ rewritten, and one NAT can hide a classroom -- but the username needed a sign-in, and the
445
+ sign-in was judged to cost more visitors than the key was worth. A brake, not a wall.
446
+ """
447
+ key = _client_key(request)
448
+ used = SEEN.get(key, 0)
449
+ if used >= DAILY:
450
+ raise gr.Error(f"daily repaint limit reached ({DAILY}). Try again tomorrow, or supply "
451
+ "a first frame you painted elsewhere -- that path is not limited.")
452
+ # Yesterday's counters are dead weight in a process that stays up for weeks.
453
+ for k in [k for k in SEEN if k[1] != key[1]]:
454
+ del SEEN[k]
455
+ SEEN[key] = used + 1
456
+ return DAILY - used - 1
457
+
458
+
459
+ def _client_key(request):
460
+ ip = (request.headers.get("x-forwarded-for", "").split(",")[0].strip()
461
+ or request.client.host) if request else "?"
462
+ return ip, time.strftime("%Y-%m-%d")
463
+
464
+
465
+ def refund(request):
466
+ # A repaint the server failed to deliver should not cost one of the day's five.
467
+ key = _client_key(request)
468
+ if SEEN.get(key, 0) > 0:
469
+ SEEN[key] -= 1
470
+
471
+
472
+ # A Space restart empties /tmp/gradio, but pages opened before it still reference files there.
473
+ # The re-submitted click then dies inside the components' own preprocess (PIL.Image.open --
474
+ # production, 2026-09-05), *before* any handler runs, so only a wrapper here can turn the raw
475
+ # FileNotFoundError into something a visitor can act on.
476
+ _GONE = ("this page predates a Space restart and its uploads are gone -- "
477
+ "reload the page and upload the files again")
478
+
479
+ for _cls in (gr.Image, gr.Video):
480
+ def _guarded(self, *a, _orig=_cls.preprocess, **k):
481
+ try:
482
+ return _orig(self, *a, **k)
483
+ except FileNotFoundError:
484
+ raise gr.Error(_GONE)
485
+ _cls.preprocess = _guarded
486
+
487
+
488
+ def prepare(video, character, painted, request: gr.Request = None):
489
+ # `request` is not wired to any component: gradio fills it in from the type annotation.
490
+ if not video:
491
+ raise gr.Error("upload a driving video")
492
+ if not character and not painted:
493
+ raise gr.Error("give either a character image to paint in, or a first frame you have "
494
+ "already painted yourself")
495
+ # Backstop for the preprocess guard below: covers any stale path that slips through as a
496
+ # bare filepath without gradio touching the file first.
497
+ if any(p and not os.path.exists(p) for p in (video, character, painted)):
498
+ raise gr.Error(_GONE)
499
+
500
+ sweep()
501
+ work = Path(tempfile.mkdtemp())
502
+ sw, sh = probe(video)
503
+ w, h = canvas(sw, sh)
504
+ # For any ordinary aspect the nearest ladder entry is within ~3%, which is a trim nobody
505
+ # notices. A panorama or a tall column is a different matter: it is far from every entry, so
506
+ # cover-cropping to one throws away most of the frame. Say so rather than let someone wonder
507
+ # where their shot went -- the alternative, refusing, would be rendering nothing at all.
508
+ lost = 1 - min((sw / sh) / (w / h), (w / h) / (sw / sh))
509
+ note = f" — cropped {lost*100:.0f}% to reach it" if lost > 0.15 else ""
510
+ # Cover-crop, not stretch, for the same reason `fit` does it to the reference: the two are
511
+ # compared frame by frame, so they have to be squeezed the same way or not at all. `canvas`
512
+ # picks the nearest ladder aspect, so what is cropped here is the few percent by which the
513
+ # upload misses it -- unless the upload is a panorama, which loses its edges by design.
514
+ full = str(work / "full.mp4")
515
+ run("ffmpeg", "-y", "-loglevel", "error", "-i", video, "-vf",
516
+ f"scale={w}:{h}:force_original_aspect_ratio=increase,crop={w}:{h},fps={FPS}",
517
+ "-frames:v", str(MAX_FRAMES), "-crf", "6", "-an", full)
518
+
519
+ have = nframes(full)
520
+ if have < round(MIN_UPLOAD_S * FPS):
521
+ raise gr.Error(f"driving video is {have/FPS:.1f}s after retiming to {FPS} fps; "
522
+ f"at least {MIN_UPLOAD_S:.1f}s is needed")
523
+
524
+ # The model renders on the 17k+5 grid and never shorter than 124 frames, so the clip is
525
+ # held out to the next legal count with a frozen last frame and the render is cut back to
526
+ # `keep` afterwards. That padding is what makes a 4 s upload possible at all.
527
+ frames = grid(have)
528
+ cond = str(work / "cond.mp4")
529
+ pad = ["-vf", "tpad=stop_mode=clone:stop=-1"] if have < frames else []
530
+ run("ffmpeg", "-y", "-loglevel", "error", "-i", full, *pad,
531
+ "-frames:v", str(frames), "-crf", "6", "-an", cond)
532
+ keep = have / FPS
533
+
534
+ # The upload's own soundtrack, kept for the pin. Both ffmpeg calls above still pass `-an`:
535
+ # the driving clip is a *reference*, and its audio must not become conditioning. This is a
536
+ # separate extraction for a different destination -- the render's target audio rows.
537
+ #
538
+ # Cut to `keep`, not to the padded `frames`: the tail the 17k+5 grid forces us to render is a
539
+ # frozen frame, and real audio under a frozen frame is exactly the desync the pin exists to
540
+ # remove. The rest is zero-padded at encode time. Raw f32 rather than a container so both
541
+ # consumers read it without a decoder -- `render` with torch.frombuffer, `finish` with -f f32le.
542
+ apath = None
543
+ if has_audio(video):
544
+ apath = str(work / "audio.f32")
545
+ run("ffmpeg", "-y", "-loglevel", "error", "-i", video, "-t", f"{keep:.3f}",
546
+ "-vn", "-f", "f32le", "-ac", "2", "-ar", str(ASR), apath)
547
+
548
+ ref = str(work / "ref.png")
549
+
550
+ # Already painted: there is nothing to generate, only a canvas to agree on. This is the
551
+ # path the bundled examples take -- no OpenAI call, and the render is then deterministic
552
+ # in the seed, which the gpt-image-2 path can never be.
553
+ if painted:
554
+ fit(Image.open(painted).convert("RGB"), w, h).save(ref)
555
+ return (ref, cond, keep, frames, apath, ref, None,
556
+ f"canvas {w}x{h}{note}, {keep:.1f}s out{', audio pinned' if apath else ''}")
557
+
558
+ # The counter is taken here, not at the top: it exists for the OpenAI spend below, so the
559
+ # painted path is uncounted and a rejected upload never costs one of the day's five.
560
+ left = gate(request)
561
+ # `OpenAI()` picks up OPENAI_API_KEY *and* OPENAI_BASE_URL from the environment, so which
562
+ # provider serves the repaint is a Space-secret decision, not a code one. The two have to
563
+ # agree: a relay key against the default endpoint is a 401 on every request.
564
+ if not os.environ.get("OPENAI_API_KEY"):
565
+ raise gr.Error("OPENAI_API_KEY is not set on this Space")
566
+ frame0 = str(work / "frame0.png")
567
+ run("ffmpeg", "-y", "-loglevel", "error", "-i", cond, "-frames:v", "1", frame0)
568
+
569
+ # gpt-image-2 accepts exactly three sizes -- anything else is a 400 whose generic message
570
+ # happens to contain "size", which made every failure here look like an aspect problem
571
+ # (production, 2026-09-05). So: canonical orientation straight away, cover-crop back onto
572
+ # the canvas afterwards.
573
+ size = "1024x1536" if h > w else "1536x1024" if w > h else "1024x1024"
574
+
575
+ t0 = time.time()
576
+ b64 = None
577
+ for attempt in range(3):
578
+ try:
579
+ with open(frame0, "rb") as a, open(character, "rb") as b:
580
+ r = OpenAI(timeout=300).images.edit(
581
+ model="gpt-image-2", image=[a, b], prompt=REPAINT, size=size,
582
+ quality=QUALITY, output_format="png", n=1)
583
+ b64 = r.data[0].b64_json
584
+ break
585
+ except Exception as e:
586
+ print(f"[paint] attempt {attempt}: {e}", flush=True)
587
+ if "moderation_blocked" in str(e):
588
+ # Deterministic: the same images meet the same safety system, so retrying is
589
+ # three refusals for the price of three. It still costs one of the day's five;
590
+ # that counter is the only brake on hammering the filter with variations.
591
+ raise gr.Error("OpenAI's safety system refused this repaint. Photoreal people "
592
+ "trip it most often; stylized or costumed characters usually "
593
+ "pass.")
594
+ if attempt == 2:
595
+ low = str(e).lower()
596
+ if "server_error" in low or "connection" in low or "timed out" in low:
597
+ # The visitor did nothing wrong; during the 09-03 relay outage every 504
598
+ # still burned quota. Give it back.
599
+ refund(request)
600
+ raise gr.Error(f"gpt-image-2 failed: {e}")
601
+ time.sleep(3)
602
+
603
+ img = Image.open(io.BytesIO(base64.b64decode(b64))).convert("RGB")
604
+ fit(img, w, h).save(ref) # the canonical size is never the canvas aspect; cover-crop
605
+ return (ref, cond, keep, frames, apath, ref, None,
606
+ f"repainted in {time.time()-t0:.0f}s, canvas {w}x{h}{note}, {keep:.1f}s out"
607
+ f"{', audio pinned' if apath else ''}, {left} repaints left today")
608
+
609
+
610
+ _WIRED = False
611
+
612
+
613
+ def wire_aoti():
614
+ """Swap each repeated block's forward for its compiled package -- in the GPU worker, *after*
615
+ `PIPE.to("cuda")`. `aoti_patch` snapshots `state_dict()` and holds whatever storages the
616
+ params have at that moment, so patching before the copy would feed the compiled kernels the
617
+ CPU weights the copy abandons. Latched per worker: the parent process never wires (it has no
618
+ GPU and `render` never runs there), each forked worker wires on its first render and stays
619
+ wired while warm. One caveat rides along: the compiled graph baked the attention backend
620
+ that was active at *build* time (cudnn), so `set_attention_backend` no longer reaches these
621
+ blocks -- the cuDNN retry in `render` has to unwire before it means anything.
622
+ """
623
+ global _WIRED
624
+ if _WIRED or not AOTI_BLOCKS:
625
+ return
626
+ n = 0
627
+ for name, lazy in AOTI_BLOCKS.items():
628
+ for m in PIPE.transformer_ref.modules():
629
+ if type(m).__name__ == name:
630
+ aoti_patch(m, lazy)
631
+ n += 1
632
+ _WIRED = True
633
+ print(f"[gpu] aoti wired {n} blocks", flush=True)
634
+
635
+
636
+ def unwire_aoti():
637
+ """Back to eager, permanently for this worker: `aoti_patch` writes an instance attribute
638
+ that shadows the class `forward`, so popping it is a complete undo. Reached from `render`'s
639
+ retry, which catches *any* first-attempt failure -- an OOM at 243 frames as much as a cuDNN
640
+ refusal -- and staying eager for good is the conservative answer to every one of those
641
+ causes."""
642
+ global AOTI_BLOCKS, _WIRED
643
+ for m in PIPE.transformer_ref.modules():
644
+ if type(m).__name__ in AOTI_BLOCKS:
645
+ m.__dict__.pop("forward", None)
646
+ AOTI_BLOCKS = {}
647
+ _WIRED = False
648
+
649
+
650
+ # The geometry the packages are built at, and the different one they are validated at. Every
651
+ # bundled example is 480x832, so the second geometry -- the one that proves the sequence length
652
+ # stayed a dynamic dim instead of silently specializing -- has to be synthesized (`build_aoti`
653
+ # cover-crops an example drive to it). 544x736 is a real ladder entry, so it is also a shape
654
+ # production will actually serve.
655
+ BUILD_CANVASES = [(480, 832), (544, 736)]
656
+ # Off by default: max_autotune benchmarks kernel variants per compile and can add tens of
657
+ # minutes, and the build has to fit one PRO day's xlarge admission (see build_aoti).
658
+ AUTOTUNE = os.environ.get("AOTI_AUTOTUNE", "0") == "1"
659
+
660
+
661
+ def _capture_kwargs(cond, ref, w, h):
662
+ # Exactly what `render` passes -- the captured tensors must have the shapes production sees.
663
+ # `render` sets PIN on every call, so this cannot inherit a stale True from a render that
664
+ # raised; cleared here anyway because this path calls the pipeline without going through it.
665
+ global PIN
666
+ PIN = False
667
+ PIPE.register_to_config(canvas_short_edge=min(w, h),
668
+ canvas_max_pixels=min(w, h) * max(w, h),
669
+ reference_image_short_edge=min(w, h))
670
+ video = MiniMaxH3VideoReference.from_file(cond)
671
+ video.audio, video.sample_rate = None, None
672
+ return dict(
673
+ prompt=FIXED["presentation"],
674
+ references=[video, MiniMaxH3ImageReference.from_file(ref)],
675
+ num_frames=MIN_FRAMES, height=h, width=w, num_inference_steps=4,
676
+ generator=torch.Generator().manual_seed(42),
677
+ output=["videos", "audio", "sampling_rate"],
678
+ )
679
+
680
+
681
+ @spaces.GPU(size="xlarge", duration=int(os.environ.get("AOTI_BUILD_BUDGET", "1100")))
682
+ def build_aoti():
683
+ """Compile the two repeated block classes on this card and hand the packages back as bytes.
684
+
685
+ One export covers all 52 block instances and every shape bucket: the sequence dims are left
686
+ to Dim.AUTO, and the artifact is then run on a geometry the export never saw -- a dim that
687
+ silently specialized fails that call loudly instead of failing some visitor's render later.
688
+ Inputs come from `aoti_capture`, which aborts a real pipeline call at the block's first
689
+ forward -- diffusers logs each abort as a big ERROR traceback; in this build that is the
690
+ plan working, not a failure.
691
+
692
+ Billed like any render, from the clicker's quota -- and admission doubles the request on
693
+ xlarge, so duration=1100 asks for 2200 s of a PRO day's 2400: the largest round request
694
+ that still clears a fresh day. Only actual elapsed is charged; without autotune the whole
695
+ build (4 captures, 2 exports, 2 compiles, a 243-frame probe) should run well under the
696
+ ceiling. If it ever hits it, raise AOTI_BUILD_BUDGET -- but past 1200 a PRO account can no
697
+ longer be admitted at all.
698
+ """
699
+ from torch.export import Dim, export
700
+ from torch.utils._pytree import tree_leaves, tree_map
701
+
702
+ logs = []
703
+
704
+ def say(s):
705
+ logs.append(s)
706
+ print(f"[build] {s}", flush=True)
707
+
708
+ PIPE.to("cuda")
709
+ if ATTN:
710
+ PIPE.transformer_ref.set_attention_backend(ATTN)
711
+ names = MiniMaxH3Transformer3DModel._repeated_blocks
712
+ # An earlier build click on this same worker may have left blocks instance-patched (the
713
+ # wired probe below, or a validation that died between patch and unpatch). The export must
714
+ # trace eager, and `aoti_capture`'s mock would restore that stale forward instead of the
715
+ # class one -- so pop before anything else. Scoped to the block classes: a blanket pop
716
+ # would strip forwards diffusers hooks may have installed on other modules.
717
+ for m in PIPE.transformer_ref.modules():
718
+ if type(m).__name__ in names:
719
+ m.__dict__.pop("forward", None)
720
+ firsts = {}
721
+ for name in names:
722
+ blocks = [m for m in PIPE.transformer_ref.modules() if type(m).__name__ == name]
723
+ # Block 0 stands in for the whole class, so every sibling must have the same structure.
724
+ # "Same class" stopped guaranteeing that when the LoRA was injected: peft rewrites the
725
+ # Linears of the layers it targets, and an adapter that skipped some blocks would make
726
+ # their state_dicts (and so the compiled graph's constants) disagree.
727
+ assert all(set(b.state_dict()) == set(blocks[0].state_dict()) for b in blocks[1:]), \
728
+ f"{name}: blocks differ in structure; one export cannot cover them"
729
+ firsts[name] = blocks[0]
730
+ say(f"{name}: {len(blocks)} instances, structurally uniform")
731
+
732
+ work = Path(tempfile.mkdtemp())
733
+ drive, still = str(EX / "prop_drive.mp4"), str(EX / "prop_ref.png")
734
+ cases = []
735
+ for w, h in BUILD_CANVASES:
736
+ cond, ref = str(work / f"cond{w}.mp4"), str(work / f"ref{w}.png")
737
+ run("ffmpeg", "-y", "-loglevel", "error", "-i", drive, "-vf",
738
+ f"scale={w}:{h}:force_original_aspect_ratio=increase,crop={w}:{h}",
739
+ "-frames:v", str(MIN_FRAMES), "-crf", "6", "-an", cond)
740
+ fit(Image.open(still).convert("RGB"), w, h).save(ref)
741
+ cases.append((cond, ref, w, h))
742
+
743
+ calls = {name: [] for name in names}
744
+ for cond, ref, w, h in cases:
745
+ kw = _capture_kwargs(cond, ref, w, h)
746
+ for name in names:
747
+ t0 = time.time()
748
+ with aoti_capture(firsts[name]) as call:
749
+ PIPE(**kw)
750
+ assert call.args or call.kwargs, f"{name} was never called at {w}x{h}"
751
+ calls[name].append(call)
752
+ say(f"captured {name} at {w}x{h} in {time.time() - t0:.0f}s")
753
+
754
+ packages = {}
755
+ for name in names:
756
+ block, (call_a, call_b) = firsts[name], calls[name]
757
+ # dynamic_shapes is keyed by the forward's parameter names; bind() recovers them no
758
+ # matter how the transformer spells the call. No apply_defaults: a key for a parameter
759
+ # the call never passed is an export error, not a wildcard.
760
+ bound = inspect.signature(block.forward).bind(*call_a.args, **call_a.kwargs)
761
+ dyn = {k: tree_map(lambda v: [Dim.AUTO] * v.ndim if isinstance(v, torch.Tensor) else None, x)
762
+ for k, x in bound.arguments.items()}
763
+ t0 = time.time()
764
+ ep = export(block, call_a.args, call_a.kwargs, dynamic_shapes=dyn)
765
+ say(f"exported {name} in {time.time() - t0:.0f}s")
766
+ t0 = time.time()
767
+ aoti_compile_and_save(work / name, ep, {"max_autotune": AUTOTUNE})
768
+ pkg = work / name / "root" / PACKAGE_FILENAME
769
+ say(f"compiled {name} in {time.time() - t0:.0f}s -> {pkg.stat().st_size / 2**20:.0f} MB")
770
+
771
+ # Run the artifact on the geometry the export never saw, against eager. This is the
772
+ # specialization check, and -- because it goes through the same aoti_patch/load path the
773
+ # render uses, with check_full_update -- the constants-fqn check for the peft-wrapped
774
+ # structure too. The refiner's inputs are the same shape in both cases (its tokens are
775
+ # the frozen text, not the video), so for it this is only the fqn half -- and also why
776
+ # its specializing to that shape is harmless.
777
+ with torch.no_grad():
778
+ want = block(*call_b.args, **call_b.kwargs)
779
+ aoti_patch(block, LazyAOTIModel(str(pkg)))
780
+ try:
781
+ got = block(*call_b.args, **call_b.kwargs)
782
+ finally:
783
+ del block.forward # even on failure -- the worker survives this fn
784
+ want, got = tree_leaves(want), tree_leaves(got)
785
+ assert len(want) == len(got), f"{name}: output arity {len(got)} vs {len(want)}"
786
+ rel = max((a - b).abs().max().item() / max(a.abs().max().item(), 1e-6)
787
+ for a, b in zip(want, got))
788
+ assert rel < 0.05, f"{name}: compiled vs eager rel diff {rel:.3f} -- wrong weights?"
789
+ say(f"validated {name} at {cases[1][2]}x{cases[1][3]}: rel diff {rel:.4f}")
790
+ packages[name] = pkg.read_bytes()
791
+
792
+ # The worst case production can serve -- 243 frames at the largest-area canvas -- has only
793
+ # ever been measured eager, where it peaks ~86.8 of the card's 95 GiB. Run it once with the
794
+ # fresh packages wired exactly as `render` will wire them, so an out-of-memory (dlopen'd
795
+ # kernels + their workspaces on top of that peak) fails here, on the owner's click, and not
796
+ # on a visitor's longest upload. Also the third geometry: any frame-count-dependent dim
797
+ # that both 124-frame build cases shared, and the dual-geometry check above therefore
798
+ # could not see, breaks this call instead.
799
+ cond, ref = str(work / "probe.mp4"), str(work / "probe.png")
800
+ run("ffmpeg", "-y", "-loglevel", "error", "-i", drive, "-vf",
801
+ "scale=640:640:force_original_aspect_ratio=increase,crop=640:640,"
802
+ "tpad=stop_mode=clone:stop=-1",
803
+ "-frames:v", str(MAX_FRAMES), "-crf", "6", "-an", cond)
804
+ fit(Image.open(still).convert("RGB"), 640, 640).save(ref)
805
+ lazies = {name: LazyAOTIModel(str(work / name / "root" / PACKAGE_FILENAME))
806
+ for name in names}
807
+ try:
808
+ for m in PIPE.transformer_ref.modules():
809
+ if type(m).__name__ in lazies:
810
+ aoti_patch(m, lazies[type(m).__name__])
811
+ # 2 steps, not 1: the scheduler refuses num_inference_steps < 2 without an explicit
812
+ # sigmas schedule (this killed the first two builds, after everything had compiled).
813
+ # Peak memory is the same either way.
814
+ kw = _capture_kwargs(cond, ref, 640, 640) | dict(num_frames=MAX_FRAMES,
815
+ num_inference_steps=2)
816
+ torch.cuda.reset_peak_memory_stats()
817
+ t0 = time.time()
818
+ PIPE(**kw)
819
+ say(f"wired probe: {MAX_FRAMES} frames at 640x640 in {time.time() - t0:.0f}s, "
820
+ f"peak {torch.cuda.max_memory_allocated() / 2**30:.1f} GiB")
821
+ finally:
822
+ for m in PIPE.transformer_ref.modules():
823
+ if type(m).__name__ in lazies:
824
+ m.__dict__.pop("forward", None)
825
+
826
+ return packages, "\n".join(logs)
827
+
828
+
829
+ def build_ui(profile: gr.OAuthProfile | None = None):
830
+ # The build burns most of the clicker's daily xlarge quota and writes to the weights repo;
831
+ # nobody but the owner should be able to press it even if AOTI_BUILD is left on by mistake.
832
+ if profile is None or profile.username.lower() not in OWNERS:
833
+ raise gr.Error("owner-only maintenance button")
834
+ packages, log = build_aoti()
835
+ for name, blob in packages.items():
836
+ # HF_TOKEN comes from the Space secrets via the environment; HfApi picks it up itself.
837
+ HfApi().upload_file(path_or_fileobj=io.BytesIO(blob),
838
+ path_in_repo=f"{name}/{PACKAGE_FILENAME}",
839
+ repo_id=AOTI_REPO, repo_type="model")
840
+ return log + "\nuploaded -- restart the Space to pick the packages up"
841
+
842
+
843
+ def budget(ref, cond, keep, frames, apath, seed):
844
+ """Seconds of GPU to ask ZeroGPU for. Three things ride on it, none of them the bill: quota
845
+ is charged on the *actual* elapsed window (a request that never touches the GPU bills zero),
846
+ so padding costs nothing. It is an admission check -- a visitor whose remaining Hub quota is
847
+ under 2x this number is rejected before anything runs, because `xlarge` doubles server-side
848
+ -- a queue-priority hint (shorter first), and a soft ceiling: when the truly-cold worker
849
+ blew ~90 s past the old 135 s request, the render finished and the log got a warning, not a
850
+ kill. Do not lean on that leniency; keep it an over-estimate.
851
+
852
+ The slope is measured on one B200: 26 s at 124 frames on 480x832, 72 s at 243 on 480x864 --
853
+ ~0.39 s per extra frame, and that 480x864 slightly exceeds LADDER's largest area, so the
854
+ slope over-covers every canvas. SLOWDOWN is this card's measured ratio to that B200 (42/26 s
855
+ at 124 frames). H2D covers the 73.5 GiB host-to-device copy, billed inside the window but
856
+ invisible to `render`'s timer because it runs in worker init: measured 22 s from warm page
857
+ cache, 75 s typical, 154 s cold -- and one 261 s outlier (2026-09-05) that overran the
858
+ whole request by ~40 s and, again, drew only the warning.
859
+
860
+ The constants are set high ON PURPOSE. The admission check is also the
861
+ visitor filter: at these values the shortest render asks for 247 s -- 494 s at admission --
862
+ which is more than a free ZeroGPU day and small change against a PRO day (2400 s). That,
863
+ not a sign-in, is what keeps anonymous and free-tier GPU use out; lower the H2D/SLOWDOWN
864
+ Space variables and the free tier comes back.
865
+ """
866
+ if frames is None:
867
+ # gr.State does not survive a Space restart; a page opened before one sends None for
868
+ # every State. This runs at admission, before `render`, so it is the only place the
869
+ # visitor can get a message instead of a bare TypeError (production, 2026-09-05).
870
+ raise gr.Error("this session predates a Space restart -- run Prepare again")
871
+ return 35 + H2D + round(SLOWDOWN * (26 + 0.39 * (frames - MIN_FRAMES)))
872
+
873
+
874
+ @spaces.GPU(size="xlarge", duration=budget)
875
+ def render(ref, cond, keep, frames, apath, seed):
876
+ global ATTN
877
+ # The real 73.5 GiB pageable copy on a cold worker. A reused warm worker pays nothing --
878
+ # but do not count on reuse: it requires the scheduler to return `idle`, a server-side
879
+ # decision, and a worker that raised is dropped from the cache rather than re-registered.
880
+ # `budget`'s H2D term assumes the pessimistic case.
881
+ t_h2d = time.time()
882
+ PIPE.to("cuda")
883
+ h2d = time.time() - t_h2d
884
+ # Workers are reused, so without this the reported peak is the high-water mark of every
885
+ # render that worker has ever served, not this one's.
886
+ torch.cuda.reset_peak_memory_stats()
887
+
888
+ # cuDNN's attention kernel is a measured 2.05x on the denoise loop and does not move the
889
+ # sample -- same weights, same seed, same take -- so it can be switched on without
890
+ # re-rendering the bundled examples. It is selected here and not at import because there is
891
+ # no GPU at import under ZeroGPU. `set_attention_backend` validates nothing for this backend
892
+ # (`_check_attention_backend_requirements` has no branch for it), so an unserviceable shape
893
+ # raises at the first attention call, which is why the pipeline call below can retry. That
894
+ # 2.05x was measured on sm_100 and this card is sm_120. `ATTN=""` in the Space variables
895
+ # backs it out without a code change.
896
+ if ATTN:
897
+ PIPE.transformer_ref.set_attention_backend(ATTN)
898
+ wire_aoti()
899
+
900
+ # `frames` arrives from `prepare` through State -- it cut `cond` to exactly that count, so
901
+ # re-counting here would be a full ffprobe decode inside the billed window for a number the
902
+ # parent already knows.
903
+ frames = int(frames)
904
+ w, h = probe(cond)
905
+ PIPE.register_to_config(canvas_short_edge=min(w, h),
906
+ canvas_max_pixels=min(w, h) * max(w, h),
907
+ reference_image_short_edge=min(w, h))
908
+
909
+ # The reference order is frozen -- `<Video 1>` then `<Picture 1>` -- because that order
910
+ # advances the shared rotary clock. The clip's soundtrack is still cleared off the reference,
911
+ # as in training -- it is never conditioning -- but it is no longer discarded: when there is
912
+ # one it goes into the *target* audio rows instead, pinned clean, below.
913
+ #
914
+ # An older comment here claimed "the audio you hear back is generated". That was wrong. This
915
+ # finetune's audio head emits digital silence (RMS ~1e-5), which is why every render has
916
+ # needed a manual remux; nothing is lost by overwriting those rows.
917
+ video = MiniMaxH3VideoReference.from_file(cond)
918
+ video.audio, video.sample_rate = None, None
919
+
920
+ # Encode the kept soundtrack into the target audio rows. `PIPE.audio_vae` is already on the
921
+ # card, and bf16 is free here: measured against an fp32 CPU encode the rows differ by 5.4%
922
+ # relative L2, where speech and silence differ by 127% -- and the decoded waveforms are
923
+ # indistinguishable (|amp| r 0.9188 vs 0.9191, the VAE round-trip dominating both). A second
924
+ # fp32 copy would cost 578 MB of host RAM to buy nothing.
925
+ #
926
+ # `attention_backend()` rather than trusting statement order: the audio *encoder* dispatches
927
+ # `is_causal=True`, which cuDNN has no kernel for, and `set_attention_backend` above is
928
+ # process-wide despite looking per-model (its last line sets a classvar on
929
+ # `_AttentionBackendRegistry`). Without this the encode dies in `_native_cudnn_attention` with
930
+ # "No available kernel". The manager restores in `finally`, so denoise keeps the 2.05x kernel.
931
+ # It works here only because the audio VAE's own `_attention_backend` is still None -- setting
932
+ # a backend on the VAE itself would pass `backend=` to `dispatch_attention_fn` and bypass this.
933
+ global PIN
934
+ PIN = apath is not None
935
+ audio_latents = None
936
+ if PIN:
937
+ wav = torch.frombuffer(bytearray(Path(apath).read_bytes()),
938
+ dtype=torch.float32).view(-1, 2).T
939
+ n_samp = round((frames + 1) / FPS * ASR) # one frame over, so the encoder has enough
940
+ wav = torch.nn.functional.pad(wav, (0, max(0, n_samp - wav.shape[1])))[:, :n_samp]
941
+ with attention_backend(), torch.no_grad():
942
+ posterior = PIPE.audio_vae.encode(
943
+ wav[:, None].to("cuda", torch.bfloat16), return_dict=False)[0]
944
+ mean = torch.tensor(PIPE.audio_vae.config.latents_mean).view(1, 1, -1)
945
+ std = torch.tensor(PIPE.audio_vae.config.latents_std).view(1, 1, -1)
946
+ rows = (posterior.mode().float().cpu().transpose(1, 2)[:, :audio_latent_num_frames(frames)]
947
+ - mean) / std
948
+ audio_latents = rows.permute(0, 2, 1).contiguous() # (2, 32, n_lat)
949
+ print(f"[gpu] pinned {wav.shape[1]/ASR:.2f}s of audio -> {tuple(audio_latents.shape)}",
950
+ flush=True)
951
+
952
+ kwargs = dict(
953
+ prompt=FIXED["presentation"],
954
+ references=[video, MiniMaxH3ImageReference.from_file(ref)],
955
+ num_frames=frames, height=h, width=w, num_inference_steps=4,
956
+ audio_latents=audio_latents,
957
+ generator=torch.Generator().manual_seed(int(42 if seed is None else seed)),
958
+ output=["videos", "audio", "sampling_rate"],
959
+ )
960
+ t0 = time.time()
961
+ try:
962
+ result = PIPE(**kwargs)
963
+ except Exception as e: # noqa: BLE001 -- one retry, only for the backend
964
+ if not ATTN:
965
+ raise
966
+ # cuDNN rejects a shape at the *first* attention call, seconds into a budget of minutes,
967
+ # so there is room to start over on the backend that is always correct. Latching ATTN
968
+ # off means this worker retries at most once, and every later render skips cuDNN outright.
969
+ print(f"[gpu] {ATTN} failed ({type(e).__name__}: {e}); retrying on the default backend",
970
+ flush=True)
971
+ ATTN = ""
972
+ PIPE.transformer_ref.set_attention_backend("native")
973
+ # The compiled blocks baked cuDNN at build time and ignore the line above -- eager is
974
+ # the only backend change that can actually happen, so the retry drops them too.
975
+ unwire_aoti()
976
+ result = PIPE(**kwargs)
977
+ took = time.time() - t0
978
+
979
+ work = Path(tempfile.mkdtemp())
980
+ raw = str(work / "raw.mp4")
981
+ encode_video(result["videos"][0], fps=FPS, output_path=raw,
982
+ audio=result["audio"][0], audio_sample_rate=result["sampling_rate"])
983
+ msg = (f"{took:.0f}s for 4 steps at {frames} frames ({keep:.1f}s out), peak "
984
+ f"{torch.cuda.max_memory_allocated()/2**30:.1f} GiB")
985
+ # Calibrate SLOWDOWN against `took` and H2D against `h2d`.
986
+ print(f"[gpu] {msg}, weights onto card in {h2d:.0f}s "
987
+ f"(budget assumed {budget(ref, cond, keep, frames, apath, seed)}s)", flush=True)
988
+ # `keep` rides along with the path instead of being read back from State in `finish`: State
989
+ # is read when each chain link *starts*, so a second Generate click during this render would
990
+ # overwrite keep_s and the finished clip would be trimmed to the wrong length.
991
+ return (raw, keep, apath), msg
992
+
993
+
994
+ def finish(job):
995
+ """Trim and watermark, on the parent's CPU. This used to run inside `render`, where every
996
+ second is billed GPU time; x264 and drawtext need no card. `-t keep` drops the frozen tail
997
+ the 17k+5 grid forced us to render, so the clip that comes back is exactly as long as the
998
+ one that went in. drawtext needs an explicit fontfile: the container has no fontconfig
999
+ default, and without one ffmpeg fails here, after the render -- the worst place to fail
1000
+ (the boot-time assert on FONT exists to keep it unreachable).
1001
+ """
1002
+ raw, keep, apath = job
1003
+ out = str(Path(raw).parent / "viggle-animate.mp4")
1004
+ # With a pinned track the render's own audio rows do decode back to the upload's soundtrack,
1005
+ # but only through the audio VAE, at |amp| r 0.92. The original is on disk and exact, so it is
1006
+ # remuxed in instead. The timelines agree by construction: `prepare`'s fps filter retimes
1007
+ # without time-stretching, and it cut the audio to the same `keep` the video is trimmed to here.
1008
+ src = ["-f", "f32le", "-ar", str(ASR), "-ac", "2", "-i", apath] if apath else []
1009
+ amap = ["-map", "0:v:0", "-map", "1:a:0", "-c:a", "aac"] if apath else ["-c:a", "copy"]
1010
+ run("ffmpeg", "-y", "-loglevel", "error", "-i", raw, *src, "-t", f"{keep:.3f}", "-vf",
1011
+ f"drawtext=fontfile={FONT}:text='viggle-animate':x=w-tw-14:y=h-th-14:fontsize=22:"
1012
+ "fontcolor=white@0.85:shadowcolor=black@0.6:shadowx=1:shadowy=1",
1013
+ *amap, "-crf", "20", "-pix_fmt", "yuv420p", out)
1014
+ return out
1015
+
1016
+
1017
+ with gr.Blocks(title="Viggle-Animate") as demo:
1018
+ gr.Markdown(
1019
+ "# Viggle-Animate\n"
1020
+ "Put the person from a still into a driving video. No pose estimation, no "
1021
+ "segmentation, no masks — the only preprocessing is repainting the clip's first "
1022
+ f"frame. 4 sampling steps. Takes {MIN_UPLOAD_S:.0f}–{MAX_FRAMES/FPS:.0f} s of driving "
1023
+ f"video; anything longer is cut to {MAX_FRAMES/FPS:.1f} s. If the clip carries a "
1024
+ "soundtrack it is pinned into the render and the mouth tracks it; upload a silent clip "
1025
+ "and the mouth moves without saying anything.\n\n"
1026
+ f"[Model card and weights]({MODEL_CARD}) · [viggle.ai]({SITE})"
1027
+ )
1028
+ with gr.Row():
1029
+ with gr.Column():
1030
+ v = gr.Video(label="driving video — motion, framing and background are kept; "
1031
+ "its soundtrack, if it has one, is what the mouth follows")
1032
+ c = gr.Image(label="character — who to put in it", type="filepath")
1033
+ p = gr.Image(label="…or frame 0, already painted (skips gpt-image-2)",
1034
+ type="filepath")
1035
+ go = gr.Button("Generate", variant="primary")
1036
+ seed = gr.Number(value=42, label="seed", precision=0)
1037
+ gr.Markdown(f"<sub>No sign-in. The first-frame repaint is paid by this Space — "
1038
+ f"{DAILY} a day per visitor. The render runs on your own ZeroGPU "
1039
+ "quota and asks for more than a free day holds, so in practice PRO "
1040
+ "and up.</sub>")
1041
+ with gr.Column():
1042
+ shown = gr.Image(label="step 1: repainted first frame", type="filepath")
1043
+ out = gr.Video(label="step 2: render")
1044
+ log = gr.Textbox(label="", lines=2)
1045
+
1046
+ # The examples come with frame 0 already painted, so clicking one exercises the model alone:
1047
+ # no OpenAI call, and the same seed gives the same render every time. `out` is listed as an
1048
+ # input on purpose -- that is what lets a click drop the finished render into the output slot
1049
+ # next to the two things that produced it, so the pair can be read without spending quota.
1050
+ gr.Examples(
1051
+ examples=[[str(EX / f"{d}_drive.mp4"), None, str(EX / f"{n}_ref.png"),
1052
+ str(EX / f"{n}_out.mp4")] for n, (d, _) in CASES.items()],
1053
+ inputs=[v, c, p, out], examples_per_page=len(CASES),
1054
+ label="examples — click one for its driving clip, its painted first frame and the render",
1055
+ )
1056
+
1057
+ # Rendering asks ZeroGPU for more quota than a free account's day holds (see `budget`), so
1058
+ # for most people arriving here this row is the only output they will see -- the page's
1059
+ # actual evidence rather than a footnote.
1060
+ gr.Markdown("### What it produces\n"
1061
+ "Every example above, rendered at 4 steps with seed 42. Each is a single paint "
1062
+ "and a single render; the first and the last three swap in a person. Only the "
1063
+ "first one has audio — it is the only one whose driving clip had any.")
1064
+ items = list(CASES.items())
1065
+ # Rows are cut on aspect, not on a fixed width: the landscape lip-sync take on its own, then
1066
+ # six portrait swaps, the four landscape two-character takes, and the three human cases.
1067
+ # Mixing the two shapes in one row squeezes the portrait ones to a third of their height.
1068
+ for row in (items[0:1], items[1:4], items[4:7], items[7:11], items[11:14]):
1069
+ with gr.Row():
1070
+ for n, (_, caption) in row:
1071
+ gr.Video(str(EX / f"{n}_out.mp4"), label=caption, interactive=False)
1072
+
1073
+ # Maintenance, visible only when the AOTI_BUILD Space variable is set (and refused for
1074
+ # anyone but the owner even then): compiles the block packages on this hardware and uploads
1075
+ # them to the weights repo. Run once per torch/driver generation, then unset the variable.
1076
+ # The LoginButton is the only OAuth left in the app and exists purely for this gate:
1077
+ # `build_ui`'s `gr.OAuthProfile` stays None without a sign-in, and stays None for everyone
1078
+ # unless `hf_oauth: true` is in the README front matter -- keep both or the button refuses
1079
+ # even the owner.
1080
+ if os.environ.get("AOTI_BUILD") == "1":
1081
+ with gr.Accordion("maintenance -- build AOTI packages", open=False):
1082
+ gr.LoginButton(size="sm")
1083
+ b_go = gr.Button("compile the repeated blocks on this GPU (<=18 min of "
1084
+ "xlarge quota), upload to the weights repo")
1085
+ b_log = gr.Textbox(label="build log", lines=12)
1086
+ b_go.click(build_ui, [], [b_log])
1087
+
1088
+ # Repeated at the bottom because the examples and the "What it produces" rows push the
1089
+ # header well off screen -- this is where a visitor actually finishes reading.
1090
+ gr.Markdown(f"<sub>[Model card and weights]({MODEL_CARD}) · [viggle.ai]({SITE})</sub>")
1091
+
1092
+ ref_s, cond_s, keep_s, frames_s, audio_s, raw_s = (gr.State(), gr.State(), gr.State(),
1093
+ gr.State(), gr.State(), gr.State())
1094
+ # `.success`, not `.then`: `prepare` raises gr.Error for a missing upload, a too-short clip
1095
+ # or a spent daily quota, and `.then` would run the render anyway -- on stale State from the
1096
+ # previous click, or on None, which is a several-minute GPU job started by a failed one.
1097
+ # `finish` runs in the parent, but the raw path crosses fine: worker and parent share /tmp.
1098
+ # `finish` runs outside the queue: it is seconds of CPU ffmpeg, and inside the queue a
1099
+ # "Queue is full" rejection would land *after* the GPU time is already spent.
1100
+ (go.click(prepare, [v, c, p],
1101
+ [ref_s, cond_s, keep_s, frames_s, audio_s, shown, out, log])
1102
+ .success(render, [ref_s, cond_s, keep_s, frames_s, audio_s, seed], [raw_s, log])
1103
+ .success(finish, [raw_s], [out], queue=False))
1104
+
1105
+ # The bundled media sits next to app.py rather than in Gradio's temp dir, so it has to be
1106
+ # named explicitly or the file route refuses to serve it.
1107
+ # `max_file_size` matters more than it looks: gradio writes the upload to disk before
1108
+ # `prepare` can refuse it, and that disk also holds 80 GB of weights. The default is
1109
+ # None, i.e. unlimited. 10 s of 4K is comfortably under 200 MB.
1110
+ demo.queue(max_size=32).launch(show_error=True, allowed_paths=[str(EX)],
1111
+ max_file_size="200mb")
examples/clay_out.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0fdd5f18a8929d04e534f105a482d38a63b0d91a16a5d41293c1ad9ddab112e1
3
+ size 537613
examples/clay_ref.png ADDED

Git LFS Details

  • SHA256: dc5f5c461bd26d5cd174fdf851b07b80cb28dd09868881a516fe592efed1c7b9
  • Pointer size: 131 Bytes
  • Size of remote file: 464 kB
examples/corgi_out.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1d291d9f6e95bc04544210a0bcf01849012550e3822e42d51e68de466e642cd9
3
+ size 480309
examples/corgi_ref.png ADDED

Git LFS Details

  • SHA256: 762346d974c25216d6d788846b7294fe997c103eb9b17fdacea5ba85f87b4b3d
  • Pointer size: 131 Bytes
  • Size of remote file: 456 kB
examples/costume_drive.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e5f4c7b3615a4ee76fbbbfa3397ab019fc9e3c107f599d3758c595a038c68151
3
+ size 3404189
examples/costume_out.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0abb4ec4abb565a14df135d749d7b4fb93600d244f8e26469de972a6a343c971
3
+ size 549039
examples/costume_ref.png ADDED

Git LFS Details

  • SHA256: 52611deb78767d052f1ef4a8cb7530000bea337c5f7b6028871d8b74bedbb059
  • Pointer size: 131 Bytes
  • Size of remote file: 473 kB
examples/duo_anime_drive.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:73ad91ebdbd5aad74222f64eff807a1367b9a73f3513381f6a6b88e2ca1f4112
3
+ size 871014
examples/duo_anime_out.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:19869266fe1abc5575f9746f530dc65ba2d88db52ebd6ec26380d449ac8cab18
3
+ size 627889
examples/duo_anime_ref.png ADDED

Git LFS Details

  • SHA256: 679999683e570578bed83cc95cee4249ac51a784f6041b62ebdeb8c3cb9c92f3
  • Pointer size: 131 Bytes
  • Size of remote file: 473 kB
examples/duo_real_out.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dc25c2f383504d8e3429e08ec7424156e3eddead2021074b031ef6ee2f4648c3
3
+ size 729838
examples/duo_real_ref.png ADDED

Git LFS Details

  • SHA256: df6987376063c50f5a541c08a3986e251490bd3173ad34b4663530ef879bf60e
  • Pointer size: 131 Bytes
  • Size of remote file: 525 kB
examples/lipsync_drive.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fc3dd85a5be2e6246fb40afe46e337cb75d6c3558105fd81fa02f1ff286a5e92
3
+ size 4223283
examples/lipsync_out.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f0daf870fb10c109ecfbb33a313a16ec69e0e49bc4995fe5717557b6effeca15
3
+ size 442574
examples/lipsync_ref.png ADDED

Git LFS Details

  • SHA256: 6bf55661c6e0b3ba9a0b14999462deab9d6de8333d35b6cbd360c3b3cbf855e7
  • Pointer size: 131 Bytes
  • Size of remote file: 442 kB
examples/panda_drive.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7070396b18dc8f1aaa697f86fb0dd9ceafb71957ab5216d08e0e7c5f6a853e59
3
+ size 4679531
examples/panda_out.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3bd12a097111983f5f0961eef55409a027c38e8050f71d7e3106efa1288172e6
3
+ size 765933
examples/panda_ref.png ADDED

Git LFS Details

  • SHA256: 65d87739c6699e47f37dd97bca04c74a21e4a90ee9a5815f296f0f5f11a4db70
  • Pointer size: 131 Bytes
  • Size of remote file: 470 kB
examples/penguin_drive.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ef03cc513e13e32621302850fcb5e570678f35a6d3cf5abf52f9d495e3e948ae
3
+ size 5531393
examples/penguin_out.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9524d3114ef2d69d1ace256d486ae49a8490b7670d1f9c9e2bf48d7d686334a3
3
+ size 890366
examples/penguin_ref.png ADDED

Git LFS Details

  • SHA256: 6707d8c641fcbc801fc2bb92cdd8dd480ad442c93cd0c411b7834d479442f65a
  • Pointer size: 131 Bytes
  • Size of remote file: 551 kB
examples/plane_drive.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:78b18831d72834c5a6bce3d942a839db994929556e8a16f7811e7797e4a650a8
3
+ size 2898975
examples/plane_out.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ad0175d6b9759cf9bf4d3ed0599d9d216f6af6d22564fc97cfcf92778836e460
3
+ size 824657
examples/plane_ref.png ADDED

Git LFS Details

  • SHA256: 5978d446600f1b873d38c67dcc7da520839582a7e8cfa76ff529f4b20ef3cbdf
  • Pointer size: 131 Bytes
  • Size of remote file: 484 kB
examples/prop_drive.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bf9e00c3f72bc27796bd05d90fd71c4f4407389d5524d94fdea9b01741364e1e
3
+ size 4773104
examples/prop_out.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d7f3fdd374650ed382952dfb1b516a39aa4c9f54f78e563382ee93ba87485137
3
+ size 695307
examples/prop_ref.png ADDED

Git LFS Details

  • SHA256: 62888969c274b5b07889590622131f4f8cdc6df04ddf8cb487e963fb70cb9535
  • Pointer size: 131 Bytes
  • Size of remote file: 496 kB
examples/robot_drive.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d9d24761386c029d5466e5c54c77a63eeeb228d8e7a2ecf4f74d793090186080
3
+ size 2049633
examples/robot_out.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:262d110526755d525c3acc47bb18cbf4c3987499e2d4070f8ac148c210c056cd
3
+ size 414859
examples/robot_ref.png ADDED

Git LFS Details

  • SHA256: f817ff81b366221ab91f99e27d592cf0fbf34b95bfa86a5a6f4158373a2cf4d6
  • Pointer size: 131 Bytes
  • Size of remote file: 414 kB
examples/style_drive.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c75b25827742bf455815c8adc0e9e906590d54296412d82f0010bed1d916bdde
3
+ size 3377808
examples/style_out.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b0c548886a374560416fed12599578e5862a866b4d082c1549fe932223dc5d9f
3
+ size 652792
examples/style_ref.png ADDED

Git LFS Details

  • SHA256: 66ec90fb14b68d5d892cc1c6e43a9bf58d6e98025ed0701cea0ed44e650fc741
  • Pointer size: 131 Bytes
  • Size of remote file: 494 kB
examples/wushu_animals_drive.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f661883104c371f5ca50e4c8caf7bca6a1ca9e31d125b82f1e98a41f85982999
3
+ size 1361277
examples/wushu_animals_out.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:94c69eac46b0ef18fc5fec48a3cd6e1847bc1b1729621fee39f4862a6a1aa73f
3
+ size 1216878
examples/wushu_animals_ref.png ADDED

Git LFS Details

  • SHA256: 06a5c91e688afd8c0c1dc705589d032efd4c359ef4964b34690172fd0cb3c1b7
  • Pointer size: 131 Bytes
  • Size of remote file: 576 kB
examples/wushu_robots_out.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3a31d90f8fb124e4123265ccd7d9bdefac3313591adbff3b22d30a556db78be7
3
+ size 1201561
examples/wushu_robots_ref.png ADDED

Git LFS Details

  • SHA256: 050ef34c62cab4b6f85f6195ab8d94b6f7033eff4d9dd1a24b057344831a5c49
  • Pointer size: 131 Bytes
  • Size of remote file: 582 kB
packages.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ ffmpeg
2
+ fonts-dejavu-core
requirements.txt ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # gradio is deliberately absent: the Spaces builder installs it from `sdk_version` in README.md
2
+ # (pinned to 5.50.0, the last 5.x -- the app is written against 5's API, and an unpinned build
3
+ # would have picked up gradio 6 on the next rebuild).
4
+ torch==2.9.1
5
+ git+https://github.com/huggingface/diffusers@d6726f3
6
+ # Pinned to what the 2026-09-01 build actually resolved and booted on. transformers and
7
+ # huggingface_hub are both past a major bump (5.x, 1.x) that this diffusers commit predates, so
8
+ # leaving them open means the next rebuild is a different app than the one that was tested.
9
+ transformers==5.16.1
10
+ huggingface_hub==1.29.0
11
+ accelerate==1.14.0
12
+ peft==0.20.0
13
+ safetensors
14
+ # `spaces` is deliberately absent, like gradio: the builder pins and installs it itself
15
+ # (spaces==0.51.1 in the same pip command as this file, so listing any other version is
16
+ # ResolutionImpossible). app.py imports from its private module `spaces.zero.torch.aoti`;
17
+ # that module is byte-identical in 0.51.1 and 0.51.3, the versions this was written against.
18
+ openai>=3.0 # 3.0.0 is the version the relay call was verified against
19
+ pillow
20
+ av