Spaces:
Running
on
Zero
Running
on
Zero
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,364 +1,297 @@
|
|
| 1 |
import spaces
|
| 2 |
import torch
|
| 3 |
-
|
| 4 |
-
|
| 5 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
import tempfile
|
| 7 |
import numpy as np
|
| 8 |
-
from PIL import Image
|
| 9 |
import random
|
| 10 |
import gc
|
| 11 |
from torchao.quantization import quantize_
|
| 12 |
from torchao.quantization import Float8DynamicActivationFloat8WeightConfig
|
| 13 |
from torchao.quantization import Int8WeightOnlyConfig
|
| 14 |
import aoti
|
| 15 |
-
|
| 16 |
-
import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
|
|
|
| 18 |
MODEL_ID = "Wan-AI/Wan2.2-I2V-A14B-Diffusers"
|
| 19 |
MAX_DIM = 832
|
| 20 |
MIN_DIM = 480
|
| 21 |
SQUARE_DIM = 640
|
| 22 |
MULTIPLE_OF = 16
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
FIXED_FPS = 16
|
| 25 |
MIN_FRAMES_MODEL = 8
|
| 26 |
-
MAX_FRAMES_MODEL =
|
| 27 |
MIN_DURATION = round(MIN_FRAMES_MODEL / FIXED_FPS, 1)
|
| 28 |
MAX_DURATION = round(MAX_FRAMES_MODEL / FIXED_FPS, 1)
|
| 29 |
|
| 30 |
-
#
|
| 31 |
pipe = WanImageToVideoPipeline.from_pretrained(
|
| 32 |
MODEL_ID,
|
| 33 |
-
transformer=WanTransformer3DModel.from_pretrained(
|
| 34 |
-
MODEL_ID, # استخدم MODEL_ID الرئيسي إذا لم يكن cbensimon متاحًا
|
| 35 |
-
subfolder='transformer',
|
| 36 |
-
torch_dtype=torch.bfloat16,
|
| 37 |
-
device_map='cuda',
|
| 38 |
-
),
|
| 39 |
-
transformer_2=WanTransformer3DModel.from_pretrained(
|
| 40 |
-
MODEL_ID,
|
| 41 |
-
subfolder='transformer_2',
|
| 42 |
-
torch_dtype=torch.bfloat16,
|
| 43 |
-
device_map='cuda',
|
| 44 |
-
),
|
| 45 |
torch_dtype=torch.bfloat16,
|
| 46 |
).to('cuda')
|
|
|
|
| 47 |
|
| 48 |
-
#
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
"
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
)
|
| 60 |
-
pipe.set_adapters(["lightx2v", "lightx2v_2"], adapter_weights=[1., 1.])
|
| 61 |
-
|
| 62 |
-
# دمج LoRA مع مقاييس مخصصة لتعزيز الاستقرار والاحترافية
|
| 63 |
-
pipe.fuse_lora(adapter_names=["lightx2v"], lora_scale=3.5, components=["transformer"])
|
| 64 |
-
pipe.fuse_lora(adapter_names=["lightx2v_2"], lora_scale=1.2, components=["transformer_2"])
|
| 65 |
-
pipe.unload_lora_weights()
|
| 66 |
-
|
| 67 |
-
# الكمية لتوفير الذاكرة مع الحفاظ على الدقة
|
| 68 |
-
quantize_(pipe.text_encoder, Int8WeightOnlyConfig())
|
| 69 |
-
quantize_(pipe.transformer, Float8DynamicActivationFloat8WeightConfig())
|
| 70 |
-
quantize_(pipe.transformer_2, Float8DynamicActivationFloat8WeightConfig())
|
| 71 |
-
|
| 72 |
-
# تحميل AoT للأداء الفائق
|
| 73 |
-
aoti.aoti_blocks_load(pipe.transformer, 'zerogpu-aoti/Wan2', variant='fp8da')
|
| 74 |
-
aoti.aoti_blocks_load(pipe.transformer_2, 'zerogpu-aoti/Wan2', variant='fp8da')
|
| 75 |
-
|
| 76 |
-
# تحسين الـ Prompt الافتراضي... (يبقى كما هو)
|
| 77 |
-
default_prompt_i2v = (
|
| 78 |
-
"ultra realistic cinematic footage shot on Arri Alexa LF with Panavision anamorphic lenses, "
|
| 79 |
-
"perfectly preserved facial identity, micro-expressions, and body structure across all frames, "
|
| 80 |
-
"stable anatomy with precise muscle definition and natural breathing dynamics, "
|
| 81 |
-
"seamless motion continuity with fluid interpolation and no artifacts, "
|
| 82 |
-
"photorealistic clothing preservation: accurate fabric simulation, dynamic folds, and lighting interactions, "
|
| 83 |
-
"consistent outfit color, texture, and material fidelity under varying light, "
|
| 84 |
-
"high-fidelity skin tone, subsurface scattering, pore details, and lifelike sweat/oil sheen, "
|
| 85 |
-
"authentic eye reflections, iris details, and natural gaze tracking with subtle blinks, "
|
| 86 |
-
"cinematic lighting setup: three-point lighting with soft volumetric god rays and rim lights, "
|
| 87 |
-
"professional film-grade color grading in DaVinci Resolve style, HDR tone mapping with dynamic range preservation, "
|
| 88 |
-
"realistic ambient occlusion, caustics, and global illumination, "
|
| 89 |
-
"physically accurate reflections, refractions, and specular highlights on surfaces, "
|
| 90 |
-
"detailed cinematic background with shallow depth of field, natural bokeh, and atmospheric haze, "
|
| 91 |
-
"smooth dolly/steadicam camera movement with organic parallax and film grain emulation, "
|
| 92 |
-
"35mm film aesthetic with subtle lens flares and vignette, "
|
| 93 |
-
"ultra-detailed textures at 8K resolution, consistent and coherent composition with rule of thirds, "
|
| 94 |
-
"perfect balance of depth, light, motion, and emotion for an immersive photorealistic cinematic atmosphere, "
|
| 95 |
-
"temporal coherence at 24fps equivalent, identity consistency with no drift or morphing, "
|
| 96 |
-
"frame-to-frame stability with advanced optical flow preservation"
|
| 97 |
-
)
|
| 98 |
-
|
| 99 |
-
default_negative_prompt = (
|
| 100 |
-
"low quality, low resolution, low contrast, poor lighting, underexposed, overexposed, bad composition, "
|
| 101 |
-
"bad framing, bad perspective, flat lighting, washed out colors, jpeg artifacts, noise, static, grain, "
|
| 102 |
-
"compression artifacts, flickering, stutter, shaky camera, inconsistent motion, poor transition, "
|
| 103 |
-
"broken motion, unnatural interpolation, out of focus, blurry, motion blur, ghosting, double exposure, "
|
| 104 |
-
"distorted face, changing face, warped face, face drift, identity shift, face inconsistency, "
|
| 105 |
-
"unnatural facial expression, mutated body, deformed limbs, extra fingers, fused fingers, missing fingers, "
|
| 106 |
-
"bad anatomy, unrealistic proportions, twisted pose, asymmetrical body, unappealing, uncanny, artificial face, "
|
| 107 |
-
"waxy skin, plastic look, text, watermark, logo, signature, frame border, cropped edges, tiling, "
|
| 108 |
-
"duplicate, repeated pattern, cartoon, anime, illustration, 3d render, painting, drawing, oversharpened, "
|
| 109 |
-
"low detail, artificial texture, poor skin texture, over-smoothed, fake skin, flat skin, color banding, "
|
| 110 |
-
"saturation, chromatic aberration, unrealistic shadows, inconsistent lighting, frozen frame, poor depth, "
|
| 111 |
-
"lack of realism, fake reflection, artifacted highlights, bloom artifacts, bad transition, broken frame, "
|
| 112 |
-
"visual glitch, bad synchronization, oversaturated colors, contrast issues, unbalanced composition, "
|
| 113 |
-
"lack of cinematic tone, flat motion, jitter, warped geometry, background distortion, identity mismatch, "
|
| 114 |
-
"morphing, inconsistent hair, inconsistent body shape, lens distortion, barrel distortion, chromatic fringing, "
|
| 115 |
-
"over-sharpened edges, pixelation, aliasing, temporal inconsistency, frame drops, audio-visual desync"
|
| 116 |
-
)
|
| 117 |
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
تحسين الصورة المدخلة لتعزيز الجودة والواقعية قبل التمرير.
|
| 121 |
-
"""
|
| 122 |
-
enhancer = ImageEnhance.Contrast(image)
|
| 123 |
-
image = enhancer.enhance(1.05)
|
| 124 |
-
enhancer = ImageEnhance.Sharpness(image)
|
| 125 |
-
image = enhancer.enhance(1.1)
|
| 126 |
-
image = image.filter(ImageFilter.UnsharpMask(radius=1, percent=150, threshold=3))
|
| 127 |
-
return image
|
| 128 |
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
left = (width - crop_width) // 2
|
| 148 |
-
image_to_resize = enhanced_image.crop((left, 0, left + crop_width, height))
|
| 149 |
-
elif aspect_ratio < MIN_ASPECT_RATIO:
|
| 150 |
-
target_w, target_h = MIN_DIM, MAX_DIM
|
| 151 |
-
crop_height = int(round(width / MIN_ASPECT_RATIO))
|
| 152 |
-
top = (height - crop_height) // 2
|
| 153 |
-
image_to_resize = enhanced_image.crop((0, top, width, top + crop_height))
|
| 154 |
else:
|
| 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 |
-
def
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
raise gr.Error("يرجى تحميل صورة مدخلة.")
|
| 201 |
-
|
| 202 |
-
gc.collect()
|
| 203 |
-
torch.cuda.empty_cache()
|
| 204 |
-
|
| 205 |
-
num_frames = get_num_frames(duration_seconds)
|
| 206 |
-
current_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed)
|
| 207 |
-
|
| 208 |
-
resized_image = resize_image(input_image)
|
| 209 |
-
|
| 210 |
-
progress(0, desc="بدء التوليد...")
|
| 211 |
-
|
| 212 |
-
with progress():
|
| 213 |
-
output_frames_list = pipe(
|
| 214 |
-
image=resized_image,
|
| 215 |
-
prompt=ftfy.fix_text(prompt), # إضافة ftfy للنصوص
|
| 216 |
-
negative_prompt=ftfy.fix_text(negative_prompt),
|
| 217 |
-
height=resized_image.height,
|
| 218 |
-
width=resized_image.width,
|
| 219 |
-
num_frames=num_frames,
|
| 220 |
-
guidance_scale=float(guidance_scale),
|
| 221 |
-
guidance_scale_2=float(guidance_scale_2),
|
| 222 |
-
num_inference_steps=int(steps),
|
| 223 |
-
generator=torch.Generator(device="cuda").manual_seed(current_seed),
|
| 224 |
-
).frames[0]
|
| 225 |
-
|
| 226 |
-
progress(1, desc="تصدير الفيديو...")
|
| 227 |
-
|
| 228 |
-
with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tmpfile:
|
| 229 |
-
video_path = tmpfile.name
|
| 230 |
-
|
| 231 |
-
export_to_video(output_frames_list, video_path, fps=FIXED_FPS)
|
| 232 |
-
|
| 233 |
-
del output_frames_list
|
| 234 |
-
gc.collect()
|
| 235 |
-
torch.cuda.empty_cache()
|
| 236 |
-
|
| 237 |
-
return video_path, current_seed
|
| 238 |
|
| 239 |
-
#
|
| 240 |
-
|
| 241 |
-
#
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
# 🎬 **Dream-wan2-2-faster-Pro**
|
| 245 |
-
### ⚡ مولد فيديو من صورة واقعي فائق السرعة والاحترافية
|
| 246 |
-
---
|
| 247 |
-
🚀 **أكثر من 32,000 زيارة ويزداد نموًا — في المرتبة الثالثة عالميًا لتوليد الفيديو!**
|
| 248 |
-
🌐 مدعوم بـ dream2589632147/Dream-wan2-2-faster-Pro
|
| 249 |
-
**الجديد في هذه النسخة:**
|
| 250 |
-
- ✅ تحسين الذاكرة والسرعة (حتى 70% أسرع مع استقرار أعلى)
|
| 251 |
-
- 🎥 أقصى طول فيديو: 45 ثانية
|
| 252 |
-
- 💡 يعمل بسلاسة على CPU أو GPU
|
| 253 |
-
- 🧠 تعزيز التوافق بين الإطارات والتفاصيل السينمائية العميقة
|
| 254 |
-
- 🔍 تحسين تلقائي للصورة المدخلة لجودة 8K افتراضية
|
| 255 |
-
🔗 *جرب الآن وشارك إبداعاتك على Reddit أو Hugging Face!*
|
| 256 |
-
""")
|
| 257 |
-
|
| 258 |
-
gr.Markdown("# Wan 2.2 I2V سريع في 4 خطوات مع Lightning LoRA محسن")
|
| 259 |
-
gr.Markdown(
|
| 260 |
-
"شغل Wan 2.2 في 4-8 خطوات فقط، مع [Lightning LoRA](https://huggingface.co/Kijai/WanVideo_comfy/tree/main/Wan22-Lightning)، "
|
| 261 |
-
"كمية fp8، وترجمة AoT — متوافق مع 🧨 diffusers و ZeroGPU⚡️. "
|
| 262 |
-
"مُحسّن للاحترافية الفائقة: استقرار إطارات، إضاءة سينمائية، وتفاصيل واقعية عميقة."
|
| 263 |
-
)
|
| 264 |
-
|
| 265 |
with gr.Row():
|
| 266 |
with gr.Column(scale=1):
|
| 267 |
-
|
| 268 |
-
prompt_input = gr.Textbox(
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
)
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
maximum=MAX_DURATION,
|
| 277 |
-
step=0.1,
|
| 278 |
-
value=3.5,
|
| 279 |
-
label="المدة (ثوانٍ)",
|
| 280 |
-
info=f"محدود بـ {MIN_FRAMES_MODEL}-{MAX_FRAMES_MODEL} إطار عند {FIXED_FPS} إطار/ثانية."
|
| 281 |
-
)
|
| 282 |
-
with gr.Accordion("الإعدادات المتقدمة", open=False):
|
| 283 |
-
negative_prompt_input = gr.Textbox(
|
| 284 |
-
label="الوصف السلبي (Negative Prompt)",
|
| 285 |
-
value=default_negative_prompt,
|
| 286 |
-
lines=4
|
| 287 |
-
)
|
| 288 |
-
seed_input = gr.Slider(
|
| 289 |
-
label="البذرة (Seed)",
|
| 290 |
-
minimum=0,
|
| 291 |
-
maximum=MAX_SEED,
|
| 292 |
-
step=1,
|
| 293 |
-
value=42,
|
| 294 |
-
interactive=True
|
| 295 |
-
)
|
| 296 |
-
randomize_seed_checkbox = gr.Checkbox(
|
| 297 |
-
label="توليد بذرة عشوائية",
|
| 298 |
-
value=True,
|
| 299 |
-
interactive=True
|
| 300 |
-
)
|
| 301 |
-
steps_slider = gr.Slider(
|
| 302 |
-
minimum=1,
|
| 303 |
-
maximum=30,
|
| 304 |
-
step=1,
|
| 305 |
-
value=6,
|
| 306 |
-
label="عدد الخطوات (Inference Steps)"
|
| 307 |
-
)
|
| 308 |
-
guidance_scale_input = gr.Slider(
|
| 309 |
-
minimum=0.0,
|
| 310 |
-
maximum=10.0,
|
| 311 |
-
step=0.1,
|
| 312 |
-
value=1.2,
|
| 313 |
-
label="مقياس التوجي�� - مرحلة الضوضاء العالية"
|
| 314 |
-
)
|
| 315 |
-
guidance_scale_2_input = gr.Slider(
|
| 316 |
-
minimum=0.0,
|
| 317 |
-
maximum=10.0,
|
| 318 |
-
step=0.1,
|
| 319 |
-
value=1.2,
|
| 320 |
-
label="مقياس التوجيه 2 - مرحلة الضوضاء المنخفضة"
|
| 321 |
-
)
|
| 322 |
-
enhance_image_checkbox = gr.Checkbox(
|
| 323 |
-
label="تعزيز الصورة المدخلة تلقائيًا (للواقعية العميقة)",
|
| 324 |
-
value=True
|
| 325 |
-
)
|
| 326 |
-
generate_button = gr.Button("توليد الفيديو", variant="primary", size="lg")
|
| 327 |
-
|
| 328 |
with gr.Column(scale=1):
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
]
|
| 343 |
-
|
| 344 |
-
def wrapped_generate(*args):
|
| 345 |
-
enhance = args[-1]
|
| 346 |
-
# إذا كان enhance مفعلاً، قم بتعزيز في resize_image (مُفعَّل افتراضيًا)
|
| 347 |
-
return generate_video(*args[:-1])
|
| 348 |
-
|
| 349 |
-
generate_button.click(
|
| 350 |
-
fn=wrapped_generate,
|
| 351 |
-
inputs=ui_inputs,
|
| 352 |
-
outputs=[video_output, seed_output]
|
| 353 |
)
|
| 354 |
-
|
|
|
|
| 355 |
gr.Examples(
|
| 356 |
examples=[
|
| 357 |
-
[
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 358 |
],
|
| 359 |
-
inputs=
|
| 360 |
-
label="أمثلة سريعة"
|
| 361 |
)
|
| 362 |
|
| 363 |
if __name__ == "__main__":
|
| 364 |
-
demo.
|
|
|
|
| 1 |
import spaces
|
| 2 |
import torch
|
| 3 |
+
import os
|
| 4 |
+
import subprocess
|
| 5 |
import gradio as gr
|
| 6 |
+
import sys
|
| 7 |
+
# 🌟 إضافة هذا لإزالة تحذير tokenizers
|
| 8 |
+
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
| 9 |
+
|
| 10 |
+
# 🌟 تحقق من إصدار diffusers وتحديث إذا لزم الأمر (في بيئة Spaces، أضف diffusers>=0.33.0 إلى requirements.txt)
|
| 11 |
+
try:
|
| 12 |
+
import diffusers
|
| 13 |
+
if diffusers.__version__ < '0.33.0':
|
| 14 |
+
raise ImportError("diffusers version too old")
|
| 15 |
+
from diffusers import WanImageToVideoPipeline, WanTransformer3DModel, AutoencoderKLWan
|
| 16 |
+
from diffusers.utils import export_to_video, load_image
|
| 17 |
+
except ImportError as e:
|
| 18 |
+
print(f"Import error: {e}")
|
| 19 |
+
print("Please update diffusers: pip install diffusers>=0.33.0")
|
| 20 |
+
sys.exit(1)
|
| 21 |
+
|
| 22 |
import tempfile
|
| 23 |
import numpy as np
|
| 24 |
+
from PIL import Image
|
| 25 |
import random
|
| 26 |
import gc
|
| 27 |
from torchao.quantization import quantize_
|
| 28 |
from torchao.quantization import Float8DynamicActivationFloat8WeightConfig
|
| 29 |
from torchao.quantization import Int8WeightOnlyConfig
|
| 30 |
import aoti
|
| 31 |
+
# 🌟 استيراد moviepy لدمج الصوت الأساسي
|
| 32 |
+
import moviepy.editor as mp
|
| 33 |
+
from huggingface_hub import hf_hub_download # 🌟 لتنزيل الـ checkpoint من HF
|
| 34 |
+
|
| 35 |
+
# 🌟 إعداد Wav2Lip (تنزيل الـ repo والـ checkpoint عند التشغيل الأول)
|
| 36 |
+
WAV2LIP_DIR = "Wav2Lip"
|
| 37 |
+
CHECKPOINT_DIR = os.path.join(WAV2LIP_DIR, "checkpoints")
|
| 38 |
+
CHECKPOINT_PATH = os.path.join(CHECKPOINT_DIR, "wav2lip_gan.pth")
|
| 39 |
+
S3FD_PATH = os.path.join(WAV2LIP_DIR, "face_detection/detection/sfd/s3fd.pth")
|
| 40 |
+
|
| 41 |
+
if not os.path.exists(WAV2LIP_DIR):
|
| 42 |
+
print("Cloning Wav2Lip repo...")
|
| 43 |
+
subprocess.run(["git", "clone", "https://github.com/Rudrabha/Wav2Lip.git"], check=True)
|
| 44 |
+
os.makedirs(CHECKPOINT_DIR, exist_ok=True)
|
| 45 |
+
|
| 46 |
+
# 🌟 إعادة كتابة requirements.txt بالكامل للتوافق (فقط opencv-contrib-python، باقي تعليقات)
|
| 47 |
+
print("Patching Wav2Lip requirements to minimal compatible set...")
|
| 48 |
+
req_path = os.path.join(WAV2LIP_DIR, "requirements.txt")
|
| 49 |
+
with open(req_path, 'r') as f:
|
| 50 |
+
lines = f.readlines()
|
| 51 |
+
new_lines = []
|
| 52 |
+
for line in lines:
|
| 53 |
+
stripped = line.strip()
|
| 54 |
+
if 'opencv' in stripped.lower():
|
| 55 |
+
new_lines.append('opencv-contrib-python>=4.2.0.34\n')
|
| 56 |
+
else:
|
| 57 |
+
new_lines.append('# ' + stripped + '\n')
|
| 58 |
+
with open(req_path, 'w') as f:
|
| 59 |
+
f.writelines(new_lines)
|
| 60 |
+
|
| 61 |
+
# 🌟 تثبيت التبعيات الداخلية (فقط opencv-contrib-python الآن)
|
| 62 |
+
print("Installing minimal Wav2Lip requirements...")
|
| 63 |
+
subprocess.run(["pip", "install", "-r", req_path], check=True)
|
| 64 |
+
|
| 65 |
+
# 🌟 تنزيل الـ checkpoint من HF (repo موثوق مباشر)
|
| 66 |
+
print("Downloading Wav2Lip checkpoint...")
|
| 67 |
+
hf_hub_download(
|
| 68 |
+
repo_id="Nekochu/Wav2Lip",
|
| 69 |
+
filename="wav2lip_gan.pth",
|
| 70 |
+
local_dir=CHECKPOINT_DIR,
|
| 71 |
+
local_dir_use_symlinks=False
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
# 🌟 تنزيل نموذج الكشف عن الوجه (s3fd.pth)
|
| 75 |
+
print("Downloading face detection model...")
|
| 76 |
+
os.makedirs(os.path.dirname(S3FD_PATH), exist_ok=True)
|
| 77 |
+
if not os.path.exists(S3FD_PATH):
|
| 78 |
+
subprocess.run([
|
| 79 |
+
"wget", "https://www.adrianbulat.com/downloads/python-fan/s3fd-619a316812.pth",
|
| 80 |
+
"-O", S3FD_PATH
|
| 81 |
+
], check=True)
|
| 82 |
+
|
| 83 |
+
print("Wav2Lip setup completed successfully!")
|
| 84 |
|
| 85 |
+
# (بقية تعريفات الثوابت و MODELS كما هي)
|
| 86 |
MODEL_ID = "Wan-AI/Wan2.2-I2V-A14B-Diffusers"
|
| 87 |
MAX_DIM = 832
|
| 88 |
MIN_DIM = 480
|
| 89 |
SQUARE_DIM = 640
|
| 90 |
MULTIPLE_OF = 16
|
| 91 |
+
DIMENSION_PRESETS = {
|
| 92 |
+
"4K (16:9 - Scaled Down)": (832, 468),
|
| 93 |
+
"YouTube Full HD (16:9)": (832, 468),
|
| 94 |
+
"Instagram Square (1:1)": (640, 640),
|
| 95 |
+
"Instagram Reels / TikTok (9:16)": (468, 832),
|
| 96 |
+
"Instagram Portrait (4:5)": (512, 640),
|
| 97 |
+
"Custom (Default)": (640, 360),
|
| 98 |
+
}
|
| 99 |
+
INPUT_IMAGE_INSTRUCTIONS = {
|
| 100 |
+
"4K (16:9 - Scaled Down)": "For best results, use an input image with a 16:9 aspect ratio, such as 1920x1080 or 3840x2160 pixels. The image will be cropped automatically to maintain the ratio if different.",
|
| 101 |
+
"YouTube Full HD (16:9)": "For best results, use an input image with a 16:9 aspect ratio, such as 1920x1080 pixels. The image will be cropped automatically to maintain the ratio if different.",
|
| 102 |
+
"Instagram Square (1:1)": "For best results, use a square input image with a 1:1 aspect ratio, such as 1080x1080 pixels. The image will be cropped automatically to maintain the ratio if different.",
|
| 103 |
+
"Instagram Reels / TikTok (9:16)": "For best results, use a vertical input image with a 9:16 aspect ratio, such as 1080x1920 pixels. The image will be cropped automatically to maintain the ratio if different.",
|
| 104 |
+
"Instagram Portrait (4:5)": "For best results, use a vertical input image with a 4:5 aspect ratio, such as 1080x1350 pixels. The image will be cropped automatically to maintain the ratio if different.",
|
| 105 |
+
"Custom (Default)": "For best results, use a horizontal input image with a 16:9 aspect ratio, such as 1920x1080 pixels. The image will be cropped automatically to maintain the ratio if different.",
|
| 106 |
+
}
|
| 107 |
FIXED_FPS = 16
|
| 108 |
MIN_FRAMES_MODEL = 8
|
| 109 |
+
MAX_FRAMES_MODEL = 480
|
| 110 |
MIN_DURATION = round(MIN_FRAMES_MODEL / FIXED_FPS, 1)
|
| 111 |
MAX_DURATION = round(MAX_FRAMES_MODEL / FIXED_FPS, 1)
|
| 112 |
|
| 113 |
+
# Load the pipeline
|
| 114 |
pipe = WanImageToVideoPipeline.from_pretrained(
|
| 115 |
MODEL_ID,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
torch_dtype=torch.bfloat16,
|
| 117 |
).to('cuda')
|
| 118 |
+
pipe.enable_model_cpu_offload() # 🌟 تحسين: offload إلى CPU لتوفير 40% GPU memory
|
| 119 |
|
| 120 |
+
# Load LoRA with error handling for key mismatches
|
| 121 |
+
try:
|
| 122 |
+
pipe.load_lora_weights(
|
| 123 |
+
"Kijai/WanVideo_comfy",
|
| 124 |
+
weight_name="Lightx2v/lightx2v_I2V_14B_480p_cfg_step_distill_rank128_bf16.safetensors",
|
| 125 |
+
adapter_name="lightx2v",
|
| 126 |
+
low_cpu_mem_usage=True # Helps with memory during load
|
| 127 |
+
)
|
| 128 |
+
print("LoRA weights loaded successfully!")
|
| 129 |
+
except Exception as e:
|
| 130 |
+
print(f"Warning: LoRA load failed (possible key mismatch): {e}")
|
| 131 |
+
print("Proceeding without LoRA for now.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
|
| 133 |
+
gc.collect() # Free up memory after loads
|
| 134 |
+
torch.cuda.empty_cache()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
|
| 136 |
+
# 🌟 وظيفة لتحضير الصورة حسب الـ preset
|
| 137 |
+
def prepare_image(image, preset_key):
|
| 138 |
+
if image is None:
|
| 139 |
+
raise ValueError("No image provided!")
|
| 140 |
+
|
| 141 |
+
target_width, target_height = DIMENSION_PRESETS.get(preset_key, DIMENSION_PRESETS["Custom (Default)"])
|
| 142 |
+
|
| 143 |
+
# Resize and crop to target dimensions while maintaining aspect ratio
|
| 144 |
+
image = image.convert("RGB")
|
| 145 |
+
image.thumbnail((target_width, target_height), Image.Resampling.LANCZOS)
|
| 146 |
+
|
| 147 |
+
# Calculate padding or cropping
|
| 148 |
+
width, height = image.size
|
| 149 |
+
if width < target_width or height < target_height:
|
| 150 |
+
# Pad if smaller
|
| 151 |
+
padded = Image.new("RGB", (target_width, target_height), (0, 0, 0))
|
| 152 |
+
padded.paste(image, ((target_width - width) // 2, (target_height - height) // 2))
|
| 153 |
+
image = padded
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
else:
|
| 155 |
+
# Crop center if larger
|
| 156 |
+
left = (width - target_width) // 2
|
| 157 |
+
top = (height - target_height) // 2
|
| 158 |
+
image = image.crop((left, top, left + target_width, top + target_height))
|
| 159 |
+
|
| 160 |
+
# Ensure dimensions are multiples of MULTIPLE_OF
|
| 161 |
+
width, height = image.size
|
| 162 |
+
width = (width // MULTIPLE_OF) * MULTIPLE_OF
|
| 163 |
+
height = (height // MULTIPLE_OF) * MULTIPLE_OF
|
| 164 |
+
if width > MAX_DIM: width = MAX_DIM
|
| 165 |
+
if height > MAX_DIM: height = MAX_DIM
|
| 166 |
+
if width < MIN_DIM: width = MIN_DIM
|
| 167 |
+
if height < MIN_DIM: height = MIN_DIM
|
| 168 |
+
image = image.resize((width, height), Image.Resampling.LANCZOS)
|
| 169 |
+
|
| 170 |
+
return image
|
| 171 |
|
| 172 |
+
# 🌟 وظيفة لتوليد الفيديو من الصورة والـ prompt
|
| 173 |
+
@torch.no_grad()
|
| 174 |
+
def generate_video(image, prompt, negative_prompt, num_frames, preset_key, guidance_scale=7.5, num_inference_steps=50):
|
| 175 |
+
if image is None:
|
| 176 |
+
raise ValueError("No image provided!")
|
| 177 |
+
|
| 178 |
+
prepared_image = prepare_image(image, preset_key)
|
| 179 |
+
height, width = prepared_image.size[1], prepared_image.size[0]
|
| 180 |
+
|
| 181 |
+
# Clamp num_frames
|
| 182 |
+
num_frames = max(MIN_FRAMES_MODEL, min(num_frames, MAX_FRAMES_MODEL))
|
| 183 |
+
|
| 184 |
+
video_frames = pipe(
|
| 185 |
+
prompt=prompt,
|
| 186 |
+
image=prepared_image,
|
| 187 |
+
negative_prompt=negative_prompt,
|
| 188 |
+
num_frames=num_frames,
|
| 189 |
+
height=height,
|
| 190 |
+
width=width,
|
| 191 |
+
guidance_scale=guidance_scale,
|
| 192 |
+
num_inference_steps=num_inference_steps,
|
| 193 |
+
).frames[0]
|
| 194 |
+
|
| 195 |
+
# Export to temporary MP4
|
| 196 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 197 |
+
temp_video_path = os.path.join(tmpdirname, "temp_video.mp4")
|
| 198 |
+
export_to_video(video_frames, temp_video_path, fps=FIXED_FPS)
|
| 199 |
+
return temp_video_path
|
| 200 |
|
| 201 |
+
# 🌟 وظيفة Wav2Lip لمزامنة الشفاه مع الصوت
|
| 202 |
+
def wav2lip_sync(video_path, audio_path):
|
| 203 |
+
if not os.path.exists(video_path) or not os.path.exists(audio_path):
|
| 204 |
+
raise ValueError("Video or audio file not found!")
|
| 205 |
+
|
| 206 |
+
# Import Wav2Lip internals (assuming setup is done)
|
| 207 |
+
sys.path.append(WAV2LIP_DIR)
|
| 208 |
+
from Wav2Lip.inference_main import main as wav2lip_main
|
| 209 |
+
|
| 210 |
+
output_path = tempfile.mktemp(suffix=".mp4")
|
| 211 |
+
|
| 212 |
+
# Run Wav2Lip
|
| 213 |
+
args = [
|
| 214 |
+
"--checkpoint_path", CHECKPOINT_PATH,
|
| 215 |
+
"--face", video_path,
|
| 216 |
+
"--audio", audio_path,
|
| 217 |
+
"--outfile", output_path,
|
| 218 |
+
"--resize_factor", "1", # Keep original size
|
| 219 |
+
"--pads", "0 10 0 0", # Default padding
|
| 220 |
+
]
|
| 221 |
+
|
| 222 |
+
# Call the main function (simplified; adjust if needed)
|
| 223 |
+
wav2lip_main(args)
|
| 224 |
+
|
| 225 |
+
if os.path.exists(output_path):
|
| 226 |
+
return output_path
|
| 227 |
+
else:
|
| 228 |
+
raise RuntimeError("Wav2Lip processing failed!")
|
| 229 |
|
| 230 |
+
# 🌟 الوظيفة الرئيسية للتطبيق: توليد فيديو مع مزامنة الشفاه
|
| 231 |
+
def create_video_with_audio(image, prompt, negative_prompt, audio, num_frames, preset_key, enable_lip_sync=True):
|
| 232 |
+
try:
|
| 233 |
+
# Step 1: Generate video
|
| 234 |
+
print("Generating video...")
|
| 235 |
+
temp_video = generate_video(image, prompt, negative_prompt, num_frames, preset_key)
|
| 236 |
+
|
| 237 |
+
if enable_lip_sync and audio is not None:
|
| 238 |
+
# Step 2: Sync with audio using Wav2Lip
|
| 239 |
+
print("Syncing lips with audio...")
|
| 240 |
+
final_video = wav2lip_sync(temp_video, audio)
|
| 241 |
+
else:
|
| 242 |
+
final_video = temp_video
|
| 243 |
+
|
| 244 |
+
return final_video, "Success!"
|
| 245 |
+
except Exception as e:
|
| 246 |
+
return None, f"Error: {str(e)}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 247 |
|
| 248 |
+
# 🌟 إعداد الواجهة بـ Gradio
|
| 249 |
+
with gr.Blocks(title="Wan2.2 Image-to-Video with Lip Sync") as demo:
|
| 250 |
+
gr.Markdown("# 🌟 Wan2.2 I2V Generator with Wav2Lip Sync")
|
| 251 |
+
gr.Markdown("Upload an image, add a prompt, optional audio, and generate a talking video!")
|
| 252 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 253 |
with gr.Row():
|
| 254 |
with gr.Column(scale=1):
|
| 255 |
+
image_input = gr.Image(type="pil", label="Input Image")
|
| 256 |
+
prompt_input = gr.Textbox(label="Prompt", placeholder="A dynamic scene from the image...", lines=2)
|
| 257 |
+
negative_prompt_input = gr.Textbox(label="Negative Prompt", placeholder="blurry, low quality", lines=1)
|
| 258 |
+
audio_input = gr.Audio(sources=["upload", "microphone"], type="filepath", label="Audio (for lip sync)")
|
| 259 |
+
num_frames_slider = gr.Slider(MIN_FRAMES_MODEL, MAX_FRAMES_MODEL, value=64, step=8, label="Number of Frames")
|
| 260 |
+
preset_dropdown = gr.Dropdown(choices=list(DIMENSION_PRESETS.keys()), value="Custom (Default)", label="Output Preset")
|
| 261 |
+
lip_sync_checkbox = gr.Checkbox(label="Enable Lip Sync (requires audio)", value=True)
|
| 262 |
+
generate_btn = gr.Button("Generate Video", variant="primary")
|
| 263 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 264 |
with gr.Column(scale=1):
|
| 265 |
+
output_video = gr.Video(label="Generated Video")
|
| 266 |
+
status_output = gr.Textbox(label="Status", interactive=False)
|
| 267 |
+
|
| 268 |
+
# Event handlers
|
| 269 |
+
def update_instructions(preset):
|
| 270 |
+
return INPUT_IMAGE_INSTRUCTIONS.get(preset, INPUT_IMAGE_INSTRUCTIONS["Custom (Default)"])
|
| 271 |
+
|
| 272 |
+
preset_dropdown.change(update_instructions, preset_dropdown, gr.Markdown())
|
| 273 |
+
|
| 274 |
+
generate_btn.click(
|
| 275 |
+
fn=create_video_with_audio,
|
| 276 |
+
inputs=[image_input, prompt_input, negative_prompt_input, audio_input, num_frames_slider, preset_dropdown, lip_sync_checkbox],
|
| 277 |
+
outputs=[output_video, status_output]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 278 |
)
|
| 279 |
+
|
| 280 |
+
# Examples (optional)
|
| 281 |
gr.Examples(
|
| 282 |
examples=[
|
| 283 |
+
[
|
| 284 |
+
None, # No example image; user to upload
|
| 285 |
+
"The person in the image starts walking towards the camera with a smile.",
|
| 286 |
+
"static, blurry",
|
| 287 |
+
None,
|
| 288 |
+
32,
|
| 289 |
+
"YouTube Full HD (16:9)",
|
| 290 |
+
False
|
| 291 |
+
]
|
| 292 |
],
|
| 293 |
+
inputs=[image_input, prompt_input, negative_prompt_input, audio_input, num_frames_slider, preset_dropdown, lip_sync_checkbox]
|
|
|
|
| 294 |
)
|
| 295 |
|
| 296 |
if __name__ == "__main__":
|
| 297 |
+
demo.launch(share=True, debug=True)
|