import os import subprocess import tempfile os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True") # IMPORTANT: `spaces` must be imported before `torch` and any library that imports `torch`. try: import spaces IS_ZERO = True except ImportError: IS_ZERO = False class _NoSpaces: @staticmethod def GPU(*a, **k): if a and callable(a[0]): return a[0] return lambda f: f spaces = _NoSpaces() # type: ignore import cv2 import gradio as gr import numpy as np import torch from diffusers import AutoencoderKLWan, WanAnimatePipeline from diffusers.utils import export_to_video from huggingface_hub import hf_hub_download from peft import LoraConfig, set_peft_model_state_dict from PIL import Image from safetensors.torch import load_file from ultralytics import YOLO MODEL_ID = os.getenv("WAN_ANIMATE_MODEL", "Wan-AI/Wan2.2-Animate-14B-Diffusers") # Rəsmi relighting LoRA ayrıca repoda saxlanılır (replace rejimi üçün işıq/rəng uyğunlaşdırması) RELIGHT_REPO = "Wan-AI/Wan2.2-Animate-14B" RELIGHT_FILE = "relighting_lora/adapter_model.safetensors" SKELETON_EDGES = [ (0, 1, (255, 0, 85)), (0, 2, (255, 0, 170)), (1, 3, (255, 0, 255)), (2, 4, (170, 0, 255)), (5, 6, (255, 85, 0)), (5, 7, (255, 170, 0)), (7, 9, (255, 255, 0)), (6, 8, (170, 255, 0)), (8, 10, (85, 255, 0)), (5, 11, (0, 255, 85)), (6, 12, (0, 255, 170)), (11, 12, (0, 255, 255)), (11, 13, (0, 170, 255)), (13, 15, (0, 85, 255)), (12, 14, (0, 0, 255)), (14, 16, (85, 0, 255)), ] DEFAULT_PROMPT = ( "The person from the reference image performing the exact same actions in the video, " "seamlessly integrated into the scene with matching lighting and color tone, photorealistic, high quality" ) DEFAULT_NEGATIVE = ( "blurry, low quality, distorted, deformed, disfigured, extra limbs, extra fingers, " "inconsistent lighting, floating, watermark, text, worst quality, jpeg artifacts" ) def _is_720p(resolution) -> bool: """Gradio Radio etiketi '720p (tövsiyə)' kimi gəlir — startswith ilə yoxla.""" return str(resolution).lower().startswith("720") vae = AutoencoderKLWan.from_pretrained(MODEL_ID, subfolder="vae", torch_dtype=torch.float32) pipe = WanAnimatePipeline.from_pretrained(MODEL_ID, vae=vae, torch_dtype=torch.bfloat16) pipe.to("cuda") try: pipe.vae.enable_tiling() except Exception: pass seg_model = YOLO("yolov8n-seg.pt") pose_model = YOLO("yolov8n-pose.pt") # --------------------------------------------------------------------------- # Relighting LoRA — rəsmi fayl xam PEFT formatındadır (base_model.model.* açarları). # Diffusers-ün pipeline-level load_lora_weights() onu tanımır — PEFT ilə birbaşa # transformer-ə inject edirik (Wan-ın öz kodundakı add_adapter/set_peft_model_state_dict # sxeminə uyğun). Uğursuz olsa app relightingsiz işləməyə davam edir. # --------------------------------------------------------------------------- _RELIGHT = {"ok": False, "sd": None, "targets": None, "scale": None, "component": None} def _relight_parent(key: str) -> str: """PEFT/diffusers önəklərini təmizləyib hədəf modul yolunu qaytarır.""" parent = key.split(".lora_A.")[0] for prefix in ("text_encoder.", "transformer.", "state_dict."): if parent.startswith(prefix): parent = parent[len(prefix):] if "base_model.model." in parent: parent = parent.split("base_model.model.")[-1] return parent def _apply_relighting(scale: float): """LoRA-nı verilmiş güclə (yenidən) tətbiq edir. scale=0 → effektiv sönük.""" if not _RELIGHT["ok"]: return scale = float(scale) if _RELIGHT["scale"] == scale: return component = _RELIGHT["component"] cfg = LoraConfig( r=128, lora_alpha=128, lora_dropout=0.0, bias="none", target_modules=_RELIGHT["targets"], ) if _RELIGHT["scale"] is not None: component.delete_adapters(["default"]) component.add_adapter(cfg) scaled = {k: v * scale for k, v in _RELIGHT["sd"].items()} out = set_peft_model_state_dict(component, scaled, adapter_name="default") load_result = out[0] if isinstance(out, tuple) else out unexpected = list(getattr(load_result, "unexpected_keys", []) or []) if len(unexpected) > max(10, int(0.2 * len(scaled))): component.delete_adapters(["default"]) raise RuntimeError( f"relighting LoRA: {len(unexpected)}/{len(scaled)} açar modele uyğun gəlmədi" ) component.set_adapter("default") _RELIGHT["scale"] = scale def _prepare_relighting(): try: path = hf_hub_download(RELIGHT_REPO, RELIGHT_FILE) sd = load_file(path) if not sd: raise RuntimeError("boş state dict") te_only = all(k.startswith("text_encoder.") for k in sd) component = pipe.text_encoder if te_only else pipe.transformer targets = set() for k in sd: if ".lora_A." in k: parent = _relight_parent(k) if parent: targets.add(parent.split(".")[-1]) if not targets: raise RuntimeError("heç bir .lora_A. açarı tapılmadı — tanınmayan format") _RELIGHT.update(ok=True, sd=sd, targets=sorted(targets), component=component) _apply_relighting(1.0) print(f"[relighting] OK: {len(sd)} tensor, {len(targets)} target modul " f"({'text_encoder' if te_only else 'transformer'})") except Exception as e: _RELIGHT.update(ok=False, sd=None, targets=None, scale=None) print(f"[relighting] YÜKLƏNMƏDİ — relightsiz davam olunur: {e}") _prepare_relighting() def _snap_frames(n: int) -> int: """Snap to valid Wan frame count (4k + 1), capped at 77 frames (~4.8s).""" n = max(17, min(77, int(n))) return ((n - 1) // 4) * 4 + 1 def _target_size(src_w: int, src_h: int, resolution: str) -> tuple[int, int]: """720p (tövsiyə) və ya 480p (sürətli/ZeroGPU yaddaşı üçün), 16-ya bölünən.""" is_720 = _is_720p(resolution) base = 1280 if is_720 else 832 short_side = 720 if is_720 else 480 if src_w > src_h * 1.15: return base, short_side if src_h > src_w * 1.15: return short_side, base side = 960 if is_720 else 640 return side, side def _match_aspect(ref: Image.Image, width: int, height: int) -> Image.Image: """Pipeline reference şəkli 'fill' ilə hədəf ölçüyə sıxır; fərq böyüksə mərkəz kəsim.""" w, h = ref.size target = width / height cur = w / h if abs(cur - target) < 0.02: return ref if cur > target: nw = max(16, int(round(h * target)) // 16 * 16) x = (w - nw) // 2 return ref.crop((x, 0, x + nw, h)) nh = max(16, int(round(w / target)) // 16 * 16) y = (h - nh) // 2 return ref.crop((0, y, w, y + nh)) def _read_video_frames(video_path: str, max_frames: int) -> tuple[list[np.ndarray], float]: cap = cv2.VideoCapture(video_path) if not cap.isOpened(): raise gr.Error("Videonu oxumaq mümkün olmadı.") fps = cap.get(cv2.CAP_PROP_FPS) or 16.0 if not (fps == fps) or fps <= 0: # NaN/0 qorunması fps = 16.0 raw = [] while len(raw) < max_frames: ok, frame = cap.read() if not ok: break raw.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)) cap.release() if len(raw) < 17: raise gr.Error(f"Video çox qısadır ({len(raw)} kadr). Ən azı 17 kadr (~1 saniyə) olmalıdır.") snapped = _snap_frames(len(raw)) return raw[:snapped], float(fps) class _PersonTracker: """Videodakı EYNİ insanı kadr-boyu izləyir.""" def __init__(self): self.prev_center: tuple[float, float] | None = None def select(self, boxes: np.ndarray) -> int | None: if boxes is None or len(boxes) == 0: return None boxes = np.asarray(boxes, dtype=np.float32) if self.prev_center is None: areas = (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1]) idx = int(np.argmax(areas)) else: centers = np.stack([(boxes[:, 0] + boxes[:, 2]) / 2, (boxes[:, 1] + boxes[:, 3]) / 2], axis=1) d = np.linalg.norm(centers - np.asarray(self.prev_center), axis=1) idx = int(np.argmin(d)) self.prev_center = ( float((boxes[idx, 0] + boxes[idx, 2]) / 2), float((boxes[idx, 1] + boxes[idx, 3]) / 2), ) return idx def _draw_pose_black(width, height, kpts_xy, kpts_conf, person_idx): canvas = np.zeros((height, width, 3), dtype=np.uint8) if kpts_xy is None or kpts_conf is None or person_idx is None or person_idx >= kpts_xy.shape[0]: return canvas pts = kpts_xy[person_idx] confs = kpts_conf[person_idx] thick = max(3, width // 210) for i, j, color in SKELETON_EDGES: if confs[i] > 0.3 and confs[j] > 0.3: p1 = (int(round(pts[i, 0])), int(round(pts[i, 1]))) p2 = (int(round(pts[j, 0])), int(round(pts[j, 1]))) cv2.line(canvas, p1, p2, color[::-1], thickness=thick, lineType=cv2.LINE_AA) for k in range(pts.shape[0]): if confs[k] > 0.3: cx, cy = int(round(pts[k, 0])), int(round(pts[k, 1])) cv2.circle(canvas, (cx, cy), max(3, width // 256), (255, 255, 255), -1, cv2.LINE_AA) return canvas _FACE_STATE: dict = {} def _face_crop(frame_rgb, kpts_xy, kpts_conf, person_idx, out_size=256): h, w = frame_rgb.shape[:2] box = None if kpts_xy is not None and kpts_conf is not None and person_idx is not None and person_idx < kpts_xy.shape[0]: pts = kpts_xy[person_idx][:5] confs = kpts_conf[person_idx][:5] valid = pts[confs > 0.3] if len(valid) >= 2: x_min, y_min = valid.min(axis=0) x_max, y_max = valid.max(axis=0) cx = float((x_min + x_max) / 2) cy = float((y_min + y_max) / 2 + (y_max - y_min) * 0.35) size = float(max(x_max - x_min, y_max - y_min) * 2.6) box = (cx, cy, size) if box is None: box = _FACE_STATE.get("last") or (w / 2, h / 4, min(w, h) / 3) if _FACE_STATE.get("smooth") is None: _FACE_STATE["smooth"] = box else: a = 0.35 _FACE_STATE["smooth"] = tuple(a * b + (1 - a) * s for b, s in zip(box, _FACE_STATE["smooth"])) _FACE_STATE["last"] = box cx, cy, size = _FACE_STATE["smooth"] half = float(np.clip(size / 2.0, 48, min(w, h) / 2)) x1 = int(np.clip(cx - half, 0, w - 8)) y1 = int(np.clip(cy - half, 0, h - 8)) x2 = int(np.clip(cx + half, x1 + 8, w)) y2 = int(np.clip(cy + half, y1 + 8, h)) crop = frame_rgb[y1:y2, x1:x2] if crop.size == 0: crop = frame_rgb return cv2.resize(crop, (out_size, out_size), interpolation=cv2.INTER_LINEAR) def _prepare_animate_inputs(frames_rgb, width, height, dilation_px): """background_video, mask_video, pose_video, face_video — mode='replace' üçün.""" bg_pils, mask_pils, pose_pils, face_pils = [], [], [], [] tracker = _PersonTracker() _FACE_STATE.clear() res_scale = max(width, height) / 832.0 d = int(round(dilation_px * res_scale)) kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (d * 2 + 1, d * 2 + 1)) if d > 0 else None detected_any = False for frame in frames_rgb: resized = cv2.resize(frame, (width, height), interpolation=cv2.INTER_AREA) bg_pils.append(Image.fromarray(resized)) pose_res = pose_model.predict(resized, conf=0.25, verbose=False) kpts_xy = kpts_conf = None boxes = None if pose_res and pose_res[0].keypoints is not None and pose_res[0].keypoints.xy is not None: kpts_xy = pose_res[0].keypoints.xy.cpu().numpy() kpts_conf = ( pose_res[0].keypoints.conf.cpu().numpy() if pose_res[0].keypoints.conf is not None else np.ones(kpts_xy.shape[:2], dtype=np.float32) ) if pose_res[0].boxes is not None and len(pose_res[0].boxes) == len(kpts_xy): boxes = pose_res[0].boxes.xyxy.cpu().numpy() person_idx = tracker.select(boxes) seg_res = seg_model.predict(resized, classes=[0], conf=0.25, verbose=False) mask = np.zeros((height, width), dtype=np.uint8) if seg_res and seg_res[0].masks is not None: best, best_d = None, None pc = tracker.prev_center for m in seg_res[0].masks.data: m_np = (m.cpu().numpy() > 0.5).astype(np.uint8) * 255 m_resized = cv2.resize(m_np, (width, height), interpolation=cv2.INTER_NEAREST) if pc is not None and m_resized.max() > 0: ys, xs = np.where(m_resized > 127) c = (float(xs.mean()), float(ys.mean())) dist = (c[0] - pc[0]) ** 2 + (c[1] - pc[1]) ** 2 if best_d is None or dist < best_d: best, best_d = m_resized, dist elif best is None: best = m_resized if best is not None: mask = best detected_any = True if mask.max() == 0 and boxes is not None and person_idx is not None: x1, y1, x2, y2 = boxes[person_idx].astype(int) pad = int(12 * res_scale) mask = np.zeros((height, width), dtype=np.uint8) cv2.rectangle( mask, (max(0, x1 - pad), max(0, y1 - pad)), (min(width, x2 + pad), min(height, y2 + pad)), 255, -1, ) detected_any = True if kernel is not None and mask.max() > 0: mask = cv2.dilate(mask, kernel, iterations=1) mask_pils.append(Image.fromarray(mask, mode="L")) pose_pils.append(Image.fromarray(_draw_pose_black(width, height, kpts_xy, kpts_conf, person_idx))) face_pils.append(Image.fromarray(_face_crop(resized, kpts_xy, kpts_conf, person_idx))) if not detected_any: raise gr.Error("Videoda heç bir insan (person) aşkarlanmadı. Başqa video sınayın.") return bg_pils, mask_pils, pose_pils, face_pils def _mux_audio(src_video, gen_video, out_video): cmd = [ "ffmpeg", "-y", "-i", gen_video, "-i", src_video, "-c:v", "copy", "-map", "0:v:0", "-map", "1:a:0?", "-shortest", out_video, ] proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) return out_video if proc.returncode == 0 and os.path.isfile(out_video) else gen_video def _gpu_duration(source_video, ref_image, prompt, negative_prompt, resolution, max_frames, steps, guidance_scale, *args, **kwargs): res_factor = 2.2 if _is_720p(resolution) else 1.0 cfg_factor = 1.9 if float(guidance_scale) > 1 else 1.0 est = int((45 + float(steps) * 6.5) * res_factor * cfg_factor) return max(120, min(280, est)) @spaces.GPU(duration=_gpu_duration, size="xlarge") def replace_character( source_video, ref_image, prompt, negative_prompt, resolution, max_frames, steps, guidance_scale, mask_dilation, relight_strength, seed, keep_audio, progress=gr.Progress(track_tqdm=True), ): if not source_video: raise gr.Error("Zəhmət olmasa orijinal videonu yükləyin.") if ref_image is None: raise gr.Error("Zəhmət olmasa yeni personajın şəklini yükləyin.") progress(0.05, desc="Video oxunur, pose, üz və maska çıxarılır...") frames_rgb, src_fps = _read_video_frames(source_video, int(max_frames)) src_h, src_w = frames_rgb[0].shape[:2] width, height = _target_size(src_w, src_h, resolution) num_frames = len(frames_rgb) bg_pils, mask_pils, pose_pils, face_pils = _prepare_animate_inputs(frames_rgb, width, height, int(mask_dilation)) ref_pil = _match_aspect(ref_image.convert("RGB"), width, height) effective_prompt = (prompt or DEFAULT_PROMPT).strip() effective_neg = (negative_prompt or DEFAULT_NEGATIVE).strip() # Relighting LoRA gücü (slayderdən) — PEFT adapteri ilə _apply_relighting(relight_strength) progress(0.25, desc=f"Wan2.2-Animate-14B karakteri dəyişir ({int(steps)} addım)...") generator = torch.Generator(device="cuda").manual_seed(int(seed)) try: output_frames = pipe( image=ref_pil, pose_video=pose_pils, face_video=face_pils, background_video=bg_pils, mask_video=mask_pils, mode="replace", prompt=effective_prompt, negative_prompt=effective_neg, height=height, width=width, segment_frame_length=num_frames, prev_segment_conditioning_frames=1, num_inference_steps=int(steps), guidance_scale=float(guidance_scale), generator=generator, ).frames[0] finally: torch.cuda.empty_cache() progress(0.92, desc="Video yaddaşa yazılır...") raw_out = tempfile.NamedTemporaryFile(suffix="_wan_animate.mp4", delete=False).name out_fps = max(12, min(30, round(src_fps))) export_to_video(output_frames, raw_out, fps=out_fps) if keep_audio: muxed_out = tempfile.NamedTemporaryFile(suffix="_wan_animate_audio.mp4", delete=False).name return _mux_audio(source_video, raw_out, muxed_out) return raw_out with gr.Blocks(title="Wan2.2-Animate-14B · Character Swap") as demo: gr.Markdown( "# Wan2.2-Animate-14B · Realistik Karakter Swap\n" "Yeni: **rəsmi relighting LoRA** (PEFT ilə düzgün yüklənmə), stabil üz kropu, " "negative prompt (CFG) və 720p dəstəyi." ) with gr.Row(): with gr.Column(scale=1): source_video = gr.Video(label="Orijinal video (maks ~5 san / 77 kadr)") ref_image = gr.Image(label="Yeni personaj (aydın, düz baxan üz/bədən şəkli)", type="pil") prompt = gr.Textbox(label="Prompt", value=DEFAULT_PROMPT, lines=2) negative_prompt = gr.Textbox(label="Negative prompt (CFG > 1 olanda işləyir)", value=DEFAULT_NEGATIVE, lines=2) run_btn = gr.Button("Karakteri Dəyiş (Wan2.2-Animate)", variant="primary", size="lg") with gr.Accordion("Əlavə parametrlər", open=False): resolution = gr.Radio(label="Görüntü ölçüsü", choices=["720p (tövsiyə)", "480p (sürətli)"], value="720p (tövsiyə)") max_frames = gr.Slider(label="Maksimum kadr sayı (4k+1)", minimum=17, maximum=77, step=4, value=49) steps = gr.Slider(label="Inference steps", minimum=10, maximum=40, step=1, value=25) guidance_scale = gr.Slider( label="Guidance scale (oxşarlıq üçün 3.5–5.0; sürət üçün 1.0)", minimum=1.0, maximum=7.0, step=0.5, value=3.5, ) mask_dilation = gr.Slider(label="Maska genişlənməsi (px, 480p ölçüsündə)", minimum=0, maximum=40, step=2, value=18) relight_strength = gr.Slider(label="Relighting LoRA gücü", minimum=0.0, maximum=1.5, step=0.1, value=1.0) seed = gr.Number(label="Seed", value=42, precision=0) keep_audio = gr.Checkbox(label="Orijinal səsi saxla", value=True) with gr.Column(scale=1): result_video = gr.Video(label="Nəticə", autoplay=True) run_btn.click( replace_character, inputs=[ source_video, ref_image, prompt, negative_prompt, resolution, max_frames, steps, guidance_scale, mask_dilation, relight_strength, seed, keep_audio, ], outputs=[result_video], ) if __name__ == "__main__": demo.queue(max_size=10).launch(server_name="0.0.0.0", server_port=7860, show_error=True)