Update app.py
Browse files
app.py
CHANGED
|
@@ -1,241 +1,297 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import requests
|
| 3 |
-
import json
|
| 4 |
-
import time
|
| 5 |
-
import
|
| 6 |
-
import
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
from
|
| 10 |
-
import
|
| 11 |
-
|
| 12 |
-
import
|
| 13 |
-
import
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
"
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
try:
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
)
|