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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +296 -240
app.py CHANGED
@@ -1,241 +1,297 @@
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
  )
 
1
+ import os
2
+ import requests
3
+ import json
4
+ import time
5
+ import random
6
+ import base64
7
+ import uuid
8
+ import threading
9
+ from pathlib import Path
10
+ from dotenv import load_dotenv
11
+ import gradio as gr
12
+ import torch
13
+ from PIL import Image, ImageDraw, ImageFont
14
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
15
+
16
+ load_dotenv()
17
+
18
+ MODEL_URL = "TostAI/nsfw-text-detection-large"
19
+ CLASS_NAMES = {0: "✅ SAFE", 1: "⚠️ QUESTIONABLE", 2: "🚫 UNSAFE"}
20
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_URL)
21
+ model = AutoModelForSequenceClassification.from_pretrained(MODEL_URL)
22
+
23
+ class SessionManager:
24
+ _instances = {}
25
+ _lock = threading.Lock()
26
+
27
+ @classmethod
28
+ def get_session(cls, session_id):
29
+ with cls._lock:
30
+ if session_id not in cls._instances:
31
+ cls._instances[session_id] = {
32
+ 'count': 0,
33
+ 'history': [],
34
+ 'last_active': time.time()
35
+ }
36
+ return cls._instances[session_id]
37
+
38
+ @classmethod
39
+ def cleanup_sessions(cls):
40
+ with cls._lock:
41
+ now = time.time()
42
+ expired = [k for k, v in cls._instances.items() if now - v['last_active'] > 3600]
43
+ for k in expired:
44
+ del cls._instances[k]
45
+
46
+ class RateLimiter:
47
+ def __init__(self):
48
+ self.clients = {}
49
+ self.lock = threading.Lock()
50
+
51
+ def check(self, client_id):
52
+ with self.lock:
53
+ now = time.time()
54
+ if client_id not in self.clients:
55
+ self.clients[client_id] = {'count': 1, 'reset': now + 3600}
56
+ return True
57
+ if now > self.clients[client_id]['reset']:
58
+ self.clients[client_id] = {'count': 1, 'reset': now + 3600}
59
+ return True
60
+ if self.clients[client_id]['count'] >= 20:
61
+ return False
62
+ self.clients[client_id]['count'] += 1
63
+ return True
64
+
65
+ session_manager = SessionManager()
66
+ rate_limiter = RateLimiter()
67
+
68
+ def create_error_image(message):
69
+ img = Image.new("RGB", (832, 480), "#ffdddd")
70
+ try:
71
+ font = ImageFont.truetype("arial.ttf", 24)
72
+ except:
73
+ font = ImageFont.load_default()
74
+ draw = ImageDraw.Draw(img)
75
+ text = f"Error: {message[:60]}..." if len(message) > 60 else message
76
+ draw.text((50, 200), text, fill="#ff0000", font=font)
77
+ img.save("error.jpg")
78
+ return "error.jpg"
79
+
80
+ def classify_prompt(prompt):
81
+ inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512)
82
+ with torch.no_grad():
83
+ outputs = model(**inputs)
84
+ return torch.argmax(outputs.logits).item()
85
+
86
+ def image_to_base64(file_path):
87
+ try:
88
+ with open(file_path, "rb") as image_file:
89
+ ext = Path(file_path).suffix.lower().lstrip('.')
90
+ mime_map = {
91
+ 'jpg': 'jpeg',
92
+ 'jpeg': 'jpeg',
93
+ 'png': 'png',
94
+ 'webp': 'webp',
95
+ 'gif': 'gif'
96
+ }
97
+ mime_type = mime_map.get(ext, 'jpeg')
98
+
99
+ raw_data = image_file.read()
100
+ encoded = base64.b64encode(raw_data)
101
+ missing_padding = len(encoded) % 4
102
+ if missing_padding:
103
+ encoded += b'=' * (4 - missing_padding)
104
+
105
+ return f"data:image/{mime_type};base64,{encoded.decode('utf-8')}"
106
+ except Exception as e:
107
+ raise ValueError(f"Base64编码失败: {str(e)}")
108
+
109
+ def generate_video(
110
+ image,
111
+ prompt,
112
+ enable_safety,
113
+ flow_shift,
114
+ guidance_scale,
115
+ negative_prompt,
116
+ seed,
117
+ size,
118
+ session_id
119
+ ):
120
+
121
+ safety_level = classify_prompt(prompt)
122
+ if safety_level != 0:
123
+ error_img = create_error_image(CLASS_NAMES[safety_level])
124
+ yield f" Blocked: {CLASS_NAMES[safety_level]}", error_img
125
+ return
126
+
127
+ if not rate_limiter.check(session_id):
128
+ error_img = create_error_image("每小时限制20次请求")
129
+ yield "❌ 请求过于频繁,请稍后再试", error_img
130
+ return
131
+
132
+ session = session_manager.get_session(session_id)
133
+ session['last_active'] = time.time()
134
+ session['count'] += 1
135
+
136
+ API_KEY = os.getenv("WAVESPEED_API_KEY")
137
+ if not API_KEY:
138
+ error_img = create_error_image("API密钥缺失")
139
+ yield "❌ Error: Missing API Key", error_img
140
+ return
141
+
142
+ try:
143
+ base64_image = image_to_base64(image)
144
+ except Exception as e:
145
+ error_img = create_error_image(str(e))
146
+ yield f"❌ 文件上传失败: {str(e)}", error_img
147
+ return
148
+
149
+ payload = {
150
+ "enable_safety_checker": enable_safety,
151
+ "flow_shift": flow_shift,
152
+ "guidance_scale": guidance_scale,
153
+ "image": base64_image,
154
+ "negative_prompt": negative_prompt,
155
+ "prompt": prompt,
156
+ "seed": seed if seed != -1 else random.randint(0, 999999),
157
+ "size": size
158
+ }
159
+
160
+ headers = {
161
+ "Content-Type": "application/json",
162
+ "Authorization": f"Bearer {API_KEY}",
163
+ }
164
+
165
+ try:
166
+ response = requests.post(
167
+ "https://api.wavespeed.ai/api/v2/wavespeed-ai/hunyuan-custom-ref2v-480p",
168
+ headers=headers,
169
+ data=json.dumps(payload)
170
+ )
171
+
172
+ if response.status_code != 200:
173
+ error_img = create_error_image(response.text)
174
+ yield f"❌ API错误 ({response.status_code}): {response.text}", error_img
175
+ return
176
+
177
+ request_id = response.json()["data"]["id"]
178
+ yield f"✅ 任务已提交 (ID: {request_id})", None
179
+ except Exception as e:
180
+ error_img = create_error_image(str(e))
181
+ yield f"❌ 连接错误: {str(e)}", error_img
182
+ return
183
+
184
+ result_url = f"https://api.wavespeed.ai/api/v2/predictions/{request_id}/result"
185
+ start_time = time.time()
186
+
187
+ while True:
188
+ time.sleep(0.5)
189
+ try:
190
+ response = requests.get(result_url, headers=headers)
191
+ if response.status_code != 200:
192
+ error_img = create_error_image(response.text)
193
+ yield f"❌ 轮询错误 ({response.status_code}): {response.text}", error_img
194
+ return
195
+
196
+ data = response.json()["data"]
197
+ status = data["status"]
198
+
199
+ if status == "completed":
200
+ elapsed = time.time() - start_time
201
+ video_url = data['outputs'][0]
202
+ session["history"].append(video_url)
203
+ yield (f"🎉 完成! 耗时 {elapsed:.1f}秒\n"
204
+ f"下载链接: {video_url}"), video_url
205
+ return
206
+
207
+ elif status == "failed":
208
+ error_img = create_error_image(data.get('error', '未知错误'))
209
+ yield f"❌ 任务失败: {data.get('error', '未知错误')}", error_img
210
+ return
211
+
212
+ else:
213
+ yield f"⏳ 状态: {status.capitalize()}...", None
214
+
215
+ except Exception as e:
216
+ error_img = create_error_image(str(e))
217
+ yield f"❌ 轮询失败: {str(e)}", error_img
218
+ return
219
+
220
+ def cleanup_task():
221
+ while True:
222
+ session_manager.cleanup_sessions()
223
+ time.sleep(3600)
224
+
225
+ with gr.Blocks(
226
+ theme=gr.themes.Soft(),
227
+ css="""
228
+ .video-preview { max-width: 600px !important; }
229
+ .status-box { padding: 10px; border-radius: 5px; margin: 5px; }
230
+ .safe { background: #e8f5e9; border: 1px solid #a5d6a7; }
231
+ .warning { background: #fff3e0; border: 1px solid #ffcc80; }
232
+ .error { background: #ffebee; border: 1px solid #ef9a9a; }
233
+ """
234
+ ) as app:
235
+
236
+ session_id = gr.State(str(uuid.uuid4()))
237
+
238
+ gr.Markdown("# 🌊Hunyuan-Custom-Ref2v Run On [WaveSpeedAI](https://wavespeed.ai/)")
239
+ gr.Markdown("""HunyuanCustom, a multi-modal, conditional, and controllable generation model centered on subject consistency, built upon the Hunyuan Video generation framework. It enables the generation of subject-consistent videos conditioned on text, images, audio, and video inputs.""")
240
+
241
+ with gr.Row():
242
+ with gr.Column(scale=1):
243
+ img_input = gr.Image(type="filepath", label="Input Image")
244
+ prompt = gr.Textbox(label="Prompt", lines=5, placeholder="Prompt...")
245
+ negative_prompt = gr.Textbox(label="Negative Prompt", lines=2)
246
+ size = gr.Dropdown(["832*480", "480*832"], value="832*480", label="Size")
247
+ guidance = gr.Slider(1, 30, value=5, step=0.1, label="Guidance")
248
+ seed = gr.Number(-1, label="Seed")
249
+ random_seed_btn = gr.Button("Random🎲Seed", variant="secondary")
250
+ flow_shift = gr.Number(3, label="Shift", interactive=False)
251
+ enable_safety = gr.Checkbox(True, label="Enable Safety Checker", interactive=False)
252
+
253
+ with gr.Column(scale=1):
254
+ video_output = gr.Video(label="Video Output", format="mp4", interactive=False, elem_classes=["video-preview"])
255
+ generate_btn = gr.Button("Generate", variant="primary")
256
+ status_output = gr.Textbox(label="status", interactive=False, lines=4)
257
+
258
+ gr.Examples(
259
+ examples=[
260
+ [
261
+ "Create a dynamic and intense scene depicting a warrior fighting a fearsome fire dragon. The setting should be grand and immersive, capturing the scale and drama of the confrontation.",
262
+ "https://d2g64w682n9w0w.cloudfront.net/media/images/1745337597019716935_RS1XUQMI.jpg"
263
+ ]
264
+ ],
265
+ inputs=[prompt, img_input],
266
+ label="Examples Prompt",
267
+ examples_per_page=3
268
+ )
269
+
270
+ random_seed_btn.click(
271
+ fn=lambda: random.randint(0, 999999),
272
+ outputs=seed
273
+ )
274
+
275
+ generate_btn.click(
276
+ generate_video,
277
+ inputs=[
278
+ img_input,
279
+ prompt,
280
+ enable_safety,
281
+ flow_shift,
282
+ guidance,
283
+ negative_prompt,
284
+ seed,
285
+ size,
286
+ session_id
287
+ ],
288
+ outputs=[status_output, video_output]
289
+ )
290
+
291
+ if __name__ == "__main__":
292
+ threading.Thread(target=cleanup_task, daemon=True).start()
293
+ app.queue(max_size=4).launch(
294
+ server_name="0.0.0.0",
295
+ max_threads=16,
296
+ share=False
297
  )