bann commited on
Commit
342ec8c
·
0 Parent(s):

feat: initial commit for Wan 2.1 / 2.2 Studio Space with ZeroGPU and Multi-LoRA

Browse files
Files changed (5) hide show
  1. .gitignore +11 -0
  2. README.md +24 -0
  3. app.py +943 -0
  4. loras/README.md +4 -0
  5. requirements.txt +13 -0
.gitignore ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.py[cod]
3
+ *$py.class
4
+ *.mp4
5
+ *.png
6
+ *.jpg
7
+ *.safetensors
8
+ !loras/*.safetensors
9
+ *.download
10
+ *.tmp
11
+ .env
README.md ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Wan 2.1 Studio
3
+ emoji: 🎬
4
+ colorFrom: indigo
5
+ colorTo: purple
6
+ sdk: gradio
7
+ sdk_version: 5.20.0
8
+ app_file: app.py
9
+ pinned: false
10
+ license: apache-2.0
11
+ short_description: Wan 2.1 Video Studio with Multi-LoRA and I2V/T2V
12
+ suggested_hardware: zero-a10g
13
+ ---
14
+
15
+ # Wan 2.1 / 2.2 Video Studio (ZeroGPU + Multi-LoRA)
16
+
17
+ A high-performance AI video generation studio running **Wan 2.1 / Wan 2.2** on **ZeroGPU**.
18
+
19
+ ### Features:
20
+ - 🖼️ **Image-to-Video (I2V)** and 📝 **Text-to-Video (T2V)** support.
21
+ - ⚡ **ZeroGPU Acceleration**: Runs with dynamic GPU scheduling on A10G / H100 hardware.
22
+ - 🧩 **Multi-LoRA Engine**: Load up to 2 custom LoRAs from Civitai, Hugging Face, or local files with Trigger Words.
23
+ - 📐 **300-Hours Civitai Optimization**: Strict multiple-of-16 aspect ratios (832x480, 480x832, 1280x720, etc.) for clean motion.
24
+ - 📖 **Built-in Prompt & Anatomical Motion Guide**: Designed with the official structured prompt standards.
app.py ADDED
@@ -0,0 +1,943 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Wan 2.1 / 2.2 Space with ZeroGPU, Multi-LoRA (Civitai + HF), Presets, Trigger Words, and 300-Hours Optimizations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import ipaddress
7
+ import json
8
+ import mimetypes
9
+ import os
10
+ import random
11
+ import re
12
+ import shutil
13
+ import socket
14
+ import tempfile
15
+ import time
16
+ import traceback
17
+ from functools import cache
18
+ from urllib.parse import urljoin, urlsplit
19
+
20
+ import spaces
21
+ import gradio as gr
22
+ import torch
23
+ from PIL import Image, ImageOps
24
+ from diffusers.utils import export_to_video
25
+ from safetensors import safe_open
26
+
27
+ DEFAULT_MODEL_REPO = os.environ.get("WAN_MODEL_REPO", "Wan-AI/Wan2.1-I2V-14B-480P-Diffusers")
28
+ GPU_SIZE = os.environ.get("WAN_GPU_SIZE", "xlarge")
29
+ MAX_GPU_DURATION = int(os.environ.get("WAN_MAX_GPU_DURATION", "300"))
30
+ OUTPUT_DIR = os.path.join(tempfile.gettempdir(), "wan-outputs")
31
+ LOCAL_LORAS_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "loras")
32
+ LORA_MAX_BYTES = 2 * 1024**3
33
+ DEFAULT_FPS = 16
34
+
35
+ # =========================================================================
36
+ # Preset Catalog for Wan 2.1 / 2.2 LoRAs
37
+ # =========================================================================
38
+ LORA_PRESETS = {
39
+ "None / Desativado": {
40
+ "type": "none",
41
+ "trigger_words": "",
42
+ "default_strength": 1.0,
43
+ "description": "Nenhum LoRA selecionado neste slot.",
44
+ },
45
+ "HMNSFW AIO V2 / hmmotion (Wan 2.1 / 2.2)": {
46
+ "type": "civitai",
47
+ "source": "https://civitai.com/api/download/models/3206518",
48
+ "trigger_words": "hmmotion, missionary, side, fast, third-person side view, medium shot.",
49
+ "default_strength": 0.5,
50
+ "description": "LoRA All-in-One de anatomia e movimento realista (Civitai 2834417 / 3206518). Use força <= 0.5 com prompts descritivos.",
51
+ },
52
+ "Icy Twerk Pro Max (Wan 2.1 / 2.2)": {
53
+ "type": "civitai",
54
+ "source": "https://civitai.com/api/download/models/3201584",
55
+ "trigger_words": "icytw3rk, twerking, booty shake, rhythmic hip movement, dynamic motion, bouncing buttocks, high quality",
56
+ "default_strength": 0.9,
57
+ "description": "LoRA de animação e movimento de twerk / booty shake para Wan (Civitai 2836640 / 3201584).",
58
+ },
59
+ "Cumouf - Oral Creampie / CIM with Spasms": {
60
+ "type": "civitai",
61
+ "source": "https://civitai.com/api/download/models/3223411",
62
+ "trigger_words": "cum in mouth, oral creampie, cum overflow, spasms, throat bulge, choking on cum, messy facial, open mouth",
63
+ "default_strength": 0.85,
64
+ "description": "Oral creampie com espasmos faciais e garganta (Civitai 2846978 / 3223411).",
65
+ },
66
+ "Epic Cumshots & Facials": {
67
+ "type": "civitai",
68
+ "source": "https://civitai.com/api/download/models/3052864",
69
+ "trigger_words": "cumshot, thick semen, facial, climax, sticky ejaculation, messy dripping, high viscosity",
70
+ "default_strength": 0.9,
71
+ "description": "Ejaculação realista de alta viscosidade com respingos faciais e corporais.",
72
+ },
73
+ "Dynamic Cinematic Camera Motion": {
74
+ "type": "prompt_only",
75
+ "trigger_words": "dynamic cinematic camera, slow orbit shot, dramatic lighting, sweeping drone view, motion blur",
76
+ "default_strength": 0.85,
77
+ "description": "Movimento de câmera fluído e cinematográfico.",
78
+ },
79
+ "Cyberpunk / Sci-Fi Neon Realism": {
80
+ "type": "prompt_only",
81
+ "trigger_words": "cyberpunk, holographic HUD, volumetric neon reflections, cybernetic glow, futuristic city, 8k cinematic",
82
+ "default_strength": 0.9,
83
+ "description": "Estilo cyberpunk hiper-detalhado com iluminação volumétrica e neons.",
84
+ },
85
+ }
86
+
87
+ # 300 Hours Civitai Guide: Strict multiples-of-16 resolutions
88
+ CANVASES = {
89
+ # 16:9 Landscape
90
+ "832x480 · 16:9 Landscape (Fast 480p)": (480, 832),
91
+ "960x544 · 16:9 Landscape (Balanced)": (544, 960),
92
+ "1280x720 · 16:9 Landscape (HD 720p)": (720, 1280),
93
+ # 9:16 Portrait / Reels
94
+ "480x832 · 9:16 Portrait (Fast 480p)": (832, 480),
95
+ "544x960 · 9:16 Portrait (Balanced)": (960, 544),
96
+ "720x1280 · 9:16 Portrait (HD 720p)": (1280, 720),
97
+ # 1:1 Square
98
+ "640x640 · 1:1 Square (Fast)": (640, 640),
99
+ "768x768 · 1:1 Square (HD)": (768, 768),
100
+ # 4:3 / 3:4
101
+ "768x576 · 4:3 Standard": (576, 768),
102
+ "576x768 · 3:4 Portrait": (768, 576),
103
+ # 21:9 Ultrawide
104
+ "1152x512 · 21:9 Ultrawide": (512, 1152),
105
+ }
106
+ DEFAULT_CANVAS = "832x480 · 16:9 Landscape (Fast 480p)"
107
+
108
+ PIPE = None
109
+ CURRENT_MODEL_REPO = None
110
+ LOAD_ERROR: str | None = None
111
+ LOADED_IN: float | None = None
112
+
113
+
114
+ def get_local_loras() -> list[str]:
115
+ """Scans the local loras/ folder for .safetensors files."""
116
+ if not os.path.exists(LOCAL_LORAS_DIR):
117
+ try:
118
+ os.makedirs(LOCAL_LORAS_DIR, exist_ok=True)
119
+ except Exception:
120
+ return []
121
+ files = [f for f in os.listdir(LOCAL_LORAS_DIR) if f.endswith(".safetensors")]
122
+ return sorted(files)
123
+
124
+
125
+ def normalize_civitai_url(url: str) -> str:
126
+ """Extracts direct download link from any Civitai model or version URL."""
127
+ url = url.strip()
128
+ if not url:
129
+ return url
130
+
131
+ match_version = re.search(r"modelVersionId=(\d+)", url)
132
+ if match_version:
133
+ version_id = match_version.group(1)
134
+ return f"https://civitai.com/api/download/models/{version_id}"
135
+
136
+ if "api/download/models/" in url:
137
+ return re.sub(r"https?://[^/]+", "https://civitai.com", url)
138
+
139
+ match_model = re.search(r"civitai\.(?:com|red|org|blue|work)/models/(\d+)", url)
140
+ if match_model:
141
+ model_id = match_model.group(1)
142
+ try:
143
+ import requests
144
+ r = requests.get(f"https://civitai.com/api/v1/models/{model_id}", timeout=8)
145
+ if r.ok:
146
+ data = r.json()
147
+ versions = data.get("modelVersions", [])
148
+ if versions and "id" in versions[0]:
149
+ return f"https://civitai.com/api/download/models/{versions[0]['id']}"
150
+ except Exception as err:
151
+ print(f"[civitai] failed to resolve model {model_id} metadata: {err}", flush=True)
152
+ return url
153
+
154
+
155
+ def resolve_canvas(value: str) -> str:
156
+ canvas = str(value).strip()
157
+ if canvas in CANVASES:
158
+ return canvas
159
+ return DEFAULT_CANVAS
160
+
161
+
162
+ def _sha256(path: str) -> str:
163
+ digest = hashlib.sha256()
164
+ with open(path, "rb") as source:
165
+ for chunk in iter(lambda: source.read(1024 * 1024), b""):
166
+ digest.update(chunk)
167
+ return digest.hexdigest()
168
+
169
+
170
+ def _lora_cache_directory(source: str) -> str:
171
+ root = os.path.join(tempfile.gettempdir(), "wan-lora-downloads")
172
+ cache_key = hashlib.sha256(source.encode()).hexdigest()[:20]
173
+ local_dir = os.path.join(root, cache_key)
174
+ os.makedirs(local_dir, exist_ok=True)
175
+ others = sorted(
176
+ (entry for entry in os.scandir(root) if entry.is_dir() and entry.path != local_dir),
177
+ key=lambda entry: entry.stat().st_mtime,
178
+ reverse=True,
179
+ )
180
+ for stale in others[4:]:
181
+ shutil.rmtree(stale.path, ignore_errors=True)
182
+ return local_dir
183
+
184
+
185
+ def _validate_public_lora_url(url: str) -> str:
186
+ if len(url) > 2048:
187
+ raise ValueError("Direct LoRA URL is too long.")
188
+ parsed = urlsplit(url)
189
+ if parsed.scheme.lower() != "https" or not parsed.hostname:
190
+ raise ValueError("Direct LoRA URLs must use public HTTPS.")
191
+ if parsed.username or parsed.password or parsed.port not in (None, 443):
192
+ raise ValueError("Direct LoRA URLs cannot contain credentials or non-standard ports.")
193
+ try:
194
+ addresses = {item[4][0] for item in socket.getaddrinfo(parsed.hostname, 443, type=socket.SOCK_STREAM)}
195
+ except socket.gaierror as error:
196
+ raise ValueError("Direct LoRA URL hostname could not be resolved.") from error
197
+ for raw_address in addresses:
198
+ address = ipaddress.ip_address(raw_address)
199
+ if isinstance(address, ipaddress.IPv6Address) and address.ipv4_mapped is not None:
200
+ address = address.ipv4_mapped
201
+ if not address.is_global:
202
+ raise ValueError("Direct LoRA URLs cannot access private or local networks.")
203
+ return url
204
+
205
+
206
+ def _download_lora_url(url: str, civitai_token: str = "") -> tuple[str, str]:
207
+ import requests
208
+
209
+ token = (civitai_token or os.environ.get("CIVITAI_API_KEY", "") or os.environ.get("CIVITAI_TOKEN", "")).strip()
210
+
211
+ if "civitai." in url and token and "token=" not in url:
212
+ sep = "&" if "?" in url else "?"
213
+ url = f"{url}{sep}token={token}"
214
+
215
+ original = _validate_public_lora_url(url)
216
+ local_dir = _lora_cache_directory(original)
217
+ path = os.path.join(local_dir, "adapter.safetensors")
218
+ if os.path.isfile(path) and 0 < os.path.getsize(path) <= LORA_MAX_BYTES:
219
+ try:
220
+ with safe_open(path, framework="pt", device="cpu") as handle:
221
+ if handle.keys():
222
+ os.utime(local_dir, None)
223
+ parsed = urlsplit(original)
224
+ return path, f"{parsed.hostname}{parsed.path}"[:180]
225
+ except Exception:
226
+ os.unlink(path)
227
+
228
+ temporary = path + ".download"
229
+ current = original
230
+ for _ in range(6):
231
+ current = _validate_public_lora_url(current)
232
+ parsed_current = urlsplit(current)
233
+ req_headers = {"User-Agent": "Wan-Studio-Space/1.0"}
234
+ if token and ("civitai.com" in parsed_current.netloc or "civitai.red" in parsed_current.netloc):
235
+ req_headers["Authorization"] = f"Bearer {token}"
236
+
237
+ try:
238
+ with requests.get(
239
+ current,
240
+ stream=True,
241
+ allow_redirects=False,
242
+ timeout=(15, 300),
243
+ headers=req_headers,
244
+ ) as response:
245
+ if response.is_redirect or response.is_permanent_redirect:
246
+ location = response.headers.get("location")
247
+ if not location:
248
+ raise ValueError("Direct LoRA URL returned an empty redirect.")
249
+ current = urljoin(current, location)
250
+ continue
251
+ if response.status_code in (401, 403):
252
+ raise gr.Error(
253
+ "🔒 O Civitai bloqueou o download deste modelo (401 Unauthorized / NSFW). "
254
+ "Gere um Civitai API Key em https://civitai.com/user/account-settings "
255
+ "e cole no campo 'Civitai API Key' no painel do Space."
256
+ )
257
+ response.raise_for_status()
258
+ total = 0
259
+ with open(temporary, "wb") as output:
260
+ for chunk in response.iter_content(1024 * 1024):
261
+ if not chunk:
262
+ continue
263
+ total += len(chunk)
264
+ if total > LORA_MAX_BYTES:
265
+ raise ValueError("Direct LoRA exceeds the 2 GiB safety limit.")
266
+ output.write(chunk)
267
+ with safe_open(temporary, framework="pt", device="cpu") as handle:
268
+ if not handle.keys():
269
+ raise ValueError("Direct LoRA contains no safetensors tensors.")
270
+ os.replace(temporary, path)
271
+ os.utime(local_dir, None)
272
+ parsed = urlsplit(original)
273
+ return path, f"{parsed.hostname}{parsed.path}"[:180]
274
+ except requests.exceptions.HTTPError as err:
275
+ if "response" in locals() and response.status_code in (401, 403):
276
+ raise gr.Error(
277
+ "🔒 O Civitai bloqueou o download deste modelo (401 Unauthorized / NSFW). "
278
+ "Gere um Civitai API Key em https://civitai.com/user/account-settings e cole no campo 'Civitai API Key'."
279
+ ) from err
280
+ raise
281
+ raise ValueError("Too many redirects downloading LoRA.")
282
+
283
+
284
+ def resolve_single_lora(
285
+ preset_type: str, custom_url: str, hf_repo: str, hf_file: str, local_file: str, strength: float, civitai_token: str = ""
286
+ ) -> tuple[str | None, str, float]:
287
+ """Resolves one LoRA file path, label and scale for Wan 2.1/2.2."""
288
+ if float(strength) == 0.0 or preset_type in ("None / Desativado", "None", ""):
289
+ return None, "None", 0.0
290
+
291
+ if preset_type in LORA_PRESETS:
292
+ spec = LORA_PRESETS[preset_type]
293
+ if spec.get("type") == "hf":
294
+ from huggingface_hub import hf_hub_download
295
+ repo_id = spec["hf_repo"]
296
+ filename = spec["hf_file"]
297
+ local_dir = _lora_cache_directory(f"hf://{repo_id}/{filename}")
298
+ path = hf_hub_download(repo_id=repo_id, filename=filename, token=False, local_dir=local_dir)
299
+ os.utime(local_dir, None)
300
+ return path, preset_type, strength
301
+
302
+ if spec.get("source"):
303
+ url = normalize_civitai_url(spec["source"])
304
+ if url:
305
+ path, label = _download_lora_url(url, civitai_token)
306
+ return path, preset_type, strength
307
+ return None, "None", 0.0
308
+
309
+ if preset_type == "Custom URL / Civitai":
310
+ url = normalize_civitai_url(custom_url)
311
+ if not url:
312
+ return None, "None", 0.0
313
+ path, label = _download_lora_url(url, civitai_token)
314
+ return path, f"URL: {label}", strength
315
+
316
+ if preset_type == "Custom Hugging Face":
317
+ repo_id = str(hf_repo or "").strip()
318
+ filename = str(hf_file or "").strip()
319
+ if not repo_id or not filename:
320
+ return None, "None", 0.0
321
+ if not re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repo_id):
322
+ raise ValueError("Custom LoRA repo must be in `owner/repository` format.")
323
+ if not filename.endswith(".safetensors"):
324
+ raise ValueError("Custom LoRA file must be a `.safetensors` file.")
325
+
326
+ from huggingface_hub import get_hf_file_metadata, hf_hub_download, hf_hub_url
327
+ metadata = get_hf_file_metadata(hf_hub_url(repo_id, filename), token=False)
328
+ if metadata.size is None or metadata.size > LORA_MAX_BYTES:
329
+ raise ValueError("LoRA file exceeds the 2 GiB limit.")
330
+ local_dir = _lora_cache_directory(f"hf://{repo_id}/{filename}")
331
+ path = hf_hub_download(repo_id=repo_id, filename=filename, token=False, local_dir=local_dir)
332
+ os.utime(local_dir, None)
333
+ return path, f"{repo_id}/{filename}", strength
334
+
335
+ if preset_type == "Local File (loras/ folder)":
336
+ if not local_file:
337
+ return None, "None", 0.0
338
+ local_path = os.path.join(LOCAL_LORAS_DIR, local_file)
339
+ if not os.path.isfile(local_path):
340
+ raise ValueError(f"Arquivo local {local_file} não encontrado na pasta loras/.")
341
+ return local_path, f"local:{local_file}", strength
342
+
343
+ return None, "None", 0.0
344
+
345
+
346
+ def load_pipeline(model_repo: str = DEFAULT_MODEL_REPO):
347
+ global PIPE, CURRENT_MODEL_REPO, LOAD_ERROR, LOADED_IN
348
+
349
+ if PIPE is not None and CURRENT_MODEL_REPO == model_repo:
350
+ return PIPE
351
+
352
+ started = time.time()
353
+ try:
354
+ from diffusers import WanImageToVideoPipeline, WanPipeline
355
+
356
+ print(f"[wan] loading pipeline from {model_repo} ...", flush=True)
357
+ if "I2V" in model_repo or "i2v" in model_repo:
358
+ pipe = WanImageToVideoPipeline.from_pretrained(
359
+ model_repo,
360
+ torch_dtype=torch.bfloat16,
361
+ )
362
+ else:
363
+ pipe = WanPipeline.from_pretrained(
364
+ model_repo,
365
+ torch_dtype=torch.bfloat16,
366
+ )
367
+
368
+ PIPE = pipe
369
+ CURRENT_MODEL_REPO = model_repo
370
+ LOADED_IN = time.time() - started
371
+ print(f"[wan] ready in {LOADED_IN:.0f}s", flush=True)
372
+ except Exception as error:
373
+ traceback.print_exc()
374
+ LOAD_ERROR = f"**Loading `{model_repo}` failed**: `{type(error).__name__}: {error}`"
375
+ raise RuntimeError(LOAD_ERROR) from error
376
+ return PIPE
377
+
378
+
379
+ def _fit_keyframe(image_input, target_width: int, target_height: int) -> Image.Image:
380
+ if isinstance(image_input, str):
381
+ img = Image.open(image_input)
382
+ elif isinstance(image_input, Image.Image):
383
+ img = image_input
384
+ else:
385
+ raise ValueError("Invalid image input")
386
+
387
+ img = ImageOps.exif_transpose(img).convert("RGB")
388
+ target_aspect = target_width / target_height
389
+ img_aspect = img.width / img.height
390
+
391
+ if abs(img_aspect - target_aspect) > 1e-3:
392
+ if img_aspect > target_aspect:
393
+ new_w = int(img.height * target_aspect)
394
+ left = (img.width - new_w) // 2
395
+ img = img.crop((left, 0, left + new_w, img.height))
396
+ else:
397
+ new_h = int(img.width / target_aspect)
398
+ top = (img.height - new_h) // 2
399
+ img = img.crop((0, top, img.width, top + new_h))
400
+
401
+ img = img.resize((target_width, target_height), Image.Resampling.LANCZOS)
402
+ return img
403
+
404
+
405
+ def get_duration(prompt, negative_prompt, input_image, canvas, num_frames, fps, steps, *a, **k):
406
+ steps = int(steps)
407
+ num_frames = int(num_frames)
408
+ h, w = CANVACES_GET = CANVASES.get(canvas, (480, 832))
409
+ pixels_per_frame = h * w
410
+ total_tokens = (pixels_per_frame / 256) * (num_frames / 4)
411
+ estimated = int(steps * (total_tokens * 0.00012) + 20)
412
+ return max(60, min(MAX_GPU_DURATION, estimated))
413
+
414
+
415
+ @spaces.GPU(duration=get_duration, size=GPU_SIZE)
416
+ def _generate_video_gpu(
417
+ prompt: str,
418
+ negative_prompt: str,
419
+ image_input: Image.Image | None,
420
+ height: int,
421
+ width: int,
422
+ num_frames: int,
423
+ steps: int,
424
+ guidance_scale: float,
425
+ seed: int,
426
+ lora_configs: list[tuple[str, float]],
427
+ model_repo: str,
428
+ ):
429
+ pipe = load_pipeline(model_repo)
430
+ pipe.to("cuda")
431
+
432
+ active_lora_names = []
433
+ if lora_configs:
434
+ try:
435
+ pipe.unload_lora_weights()
436
+ except Exception:
437
+ pass
438
+
439
+ for lora_path, lora_scale in lora_configs:
440
+ if lora_path and lora_scale > 0:
441
+ adapter_name = f"lora_{len(active_lora_names)}"
442
+ pipe.load_lora_weights(lora_path, adapter_name=adapter_name)
443
+ active_lora_names.append(adapter_name)
444
+
445
+ if active_lora_names:
446
+ scales = [scale for _, scale in lora_configs if scale > 0]
447
+ pipe.set_adapters(active_lora_names, adapter_weights=scales)
448
+
449
+ generator = torch.Generator("cuda").manual_seed(int(seed))
450
+
451
+ try:
452
+ with torch.inference_mode():
453
+ if image_input is not None and ("I2V" in model_repo or "i2v" in model_repo):
454
+ output = pipe(
455
+ image=image_input,
456
+ prompt=prompt,
457
+ negative_prompt=negative_prompt if negative_prompt else None,
458
+ height=height,
459
+ width=width,
460
+ num_frames=num_frames,
461
+ num_inference_steps=int(steps),
462
+ guidance_scale=float(guidance_scale),
463
+ generator=generator,
464
+ )
465
+ else:
466
+ output = pipe(
467
+ prompt=prompt,
468
+ negative_prompt=negative_prompt if negative_prompt else None,
469
+ height=height,
470
+ width=width,
471
+ num_frames=num_frames,
472
+ num_inference_steps=int(steps),
473
+ guidance_scale=float(guidance_scale),
474
+ generator=generator,
475
+ )
476
+ frames = output.frames[0]
477
+ finally:
478
+ if active_lora_names:
479
+ try:
480
+ pipe.unload_lora_weights()
481
+ except Exception:
482
+ pass
483
+
484
+ return frames
485
+
486
+
487
+ def generate_video(
488
+ prompt: str,
489
+ negative_prompt: str,
490
+ input_image: Image.Image | str | None,
491
+ canvas: str,
492
+ num_frames: int,
493
+ fps: int,
494
+ steps: int,
495
+ guidance_scale: float,
496
+ seed: int,
497
+ randomize_seed: bool,
498
+ model_choice: str,
499
+ lora1_preset: str,
500
+ lora1_custom_url: str,
501
+ lora1_hf_repo: str,
502
+ lora1_hf_file: str,
503
+ lora1_local_file: str,
504
+ lora1_strength: float,
505
+ lora2_preset: str,
506
+ lora2_custom_url: str,
507
+ lora2_hf_repo: str,
508
+ lora2_hf_file: str,
509
+ lora2_local_file: str,
510
+ lora2_strength: float,
511
+ civitai_api_key: str,
512
+ progress=gr.Progress(track_tqdm=True),
513
+ ):
514
+ if not prompt or not prompt.strip():
515
+ raise gr.Error("Por favor, digite um prompt descrevendo a cena do vídeo.")
516
+
517
+ if randomize_seed:
518
+ seed = random.randint(0, 2147483647)
519
+
520
+ canvas = resolve_canvas(canvas)
521
+ height, width = CANVASES[canvas]
522
+
523
+ processed_image = None
524
+ if input_image is not None:
525
+ processed_image = _fit_keyframe(input_image, width, height)
526
+
527
+ lora_configs = []
528
+ active_labels = []
529
+
530
+ l1_path, l1_label, l1_scale = resolve_single_lora(
531
+ lora1_preset, lora1_custom_url, lora1_hf_repo, lora1_hf_file, lora1_local_file, lora1_strength, civitai_api_key
532
+ )
533
+ if l1_path and l1_scale > 0:
534
+ lora_configs.append((l1_path, l1_scale))
535
+ active_labels.append(f"{l1_label} (@ {lora1_strength:g})")
536
+
537
+ l2_path, l2_label, l2_scale = resolve_single_lora(
538
+ lora2_preset, lora2_custom_url, lora2_hf_repo, lora2_hf_file, lora2_local_file, lora2_strength, civitai_api_key
539
+ )
540
+ if l2_path and l2_scale > 0:
541
+ lora_configs.append((l2_path, l2_scale))
542
+ active_labels.append(f"{l2_label} (@ {lora2_strength:g})")
543
+
544
+ progress(0.1, desc=f"Gerando {steps} passos a {width}x{height} ({num_frames} frames)...")
545
+ started = time.time()
546
+
547
+ frames = _generate_video_gpu(
548
+ prompt=prompt,
549
+ negative_prompt=negative_prompt,
550
+ image_input=processed_image,
551
+ height=height,
552
+ width=width,
553
+ num_frames=int(num_frames),
554
+ steps=int(steps),
555
+ guidance_scale=float(guidance_scale),
556
+ seed=int(seed),
557
+ lora_configs=lora_configs,
558
+ model_repo=model_choice,
559
+ )
560
+
561
+ gen_time = time.time() - started
562
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
563
+ out_video_path = os.path.join(OUTPUT_DIR, f"wan_{int(time.time() * 1000)}.mp4")
564
+ export_to_video(frames, out_video_path, fps=int(fps))
565
+
566
+ loras_str = " + ".join(active_labels) if active_labels else "None (Base Model)"
567
+ report = (
568
+ f"**Modelo**: `{model_choice.split('/')[-1]}` | **Resolução**: `{width}x{height}` (Múltiplo de 16) | "
569
+ f"**Frames**: {num_frames} ({num_frames / fps:.2f}s @ {fps}fps) | **Passos**: {steps} | **Seed**: {seed}\n\n"
570
+ f"🎯 **Active LoRAs**: `{loras_str}`\n\n"
571
+ f"⏱️ **Tempo de Renderização**: {gen_time:.1f}s"
572
+ )
573
+
574
+ return out_video_path, report, seed
575
+
576
+
577
+ # =========================================================================
578
+ # Gradio UI Interface
579
+ # =========================================================================
580
+
581
+ custom_css = """
582
+ .gradio-container {
583
+ max-width: 1350px !important;
584
+ margin: 0 auto !important;
585
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
586
+ }
587
+ .header-card {
588
+ background: linear-gradient(135deg, #1e1b4b 0%, #3b0764 50%, #0f172a 100%);
589
+ border: 1px solid rgba(168, 85, 247, 0.3);
590
+ border-radius: 16px;
591
+ padding: 24px 32px;
592
+ margin-bottom: 20px;
593
+ box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.4);
594
+ }
595
+ .header-card h1 {
596
+ font-size: 2.2rem;
597
+ font-weight: 800;
598
+ margin: 0 0 8px 0;
599
+ background: linear-gradient(90deg, #c084fc, #38bdf8, #818cf8);
600
+ -webkit-background-clip: text;
601
+ -webkit-text-fill-color: transparent;
602
+ }
603
+ .badge {
604
+ display: inline-block;
605
+ padding: 4px 10px;
606
+ border-radius: 9999px;
607
+ font-size: 0.8rem;
608
+ font-weight: 600;
609
+ margin-right: 6px;
610
+ }
611
+ .badge-zerogpu {
612
+ background: rgba(16, 185, 129, 0.2);
613
+ color: #34d399;
614
+ border: 1px solid rgba(16, 185, 129, 0.4);
615
+ }
616
+ .badge-model {
617
+ background: rgba(99, 102, 241, 0.2);
618
+ color: #a5b4fc;
619
+ border: 1px solid rgba(99, 102, 241, 0.4);
620
+ }
621
+ .badge-multilora {
622
+ background: rgba(236, 72, 153, 0.2);
623
+ color: #f472b6;
624
+ border: 1px solid rgba(236, 72, 153, 0.4);
625
+ }
626
+ .trigger-btn {
627
+ background: rgba(168, 85, 247, 0.2) !important;
628
+ border: 1px solid rgba(168, 85, 247, 0.5) !important;
629
+ color: #e9d5ff !important;
630
+ font-size: 0.85rem !important;
631
+ font-weight: 600 !important;
632
+ padding: 4px 12px !important;
633
+ border-radius: 6px !important;
634
+ }
635
+ .generate-btn {
636
+ background: linear-gradient(135deg, #9333ea 0%, #4f46e5 100%) !important;
637
+ color: white !important;
638
+ font-weight: 700 !important;
639
+ font-size: 1.15rem !important;
640
+ border-radius: 12px !important;
641
+ padding: 12px 24px !important;
642
+ box-shadow: 0 4px 15px rgba(147, 51, 234, 0.4) !important;
643
+ border: none !important;
644
+ transition: all 0.2s ease !important;
645
+ }
646
+ .generate-btn:hover {
647
+ transform: translateY(-2px) !important;
648
+ box-shadow: 0 6px 20px rgba(147, 51, 234, 0.6) !important;
649
+ }
650
+ """
651
+
652
+ all_preset_choices = (
653
+ list(LORA_PRESETS.keys())
654
+ + ["Custom URL / Civitai", "Custom Hugging Face"]
655
+ + (["Local File (loras/ folder)"] if get_local_loras() else [])
656
+ )
657
+
658
+ with gr.Blocks(css=custom_css, title="Wan 2.1 / 2.2 Video Studio") as app:
659
+ gr.HTML(
660
+ """
661
+ <div class="header-card">
662
+ <div style="margin-bottom: 12px;">
663
+ <span class="badge badge-zerogpu">⚡ ZeroGPU</span>
664
+ <span class="badge badge-model">🎬 Wan 2.1 (14B Diffusers)</span>
665
+ <span class="badge badge-multilora">🧩 Multi-LoRA Engine</span>
666
+ </div>
667
+ <h1>Wan 2.1 / 2.2 AI Video Studio</h1>
668
+ <p>Image-to-Video (I2V) & Text-to-Video (T2V) com suporte a múltiplos LoRAs e resoluções otimizadas (Múltiplos de 16).</p>
669
+ </div>
670
+ """
671
+ )
672
+
673
+ with gr.Row():
674
+ with gr.Column(scale=6):
675
+ prompt = gr.Textbox(
676
+ label="Prompt",
677
+ placeholder="Descreva a cena detalhada do vídeo...",
678
+ lines=4,
679
+ value="A cinematic shot of a beautiful woman with glowing eyes, dramatic lighting, 8k masterpiece",
680
+ )
681
+
682
+ negative_prompt = gr.Textbox(
683
+ label="Negative Prompt",
684
+ placeholder="Elementos indesejados (distorções, membros extras, baixa qualidade)...",
685
+ lines=2,
686
+ value="deformed, bad anatomy, extra limbs, blurry, low resolution, bad quality, distortion",
687
+ )
688
+
689
+ with gr.Accordion("📖 Guia & Modelos de Prompt HMNSFW / hmmotion (Wan 2.1 / 2.2)", open=False):
690
+ gr.Markdown(
691
+ """
692
+ **Estrutura Recomendada pelo Guia de 300 Horas / Autor do LoRA (`hmmotion`)**:
693
+ - **Força recomendada**: `0.3` a `0.5` (use `<= 0.5`).
694
+ - **Cabeçalho Obrigatório**: `hmmotion, <class>, <viewpoint>, <pace>, <shot>.`
695
+ - *Class*: `missionary` / `cowgirl` / `blowjob` / `doggy` / `handjob` / `insertion`
696
+ - *Viewpoint*: `pov` ou `side`
697
+ - *Pace*: `fast` ou `slow`
698
+ - *Shot*: `close-up` / `medium shot` / `third-person side view` / `high-angle downward shot`
699
+ - **Dica**: Escreva um parágrafo contínuo descritivo de 180 a 260 palavras detalhando a pose, anatomia, movimento (*"The motion is..."*), superfícies (*"sheen"*) e áudio (*"The audio consists of..."*).
700
+ """
701
+ )
702
+ hmnsfw_example_btn = gr.Button("💡 Inserir Exemplo Completo de Prompt HMNSFW", elem_classes=["trigger-btn"])
703
+
704
+ with gr.Tabs():
705
+ with gr.TabItem("🖼️ Image-to-Video (I2V)"):
706
+ gr.Markdown("Faça upload de uma imagem inicial (`First Frame`). O sistema ajustará o corte automaticamente para a proporção múltipla de 16 selecionada.")
707
+ input_image = gr.Image(label="First Frame (Imagem Inicial)", type="filepath")
708
+
709
+ with gr.TabItem("🎨 LoRA Slot 1 (Estilo / Ação)"):
710
+ lora1_preset = gr.Dropdown(
711
+ label="LoRA Slot 1 Preset / Fonte",
712
+ choices=all_preset_choices,
713
+ value="None / Desativado",
714
+ )
715
+ with gr.Group(visible=False) as lora1_custom_url_grp:
716
+ lora1_custom_url = gr.Textbox(
717
+ label="URL de Download do Civitai / SafeTensor",
718
+ placeholder="https://civitai.red/models/... ou https://civitai.com/api/download/models/...",
719
+ )
720
+ with gr.Group(visible=False) as lora1_hf_grp:
721
+ with gr.Row():
722
+ lora1_hf_repo = gr.Textbox(label="HF Repo ID", placeholder="owner/repo")
723
+ lora1_hf_file = gr.Textbox(label="HF Filename", placeholder="model.safetensors")
724
+ with gr.Group(visible=False) as lora1_local_grp:
725
+ lora1_local_file = gr.Dropdown(label="Arquivo Local (pasta loras/)", choices=get_local_loras())
726
+
727
+ lora1_trigger_display = gr.Textbox(
728
+ label="Trigger Words",
729
+ value="",
730
+ interactive=False,
731
+ )
732
+ add_lora1_triggers_btn = gr.Button("📋 Inserir Trigger Words no Prompt", elem_classes=["trigger-btn"])
733
+
734
+ lora1_strength = gr.Slider(
735
+ label="LoRA 1 Força (Scale)",
736
+ minimum=0.0,
737
+ maximum=2.0,
738
+ step=0.05,
739
+ value=1.0,
740
+ )
741
+
742
+ with gr.TabItem("🎬 LoRA Slot 2 (Movimento / Câmera)"):
743
+ lora2_preset = gr.Dropdown(
744
+ label="LoRA Slot 2 Preset / Fonte",
745
+ choices=all_preset_choices,
746
+ value="None / Desativado",
747
+ )
748
+ with gr.Group(visible=False) as lora2_custom_url_grp:
749
+ lora2_custom_url = gr.Textbox(
750
+ label="URL de Download do Civitai / SafeTensor",
751
+ placeholder="https://civitai.com/api/download/models/...",
752
+ )
753
+ with gr.Group(visible=False) as lora2_hf_grp:
754
+ with gr.Row():
755
+ lora2_hf_repo = gr.Textbox(label="HF Repo ID", placeholder="owner/repo")
756
+ lora2_hf_file = gr.Textbox(label="HF Filename", placeholder="model.safetensors")
757
+ with gr.Group(visible=False) as lora2_local_grp:
758
+ lora2_local_file = gr.Dropdown(label="Arquivo Local (pasta loras/)", choices=get_local_loras())
759
+
760
+ lora2_trigger_display = gr.Textbox(
761
+ label="Trigger Words",
762
+ value="",
763
+ interactive=False,
764
+ )
765
+ add_lora2_triggers_btn = gr.Button("📋 Inserir Trigger Words no Prompt", elem_classes=["trigger-btn"])
766
+
767
+ lora2_strength = gr.Slider(
768
+ label="LoRA 2 Força (Scale)",
769
+ minimum=0.0,
770
+ maximum=2.0,
771
+ step=0.05,
772
+ value=0.85,
773
+ )
774
+
775
+ with gr.Accordion("⚙️ Configurações de Resolução & Renderização (Guia 300h)", open=True):
776
+ with gr.Row():
777
+ model_choice = gr.Dropdown(
778
+ label="Modelo Base Wan",
779
+ choices=[
780
+ ("Wan 2.1 I2V 14B 480P (Recomendado ZeroGPU)", "Wan-AI/Wan2.1-I2V-14B-480P-Diffusers"),
781
+ ("Wan 2.1 I2V 14B 720P (Alta Definição)", "Wan-AI/Wan2.1-I2V-14B-720P-Diffusers"),
782
+ ("Wan 2.1 T2V 1.3B (Ultra Rápido)", "Wan-AI/Wan2.1-T2V-1.3B-Diffusers"),
783
+ ("Wan 2.1 T2V 14B (Texto para Vídeo)", "Wan-AI/Wan2.1-T2V-14B-Diffusers"),
784
+ ],
785
+ value="Wan-AI/Wan2.1-I2V-14B-480P-Diffusers",
786
+ )
787
+ canvas = gr.Dropdown(
788
+ label="Proporção & Resolução (Múltiplos de 16)",
789
+ choices=list(CANVASES.keys()),
790
+ value=DEFAULT_CANVAS,
791
+ )
792
+
793
+ with gr.Row():
794
+ num_frames = gr.Slider(
795
+ label="Número de Frames",
796
+ minimum=17,
797
+ maximum=81,
798
+ step=16,
799
+ value=81,
800
+ info="81 frames = ~5 segundos a 16 fps; 49 frames = ~3 segundos.",
801
+ )
802
+ fps = gr.Slider(
803
+ label="FPS do Vídeo",
804
+ minimum=8,
805
+ maximum=30,
806
+ step=1,
807
+ value=16,
808
+ )
809
+ steps = gr.Slider(
810
+ label="Passos de Inferência (Steps)",
811
+ minimum=4,
812
+ maximum=40,
813
+ step=1,
814
+ value=20,
815
+ info="O guia recomenda 15-25 passos para qualidade ideal.",
816
+ )
817
+
818
+ with gr.Row():
819
+ guidance_scale = gr.Slider(
820
+ label="Guidance Scale (CFG)",
821
+ minimum=1.0,
822
+ maximum=10.0,
823
+ step=0.5,
824
+ value=5.0,
825
+ )
826
+ seed = gr.Number(label="Seed", value=42, precision=0)
827
+ randomize_seed = gr.Checkbox(label="🎲 Randomizar Seed", value=True)
828
+
829
+ civitai_api_key = gr.Textbox(
830
+ label="🔑 Civitai API Key (Opcional)",
831
+ placeholder="Cole seu token Civitai se baixar modelos restritos/NSFW direto do civitai.com (ou adicione CIVITAI_API_KEY no Space Secrets)",
832
+ type="password",
833
+ )
834
+
835
+ generate_btn = gr.Button("🚀 Gerar Vídeo Wan 2.1", variant="primary", elem_classes=["generate-btn"])
836
+
837
+ with gr.Column(scale=6):
838
+ output_video = gr.Video(label="Vídeo Gerado", autoplay=True, loop=True)
839
+ output_report = gr.Markdown(label="Detalhes da Geração", value="Pronto para renderizar vídeo.")
840
+
841
+ # Event handlers
842
+ def on_lora1_change(preset_val):
843
+ spec = LORA_PRESETS.get(preset_val, {})
844
+ triggers = spec.get("trigger_words", "")
845
+ default_s = spec.get("default_strength", 1.0)
846
+ return (
847
+ gr.update(visible=preset_val == "Custom URL / Civitai"),
848
+ gr.update(visible=preset_val == "Custom Hugging Face"),
849
+ gr.update(visible=preset_val == "Local File (loras/ folder)"),
850
+ triggers,
851
+ default_s,
852
+ )
853
+
854
+ lora1_preset.change(
855
+ fn=on_lora1_change,
856
+ inputs=[lora1_preset],
857
+ outputs=[lora1_custom_url_grp, lora1_hf_grp, lora1_local_grp, lora1_trigger_display, lora1_strength],
858
+ )
859
+
860
+ def on_lora2_change(preset_val):
861
+ spec = LORA_PRESETS.get(preset_val, {})
862
+ triggers = spec.get("trigger_words", "")
863
+ default_s = spec.get("default_strength", 1.0)
864
+ return (
865
+ gr.update(visible=preset_val == "Custom URL / Civitai"),
866
+ gr.update(visible=preset_val == "Custom Hugging Face"),
867
+ gr.update(visible=preset_val == "Local File (loras/ folder)"),
868
+ triggers,
869
+ default_s,
870
+ )
871
+
872
+ lora2_preset.change(
873
+ fn=on_lora2_change,
874
+ inputs=[lora2_preset],
875
+ outputs=[lora2_custom_url_grp, lora2_hf_grp, lora2_local_grp, lora2_trigger_display, lora2_strength],
876
+ )
877
+
878
+ def append_triggers(curr_prompt, triggers):
879
+ if not triggers:
880
+ return curr_prompt
881
+ curr = curr_prompt.strip()
882
+ if not curr:
883
+ return triggers
884
+ if triggers.lower() in curr.lower():
885
+ return curr
886
+ return f"{curr}, {triggers}"
887
+
888
+ def load_hmnsfw_example():
889
+ return (
890
+ "hmmotion, missionary, side, fast, third-person side view, medium shot. "
891
+ "A fair-skinned woman with long dark hair lies on her back, her torso angled toward the camera. "
892
+ "She wears a red and black lace garter belt around her waist but is otherwise nude. "
893
+ "Her left leg is raised and bent while her right leg is spread wide. "
894
+ "The man is positioned above her, his torso and arms visible as he thrusts. "
895
+ "In the center of the frame the woman's vulva is the focal point, situated between her thighs and below the man's pelvis. "
896
+ "The vulva is clearly rendered and hairless; the labia majora are pale pink and fully parted by the penetration. "
897
+ "The inner labia are thin, dark pink and visible at the edges of the vaginal opening. "
898
+ "The clitoral hood is visible and flushed. "
899
+ "The vaginal rim stretches significantly with each deep, fast thrust, and the surrounding skin is pulled taut. "
900
+ "The motion is fast and rhythmic, his hips driving forward and back, her thighs shifting with each impact. "
901
+ "A visible sheen of wetness coats the vulva and the base of the shaft, catching the overhead light. "
902
+ "His hands grip her raised thigh, holding her leg open. Her head is tilted back with her mouth open. "
903
+ "The audio consists of wet slapping contact and skin-on-skin impact, accompanied by her loud rhythmic moaning and heavy breathing. "
904
+ "The setting is a bed with dark grey sheets under warm, low indoor lighting."
905
+ )
906
+
907
+ hmnsfw_example_btn.click(fn=load_hmnsfw_example, outputs=[prompt])
908
+ add_lora1_triggers_btn.click(fn=append_triggers, inputs=[prompt, lora1_trigger_display], outputs=[prompt])
909
+ add_lora2_triggers_btn.click(fn=append_triggers, inputs=[prompt, lora2_trigger_display], outputs=[prompt])
910
+
911
+ generate_btn.click(
912
+ fn=generate_video,
913
+ inputs=[
914
+ prompt,
915
+ negative_prompt,
916
+ input_image,
917
+ canvas,
918
+ num_frames,
919
+ fps,
920
+ steps,
921
+ guidance_scale,
922
+ seed,
923
+ randomize_seed,
924
+ model_choice,
925
+ lora1_preset,
926
+ lora1_custom_url,
927
+ lora1_hf_repo,
928
+ lora1_hf_file,
929
+ lora1_local_file,
930
+ lora1_strength,
931
+ lora2_preset,
932
+ lora2_custom_url,
933
+ lora2_hf_repo,
934
+ lora2_hf_file,
935
+ lora2_local_file,
936
+ lora2_strength,
937
+ civitai_api_key,
938
+ ],
939
+ outputs=[output_video, output_report, seed],
940
+ )
941
+
942
+ if __name__ == "__main__":
943
+ app.launch(show_error=True, allowed_paths=[OUTPUT_DIR])
loras/README.md ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Pasta de LoRAs Locais para Wan 2.1 / 2.2
2
+
3
+ Coloque qualquer arquivo `.safetensors` de LoRA para Wan 2.1 / 2.2 nesta pasta `loras/`.
4
+ A aplicação listará automaticamente os arquivos no menu suspenso de LoRAs locais.
requirements.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ git+https://github.com/huggingface/diffusers.git
2
+ transformers>=4.49.0
3
+ accelerate>=1.2.0
4
+ sentencepiece
5
+ safetensors
6
+ gradio>=5.20.0
7
+ spaces>=0.51.1
8
+ imageio[ffmpeg]
9
+ torchvision
10
+ ftfy
11
+ regex
12
+ requests
13
+ Pillow