""" Custom RunPod serverless handler for Wan 2.2 I2V with HF LoRA support. Based on wlsdml1114/generate_video handler, extended to download LoRA files from HuggingFace repos before running the ComfyUI workflow. Input: image_base64 / image_url / image_path — required input image end_image_base64 / end_image_url — optional end image (FLF2V) prompt — positive prompt negative_prompt — negative prompt (optional) seed — random seed cfg — guidance scale steps — inference steps width, height — resolution length — number of frames (default 81) fps — frames per second (default 16) lora_pairs — array of {repo_id, high_file, low_file, high_weight, low_weight} The handler downloads LoRA .safetensors files from HF to /ComfyUI/models/loras/ before submitting the ComfyUI workflow. """ import runpod import os import base64 import json import uuid import logging import urllib.request import urllib.parse import subprocess import time import websocket import binascii logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) server_address = os.getenv('SERVER_ADDRESS', '127.0.0.1') client_id = str(uuid.uuid4()) LORA_DIR = "/ComfyUI/models/loras" def save_data_if_base64(data_input, temp_dir, output_filename): if not isinstance(data_input, str): return data_input try: decoded_data = base64.b64decode(data_input) os.makedirs(temp_dir, exist_ok=True) file_path = os.path.abspath(os.path.join(temp_dir, output_filename)) with open(file_path, 'wb') as f: f.write(decoded_data) return file_path except (binascii.Error, ValueError): return data_input def download_file_from_url(url, output_path): try: result = subprocess.run( ['wget', '-O', output_path, '--no-verbose', url], capture_output=True, text=True ) if result.returncode == 0: return output_path raise Exception(f"wget failed: {result.stderr}") except Exception as e: raise Exception(f"Download failed: {e}") def process_input(input_data, temp_dir, output_filename, input_type): if input_type == "path": return input_data elif input_type == "url": os.makedirs(temp_dir, exist_ok=True) file_path = os.path.abspath(os.path.join(temp_dir, output_filename)) return download_file_from_url(input_data, file_path) elif input_type == "base64": return save_data_if_base64(input_data, temp_dir, output_filename) else: raise Exception(f"Unsupported input type: {input_type}") def download_lora_from_hf(repo_id, filename, token=None): """Download a LoRA file from HuggingFace to /ComfyUI/models/loras/""" os.makedirs(LORA_DIR, exist_ok=True) local_name = f"{repo_id.replace('/', '__')}__{filename}" local_path = os.path.join(LORA_DIR, local_name) if os.path.exists(local_path) and os.path.getsize(local_path) > 0: logger.info(f"LoRA already cached: {local_path}") return local_name # Return just filename for ComfyUI # Download via HF resolve URL url = f"https://huggingface.co/{repo_id}/resolve/main/{urllib.parse.quote(filename)}" if token: url += f"?token={token}" logger.info(f"Downloading LoRA: {repo_id}/{filename} -> {local_path}") try: result = subprocess.run( ['wget', '-q', '-O', local_path, url], capture_output=True, text=True, timeout=300 ) if result.returncode != 0 or os.path.getsize(local_path) == 0: # Try with token header if token: result = subprocess.run( ['wget', '-q', '-O', local_path, '--header', f'Authorization: Bearer {token}', url], capture_output=True, text=True, timeout=300 ) if result.returncode != 0 or os.path.getsize(local_path) == 0: raise Exception(f"Failed to download LoRA: {repo_id}/{filename}") logger.info(f"LoRA downloaded: {local_path} ({os.path.getsize(local_path)} bytes)") return local_name except Exception as e: logger.error(f"LoRA download failed: {e}") raise def to_nearest_multiple_of_16(n): return ((n + 15) // 16) * 16 def queue_prompt(prompt): url = f"http://{server_address}:8188/prompt" p = {"prompt": prompt, "client_id": client_id} data = json.dumps(p).encode('utf-8') req = urllib.request.Request(url, data=data) return json.loads(urllib.request.urlopen(req).read()) def get_history(prompt_id): url = f"http://{server_address}:8188/history/{prompt_id}" with urllib.request.urlopen(url) as response: return json.loads(response.read()) def get_videos(ws, prompt): prompt_id = queue_prompt(prompt)['prompt_id'] output_videos = {} while True: out = ws.recv() if isinstance(out, str): message = json.loads(out) if message['type'] == 'executing': data = message['data'] if data['node'] is None and data['prompt_id'] == prompt_id: break else: continue history = get_history(prompt_id)[prompt_id] for node_id in history['outputs']: node_output = history['outputs'][node_id] videos_output = [] if 'gifs' in node_output: for video in node_output['gifs']: with open(video['fullpath'], 'rb') as f: video_data = base64.b64encode(f.read()).decode('utf-8') videos_output.append(video_data) output_videos[node_id] = videos_output return output_videos def load_workflow(workflow_path): with open(workflow_path, 'r') as file: return json.load(file) def handler(job): job_input = job.get("input", {}) logger.info(f"Received job input keys: {list(job_input.keys())}") task_id = f"task_{uuid.uuid4()}" # Image input image_path = None if "image_path" in job_input: image_path = process_input(job_input["image_path"], task_id, "input_image.jpg", "path") elif "image_url" in job_input: image_path = process_input(job_input["image_url"], task_id, "input_image.jpg", "url") elif "image_base64" in job_input: image_path = process_input(job_input["image_base64"], task_id, "input_image.jpg", "base64") if image_path is None: raise Exception("Image input is required. Provide image_path, image_url, or image_base64") # End image input (optional, for FLF2V) end_image_path_local = None if "end_image_path" in job_input: end_image_path_local = process_input(job_input["end_image_path"], task_id, "end_image.jpg", "path") elif "end_image_url" in job_input: end_image_path_local = process_input(job_input["end_image_url"], task_id, "end_image.jpg", "url") elif "end_image_base64" in job_input: end_image_path_local = process_input(job_input["end_image_base64"], task_id, "end_image.jpg", "base64") # LoRA processing — download from HF if needed lora_pairs = job_input.get("lora_pairs", []) hf_token = job_input.get("hf_token") or os.environ.get("HF_TOKEN", "") processed_lora_pairs = [] for pair in lora_pairs[:4]: # Max 4 LoRA pairs repo_id = pair.get("repo_id") high_file = pair.get("high_file") or pair.get("high") low_file = pair.get("low_file") or pair.get("low") high_weight = pair.get("high_weight", 1.0) low_weight = pair.get("low_weight", 1.0) high_local = None low_local = None if high_file: if repo_id: high_local = download_lora_from_hf(repo_id, high_file, hf_token) else: high_local = high_file # Already a local path if low_file: if repo_id: low_local = download_lora_from_hf(repo_id, low_file, hf_token) else: low_local = low_file processed_lora_pairs.append({ "high": high_local, "low": low_local, "high_weight": high_weight, "low_weight": low_weight, }) lora_count = len(processed_lora_pairs) # Select workflow workflow_file = "/new_Wan22_flf2v_api.json" if end_image_path_local else "/new_Wan22_api.json" logger.info(f"Using {'FLF2V' if end_image_path_local else 'single'} workflow with {lora_count} LoRA pairs") prompt = load_workflow(workflow_file) length = job_input.get("length", 81) steps = job_input.get("steps", 10) prompt["244"]["inputs"]["image"] = image_path prompt["541"]["inputs"]["num_frames"] = length prompt["135"]["inputs"]["positive_prompt"] = job_input["prompt"] prompt["135"]["inputs"]["negative_prompt"] = job_input.get("negative_prompt", "") prompt["220"]["inputs"]["seed"] = job_input["seed"] prompt["540"]["inputs"]["seed"] = job_input["seed"] prompt["540"]["inputs"]["cfg"] = job_input["cfg"] # Resolution adjusted_width = to_nearest_multiple_of_16(job_input["width"]) adjusted_height = to_nearest_multiple_of_16(job_input["height"]) prompt["235"]["inputs"]["value"] = adjusted_width prompt["236"]["inputs"]["value"] = adjusted_height prompt["498"]["inputs"]["context_overlap"] = job_input.get("context_overlap", 48) prompt["498"]["inputs"]["context_frames"] = length # Steps if "834" in prompt: prompt["834"]["inputs"]["steps"] = steps lowsteps = int(steps * 0.6) prompt["829"]["inputs"]["step"] = lowsteps # End image if end_image_path_local: prompt["617"]["inputs"]["image"] = end_image_path_local # LoRA application if lora_count > 0: high_lora_node_id = "279" low_lora_node_id = "553" for i, lora_pair in enumerate(processed_lora_pairs): if i < 4: lora_high = lora_pair.get("high") lora_low = lora_pair.get("low") lora_high_weight = lora_pair.get("high_weight", 1.0) lora_low_weight = lora_pair.get("low_weight", 1.0) if lora_high: prompt[high_lora_node_id]["inputs"][f"lora_{i+1}"] = lora_high prompt[high_lora_node_id]["inputs"][f"strength_{i+1}"] = lora_high_weight logger.info(f"LoRA {i+1} HIGH: {lora_high} weight={lora_high_weight}") if lora_low: prompt[low_lora_node_id]["inputs"][f"lora_{i+1}"] = lora_low prompt[low_lora_node_id]["inputs"][f"strength_{i+1}"] = lora_low_weight logger.info(f"LoRA {i+1} LOW: {lora_low} weight={lora_low_weight}") # Connect to ComfyUI ws_url = f"ws://{server_address}:8188/ws?clientId={client_id}" logger.info(f"Connecting to WebSocket: {ws_url}") http_url = f"http://{server_address}:8188/" max_http_attempts = 180 for http_attempt in range(max_http_attempts): try: response = urllib.request.urlopen(http_url, timeout=5) logger.info(f"HTTP connected (attempt {http_attempt+1})") break except Exception as e: logger.warning(f"HTTP failed (attempt {http_attempt+1}/{max_http_attempts}): {e}") if http_attempt == max_http_attempts - 1: raise Exception("Cannot connect to ComfyUI server") time.sleep(1) ws = websocket.WebSocket() max_attempts = int(180 / 5) for attempt in range(max_attempts): try: ws.connect(ws_url) logger.info("WebSocket connected") break except Exception as e: logger.warning(f"WebSocket failed (attempt {attempt+1}): {e}") if attempt == max_attempts - 1: raise Exception("Cannot connect to ComfyUI WebSocket") time.sleep(5) try: output_videos = get_videos(ws, prompt) ws.close() except Exception as e: ws.close() raise e # Extract video result_video = None for node_id, videos in output_videos.items(): if videos: result_video = videos[0] break if not result_video: raise Exception("No video output from ComfyUI") return {"video": result_video} runpod.serverless.start({"handler": handler})