jiandan1998 commited on
Commit
7e57ee1
·
verified ·
1 Parent(s): b483eea

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +241 -0
app.py ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import requests
3
+ import json
4
+ import time
5
+ import threading
6
+ import shutil
7
+ from datetime import datetime
8
+ from pathlib import Path
9
+ from http.server import HTTPServer, SimpleHTTPRequestHandler
10
+ import base64
11
+ from dotenv import load_dotenv
12
+ import gradio as gr
13
+ import random
14
+
15
+ load_dotenv()
16
+
17
+ def image_to_base64(file_path):
18
+ try:
19
+ with open(file_path, "rb") as image_file:
20
+ # 处理特殊MIME类型
21
+ ext = Path(file_path).suffix.lower().lstrip('.')
22
+ mime_map = {
23
+ 'jpg': 'jpeg',
24
+ 'jpeg': 'jpeg',
25
+ 'png': 'png',
26
+ 'webp': 'webp',
27
+ 'gif': 'gif'
28
+ }
29
+ mime_type = mime_map.get(ext, 'jpeg')
30
+
31
+ # 读取并编码
32
+ raw_data = image_file.read()
33
+ encoded = base64.b64encode(raw_data)
34
+ missing_padding = len(encoded) % 4
35
+ if missing_padding:
36
+ encoded += b'=' * (4 - missing_padding)
37
+
38
+ return f"data:image/{mime_type};base64,{encoded.decode('utf-8')}"
39
+
40
+ except Exception as e:
41
+ raise ValueError(f"Base64编码失败: {str(e)}")
42
+
43
+ def generate_random_seed():
44
+ return random.randint(0, 999999)
45
+
46
+ def generate_video(
47
+ image,
48
+ prompt,
49
+ duration,
50
+ enable_safety,
51
+ flow_shift,
52
+ guidance_scale,
53
+ negative_prompt,
54
+ inference_steps,
55
+ seed,
56
+ size
57
+ ):
58
+ API_KEY = os.getenv("WAVESPEED_API_KEY")
59
+ if not API_KEY:
60
+ yield "❌ Error: Missing API Key", None
61
+ return
62
+
63
+ try:
64
+ base64_image = image_to_base64(image)
65
+ except Exception as e:
66
+ yield f"❌ File upload failed: {str(e)}", None
67
+ return
68
+
69
+ payload = {
70
+ "duration": duration,
71
+ "enable_safety_checker": enable_safety,
72
+ "flow_shift": flow_shift,
73
+ "guidance_scale": guidance_scale,
74
+ "image": base64_image,
75
+ "negative_prompt": negative_prompt,
76
+ "num_inference_steps": inference_steps,
77
+ "prompt": prompt,
78
+ "seed": seed,
79
+ "size": size
80
+ }
81
+
82
+ headers = {
83
+ "Content-Type": "application/json",
84
+ "Authorization": f"Bearer {API_KEY}",
85
+ }
86
+
87
+ try:
88
+ response = requests.post(
89
+ "https://api.wavespeed.ai/api/v2/wavespeed-ai/wan-2.1/i2v-480p-ultra-fast",
90
+ headers=headers,
91
+ data=json.dumps(payload)
92
+ )
93
+
94
+ if response.status_code != 200:
95
+ yield f"❌ API Error ({response.status_code}): {response.text}", None
96
+ return
97
+
98
+ request_id = response.json()["data"]["id"]
99
+ yield f"✅ Task submitted (ID: {request_id})", None
100
+ except Exception as e:
101
+ yield f"❌ Connection Error: {str(e)}", None
102
+ return
103
+
104
+ # 轮询结果
105
+ result_url = f"https://api.wavespeed.ai/api/v2/predictions/{request_id}/result"
106
+ start_time = time.time()
107
+ video_url = None
108
+
109
+ while True:
110
+ time.sleep(1)
111
+ try:
112
+ response = requests.get(result_url, headers={"Authorization": f"Bearer {API_KEY}"})
113
+ if response.status_code != 200:
114
+ yield f"❌ Polling Error ({response.status_code}): {response.text}", None
115
+ return
116
+
117
+ data = response.json()["data"]
118
+ status = data["status"]
119
+
120
+ if status == "completed":
121
+ elapsed = time.time() - start_time
122
+ video_url = data['outputs'][0]
123
+ yield (f"🎉 Completed in {elapsed:.1f}s!\n"
124
+ f"Download URL: {video_url}"), video_url
125
+ return
126
+
127
+ elif status == "failed":
128
+ yield f"❌ Failed: {data.get('error', 'Unknown error')}", None
129
+ return
130
+
131
+ else:
132
+ yield f"⏳ Status: {status.capitalize()}...", None
133
+
134
+ except Exception as e:
135
+ yield f"❌ Polling Failed: {str(e)}", None
136
+ return
137
+
138
+ # Gradio UI
139
+ with gr.Blocks(
140
+ theme=gr.themes.Soft(),
141
+ css="""
142
+ .video-preview {
143
+ max-width: 600px !important
144
+ }
145
+ .example-preview {
146
+ border: 1px solid #e0e0e0;
147
+ border-radius: 8px;
148
+ padding: 10px;
149
+ margin: 5px;
150
+ }
151
+ .example-preview img {
152
+ max-width: 200px;
153
+ max-height: 150px;
154
+ }
155
+ """
156
+ ) as app:
157
+
158
+ session_id = gr.State(None)
159
+
160
+ gr.Markdown("# 🌊 Wan-2.1-i2v-480p-Ultra-Fast Run On WaveSpeedAI")
161
+
162
+ gr.Markdown("""
163
+ [WaveSpeedAI](https://wavespeed.ai/) is the global pioneer in accelerating AI-powered video and image generation.
164
+ Our in-house inference accelerator provides lossless speedup on image & video generation based on our rich inference optimization software stack, including our in-house inference compiler, CUDA kernel libraries and parallel computing libraries.
165
+ """)
166
+ gr.Markdown("""
167
+ The Wan2.1 14B model is an advanced image-to-video model that offers accelerated inference capabilities, enabling high-res video generation with high visual quality and motion diversity.
168
+ """)
169
+
170
+ with gr.Row():
171
+ # 右侧控制面板
172
+ with gr.Column(scale=1):
173
+ with gr.Row():
174
+ with gr.Column(scale=1):
175
+ img_input = gr.Image(type="filepath", label="Upload Image")
176
+ prompt = gr.Textbox(label="Prompt", lines=5, placeholder="Describe your scene...")
177
+ negative_prompt = gr.Textbox(label="Negative Prompt", lines=2)
178
+ size = gr.Dropdown(["832*480"], value="832*480", label="Resolution")
179
+ steps = gr.Slider(1, 50, value=30, step=1, label="Inference Steps")
180
+ duration = gr.Slider(0, 10, value=5, step=5, label="Duration (seconds)")
181
+ guidance = gr.Slider(1, 30, value=5, step=0.1, label="Guidance Scale")
182
+ seed = gr.Number(-1, label="Seed")
183
+ random_seed_btn = gr.Button("🎲random seed", variant="secondary")
184
+ flow_shift = gr.Number(3, label="Flow Shift",interactive=False)
185
+ enable_safety = gr.Checkbox(True, label="Safety Checker",interactive=False)
186
+ # 左侧视频展示区域
187
+ with gr.Column(scale=1):
188
+ video_output = gr.Video(label="Generated Video",format="mp4",interactive=False,elem_classes=["video-preview"]
189
+ )
190
+ generate_btn = gr.Button("Generate Video", variant="primary")
191
+ output = gr.Textbox(label="Status", interactive=False, lines=4)
192
+ gr.Examples(
193
+ examples=[
194
+ [
195
+ "Victorian era, 19th-century gentleman wearing a black top hat and tuxedo, standing on a cobblestone street, dim gaslight lamps, passersby in vintage clothing, gentle breeze moving his coat, slow cinematic pan around him, nostalgic retro film style, realistic textures",
196
+ "https://d2g64w682n9w0w.cloudfront.net/media/images/1745725874603980753_95mFCAxu.jpg"
197
+ ],
198
+ [
199
+ "A cyberpunk female warrior with short silver hair and glowing green eyes, wearing a futuristic armored suit, standing in a neon-lit rainy city street, camera slowly circling around her, raindrops falling in slow motion, neon reflections on wet pavement, cinematic atmosphere, highly detailed, ultra realistic, 4K",
200
+ "https://d2g64w682n9w0w.cloudfront.net/media/images/1745726299175719855_pFO0WSRM.jpg"
201
+ ],
202
+ [
203
+ "Wide shot of a brave medieval female knight in shining silver armor and a red cape, standing on a castle rooftop at sunset, slowly drawing a large ornate sword from its scabbard, seen from a distance with the vast castle and surrounding landscape in the background, golden light bathing the scene, hair and cape flowing gently in the wind, cinematic epic atmosphere, dynamic motion, majestic clouds drifting, ultra realistic, high fantasy world, 4K ultra-detailed",
204
+ "https://d2g64w682n9w0w.cloudfront.net/media/images/1745727436576834405_rtsokheb.jpg"
205
+ ],
206
+ [
207
+ "A girl stands in a lively 17th-century market. She holds a red tomato, looks gently into the camera and smiles briefly. Then, she glances at the tomato in her hand, slowly sets it back into the basket, turns around gracefully, and walks away with her back to the camera. The market around her is rich with colorful vegetables, meats hanging above, and bustling townsfolk. Golden-hour painterly lighting, subtle facial expressions, smooth cinematic motion, ultra-realistic detail, Vermeer-inspired style",
208
+ "https://d2g64w682n9w0w.cloudfront.net/media/images/1745079024013078406_QT6jKNPZ.png"
209
+ ],
210
+ [
211
+ "A calming video explaining diabetes management and prevention tips to reduce anxiety.",
212
+ "https://d2g64w682n9w0w.cloudfront.net/predictions/517d518c28ef49ed9464610af48528f5/1.jpg"
213
+ ],
214
+ [
215
+ "Girl dancing and spinning with friends.",
216
+ "https://d2g64w682n9w0w.cloudfront.net/media/d45e0d4893d44712b359f3ad0b3c2795/images/1745449961409630099_KISOKGEB.jpg"
217
+ ]
218
+ ],
219
+ inputs=[prompt, img_input], # 同时绑定到图片和提示输入框
220
+ label="Example Inputs",
221
+ examples_per_page=3
222
+ )
223
+
224
+ random_seed_btn.click(
225
+ fn=lambda: random.randint(0, 999999),
226
+ outputs=seed
227
+ )
228
+
229
+ generate_btn.click(
230
+ generate_video,
231
+ inputs=[img_input, prompt, duration, enable_safety, flow_shift,
232
+ guidance, negative_prompt, steps, seed, size],
233
+ outputs=[output, video_output]
234
+ )
235
+
236
+ if __name__ == "__main__":
237
+ app.queue(max_size=4).launch(
238
+ server_name="0.0.0.0",
239
+ max_threads=16,
240
+ debug=True
241
+ )