GiorgioV commited on
Commit
804e528
·
verified ·
1 Parent(s): c966318

Upload app-6.py

Browse files
Files changed (1) hide show
  1. app-6.py +312 -0
app-6.py ADDED
@@ -0,0 +1,312 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import spaces
3
+ import torch
4
+ from diffusers.pipelines.wan.pipeline_wan_i2v import WanImageToVideoPipeline
5
+ from diffusers.models.transformers.transformer_wan import WanTransformer3DModel
6
+ from diffusers.utils.export_utils import export_to_video
7
+ import gradio as gr
8
+ import tempfile
9
+ import numpy as np
10
+ from PIL import Image
11
+ import random
12
+ import gc
13
+ from huggingface_hub import HfApi
14
+ from torchao.quantization import quantize_
15
+ from torchao.quantization import Float8DynamicActivationFloat8WeightConfig, Int8WeightOnlyConfig
16
+ import aoti
17
+ import uuid
18
+ import imageio.v3 as iio
19
+
20
+
21
+ def export_browser_safe_video(frames, path, fps=16):
22
+ """
23
+ frames: list of PIL images or numpy arrays (H, W, 3), uint8
24
+ path: output .mp4 path
25
+ """
26
+ # convert PIL to np if needed
27
+ np_frames = []
28
+ for f in frames:
29
+ if hasattr(f, "convert"):
30
+ f = f.convert("RGB")
31
+ f = np.array(f)
32
+ np_frames.append(f)
33
+
34
+ iio.imwrite(
35
+ path,
36
+ np_frames,
37
+ fps=fps,
38
+ codec="libx264",
39
+ pixelformat="yuv420p", # important for browser support
40
+ )
41
+ # =========================================================
42
+ # MODEL CONFIGURATION
43
+ # =========================================================
44
+ MODEL_ID = "Wan-AI/Wan2.2-I2V-A14B-Diffusers"
45
+ HF_TOKEN = os.environ.get("HF_TOKEN")
46
+ DATASET_KEY = os.environ.get("DATASET_KEY")
47
+
48
+ MAX_DIM = 832
49
+ MIN_DIM = 480
50
+ SQUARE_DIM = 640
51
+ MULTIPLE_OF = 16
52
+
53
+ MAX_SEED = np.iinfo(np.int32).max
54
+
55
+ FIXED_FPS = 16
56
+ MIN_FRAMES_MODEL = 8
57
+ MAX_FRAMES_MODEL = 7720
58
+
59
+ MIN_DURATION = round(MIN_FRAMES_MODEL / FIXED_FPS, 1)
60
+ MAX_DURATION = round(MAX_FRAMES_MODEL / FIXED_FPS, 1)
61
+
62
+ # =========================================================
63
+ # LOAD PIPELINE
64
+ # =========================================================
65
+ pipe = WanImageToVideoPipeline.from_pretrained(
66
+ MODEL_ID,
67
+ transformer=WanTransformer3DModel.from_pretrained(
68
+ MODEL_ID,
69
+ subfolder="transformer",
70
+ torch_dtype=torch.bfloat16,
71
+ device_map="cuda",
72
+ token=HF_TOKEN
73
+ ),
74
+ transformer_2=WanTransformer3DModel.from_pretrained(
75
+ MODEL_ID,
76
+ subfolder="transformer_2",
77
+ torch_dtype=torch.bfloat16,
78
+ device_map="cuda",
79
+ token=HF_TOKEN
80
+ ),
81
+ torch_dtype=torch.bfloat16,
82
+ ).to("cuda")
83
+
84
+ # =========================================================
85
+ # LOAD LORA ADAPTERS
86
+ # =========================================================
87
+ pipe.load_lora_weights(
88
+ "obsxrver/wan2.2-i2v-scat",
89
+ weight_name="WAN2.2-I2V-HighNoise_scat-xxi-i2v.safetensors",
90
+ adapter_name="i2v_scat"
91
+ )
92
+ pipe.load_lora_weights(
93
+ "lightx2v/Wan2.2-Lightning",
94
+ weight_name="Wan2.2-I2V-A14B-4steps-lora-rank64-Seko-V1/high_noise_model.safetensors",
95
+ adapter_name="lightx2v"
96
+ )
97
+
98
+ pipe.load_lora_weights(
99
+ "obsxrver/wan2.2-i2v-scat",
100
+ weight_name="WAN2.2-I2V-LowNoise_scat-xxi-i2v.safetensors",
101
+ adapter_name="i2v_scat_2",
102
+ load_into_transformer_2=True
103
+ )
104
+ pipe.load_lora_weights(
105
+ "lightx2v/Wan2.2-Lightning",
106
+ weight_name="Wan2.2-I2V-A14B-4steps-lora-rank64-Seko-V1/low_noise_model.safetensors",
107
+ adapter_name="lightx2v_2",
108
+ load_into_transformer_2=True
109
+ )
110
+
111
+
112
+ pipe.set_adapters([ "i2v_scat","lightx2v","i2v_scat_2","lightx2v_2"], adapter_weights=[0.95, 0.9, 0.95, 0.9])
113
+ pipe.fuse_lora(adapter_names=["i2v_scat","lightx2v"], lora_scale=1., components=["transformer"])
114
+ pipe.fuse_lora(adapter_names=["i2v_scat_2","lightx2v_2"], lora_scale=1., components=["transformer_2"])
115
+ pipe.unload_lora_weights()
116
+
117
+ # =========================================================
118
+ # QUANTIZATION & AOT OPTIMIZATION
119
+ # =========================================================
120
+ quantize_(pipe.text_encoder, Int8WeightOnlyConfig())
121
+ quantize_(pipe.transformer, Float8DynamicActivationFloat8WeightConfig())
122
+ quantize_(pipe.transformer_2, Float8DynamicActivationFloat8WeightConfig())
123
+
124
+ aoti.aoti_blocks_load(pipe.transformer, 'zerogpu-aoti/Wan2', variant='fp8da')
125
+ aoti.aoti_blocks_load(pipe.transformer_2, 'zerogpu-aoti/Wan2', variant='fp8da')
126
+
127
+ # =========================================================
128
+ # DEFAULT PROMPTS
129
+ # =========================================================
130
+ default_prompt_i2v = "the video cuts, in the next scene, she takes off her clothes and is nude and covered in feces, on her back with her with legs spread, looking at the camera, she defecates and rubs her pussy, no camera movement"
131
+ default_negative_prompt = (
132
+ "色调艳丽, 过曝, 静态, 细节模糊不清, 字幕, 风格, 作品, 画作, 画面, 静止, 整体发灰, "
133
+ "最差质量, 低质量, JPEG压缩残留, 丑陋的, 残缺的, 多余的手指, 画得不好的手部, 画得不好的脸部, "
134
+ "畸形的, 毁容的, 形态畸形的肢体, 手指融合, 静止不动的画面, 杂乱的背景, 三条腿, 背景人很多, 倒着走"
135
+ )
136
+
137
+ # =========================================================
138
+ # IMAGE RESIZING LOGIC
139
+ # =========================================================
140
+ def resize_image(image: Image.Image) -> Image.Image:
141
+ width, height = image.size
142
+ if width == height:
143
+ return image.resize((SQUARE_DIM, SQUARE_DIM), Image.LANCZOS)
144
+
145
+ aspect_ratio = width / height
146
+ MAX_ASPECT_RATIO = MAX_DIM / MIN_DIM
147
+ MIN_ASPECT_RATIO = MIN_DIM / MAX_DIM
148
+
149
+ image_to_resize = image
150
+
151
+ if aspect_ratio > MAX_ASPECT_RATIO:
152
+ crop_width = int(round(height * MAX_ASPECT_RATIO))
153
+ left = (width - crop_width) // 2
154
+ image_to_resize = image.crop((left, 0, left + crop_width, height))
155
+ elif aspect_ratio < MIN_ASPECT_RATIO:
156
+ crop_height = int(round(width / MIN_ASPECT_RATIO))
157
+ top = (height - crop_height) // 2
158
+ image_to_resize = image.crop((0, top, width, top + crop_height))
159
+
160
+ if width > height:
161
+ target_w = MAX_DIM
162
+ target_h = int(round(target_w / aspect_ratio))
163
+ else:
164
+ target_h = MAX_DIM
165
+ target_w = int(round(target_h * aspect_ratio))
166
+
167
+ final_w = round(target_w / MULTIPLE_OF) * MULTIPLE_OF
168
+ final_h = round(target_h / MULTIPLE_OF) * MULTIPLE_OF
169
+
170
+ final_w = max(MIN_DIM, min(MAX_DIM, final_w))
171
+ final_h = max(MIN_DIM, min(MAX_DIM, final_h))
172
+
173
+ return image_to_resize.resize((final_w, final_h), Image.LANCZOS)
174
+
175
+ # =========================================================
176
+ # UTILITY FUNCTIONS
177
+ # =========================================================
178
+ def get_num_frames(duration_seconds: float):
179
+ return 1 + int(np.clip(int(round(duration_seconds * FIXED_FPS)), MIN_FRAMES_MODEL, MAX_FRAMES_MODEL))
180
+
181
+ def get_duration(
182
+ input_image, prompt, steps, negative_prompt,
183
+ duration_seconds, guidance_scale, guidance_scale_2,
184
+ seed, randomize_seed, progress,
185
+ ):
186
+ BASE_FRAMES_HEIGHT_WIDTH = 81 * 832 * 624
187
+ BASE_STEP_DURATION = 15
188
+ width, height = resize_image(input_image).size
189
+ frames = get_num_frames(duration_seconds)
190
+ factor = frames * width * height / BASE_FRAMES_HEIGHT_WIDTH
191
+ step_duration = BASE_STEP_DURATION * factor ** 1.5
192
+ return 10 + int(steps) * step_duration
193
+
194
+ # =========================================================
195
+ # MAIN GENERATION FUNCTION
196
+ # =========================================================
197
+ @spaces.GPU(duration=get_duration)
198
+ def generate_video(
199
+ input_image,
200
+ prompt,
201
+ steps=4,
202
+ negative_prompt=default_negative_prompt,
203
+ duration_seconds=MAX_DURATION,
204
+ guidance_scale=1,
205
+ guidance_scale_2=1,
206
+ seed=42,
207
+ randomize_seed=False,
208
+ progress=gr.Progress(track_tqdm=True),
209
+ ):
210
+ if input_image is None:
211
+ raise gr.Error("Please upload an input image.")
212
+
213
+ num_frames = get_num_frames(duration_seconds)
214
+ current_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed)
215
+ resized_image = resize_image(input_image)
216
+
217
+ output_frames_list = pipe(
218
+ image=resized_image,
219
+ prompt=prompt,
220
+ negative_prompt=negative_prompt,
221
+ height=resized_image.height,
222
+ width=resized_image.width,
223
+ num_frames=num_frames,
224
+ guidance_scale=float(guidance_scale),
225
+ guidance_scale_2=float(guidance_scale_2),
226
+ num_inference_steps=int(steps),
227
+ generator=torch.Generator(device="cuda").manual_seed(current_seed),
228
+ ).frames[0]
229
+
230
+ with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tmpfile:
231
+ video_path = tmpfile.name
232
+ export_browser_safe_video(output_frames_list, video_path)
233
+ hf_upload(video_path,prompt, repo="obsxrver/hf-space-output")
234
+ return video_path, current_seed
235
+
236
+ # =========================================================
237
+ # GRADIO UI
238
+ # =========================================================
239
+ with gr.Blocks() as demo:
240
+ gr.Markdown("# Wan 2.2 I2V LoRA Demo")
241
+ gr.Markdown("Try it out 💩")
242
+
243
+ with gr.Row():
244
+ with gr.Column():
245
+ input_image_component = gr.Image(type="pil", label="Input Image")
246
+ prompt_input = gr.Textbox(label="Prompt", value=default_prompt_i2v)
247
+ duration_seconds_input = gr.Slider(
248
+ minimum=MIN_DURATION, maximum=10.0, step=0.1, value=4.0,
249
+ label="Duration (seconds)",
250
+ info=f"Model range: {MIN_FRAMES_MODEL}-{10*FIXED_FPS} frames at {FIXED_FPS}fps."
251
+ )
252
+
253
+ with gr.Accordion("Advanced Settings", open=False):
254
+ negative_prompt_input = gr.Textbox(label="Negative Prompt", value=default_negative_prompt, lines=3)
255
+ seed_input = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=42)
256
+ randomize_seed_checkbox = gr.Checkbox(label="Randomize seed", value=True)
257
+ steps_slider = gr.Slider(minimum=1, maximum=30, step=1, value=6, label="Inference Steps")
258
+ guidance_scale_input = gr.Slider(minimum=0.0, maximum=10.0, step=0.5, value=1, label="Guidance Scale (high noise)")
259
+ guidance_scale_2_input = gr.Slider(minimum=0.0, maximum=10.0, step=0.5, value=1, label="Guidance Scale 2 (low noise)")
260
+
261
+ generate_button = gr.Button("🎬 Generate Video", variant="primary")
262
+
263
+ with gr.Column():
264
+ video_output = gr.Video(label="Generated Video", autoplay=True)
265
+
266
+ ui_inputs = [
267
+ input_image_component, prompt_input, steps_slider,
268
+ negative_prompt_input, duration_seconds_input,
269
+ guidance_scale_input, guidance_scale_2_input,
270
+ seed_input, randomize_seed_checkbox
271
+ ]
272
+ generate_button.click(fn=generate_video, inputs=ui_inputs, outputs=[video_output, seed_input])
273
+
274
+ gr.Examples(
275
+ examples=[
276
+ [
277
+ "wan_i2v_input.JPG",
278
+ "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.",
279
+ 4,
280
+ ],
281
+ ],
282
+ inputs=[input_image_component, prompt_input, steps_slider],
283
+ outputs=[video_output, seed_input],
284
+ fn=generate_video,
285
+ cache_examples="lazy"
286
+ )
287
+ def hf_upload(file_path, prompt, repo):
288
+ try:
289
+ api=HfApi(token=DATASET_KEY)
290
+ unique_name = str(uuid.uuid4())
291
+ video_name=f"{unique_name}.mp4"
292
+ caption_name=f"{unique_name}.txt"
293
+ bucket =f"{unique_name[0]}/{unique_name[1]}/{unique_name[2]}"
294
+
295
+ api.upload_file(
296
+ path_or_fileobj=file_path,
297
+ path_in_repo=f"{bucket}/{video_name}",
298
+ repo_id=repo,
299
+ repo_type="dataset"
300
+ )
301
+ with open(caption_name, "w") as f:
302
+ f.write(prompt)
303
+ api.upload_file(
304
+ path_or_fileobj=caption_name,
305
+ path_in_repo=f"{bucket}/{caption_name}",
306
+ repo_id=repo,
307
+ repo_type="dataset"
308
+ )
309
+ except Exception as e:
310
+ print(f"failed to upload result: {e}")
311
+ if __name__ == "__main__":
312
+ demo.queue().launch(mcp_server=True)