rahul7star commited on
Commit
f770871
·
verified ·
1 Parent(s): 3629559

Create app1.py

Browse files
Files changed (1) hide show
  1. app1.py +208 -0
app1.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Got it—here’s a cleaned-up version of your script with the extra LoRA wired **only into the low-noise stage (`transformer_2`)** of Wan 2.2. I’ve kept everything else intact and added the adapter with a clear name so you can tweak weights later if you want.
2
+
3
+ ```python
4
+ # PyTorch 2.8 (temporary hack)
5
+ import os
6
+ os.system('pip install --upgrade --pre --extra-index-url https://download.pytorch.org/whl/nightly/cu126 "torch<2.9" spaces')
7
+
8
+ # Actual demo code
9
+ import spaces
10
+ import torch
11
+ from diffusers import WanPipeline, AutoencoderKLWan
12
+ from diffusers.models.transformers.transformer_wan import WanTransformer3DModel
13
+ from diffusers.utils.export_utils import export_to_video
14
+ import gradio as gr
15
+ import tempfile
16
+ import numpy as np
17
+ from PIL import Image
18
+ import random
19
+ import gc
20
+ from optimization import optimize_pipeline_
21
+
22
+ MODEL_ID = "Wan-AI/Wan2.2-T2V-A14B-Diffusers"
23
+
24
+ LANDSCAPE_WIDTH = 832
25
+ LANDSCAPE_HEIGHT = 480
26
+ MAX_SEED = np.iinfo(np.int32).max
27
+
28
+ FIXED_FPS = 16
29
+ MIN_FRAMES_MODEL = 8
30
+ MAX_FRAMES_MODEL = 81
31
+
32
+ MIN_DURATION = round(MIN_FRAMES_MODEL / FIXED_FPS, 1)
33
+ MAX_DURATION = round(MAX_FRAMES_MODEL / FIXED_FPS, 1)
34
+
35
+ # Build the pipeline (bf16 on GPU)
36
+ vae = AutoencoderKLWan.from_pretrained(
37
+ MODEL_ID, subfolder="vae", torch_dtype=torch.float32
38
+ )
39
+ pipe = WanPipeline.from_pretrained(
40
+ MODEL_ID,
41
+ transformer=WanTransformer3DModel.from_pretrained(
42
+ "linoyts/Wan2.2-T2V-A14B-Diffusers-BF16",
43
+ subfolder="transformer",
44
+ torch_dtype=torch.bfloat16,
45
+ device_map="cuda",
46
+ ),
47
+ transformer_2=WanTransformer3DModel.from_pretrained(
48
+ "linoyts/Wan2.2-T2V-A14B-Diffusers-BF16",
49
+ subfolder="transformer_2",
50
+ torch_dtype=torch.bfloat16,
51
+ device_map="cuda",
52
+ ),
53
+ vae=vae,
54
+ torch_dtype=torch.bfloat16,
55
+ ).to("cuda")
56
+
57
+ # ---- NEW: Load Orbit-Shot LoRA on the LOW-NOISE stage only (transformer_2) ----
58
+ # Repo: ostris/wan22_i2v_14b_orbit_shot_lora
59
+ # File: wan22_14b_i2v_orbit_low_noise.safetensors
60
+ #
61
+ # Notes:
62
+ # - We attach this LoRA only to transformer_2 (the low-noise stage for Wan2.2).
63
+ # - Adapter name `orbit_low` lets you adjust/enable later via set_adapters if needed.
64
+ pipe.load_lora_weights(
65
+ "ostris/wan22_i2v_14b_orbit_shot_lora",
66
+ weight_name="wan22_14b_i2v_orbit_low_noise.safetensors",
67
+ adapter_name="orbit_low",
68
+ components=["transformer_2"], # IMPORTANT: apply only to low-noise stage
69
+ )
70
+ # Activate the adapter on transformer_2 with weight 1.0 (changeable)
71
+ pipe.set_adapters(
72
+ ["orbit_low"], adapter_weights=[1.0], components=["transformer_2"]
73
+ )
74
+ # -------------------------------------------------------------------------------
75
+
76
+ # Usual CUDA cleanup
77
+ for _ in range(3):
78
+ gc.collect()
79
+ torch.cuda.synchronize()
80
+ torch.cuda.empty_cache()
81
+
82
+ # Keep your current optimization hook
83
+ optimize_pipeline_(
84
+ pipe,
85
+ prompt="prompt",
86
+ height=LANDSCAPE_HEIGHT,
87
+ width=LANDSCAPE_WIDTH,
88
+ num_frames=MAX_FRAMES_MODEL,
89
+ )
90
+
91
+ default_prompt_t2v = "Two anthropomorphic cats in comfy boxing gear and bright gloves fight intensely on a spotlighted stage."
92
+ default_negative_prompt = "色调艳丽, 过曝, 静态, 细节模糊不清, 字幕, 风格, 作品, 画作, 画面, 静止, 整体发灰, 最差质量, 低质量, JPEG压缩残留, 丑陋的, 残缺的, 多余的手指, 画得不好的手部, 画得不好的脸部, 畸形的, 毁容的, 形态畸形的肢体, 手指融合, 静止不动的画面, 杂乱的背景, 三条腿, 背景人很多, 倒着走"
93
+
94
+ def get_duration(
95
+ prompt,
96
+ negative_prompt,
97
+ duration_seconds,
98
+ guidance_scale,
99
+ guidance_scale_2,
100
+ steps,
101
+ seed,
102
+ randomize_seed,
103
+ progress,
104
+ ):
105
+ return steps * 15
106
+
107
+ @spaces.GPU(duration=get_duration)
108
+ def generate_video(
109
+ prompt,
110
+ negative_prompt=default_negative_prompt,
111
+ duration_seconds=MAX_DURATION,
112
+ guidance_scale=1,
113
+ guidance_scale_2=3,
114
+ steps=4,
115
+ seed=42,
116
+ randomize_seed=False,
117
+ progress=gr.Progress(track_tqdm=True),
118
+ ):
119
+ """
120
+ Generate a video from a text prompt using the Wan 2.2 14B T2V model with a low-noise Orbit-Shot LoRA adapter.
121
+ """
122
+ num_frames = np.clip(int(round(duration_seconds * FIXED_FPS)), MIN_FRAMES_MODEL, MAX_FRAMES_MODEL)
123
+ current_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed)
124
+
125
+ output_frames_list = pipe(
126
+ prompt=prompt,
127
+ negative_prompt=negative_prompt,
128
+ height=480,
129
+ width=832,
130
+ num_frames=num_frames,
131
+ guidance_scale=float(guidance_scale),
132
+ guidance_scale_2=float(guidance_scale_2),
133
+ num_inference_steps=int(steps),
134
+ generator=torch.Generator(device="cuda").manual_seed(current_seed),
135
+ ).frames[0]
136
+
137
+ with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tmpfile:
138
+ video_path = tmpfile.name
139
+
140
+ export_to_video(output_frames_list, video_path, fps=FIXED_FPS)
141
+ return video_path, current_seed
142
+
143
+ with gr.Blocks() as demo:
144
+ gr.Markdown("# Fast 4 steps Wan 2.2 T2V (14B) + Orbit-Shot LoRA (low-noise)")
145
+ gr.Markdown(
146
+ "Runs Wan 2.2 in 4–8 steps. Low-noise **Orbit-Shot** LoRA is applied to `transformer_2` only."
147
+ )
148
+ with gr.Row():
149
+ with gr.Column():
150
+ prompt_input = gr.Textbox(label="Prompt", value=default_prompt_t2v)
151
+ duration_seconds_input = gr.Slider(
152
+ minimum=MIN_DURATION, maximum=MAX_DURATION, step=0.1, value=MAX_DURATION,
153
+ label="Duration (seconds)",
154
+ info=f"Clamped to model's {MIN_FRAMES_MODEL}-{MAX_FRAMES_MODEL} frames at {FIXED_FPS}fps."
155
+ )
156
+ with gr.Accordion("Advanced Settings", open=False):
157
+ negative_prompt_input = gr.Textbox(label="Negative Prompt", value=default_negative_prompt, lines=3)
158
+ seed_input = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=42, interactive=True)
159
+ randomize_seed_checkbox = gr.Checkbox(label="Randomize seed", value=True, interactive=True)
160
+ steps_slider = gr.Slider(minimum=1, maximum=30, step=1, value=4, label="Inference Steps")
161
+ guidance_scale_input = gr.Slider(minimum=0.0, maximum=10.0, step=0.5, value=1, label="Guidance Scale - high noise stage")
162
+ guidance_scale_2_input = gr.Slider(minimum=0.0, maximum=10.0, step=0.5, value=3, label="Guidance Scale 2 - low noise stage")
163
+ generate_button = gr.Button("Generate Video", variant="primary")
164
+ with gr.Column():
165
+ video_output = gr.Video(label="Generated Video", autoplay=True, interactive=False)
166
+
167
+ ui_inputs = [
168
+ prompt_input,
169
+ negative_prompt_input,
170
+ duration_seconds_input,
171
+ guidance_scale_input,
172
+ guidance_scale_2_input,
173
+ steps_slider,
174
+ seed_input,
175
+ randomize_seed_checkbox,
176
+ ]
177
+ generate_button.click(fn=generate_video, inputs=ui_inputs, outputs=[video_output, seed_input])
178
+
179
+ gr.Examples(
180
+ examples=[
181
+ [
182
+ "POV selfie video, white cat with sunglasses standing on surfboard, relaxed smile, tropical beach behind (clear water, green hills, blue sky with clouds). Surfboard tips, cat falls into ocean, camera plunges underwater with bubbles and sunlight beams. Brief underwater view of cat’s face, then cat resurfaces, still filming selfie, playful summer vacation mood.",
183
+ ],
184
+ [
185
+ "Two anthropomorphic cats in comfy boxing gear and bright gloves fight intensely on a spotlighted stage.",
186
+ ],
187
+ [
188
+ "A cinematic shot of a boat sailing on a calm sea at sunset.",
189
+ ],
190
+ [
191
+ "Drone footage flying over a futuristic city with flying cars.",
192
+ ],
193
+ ],
194
+ inputs=[prompt_input],
195
+ outputs=[video_output, seed_input],
196
+ fn=generate_video,
197
+ cache_examples="lazy",
198
+ )
199
+
200
+ if __name__ == "__main__":
201
+ demo.queue().launch(mcp_server=True)
202
+ ```
203
+
204
+ ### Notes
205
+
206
+ * The key lines are the `pipe.load_lora_weights(..., components=["transformer_2"])` and `pipe.set_adapters(..., components=["transformer_2"])`, which ensure the **orbit-shot LoRA only affects the low-noise stage**.
207
+ * If you want to dial the LoRA’s strength, change `adapter_weights=[1.0]` to something like `0.6–1.2`.
208
+ * If you also plan to stack a “Lightning” LoRA, you can load it with a different `adapter_name` (e.g., `"lightning"`) and then call a combined `set_adapters` where `components=["transformer", "transformer_2"]` for lightning and only `["transformer_2"]` for orbit.