diff --git "a/app.py" "b/app.py" --- "a/app.py" +++ "b/app.py" @@ -1,29 +1,11 @@ -# ============================================================ -# CPU MULTI FACE SWAP PRO -# ComfyUI 0.3.67 + ReActor 0.6.1-b2 -# CPU ONLY -# Multi Source Face -# Multi Target Face -# Multi Face Mapping -# GIF -# Batch -# Preview -# Auto Mapping -# Mapping Preset -# Output -> Target -# GPEN fallback -# Progress -# ============================================================ - import os # ============================================================ -# FORCE CPU - MUST BE BEFORE TORCH / ONNX +# CPU / RUNTIME ENVIRONMENT # ============================================================ os.environ["CUDA_VISIBLE_DEVICES"] = "" os.environ["ORT_DISABLE_CUDA"] = "1" -os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "" # ============================================================ @@ -31,24 +13,23 @@ os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "" # ============================================================ import sys +import asyncio import gc import json -import uuid import time -import asyncio import tempfile import importlib -from pathlib import Path +import threading from collections import OrderedDict # ============================================================ # THIRD PARTY # ============================================================ -import cv2 import numpy as np -import imageio.v2 as imageio +import cv2 import gradio as gr +import imageio from PIL import Image from huggingface_hub import hf_hub_download @@ -58,7 +39,7 @@ from huggingface_hub import hf_hub_download # CONFIG # ============================================================ -APP_TITLE = "CPU Multi Face Swap PRO" +APP_TITLE = "CPU Multi Face Swap Pro" BASE_DIR = os.path.abspath( os.path.dirname(__file__) @@ -89,11 +70,6 @@ OUTPUT_DIR = os.path.join( "output" ) -PRESET_DIR = os.path.join( - BASE_DIR, - "presets" -) - COMFYUI_ROOT = BASE_DIR REACTOR_PATH = os.path.join( @@ -102,6 +78,15 @@ REACTOR_PATH = os.path.join( "comfyui-reactor-node" ) +if not os.path.isdir(REACTOR_PATH): + + REACTOR_PATH = os.path.join( + BASE_DIR, + "custom_nodes", + "comfyui-reactor-node" + ) + + DEFAULT_SWAP_MODEL = ( "inswapper_128.onnx" ) @@ -110,56 +95,49 @@ DEFAULT_RESTORE_MODEL = ( "GPEN-BFR-512.onnx" ) -DEFAULT_DET_SIZE = 640 +DEFAULT_RESTORE_STRENGTH = 0.70 -FACE_CACHE_MAX = 64 +# ============================================================ +# 16 GB RAM / 2 JOB CONFIG +# ============================================================ -MAX_OUTPUT_HISTORY = 100 +MAX_CONCURRENT_JOBS = 2 -SUPPORTED_IMAGES = [ - ".jpg", - ".jpeg", - ".png", - ".webp", -] +MAX_CONCURRENT_INFERENCE = 2 -SUPPORTED_TARGETS = [ - ".jpg", - ".jpeg", - ".png", - ".webp", - ".gif", -] +MAX_PREVIEW_JOBS = 2 -os.makedirs( - MODEL_DIR, - exist_ok=True -) +GRADIO_QUEUE_SIZE = 8 -os.makedirs( - OUTPUT_DIR, - exist_ok=True -) +# ============================================================ +# GLOBAL LOCKS +# ============================================================ -os.makedirs( - INSIGHTFACE_DIR, - exist_ok=True +JOB_SEMAPHORE = threading.BoundedSemaphore( + MAX_CONCURRENT_JOBS ) -os.makedirs( - HYPERSWAP_DIR, - exist_ok=True +INFERENCE_SEMAPHORE = threading.BoundedSemaphore( + MAX_CONCURRENT_INFERENCE ) -os.makedirs( - FACE_RESTORE_DIR, - exist_ok=True -) +MODEL_LOCK = threading.RLock() -os.makedirs( - PRESET_DIR, - exist_ok=True -) +COMFY_INIT_LOCK = threading.RLock() + +# ============================================================ +# GLOBAL STATE +# ============================================================ + +loaded_models = {} + +face_cache = OrderedDict() + +FACE_CACHE_MAX = 64 + +source_tensor_cache = OrderedDict() + +SOURCE_TENSOR_CACHE_MAX = 16 # ============================================================ @@ -167,19 +145,65 @@ os.makedirs( # ============================================================ def log(*args): + print( *args, flush=True ) +# ============================================================ +# STARTUP INFO +# ============================================================ + log("=" * 70) -log("[APP] BASE DIR:", BASE_DIR) -log("[APP] MODEL DIR:", MODEL_DIR) -log("[APP] OUTPUT DIR:", OUTPUT_DIR) + +log( + "[APP] BASE DIR:", + BASE_DIR +) + +log( + "[APP] MODEL DIR:", + MODEL_DIR +) + +log( + "[APP] OUTPUT DIR:", + OUTPUT_DIR +) + +log( + "[APP] MAX JOBS:", + MAX_CONCURRENT_JOBS +) + +log( + "[APP] MAX INFERENCE:", + MAX_CONCURRENT_INFERENCE +) + log("=" * 70) +# ============================================================ +# DIRECTORIES +# ============================================================ + +for directory in ( + MODEL_DIR, + INSIGHTFACE_DIR, + HYPERSWAP_DIR, + FACE_RESTORE_DIR, + OUTPUT_DIR +): + + os.makedirs( + directory, + exist_ok=True + ) + + # ============================================================ # MODEL DEFINITIONS # ============================================================ @@ -214,44 +238,46 @@ MODEL_REPOS = { "martintomov/comfy", "facerestore_models/GPEN-BFR-512.onnx", FACE_RESTORE_DIR - ), + ) } # ============================================================ -# MODEL CACHE +# MODEL DOWNLOAD # ============================================================ -loaded_models = {} - - def download_model(model_name): if model_name not in MODEL_REPOS: + raise RuntimeError( f"Unknown model: {model_name}" ) repo, filename, local_dir = ( - MODEL_REPOS[model_name] + MODEL_REPOS[ + model_name + ] ) - local_name = os.path.basename( + basename = os.path.basename( filename ) local_path = os.path.join( local_dir, - local_name + basename ) if os.path.isfile( local_path ): + log( "[MODEL] Already exists:", local_path ) + return local_path os.makedirs( @@ -264,25 +290,33 @@ def download_model(model_name): model_name ) - path = hf_hub_download( + downloaded_path = hf_hub_download( repo_id=repo, filename=filename, local_dir=local_dir ) - if not os.path.isfile(path): + if not os.path.isfile( + downloaded_path + ): + raise RuntimeError( - f"Model download failed: {path}" + "Model download failed:\n" + + str(downloaded_path) ) log( "[MODEL] Ready:", - path + downloaded_path ) - return path + return downloaded_path +# ============================================================ +# ENSURE MODEL +# ============================================================ + def ensure_model(model_name): if not model_name: @@ -291,24 +325,28 @@ def ensure_model(model_name): if model_name == "none": return None - cached = loaded_models.get( - model_name - ) + with MODEL_LOCK: - if cached and os.path.isfile( - cached - ): - return cached + cached = loaded_models.get( + model_name + ) - path = download_model( - model_name - ) + if ( + cached + and os.path.isfile(cached) + ): - loaded_models[ - model_name - ] = path + return cached - return path + path = download_model( + model_name + ) + + loaded_models[ + model_name + ] = path + + return path # ============================================================ @@ -318,9 +356,15 @@ def ensure_model(model_name): def setup_comfyui_path(): if COMFYUI_ROOT in sys.path: - sys.path.remove( - COMFYUI_ROOT - ) + + try: + + sys.path.remove( + COMFYUI_ROOT + ) + + except ValueError: + pass sys.path.insert( 0, @@ -332,12 +376,17 @@ def setup_comfyui_path(): COMFYUI_ROOT ) + log( + "[COMFYUI] sys.path[0]:", + sys.path[0] + ) + setup_comfyui_path() # ============================================================ -# COMFYUI UTILS FIX +# FIX UTILS COLLISION # ============================================================ def fix_comfy_utils_namespace(): @@ -350,6 +399,7 @@ def fix_comfy_utils_namespace(): if not os.path.isdir( utils_dir ): + return existing = sys.modules.get( @@ -364,33 +414,25 @@ def fix_comfy_utils_namespace(): None ) - existing_file = getattr( - existing, - "__file__", - None - ) - - log( - "[COMFYUI] Existing utils:", - existing_file - ) - if existing_path is None: try: + del sys.modules[ "utils" ] + except KeyError: pass - importlib.invalidate_caches() - if COMFYUI_ROOT in sys.path: + try: + sys.path.remove( COMFYUI_ROOT ) + except ValueError: pass @@ -399,6 +441,8 @@ def fix_comfy_utils_namespace(): COMFYUI_ROOT ) + importlib.invalidate_caches() + try: import utils @@ -424,31 +468,35 @@ fix_comfy_utils_namespace() # ============================================================ -# COMFYUI VERSION +# COMFY VERSION # ============================================================ try: import comfyui_version - COMFY_VERSION = getattr( + comfy_version = getattr( comfyui_version, "__version__", - getattr( + None + ) + + if comfy_version is None: + + comfy_version = getattr( comfyui_version, "VERSION", "unknown" ) - ) except Exception: - COMFY_VERSION = "unknown" + comfy_version = "unknown" log( "[COMFYUI] Version:", - COMFY_VERSION + comfy_version ) @@ -458,12 +506,15 @@ log( def add_extra_model_paths(): - config = os.path.join( + config_path = os.path.join( COMFYUI_ROOT, "extra_model_paths.yaml" ) - if not os.path.isfile(config): + if not os.path.isfile( + config_path + ): + return try: @@ -473,13 +524,13 @@ def add_extra_model_paths(): ) load_extra_path_config( - config + config_path ) except Exception as e: log( - "[COMFYUI] Extra path warning:", + "[COMFYUI] Extra paths warning:", repr(e) ) @@ -495,16 +546,17 @@ import torch # ============================================================ -# COMFY CPU +# COMFY MODEL MANAGEMENT # ============================================================ import comfy.model_management -try: +from comfy.model_management import ( + CPUState +) - from comfy.model_management import ( - CPUState - ) + +try: comfy.model_management.cpu_state = ( CPUState.CPU @@ -529,74 +581,90 @@ log( # ============================================================ -# COMFY NODE INITIALIZATION +# COMFY NODES # ============================================================ def import_custom_nodes(): - log( - "[COMFYUI] Initializing nodes..." - ) + with COMFY_INIT_LOCK: - fix_comfy_utils_namespace() + log( + "[COMFYUI] Initializing nodes..." + ) - import execution - import server + fix_comfy_utils_namespace() - from nodes import ( - init_extra_nodes - ) + import execution - loop = asyncio.new_event_loop() + from nodes import ( + init_extra_nodes + ) - try: + import server - asyncio.set_event_loop( - loop - ) + loop = asyncio.new_event_loop() - prompt_server = ( - server.PromptServer( + try: + + asyncio.set_event_loop( loop ) - ) - if not hasattr( - prompt_server, - "prompt_queue" - ): - - execution.PromptQueue( - prompt_server + server_instance = ( + server.PromptServer( + loop + ) ) - result = init_extra_nodes() + if not hasattr( + server_instance, + "prompt_queue" + ): + + try: - if asyncio.iscoroutine( - result - ): + execution.PromptQueue( + server_instance + ) + + except Exception as e: + + log( + "[COMFYUI] PromptQueue warning:", + repr(e) + ) - loop.run_until_complete( + result = init_extra_nodes() + + if asyncio.iscoroutine( result - ) + ): - finally: + loop.run_until_complete( + result + ) - try: - asyncio.set_event_loop( - None - ) - except Exception: - pass + finally: - try: - loop.close() - except Exception: - pass + try: - log( - "[COMFYUI] Nodes initialized." - ) + asyncio.set_event_loop( + None + ) + + except Exception: + pass + + try: + + loop.close() + + except Exception: + pass + + log( + "[COMFYUI] Nodes initialized." + ) import_custom_nodes() @@ -612,48 +680,55 @@ from nodes import ( # ============================================================ -# LOAD IMAGE NODE +# VERIFY REACTOR # ============================================================ -try: +if not os.path.isdir( + REACTOR_PATH +): - loadimage = ( - NODE_CLASS_MAPPINGS[ - "LoadImage" - ]() + raise RuntimeError( + "Không tìm thấy ComfyUI-ReActor:\n" + + REACTOR_PATH ) -except Exception as e: - raise RuntimeError( - "LoadImage unavailable:\n" - f"{e}" +if REACTOR_PATH not in sys.path: + + sys.path.insert( + 0, + REACTOR_PATH ) +log( + "[REACTOR] Path:", + REACTOR_PATH +) + + # ============================================================ -# REACTOR CHECK +# LOAD LOADIMAGE # ============================================================ -if not os.path.isdir( - REACTOR_PATH -): +try: - raise RuntimeError( - "ReActor not found:\n" - f"{REACTOR_PATH}" + loadimage = ( + NODE_CLASS_MAPPINGS[ + "LoadImage" + ]() ) -if REACTOR_PATH not in sys.path: +except Exception as e: - sys.path.insert( - 0, - REACTOR_PATH + raise RuntimeError( + "Không load được LoadImage:\n" + + repr(e) ) # ============================================================ -# REACTOR NODE +# LOAD REACTOR # ============================================================ try: @@ -667,13 +742,13 @@ try: except Exception as e: raise RuntimeError( - "ReActorFaceSwap unavailable:\n" - f"{e}" + "Không load được ReActorFaceSwap:\n" + + repr(e) ) # ============================================================ -# REACTOR FACE ANALYSIS +# REACTOR FACE FUNCTIONS # ============================================================ try: @@ -686,193 +761,172 @@ try: except Exception as e: raise RuntimeError( - "Cannot import ReActor face analyzer:\n" - f"{e}" + "Không import được reactor_swapper:\n" + + repr(e) ) # ============================================================ -# FACE CACHE +# FILE HELPERS # ============================================================ -face_cache = OrderedDict() - +def get_file_path(file): -def clear_face_cache(): + if file is None: - face_cache.clear() + return None - gc.collect() + if isinstance( + file, + str + ): + return file -def detect_faces( - image_path, - det_size=DEFAULT_DET_SIZE -): + if hasattr( + file, + "path" + ): - if not image_path: - return [] + return file.path - if not os.path.isfile( - image_path + if hasattr( + file, + "name" ): - return [] - try: - mtime = os.path.getmtime( - image_path - ) - except Exception: - return [] + return file.name - key = ( - image_path, - mtime, - det_size - ) + return str(file) - if key in face_cache: - value = face_cache.pop( - key - ) +def get_file_paths(files): - face_cache[key] = value + if not files: - return value + return [] - image = cv2.imread( - image_path - ) + if isinstance( + files, + (str, bytes) + ): - if image is None: - return [] + files = [ + files + ] - try: + result = [] - faces = analyze_faces( - image, - det_size=( - det_size, - det_size - ) + for item in files: + + path = get_file_path( + item ) - except TypeError: + if ( + path + and os.path.isfile( + path + ) + ): - faces = analyze_faces( - image, - det_size=( - det_size, - det_size + result.append( + path ) - ) - except Exception as e: + return result - log( - "[FACE] Detection error:", - repr(e) - ) - return [] +# ============================================================ +# FACE CACHE +# ============================================================ - if faces is None: - faces = [] +def clear_face_cache(): - try: + face_cache.clear() - faces = sort_by_order( - faces, - "large-small" - ) + gc.collect() - except Exception: - pass +def detect_reactor_faces( + image_path +): - face_cache[key] = faces + if not image_path: + return [] - while len(face_cache) > FACE_CACHE_MAX: + if not os.path.isfile( + image_path + ): - face_cache.popitem( - last=False - ) + return [] - return faces + try: + mtime = os.path.getmtime( + image_path + ) -# ============================================================ -# FILE HELPERS -# ============================================================ + except Exception: -def get_file_path(value): + return [] - if value is None: - return None + key = ( + image_path, + mtime + ) - if isinstance( - value, - str - ): - return value + if key in face_cache: - if hasattr( - value, - "path" - ): - return value.path + faces = face_cache.pop( + key + ) - if hasattr( - value, - "name" - ): - return value.name + face_cache[key] = faces - return str(value) + return faces + img = cv2.imread( + image_path + ) -def get_file_paths(files): + if img is None: - if not files: return [] - if isinstance( - files, - ( - str, - bytes + faces = analyze_faces( + img, + det_size=( + 640, + 640 ) - ): - files = [files] + ) - result = [] + if faces is None: - for item in files: + faces = [] - path = get_file_path( - item - ) + faces = sort_by_order( + faces, + "large-small" + ) - if ( - path - and os.path.isfile( - path - ) - ): + face_cache[key] = faces - result.append( - path - ) + while len(face_cache) > FACE_CACHE_MAX: - return result + face_cache.popitem( + last=False + ) + + return faces # ============================================================ -# GIF FRAME +# GIF FIRST FRAME # ============================================================ -def gif_first_frame( +def get_gif_first_frame( path ): @@ -886,129 +940,78 @@ def gif_first_frame( 0 ) + return np.asarray( + frame + ).copy() + finally: reader.close() - return np.asarray( - frame - ) - - -def make_temp_image( - array -): - - fd, path = tempfile.mkstemp( - suffix=".png" - ) - - os.close(fd) - - Image.fromarray( - array - ).convert( - "RGB" - ).save( - path - ) - - return path - # ============================================================ -# GET PREVIEW IMAGE +# IMAGE FOR DETECTION # ============================================================ -def get_preview_source( +def get_detection_image( path ): - if not path: - return None - if path.lower().endswith( ".gif" ): - frame = gif_first_frame( + return get_gif_first_frame( path ) - return make_temp_image( - frame - ) + img = cv2.imread( + path + ) - return path + if img is None: + + return None + + return cv2.cvtColor( + img, + cv2.COLOR_BGR2RGB + ) # ============================================================ -# FACE PREVIEW +# ANNOTATED FACE PREVIEW # ============================================================ -def build_face_preview( - image_path, - det_size=DEFAULT_DET_SIZE +def make_annotated_preview( + path, + prefix ): - preview_path = ( - get_preview_source( - image_path - ) - ) - - if not preview_path: + if not path: - return ( - None, - [] - ) + return None, 0 - image = cv2.imread( - preview_path + rgb = get_detection_image( + path ) - if image is None: - - return ( - None, - [] - ) + if rgb is None: - height, width = ( - image.shape[:2] - ) + return None, 0 - faces = detect_faces( - preview_path, - det_size + bgr = cv2.cvtColor( + rgb, + cv2.COLOR_RGB2BGR ) - if not faces: - - if ( - preview_path != image_path - and os.path.isfile( - preview_path - ) - ): - - try: - os.remove( - preview_path - ) - except Exception: - pass - - return ( - None, - [] - ) + h, w = bgr.shape[:2] - crops = [] - boxes = [] + faces = detect_reactor_faces( + path + ) - for index, face in enumerate( + for face_index, face in enumerate( faces ): @@ -1018,1321 +1021,1075 @@ def build_face_preview( x1 = max( 0, - int(x1) + min( + w - 1, + int(x1) + ) ) y1 = max( 0, - int(y1) - ) - - x2 = min( - width, - int(x2) + min( + h - 1, + int(y1) + ) ) - y2 = min( - height, - int(y2) + x2 = max( + x1 + 1, + min( + w - 1, + int(x2) + ) ) - boxes.append( - [ - x1, - y1, - x2, - y2 - ] + y2 = max( + y1 + 1, + min( + h - 1, + int(y2) + ) ) - fw = max( - 1, - x2 - x1 + cv2.rectangle( + bgr, + (x1, y1), + (x2, y2), + (0, 255, 0), + max( + 2, + int( + min(w, h) / 350 + ) + ) ) - fh = max( - 1, - y2 - y1 + label = ( + f"{prefix} FACE {face_index}" ) - px = int( - fw * 0.45 + font_scale = max( + 0.55, + min( + 1.15, + min(w, h) / 800 + ) ) - py = int( - fh * 0.55 + thickness = max( + 1, + int( + font_scale * 2 + ) ) - cx1 = max( - 0, - x1 - px + ( + tw, + th + ), baseline = cv2.getTextSize( + label, + cv2.FONT_HERSHEY_SIMPLEX, + font_scale, + thickness ) - cy1 = max( + label_y1 = max( 0, - y1 - py - ) - - cx2 = min( - width, - x2 + px - ) - - cy2 = min( - height, - y2 + py - ) - - crop = image[ - cy1:cy2, - cx1:cx2 - ] - - if crop.size == 0: - continue - - ch, cw = ( - crop.shape[:2] + y1 - th - baseline - 8 ) - size = max( - ch, - cw + label_y2 = ( + y1 + if y1 > th + baseline + 8 + else y1 + th + baseline + 12 ) - square = np.zeros( + cv2.rectangle( + bgr, ( - size, - size, - 3 + x1, + label_y1 ), - dtype=np.uint8 - ) - - ox = ( - size - cw - ) // 2 - - oy = ( - size - ch - ) // 2 - - square[ - oy:oy + ch, - ox:ox + cw - ] = crop - - square = cv2.resize( - square, ( - 320, - 320 + min( + w - 1, + x1 + tw + 12 + ), + min( + h - 1, + label_y2 + ) ), - interpolation=cv2.INTER_AREA - ) - - cv2.rectangle( - square, - (0, 0), - (320, 50), (0, 255, 0), -1 ) + text_y = ( + label_y2 - 6 + if y1 > th + baseline + 8 + else label_y1 + th + 6 + ) + cv2.putText( - square, - f"FACE {index}", - (12, 36), + bgr, + label, + ( + x1 + 6, + text_y + ), cv2.FONT_HERSHEY_SIMPLEX, - 0.9, + font_scale, (0, 0, 0), - 2, + thickness, cv2.LINE_AA ) - square = cv2.cvtColor( - square, - cv2.COLOR_BGR2RGB - ) + preview = cv2.cvtColor( + bgr, + cv2.COLOR_BGR2RGB + ) - crops.append( - square - ) + return preview, len(faces) - if ( - preview_path != image_path - and os.path.isfile( - preview_path - ) - ): - try: - os.remove( - preview_path - ) - except Exception: - pass +# ============================================================ +# MULTI FILE PREVIEW +# ============================================================ - if not crops: +def preview_source_target( + source_files, + target_files +): - return ( - None, - boxes - ) - - columns = min( - 4, - len(crops) - ) - - rows = int( - np.ceil( - len(crops) / columns - ) + source_paths = get_file_paths( + source_files ) - blank = np.zeros( - ( - rows * 320, - columns * 320, - 3 - ), - dtype=np.uint8 + target_paths = get_file_paths( + target_files ) - for i, crop in enumerate( - crops - ): + source_gallery = [] - row = i // columns - col = i % columns + target_gallery = [] - blank[ - row * 320: - row * 320 + 320, - col * 320: - col * 320 + 320 - ] = crop + source_choices = [] - return ( - blank, - boxes - ) + target_choices = [] + source_face_choices = [] -# ============================================================ -# PARSE FACE -# ============================================================ + target_face_choices = [] -def parse_face_index( - value -): + try: - if value is None: - return None + with JOB_SEMAPHORE: - text = str( - value - ).upper() + # ================================================ + # SOURCE + # ================================================ - if "FACE" in text: + for source_index, path in enumerate( + source_paths + ): - text = ( - text.split( - "FACE", - 1 - )[1] - ) + try: - digits = "" + preview, count = ( + make_annotated_preview( + path, + f"SOURCE {source_index}" + ) + ) - for char in text: + if preview is not None: + + source_gallery.append( + ( + preview, + ( + f"SOURCE {source_index} " + f"{os.path.basename(path)} " + f"[{count} faces]" + ) + ) + ) + + source_choices.append( + f"SOURCE {source_index}: " + f"{os.path.basename(path)}" + ) - if char.isdigit(): - digits += char + faces = detect_reactor_faces( + path + ) - elif digits: - break + for face_index in range( + len(faces) + ): - if not digits: - return None + source_face_choices.append( + f"SOURCE {source_index} " + f"FACE {face_index}" + ) - try: - return int(digits) - except Exception: - return None + except Exception as e: + log( + "[PREVIEW SOURCE ERROR]", + path, + repr(e) + ) -# ============================================================ -# PARSE SOURCE INDEX -# ============================================================ + # ================================================ + # TARGET + # ================================================ -def parse_source_mapping( - value -): + for target_index, path in enumerate( + target_paths + ): - if value is None: - return ( - None, - None - ) + try: - text = str( - value - ).upper() + preview, count = ( + make_annotated_preview( + path, + f"TARGET {target_index}" + ) + ) - source_index = None - face_index = None + if preview is not None: + + target_gallery.append( + ( + preview, + ( + f"TARGET {target_index} " + f"{os.path.basename(path)} " + f"[{count} faces]" + ) + ) + ) + + target_choices.append( + f"TARGET {target_index}: " + f"{os.path.basename(path)}" + ) - if "SOURCE" in text: + except Exception as e: - part = text.split( - "SOURCE", - 1 - )[1] + log( + "[PREVIEW TARGET ERROR]", + path, + repr(e) + ) - digits = "" + # ================================================ + # TARGET FACE CHOICES + # ================================================ - for char in part: + if target_paths: - if char.isdigit(): - digits += char - elif digits: - break + for target_index, path in enumerate( + target_paths + ): - if digits: + try: - source_index = int( - digits - ) + faces = detect_reactor_faces( + path + ) - face_index = parse_face_index( - text - ) + for face_index in range( + len(faces) + ): - return ( - source_index, - face_index - ) + target_face_choices.append( + f"TARGET {target_index} " + f"FACE {face_index}" + ) + except Exception as e: -# ============================================================ -# TARGET MAPPING PARSER -# ============================================================ + log( + "[TARGET FACE ERROR]", + repr(e) + ) -def parse_target_mapping( - value -): + except Exception as e: - if value is None: - return ( - None, - None + log( + "[PREVIEW ERROR]", + repr(e) ) - text = str( - value - ).upper() + source_value = ( + source_choices[0] + if source_choices + else None + ) - target_index = None - face_index = None + target_value = ( + target_choices[0] + if target_choices + else None + ) - if "TARGET" in text: + source_face_value = ( + source_face_choices[0] + if source_face_choices + else None + ) - part = text.split( - "TARGET", - 1 - )[1] + target_face_value = ( + target_face_choices[0] + if target_face_choices + else None + ) - digits = "" + return ( - for char in part: + source_gallery, - if char.isdigit(): - digits += char - elif digits: - break + target_gallery, - if digits: - target_index = int( - digits - ) + gr.update( + choices=source_choices, + value=source_value + ), - face_index = parse_face_index( - text - ) + gr.update( + choices=target_choices, + value=target_value + ), - return ( - target_index, - face_index + gr.update( + choices=source_face_choices, + value=source_face_value + ), + + gr.update( + choices=target_face_choices, + value=target_face_value + ), + + ( + f"Preview completed: " + f"{len(source_paths)} source / " + f"{len(target_paths)} target" + ) ) # ============================================================ -# MAPPING MODEL +# SOURCE FACE SELECTOR # ============================================================ -def parse_mapping_text( - text +def source_face_choices_from_source( + source_files, + source_selector ): - mappings = [] - - if not text: - return mappings - - for raw in str( - text - ).splitlines(): - - line = raw.strip() - - if not line: - continue - - if ( - "->" not in line - and "→" not in line - ): - continue + paths = get_file_paths( + source_files + ) - line = line.replace( - "→", - "->" - ) + if not paths: - left, right = ( - line.split( - "->", - 1 - ) + return gr.update( + choices=[], + value=None ) - si, sf = ( - parse_source_mapping( - left - ) - ) + index = 0 - ti, tf = ( - parse_target_mapping( - right - ) - ) + if source_selector: - if ( - si is None - or sf is None - or ti is None - or tf is None - ): - continue + try: - mappings.append( - { - "source_index": si, - "source_face": sf, - "target_index": ti, - "target_face": tf, - } - ) + index = int( + source_selector.split( + ":", + 1 + )[0].replace( + "SOURCE", + "" + ).strip() + ) - return mappings + except Exception: + index = 0 + if index < 0 or index >= len(paths): -def mapping_to_text( - mappings -): + index = 0 - if not mappings: - return "" + faces = detect_reactor_faces( + paths[index] + ) - lines = [] + choices = [ - for m in mappings: + f"SOURCE {index} FACE {i}" - lines.append( - f"SOURCE {m['source_index']} " - f"FACE {m['source_face']} " - f"-> TARGET {m['target_index']} " - f"FACE {m['target_face']}" + for i in range( + len(faces) ) + ] - return "\n".join( - lines + return gr.update( + choices=choices, + value=( + choices[0] + if choices + else None + ) ) # ============================================================ -# DEFAULT MAPPING +# TARGET FACE SELECTOR # ============================================================ -def default_mapping(): +def target_face_choices_from_target( + target_files, + target_selector +): - return ( - "SOURCE 0 FACE 0 -> " - "TARGET 0 FACE 0" + paths = get_file_paths( + target_files ) + if not paths: -# ============================================================ -# VALIDATE MAPPING -# ============================================================ + return gr.update( + choices=[], + value=None + ) -def validate_mappings( - mappings, - source_paths, - target_paths -): + index = 0 - errors = [] + if target_selector: - if not source_paths: - errors.append( - "Không có source." - ) + try: - if not target_paths: - errors.append( - "Không có target." - ) + index = int( + target_selector.split( + ":", + 1 + )[0].replace( + "TARGET", + "" + ).strip() + ) - used_targets = set() + except Exception: + index = 0 - for i, m in enumerate( - mappings, - 1 - ): + if index < 0 or index >= len(paths): - si = m[ - "source_index" - ] + index = 0 - sf = m[ - "source_face" - ] + faces = detect_reactor_faces( + paths[index] + ) - ti = m[ - "target_index" - ] + choices = [ - tf = m[ - "target_face" - ] + f"TARGET {index} FACE {i}" - if ( - si < 0 - or si >= len(source_paths) - ): + for i in range( + len(faces) + ) + ] - errors.append( - f"Mapping {i}: " - f"SOURCE {si} không tồn tại." - ) + return gr.update( + choices=choices, + value=( + choices[0] + if choices + else None + ) + ) - continue - if ( - ti < 0 - or ti >= len(target_paths) - ): +# ============================================================ +# PARSE SOURCE FACE +# ============================================================ - errors.append( - f"Mapping {i}: " - f"TARGET {ti} không tồn tại." - ) +def parse_source_face( + value +): - continue + if not value: - source_faces = detect_faces( - source_paths[si] + return ( + -1, + -1 ) - target_preview = ( - get_preview_source( - target_paths[ti] - ) + text = str( + value + ).upper() + + try: + + source_index = int( + text.split( + "SOURCE", + 1 + )[1].split( + "FACE", + 1 + )[0].strip() ) - target_faces = detect_faces( - target_preview + face_index = int( + text.split( + "FACE", + 1 + )[1].strip() ) - if ( - target_preview != - target_paths[ti] - and target_preview - and os.path.isfile( - target_preview - ) - ): + return ( + source_index, + face_index + ) - try: - os.remove( - target_preview - ) - except Exception: - pass - - if sf < 0 or sf >= len( - source_faces - ): - - errors.append( - f"Mapping {i}: " - f"SOURCE {si} FACE {sf} " - f"không tồn tại." - ) - - if tf < 0 or tf >= len( - target_faces - ): - - errors.append( - f"Mapping {i}: " - f"TARGET {ti} FACE {tf} " - f"không tồn tại." - ) - - key = ( - ti, - tf - ) - - if key in used_targets: - - errors.append( - f"Mapping {i}: " - f"TARGET {ti} FACE {tf} " - f"bị mapping trùng." - ) + except Exception: - used_targets.add( - key + return ( + -1, + -1 ) - return errors - # ============================================================ -# ADD MAPPING +# PARSE TARGET FACE # ============================================================ -def add_mapping( - mapping_text, - source_selector, - target_selector +def parse_target_face( + value ): - mappings = parse_mapping_text( - mapping_text - ) + if not value: - si, sf = ( - parse_source_mapping( - source_selector + return ( + -1, + -1 ) - ) - ti, tf = ( - parse_target_mapping( - target_selector - ) - ) + text = str( + value + ).upper() - if ( - si is None - or sf is None - or ti is None - or tf is None - ): + try: - raise gr.Error( - "Mapping không hợp lệ." + target_index = int( + text.split( + "TARGET", + 1 + )[1].split( + "FACE", + 1 + )[0].strip() ) - new_mapping = { - "source_index": si, - "source_face": sf, - "target_index": ti, - "target_face": tf, - } + face_index = int( + text.split( + "FACE", + 1 + )[1].strip() + ) - mappings = [ - m - for m in mappings - if not ( - m["target_index"] == ti - and - m["target_face"] == tf + return ( + target_index, + face_index ) - ] - mappings.append( - new_mapping - ) + except Exception: - return mapping_to_text( - mappings - ) + return ( + -1, + -1 + ) # ============================================================ -# REMOVE LAST MAPPING +# MAPPING FORMAT # ============================================================ -def remove_last_mapping( - mapping_text +def normalize_mapping_line( + source_face, + target_face ): - mappings = parse_mapping_text( - mapping_text + source_index, source_face_index = ( + parse_source_face( + source_face + ) ) - if mappings: - mappings.pop() - - return mapping_to_text( - mappings + target_index, target_face_index = ( + parse_target_face( + target_face + ) ) + if ( + source_index < 0 + or source_face_index < 0 + or target_index < 0 + or target_face_index < 0 + ): -# ============================================================ -# CLEAR MAPPING -# ============================================================ - -def clear_mapping(): + return None - return "" + return ( + f"SOURCE {source_index} " + f"FACE {source_face_index} " + f"-> TARGET {target_index} " + f"FACE {target_face_index}" + ) # ============================================================ -# AUTO MAPPING +# PARSE MAPPINGS # ============================================================ -def auto_mapping( - source_files, - target_files, - mode +def parse_mappings( + mapping_text ): - sources = get_file_paths( - source_files - ) - - targets = get_file_paths( - target_files - ) - - if not sources: - raise gr.Error( - "Chưa có source." - ) - - if not targets: - raise gr.Error( - "Chưa có target." - ) - - source_faces = [] - - for si, path in enumerate( - sources - ): + mappings = [] - faces = detect_faces( - path - ) + if not mapping_text: - for fi in range( - len(faces) - ): + return mappings - source_faces.append( - ( - si, - fi - ) - ) + for raw in str( + mapping_text + ).splitlines(): - target_faces = [] + line = raw.strip() - for ti, path in enumerate( - targets - ): + if not line: - preview_path = ( - get_preview_source( - path - ) - ) + continue - faces = detect_faces( - preview_path - ) + upper = line.upper() if ( - preview_path != path - and preview_path - and os.path.isfile( - preview_path - ) + "SOURCE" not in upper + or "TARGET" not in upper + or "FACE" not in upper ): - try: - os.remove( - preview_path - ) - except Exception: - pass + continue - for fi in range( - len(faces) - ): + try: - target_faces.append( - ( - ti, - fi + left, right = ( + upper.split( + "->", + 1 ) ) - if not source_faces: - raise gr.Error( - "Không phát hiện source face." - ) - - if not target_faces: - raise gr.Error( - "Không phát hiện target face." - ) - - mappings = [] - - if mode == "Sequential": - - count = min( - len(source_faces), - len(target_faces) - ) + s_index = int( + left.split( + "SOURCE", + 1 + )[1].split( + "FACE", + 1 + )[0].strip() + ) - for i in range(count): + s_face = int( + left.split( + "FACE", + 1 + )[1].strip() + ) - si, sf = ( - source_faces[i] + t_index = int( + right.split( + "TARGET", + 1 + )[1].split( + "FACE", + 1 + )[0].strip() ) - ti, tf = ( - target_faces[i] + t_face = int( + right.split( + "FACE", + 1 + )[1].strip() ) mappings.append( { - "source_index": si, - "source_face": sf, - "target_index": ti, - "target_face": tf + "source_index": s_index, + "source_face": s_face, + "target_index": t_index, + "target_face": t_face } ) - elif mode == "First Source → All Targets": + except Exception: - si, sf = source_faces[0] + continue - for ti, tf in target_faces: + return mappings - mappings.append( - { - "source_index": si, - "source_face": sf, - "target_index": ti, - "target_face": tf - } - ) - elif mode == "Round Robin": +# ============================================================ +# DEFAULT MAPPING +# ============================================================ - for i, ( - ti, - tf - ) in enumerate( - target_faces - ): +def default_mapping(): - si, sf = ( - source_faces[ - i % len( - source_faces - ) - ] - ) + return ( + "SOURCE 0 FACE 0 " + "-> TARGET 0 FACE 0" + ) - mappings.append( - { - "source_index": si, - "source_face": sf, - "target_index": ti, - "target_face": tf - } - ) - elif mode == "Same Face Index": +# ============================================================ +# ADD MAPPING +# ============================================================ + +def add_mapping( + mapping_text, + source_face, + target_face +): - for ti, tf in target_faces: + line = normalize_mapping_line( + source_face, + target_face + ) - for si, sf in source_faces: + if not line: - if sf == tf: + raise gr.Error( + "Mapping không hợp lệ." + ) - mappings.append( - { - "source_index": si, - "source_face": sf, - "target_index": ti, - "target_face": tf - } - ) + existing = [] - break + if mapping_text: - else: + existing = [ + x.strip() + for x in str( + mapping_text + ).splitlines() + if x.strip() + ] - raise gr.Error( - "Auto mapping mode không hợp lệ." + if line not in existing: + + existing.append( + line ) - return mapping_to_text( - mappings + return "\n".join( + existing ) # ============================================================ -# SOURCE SELECTOR +# REMOVE LAST # ============================================================ -def update_source_selector( - source_files +def remove_last_mapping( + mapping_text ): - paths = get_file_paths( - source_files - ) + lines = [ - choices = [ - f"SOURCE {i}: " - f"{os.path.basename(path)}" - for i, path in enumerate( - paths - ) + x.strip() + + for x in str( + mapping_text or "" + ).splitlines() + + if x.strip() ] - return gr.update( - choices=choices, - value=( - choices[0] - if choices - else None - ) + if lines: + + lines.pop() + + return "\n".join( + lines ) # ============================================================ -# TARGET SELECTOR +# CLEAR MAPPING # ============================================================ -def update_target_selector( - target_files -): - - paths = get_file_paths( - target_files - ) - - choices = [ - f"TARGET {i}: " - f"{os.path.basename(path)}" - for i, path in enumerate( - paths - ) - ] +def clear_mapping(): - return gr.update( - choices=choices, - value=( - choices[0] - if choices - else None - ) - ) + return "" # ============================================================ -# SOURCE FACE PREVIEW +# VALIDATE MAPPING # ============================================================ -def show_source_preview( - source_files, - source_selector +def validate_mappings( + mappings, + source_paths, + target_paths ): - paths = get_file_paths( - source_files - ) + if not mappings: - if not paths: - return ( - None, - gr.update( - choices=[], - value=None - ) + raise gr.Error( + "Chưa có Face Mapping." ) - index = 0 - - if source_selector: + for mapping in mappings: - text = str( - source_selector - ) + si = mapping[ + "source_index" + ] - digits = "" + sf = mapping[ + "source_face" + ] - if "SOURCE" in text: + ti = mapping[ + "target_index" + ] - part = text.split( - "SOURCE", - 1 - )[1] + tf = mapping[ + "target_face" + ] - for c in part: + if ( + si < 0 + or si >= len(source_paths) + ): - if c.isdigit(): - digits += c - elif digits: - break + raise gr.Error( + f"Source index không tồn tại: {si}" + ) - if digits: - index = int(digits) - - if ( - index < 0 - or index >= len(paths) - ): - index = 0 - - preview, boxes = ( - build_face_preview( - paths[index] - ) - ) - - choices = [ - f"SOURCE {index} FACE {i}" - for i in range( - len(boxes) - ) - ] + if ( + ti < 0 + or ti >= len(target_paths) + ): - return ( - preview, - gr.update( - choices=choices, - value=( - choices[0] - if choices - else None + raise gr.Error( + f"Target index không tồn tại: {ti}" ) - ) - ) - - -# ============================================================ -# TARGET FACE PREVIEW -# ============================================================ - -def show_target_preview( - target_files, - target_selector -): - - paths = get_file_paths( - target_files - ) - - if not paths: - return ( - None, - gr.update( - choices=[], - value=None + source_faces = ( + detect_reactor_faces( + source_paths[si] ) ) - index = 0 - - if target_selector: - - text = str( - target_selector + target_faces = ( + detect_reactor_faces( + target_paths[ti] + ) ) - digits = "" - - if "TARGET" in text: - - part = text.split( - "TARGET", - 1 - )[1] - - for c in part: - - if c.isdigit(): - digits += c - elif digits: - break + if ( + sf < 0 + or sf >= len(source_faces) + ): - if digits: - index = int( - digits + raise gr.Error( + f"SOURCE {si} FACE {sf} " + "không tồn tại." ) - if ( - index < 0 - or index >= len(paths) - ): - index = 0 - - preview, boxes = ( - build_face_preview( - paths[index] - ) - ) - - choices = [ - f"TARGET {index} FACE {i}" - for i in range( - len(boxes) - ) - ] + if ( + tf < 0 + or tf >= len(target_faces) + ): - return ( - preview, - gr.update( - choices=choices, - value=( - choices[0] - if choices - else None + raise gr.Error( + f"TARGET {ti} FACE {tf} " + "không tồn tại." ) - ) - ) # ============================================================ -# MAPPING SOURCE CHOICES +# LOAD IMAGE THROUGH COMFY # ============================================================ -def update_mapping_source_choices( - source_files +def comfy_load_image( + path ): - paths = get_file_paths( - source_files + result = loadimage.load_image( + image=path ) - choices = [] + if result is None: + + raise RuntimeError( + "ComfyUI LoadImage returned None." + ) - for si, path in enumerate( - paths + if isinstance( + result, + dict ): - faces = detect_faces( - path + values = list( + result.values() ) - for fi in range( - len(faces) - ): + if not values: - choices.append( - f"SOURCE {si} FACE {fi}" + raise RuntimeError( + "LoadImage returned empty dict." ) - return gr.update( - choices=choices, - value=( - choices[0] - if choices - else None - ) - ) + image = values[0] + else: -# ============================================================ -# MAPPING TARGET IMAGE -# ============================================================ + try: -def update_mapping_target_choices( - target_files -): + image = result[0] - paths = get_file_paths( - target_files - ) + except Exception: - choices = [] + image = result - for ti, path in enumerate( - paths - ): + if image is None: - choices.append( - f"TARGET {ti}: " - f"{os.path.basename(path)}" + raise RuntimeError( + "Loaded image is None." ) - return gr.update( - choices=choices, - value=( - choices[0] - if choices - else None - ) - ) + return image # ============================================================ -# MAPPING TARGET FACE +# SOURCE CACHE # ============================================================ -def update_mapping_target_faces( - target_files, - target_selector +def load_source_cached( + path ): - paths = get_file_paths( - target_files - ) - - if not paths: + try: - return gr.update( - choices=[], - value=None + mtime = os.path.getmtime( + path ) - ti, _ = ( - parse_target_mapping( - target_selector - ) - ) + except Exception: - if ti is None: - ti = 0 + mtime = 0 - if ( - ti < 0 - or ti >= len(paths) - ): - ti = 0 + key = ( + path, + mtime + ) - preview_path = ( - get_preview_source( - paths[ti] + if key in source_tensor_cache: + + value = ( + source_tensor_cache.pop( + key + ) ) - ) - faces = detect_faces( - preview_path + source_tensor_cache[ + key + ] = value + + return value + + image = comfy_load_image( + path ) - if ( - preview_path != paths[ti] - and preview_path - and os.path.isfile( - preview_path - ) - ): + source_tensor_cache[ + key + ] = image - try: - os.remove( - preview_path - ) - except Exception: - pass + while ( + len(source_tensor_cache) + > SOURCE_TENSOR_CACHE_MAX + ): - choices = [ - f"TARGET {ti} FACE {i}" - for i in range( - len(faces) + source_tensor_cache.popitem( + last=False ) - ] - return gr.update( - choices=choices, - value=( - choices[0] - if choices - else None - ) - ) + return image # ============================================================ -# SOURCE TENSOR +# GET VALUE # ============================================================ -def load_source_tensor( - path +def get_value_at_index( + obj, + index ): - data = loadimage.load_image( - image=path - ) + if obj is None: - if ( - not data - or not isinstance( - data, - (list, tuple) + raise RuntimeError( + "ComfyUI node returned None." ) + + if isinstance( + obj, + dict ): - raise RuntimeError( - f"Không load được source: {path}" + values = list( + obj.values() ) - tensor = data[0] + if index >= len(values): - if tensor is None: + raise RuntimeError( + "ComfyUI output index out of range." + ) - raise RuntimeError( - f"Source tensor = None: {path}" - ) + return values[index] - return tensor + return obj[index] # ============================================================ -# RESULT EXTRACTION +# RESULT TO PIL # ============================================================ -def extract_image_result( +def result_to_pil( result ): if result is None: raise RuntimeError( - "ReActor returned None." + "ReActor output is None." ) try: - value = result[0] + value = get_value_at_index( + result, + 0 + ) except Exception: @@ -2341,54 +2098,48 @@ def extract_image_result( if value is None: raise RuntimeError( - "ReActor output is None." + "ReActor image output is None." ) - try: + if isinstance( + value, + (list, tuple) + ): - if hasattr( - value, - "detach" - ): + if not value: - value = ( - value - .detach() - .cpu() - .numpy() + raise RuntimeError( + "ReActor returned empty image." ) - except Exception: - pass + value = value[0] + + if hasattr( + value, + "detach" + ): + + value = ( + value + .detach() + .cpu() + .float() + .numpy() + ) value = np.asarray( value ) if value.ndim == 4: - value = value[0] - if value.dtype != np.uint8: - - if value.max() <= 1.0: - - value = ( - value * 255.0 - ) - - value = np.clip( - value, - 0, - 255 - ).astype( - np.uint8 - ) + value = value[0] if value.ndim != 3: raise RuntimeError( - f"Invalid ReActor output shape: " - f"{value.shape}" + "Invalid ReActor output shape: " + + str(value.shape) ) if value.shape[-1] != 3: @@ -2403,10 +2154,22 @@ def extract_image_result( else: raise RuntimeError( - f"Invalid image shape: " - f"{value.shape}" + "Invalid image channels: " + + str(value.shape) ) + if value.max() <= 1.0: + + value = value * 255.0 + + value = np.clip( + value, + 0, + 255 + ).astype( + np.uint8 + ) + return Image.fromarray( value ).convert( @@ -2415,12 +2178,12 @@ def extract_image_result( # ============================================================ -# SAFE REACTOR SWAP +# REACTOR SWAP # ============================================================ def reactor_swap( - source_tensor, - target_tensor, + source_image, + target_image, source_face_index, target_face_index, swap_model, @@ -2428,89 +2191,98 @@ def reactor_swap( restore_strength ): - restore = ( + swap_model_path = ensure_model( + swap_model + ) + + if not swap_model_path: + + raise RuntimeError( + "Swap model unavailable." + ) + + restore_name = ( restore_model if restore_model else "none" ) - log( - "[REACTOR]", - "source_face=", - source_face_index, - "target_face=", - target_face_index - ) + if restore_name != "none": + + ensure_model( + restore_name + ) - kwargs = dict( + kwargs = { - enabled=True, + "enabled": True, - swap_model=swap_model, + "swap_model": swap_model, - facedetection=( + "facedetection": ( "retinaface_resnet50" ), - face_restore_model=restore, + "face_restore_model": ( + restore_name + ), - face_restore_visibility=float( - restore_strength + "face_restore_visibility": ( + float( + restore_strength + ) ), - codeformer_weight=0.5, + "codeformer_weight": 0.5, - detect_gender_input="no", + "detect_gender_input": "no", - detect_gender_source="no", + "detect_gender_source": "no", - input_faces_index=str( + "input_faces_index": str( target_face_index ), - source_faces_index=str( + "source_faces_index": str( source_face_index ), - console_log_level=1, + "console_log_level": 1, - input_image=target_tensor, + "input_image": target_image, - source_image=source_tensor - ) + "source_image": source_image + } + + # -------------------------------------------------------- + # First attempt + # -------------------------------------------------------- try: - result = ( - reactorfaceswap.execute( - **kwargs - ) + result = reactorfaceswap.execute( + **kwargs ) - return extract_image_result( + return result_to_pil( result ) except TypeError as e: - # ---------------------------------------------------- - # GPEN can fail after the actual swap. - # Retry with restore disabled. - # ---------------------------------------------------- + message = str(e) if ( - restore != "none" - and - "NoneType" in str(e) - ): - - log( - "[RESTORE] GPEN failed." + restore_name != "none" + and ( + "NoneType" in message + or "Unable to load" in message ) + ): log( - "[RESTORE] Falling back " - "to swap-only." + "[RESTORE FALLBACK]", + message ) kwargs[ @@ -2521,13 +2293,11 @@ def reactor_swap( "face_restore_visibility" ] = 0.0 - result = ( - reactorfaceswap.execute( - **kwargs - ) + result = reactorfaceswap.execute( + **kwargs ) - return extract_image_result( + return result_to_pil( result ) @@ -2535,24 +2305,19 @@ def reactor_swap( except Exception as e: + message = str(e) + if ( - restore != "none" - and - ( - "NoneType" in str(e) - or - "Unable to load" in str(e) + restore_name != "none" + and ( + "NoneType" in message + or "Unable to load" in message ) ): log( - "[RESTORE] Restore failed:" - , - repr(e) - ) - - log( - "[RESTORE] Retry swap-only." + "[RESTORE FALLBACK]", + message ) kwargs[ @@ -2563,13 +2328,11 @@ def reactor_swap( "face_restore_visibility" ] = 0.0 - result = ( - reactorfaceswap.execute( - **kwargs - ) + result = reactorfaceswap.execute( + **kwargs ) - return extract_image_result( + return result_to_pil( result ) @@ -2577,33 +2340,45 @@ def reactor_swap( # ============================================================ -# NORMAL IMAGE SWAP +# SWAP ONE IMAGE # ============================================================ -def swap_image_file( - source_tensor, +def swap_one_image( + source_path, target_path, + source_face_index, target_face_index, swap_model, restore_model, - restore_strength + restore_strength, + target_image_override=None ): - target_tensor = ( - load_source_tensor( - target_path - ) + source_tensor = load_source_cached( + source_path ) - try: + if target_image_override is None: + + target_tensor = comfy_load_image( + target_path + ) + + else: + + target_tensor = ( + target_image_override + ) - result = reactor_swap( + with INFERENCE_SEMAPHORE: + + result_image = reactor_swap( source_tensor, target_tensor, - 0, + source_face_index, target_face_index, @@ -2614,154 +2389,29 @@ def swap_image_file( restore_strength ) - return result - - finally: + if result_image is None: - del target_tensor + raise RuntimeError( + "Swap returned None." + ) - gc.collect() + return result_image # ============================================================ -# APPLY MULTI MAPPING TO IMAGE +# GIF PROCESS # ============================================================ -def process_target_with_mappings( +def process_gif_mapping( + source_path, target_path, - source_tensors, - mappings, - target_index, + source_face_index, + target_face_index, swap_model, restore_model, restore_strength ): - # -------------------------------------------------------- - # For multiple faces, apply mappings sequentially. - # -------------------------------------------------------- - - current_image = Image.open( - target_path - ).convert( - "RGB" - ) - - temp_paths = [] - - try: - - for map_index, mapping in enumerate( - mappings - ): - - if mapping[ - "target_index" - ] != target_index: - - continue - - si = mapping[ - "source_index" - ] - - sf = mapping[ - "source_face" - ] - - tf = mapping[ - "target_face" - ] - - if si not in source_tensors: - - raise RuntimeError( - f"Source tensor {si} " - f"not loaded." - ) - - log( - "[MAPPING]", - f"SOURCE {si} FACE {sf}", - "->", - f"TARGET {target_index} " - f"FACE {tf}" - ) - - fd, temp_path = ( - tempfile.mkstemp( - suffix=".png" - ) - ) - - os.close(fd) - - current_image.save( - temp_path - ) - - temp_paths.append( - temp_path - ) - - target_tensor = ( - load_source_tensor( - temp_path - ) - ) - - result = reactor_swap( - - source_tensors[si], - - target_tensor, - - sf, - - tf, - - swap_model, - - restore_model, - - restore_strength - ) - - current_image = result - - del target_tensor - - gc.collect() - - finally: - - for p in temp_paths: - - try: - os.remove(p) - except Exception: - pass - - gc.collect() - - return current_image - - -# ============================================================ -# GIF PROCESSING -# ============================================================ - -def process_gif_target( - target_path, - source_tensors, - mappings, - target_index, - swap_model, - restore_model, - restore_strength, - progress=None -): - reader = imageio.get_reader( target_path ) @@ -2772,33 +2422,35 @@ def process_gif_target( try: - meta = {} - try: + meta = reader.get_meta_data() + except Exception: - pass - default_duration = meta.get( + meta = {} + + duration = meta.get( "duration", 100 ) + fps = meta.get( + "fps", + None + ) + + if fps and not duration: + + duration = ( + 1000.0 / float(fps) + ) + for frame_index, frame in enumerate( reader ): - if progress: - - progress( - 0, - desc=( - f"GIF frame " - f"{frame_index + 1}" - ) - ) - - frame_image = ( + frame_pil = ( Image.fromarray( frame ).convert( @@ -2806,64 +2458,60 @@ def process_gif_target( ) ) - fd, temp_path = ( - tempfile.mkstemp( - suffix=".png" - ) - ) + with tempfile.NamedTemporaryFile( + suffix=".png", + delete=False + ) as tmp: - os.close(fd) + temp_path = tmp.name try: - frame_image.save( + frame_pil.save( temp_path ) - result = ( - process_target_with_mappings( + result = swap_one_image( - temp_path, + source_path, - source_tensors, + temp_path, - mappings, + source_face_index, - target_index, + target_face_index, - swap_model, + swap_model, - restore_model, + restore_model, - restore_strength - ) + restore_strength ) frames.append( - np.asarray( - result - ) + result ) durations.append( - default_duration + duration ) finally: try: + os.remove( temp_path ) + except Exception: pass - del frame_image - if ( - frame_index % 3 + frame_index % 5 == 0 ): + gc.collect() finally: @@ -2872,8 +2520,8 @@ def process_gif_target( if not frames: - raise RuntimeError( - "GIF has no frames." + raise gr.Error( + "GIF không có frame." ) return ( @@ -2883,144 +2531,87 @@ def process_gif_target( # ============================================================ -# OUTPUT NAME +# OUTPUT PATH # ============================================================ -def safe_output_name( - target_path, - target_index, - extension +def safe_name( + value ): - base = Path( - target_path - ).stem - - timestamp = time.strftime( - "%Y%m%d_%H%M%S" - ) + result = [] - unique = uuid.uuid4().hex[:6] + for char in str(value): - return os.path.join( - OUTPUT_DIR, - ( - f"{base}" - f"_faceswap_" - f"{target_index}_" - f"{timestamp}_" - f"{unique}" - f".{extension}" - ) - ) + if ( + char.isalnum() + or char in ( + "-", + "_", + "." + ) + ): + result.append( + char + ) -# ============================================================ -# SAVE IMAGE -# ============================================================ + else: -def save_image( - image, - path, - quality=90 -): + result.append( + "_" + ) - ext = ( - os.path.splitext( - path - )[1] - .lower() + return "".join( + result ) - if ext == ".jpg": - image.save( - path, - "JPEG", - quality=quality, - optimize=True - ) - - elif ext == ".png": - image.save( - path, - "PNG", - optimize=True - ) - - else: - image.save( - path, - "WEBP", - quality=quality, - method=6 - ) - - -# ============================================================ -# SAVE GIF -# ============================================================ -def save_gif( - frames, - durations, - output_path, - quality=90 +def make_output_path( + source_path, + target_path, + batch_index ): - images = [ - Image.fromarray( - frame - ).convert( - "RGB" - ) - for frame in frames - ] - - images[0].save( - - output_path, - - save_all=True, - - append_images=images[1:], - - duration=durations, - - loop=0, + source_name = safe_name( + os.path.splitext( + os.path.basename( + source_path + ) + )[0] + ) - format="GIF" + target_name = safe_name( + os.path.splitext( + os.path.basename( + target_path + ) + )[0] ) - del images + filename = ( + f"{source_name}" + f"_TO_" + f"{target_name}" + f"_{batch_index:04d}.webp" + ) - gc.collect() + return os.path.join( + OUTPUT_DIR, + filename + ) # ============================================================ -# GENERATE PRO +# GENERATE # ============================================================ -def generate_pro( - +def generate_image( source_files, - target_files, - mapping_text, - swap_model, - restore_model, - - restore_strength, - - output_format, - - output_quality, - - skip_existing, - - progress=gr.Progress() + restore_strength ): source_paths = get_file_paths( @@ -3034,41 +2625,29 @@ def generate_pro( if not source_paths: raise gr.Error( - "Chưa chọn Source." + "Chưa upload Source." ) if not target_paths: raise gr.Error( - "Chưa chọn Target." + "Chưa upload Target." ) - mappings = parse_mapping_text( + mappings = parse_mappings( mapping_text ) if not mappings: - raise gr.Error( - "Chưa có Face Mapping." - ) - - errors = validate_mappings( - - mappings, - - source_paths, - - target_paths - ) - - if errors: - - raise gr.Error( - "\n".join( - errors[:10] - ) - ) + mappings = [ + { + "source_index": 0, + "source_face": 0, + "target_index": 0, + "target_face": 0 + } + ] if not swap_model: @@ -3078,23 +2657,21 @@ def generate_pro( if not restore_model: - restore_model = "none" + restore_model = ( + DEFAULT_RESTORE_MODEL + ) restore_strength = float( restore_strength if restore_strength is not None - else 0.70 - ) - - quality = int( - output_quality - if output_quality is not None - else 90 + else DEFAULT_RESTORE_STRENGTH ) log("=" * 70) - log("[GENERATE] START") + log( + "[GENERATE] START" + ) log( "[GENERATE] Sources:", @@ -3121,232 +2698,382 @@ def generate_pro( restore_model ) - # -------------------------------------------------------- - # Download only selected models - # -------------------------------------------------------- - - ensure_model( - swap_model + log( + "[GENERATE] Strength:", + restore_strength ) - if restore_model != "none": + log("=" * 70) + + with JOB_SEMAPHORE: + + validate_mappings( + mappings, + source_paths, + target_paths + ) ensure_model( - restore_model + swap_model ) - # -------------------------------------------------------- - # Load source tensors - # -------------------------------------------------------- + if ( + restore_model + and restore_model != "none" + ): + + ensure_model( + restore_model + ) - source_tensors = {} + output_paths = [] - try: + # ---------------------------------------------------- + # Group mapping by target + # ---------------------------------------------------- - for si, path in enumerate( - source_paths - ): + mappings_by_target = {} - log( - "[SOURCE LOAD]", - si, - path - ) + for mapping in mappings: - source_tensors[si] = ( - load_source_tensor( - path - ) - ) + target_index = mapping[ + "target_index" + ] - outputs = [] + mappings_by_target.setdefault( + target_index, + [] + ).append( + mapping + ) - total_targets = len( - target_paths - ) + # ---------------------------------------------------- + # Process each target + # ---------------------------------------------------- - for target_number, target_path in enumerate( + for target_index, target_path in enumerate( target_paths ): - progress( - target_number / max( - 1, - total_targets - ), - desc=( - f"Target " - f"{target_number + 1}/" - f"{total_targets}" + target_mappings = ( + mappings_by_target.get( + target_index, + [] ) ) - target_mappings = [ - m - for m in mappings - if m[ - "target_index" - ] == target_number - ] - if not target_mappings: + continue - is_gif = target_path.lower().endswith( - ".gif" + log( + "[TARGET]", + target_index, + target_path ) - extension = ( - output_format.lower() - ) + # ================================================ + # GIF + # ================================================ - if is_gif and extension == "gif": + if target_path.lower().endswith( + ".gif" + ): - output_path = safe_output_name( - target_path, - target_number, - "gif" + # -------------------------------------------- + # For GIF each mapping is applied sequentially + # on every frame. + # -------------------------------------------- + + reader = imageio.get_reader( + target_path ) - if ( - skip_existing - and - os.path.isfile( - output_path - ) - ): + frames = [] - outputs.append( - output_path - ) + durations = [] - continue + try: - frames, durations = ( - process_gif_target( + try: - target_path, + meta = reader.get_meta_data() - source_tensors, + except Exception: - mappings, + meta = {} - target_number, + duration = meta.get( + "duration", + 100 + ) + + for frame_index, frame in enumerate( + reader + ): + + current = ( + Image.fromarray( + frame + ).convert( + "RGB" + ) + ) + + for mapping in target_mappings: + + source_index = mapping[ + "source_index" + ] + + source_face = mapping[ + "source_face" + ] + + target_face = mapping[ + "target_face" + ] + + source_path = ( + source_paths[ + source_index + ] + ) + + with tempfile.NamedTemporaryFile( + suffix=".png", + delete=False + ) as tmp: + + temp_path = tmp.name + + try: + + current.save( + temp_path + ) + + current = ( + swap_one_image( + + source_path, + + temp_path, + + source_face, + + target_face, + + swap_model, + + restore_model, + + restore_strength + ) + ) - swap_model, + finally: - restore_model, + try: - restore_strength, + os.remove( + temp_path + ) - progress + except Exception: + pass + + frames.append( + current + ) + + durations.append( + duration + ) + + if ( + frame_index % 3 + == 0 + ): + + gc.collect() + + finally: + + reader.close() + + if not frames: + + raise gr.Error( + "GIF không có frame." + ) + + output_path = ( + make_output_path( + source_paths[ + target_mappings[0][ + "source_index" + ] + ], + target_path, + target_index ) ) - save_gif( - frames, - durations, + frames[0].save( + output_path, - quality + + save_all=True, + + append_images=frames[1:], + + duration=durations, + + loop=0, + + format="WEBP", + + quality=90, + + method=6 + ) + + output_paths.append( + output_path ) del frames del durations + gc.collect() + + # ================================================ + # NORMAL IMAGE + # ================================================ + else: - output_path = safe_output_name( - target_path, - target_number, - extension - ) + current_path = target_path - if ( - skip_existing - and - os.path.isfile( - output_path - ) + current_image = None + + first_source_path = None + + for mapping_index, mapping in enumerate( + target_mappings ): - outputs.append( - output_path + source_index = mapping[ + "source_index" + ] + + source_face = mapping[ + "source_face" + ] + + target_face = mapping[ + "target_face" + ] + + source_path = ( + source_paths[ + source_index + ] ) - continue + if first_source_path is None: - result = ( - process_target_with_mappings( + first_source_path = ( + source_path + ) - target_path, + log( + "[MAPPING]", + ( + f"SOURCE {source_index} " + f"FACE {source_face} " + f"-> TARGET {target_index} " + f"FACE {target_face}" + ) + ) + + current_image = ( + swap_one_image( - source_tensors, + source_path, - mappings, + current_path, - target_number, + source_face, - swap_model, + target_face, - restore_model, + swap_model, - restore_strength + restore_model, + + restore_strength, + + target_image_override=( + current_image + ) + ) ) - ) - save_image( - result, - output_path, - quality - ) + if current_image is None: - del result + raise RuntimeError( + "Mapping output is None." + ) - outputs.append( - output_path - ) + current_path = None - gc.collect() + if current_image is None: - log( - "[GENERATE] COMPLETE:", - outputs - ) + raise RuntimeError( + "No output generated." + ) - return outputs + output_path = ( + make_output_path( + first_source_path, + target_path, + target_index + ) + ) - finally: + current_image.save( - source_tensors.clear() + output_path, - gc.collect() + format="WEBP", - try: + quality=90, - if torch.cuda.is_available(): - torch.cuda.empty_cache() + method=6 + ) - except Exception: - pass + output_paths.append( + output_path + ) + del current_image -# ============================================================ -# PREVIEW ALL TARGET FACES -# ============================================================ + gc.collect() -def preview_target( - target_files, - target_selector -): + gc.collect() - return show_target_preview( - target_files, - target_selector + log( + "[GENERATE] OUTPUT:", + output_paths ) + return output_paths + # ============================================================ -# USE OUTPUT AS TARGET +# OUTPUT -> TARGET # ============================================================ def use_output_as_target( @@ -3357,60 +3084,132 @@ def use_output_as_target( output_files ) - paths = [ + if not paths: + + raise gr.Error( + "Chưa có output." + ) + + valid = [ + p + for p in paths + if os.path.isfile(p) ] - if not paths: + if not valid: raise gr.Error( - "Không có output." + "Không tìm thấy output." ) - return paths + return valid + + +# ============================================================ +# CLEAR TARGET +# ============================================================ + +def clear_target(): + + clear_face_cache() + + return ( + + [], + + [], + + gr.update( + choices=[], + value=None + ), + + gr.update( + choices=[], + value=None + ), + + gr.update( + choices=[], + value=None + ), + + gr.update( + choices=[], + value=None + ), + + "Target cleared." + ) + + +# ============================================================ +# CLEAR SOURCE +# ============================================================ + +def clear_source(): + + clear_face_cache() + + source_tensor_cache.clear() + + return ( + + [], + + [], + + gr.update( + choices=[], + value=None + ), + + gr.update( + choices=[], + value=None + ), + + gr.update( + choices=[], + value=None + ), + + gr.update( + choices=[], + value=None + ), + + "Source cleared." + ) # ============================================================ -# LOAD PRESET +# SAVE MAPPING JSON # ============================================================ -def save_mapping_preset( - preset_name, +def save_mapping_json( mapping_text ): - name = ( - str( - preset_name or "" - ) - .strip() - .replace( - "/", - "_" - ) - .replace( - "\\", - "_" - ) + mappings = parse_mappings( + mapping_text ) - if not name: + if not mappings: raise gr.Error( - "Nh���p tên preset." + "Mapping trống." ) - path = os.path.join( - PRESET_DIR, - f"{name}.json" + fd, path = tempfile.mkstemp( + suffix=".json", + prefix="face_mapping_" ) - data = { - "mapping": mapping_text, - "created_at": time.time() - } + os.close(fd) with open( path, @@ -3419,254 +3218,371 @@ def save_mapping_preset( ) as f: json.dump( - data, + mappings, f, ensure_ascii=False, indent=2 ) - return ( - f"Saved: {name}" - ) + return path + + +# ============================================================ +# LOAD MAPPING JSON +# ============================================================ + +def load_mapping_json( + mapping_file +): + + path = get_file_path( + mapping_file + ) + + if not path: + + raise gr.Error( + "Chưa chọn mapping JSON." + ) + + with open( + path, + "r", + encoding="utf-8" + ) as f: + + data = json.load(f) + + lines = [] + + for item in data: + + try: + + lines.append( + + f"SOURCE " + f"{int(item['source_index'])} " + f"FACE " + f"{int(item['source_face'])} " + f"-> TARGET " + f"{int(item['target_index'])} " + f"FACE " + f"{int(item['target_face'])}" + + ) + + except Exception: + continue + + return "\n".join( + lines + ) + + +# ============================================================ +# AUTO DEFAULT MAPPING +# ============================================================ + +def auto_mapping( + source_files, + target_files +): + + source_paths = get_file_paths( + source_files + ) + + target_paths = get_file_paths( + target_files + ) + + if not source_paths: + + raise gr.Error( + "Chưa có source." + ) + + if not target_paths: + + raise gr.Error( + "Chưa có target." + ) + + target_faces = detect_reactor_faces( + target_paths[0] + ) + + source_faces_all = [] + + for path in source_paths: + + source_faces_all.append( + detect_reactor_faces( + path + ) + ) + + lines = [] + + for target_face_index in range( + len(target_faces) + ): + + source_index = ( + target_face_index + if target_face_index + < len(source_paths) + else 0 + ) + + source_faces = ( + source_faces_all[ + source_index + ] + ) + + if not source_faces: + + continue + + source_face_index = 0 + + lines.append( + + f"SOURCE " + f"{source_index} " + f"FACE " + f"{source_face_index} " + f"-> TARGET 0 FACE " + f"{target_face_index}" + + ) + + if not lines: + + lines.append( + "SOURCE 0 FACE 0 " + "-> TARGET 0 FACE 0" + ) + + return "\n".join( + lines + ) + + +# ============================================================ +# STATUS +# ============================================================ + +def status_text( + source_files, + target_files, + mapping_text +): + + sources = len( + get_file_paths( + source_files + ) + ) + + targets = len( + get_file_paths( + target_files + ) + + mappings = len( + parse_mappings( + mapping_text + ) + ) + + return ( + f"Sources: {sources} | " + f"Targets: {targets} | " + f"Mappings: {mappings} | " + f"Workers: {MAX_CONCURRENT_JOBS}" + ) + + +# ============================================================ +# UI +# ============================================================ + +with gr.Blocks( + title=APP_TITLE +) as app: + + # ======================================================== + # SOURCE + # ======================================================== + + with gr.Row(): + source_files = gr.File( -def load_mapping_preset( - preset_name -): + label="Source Images", - name = str( - preset_name or "" - ).strip() + file_count="multiple", - if not name: + file_types=[ + ".jpg", + ".jpeg", + ".png", + ".webp" + ], - raise gr.Error( - "Chưa chọn preset." + type="filepath" ) - path = os.path.join( - PRESET_DIR, - f"{name}.json" - ) - - if not os.path.isfile( - path - ): + target_files = gr.File( - raise gr.Error( - "Preset không tồn tại." - ) + label="Target Images / GIF", - with open( - path, - "r", - encoding="utf-8" - ) as f: + file_count="multiple", - data = json.load(f) + file_types=[ + ".jpg", + ".jpeg", + ".png", + ".webp", + ".gif" + ], - return data.get( - "mapping", - "" - ) + type="filepath" + ) + # ======================================================== + # PREVIEW CONTROLS + # ======================================================== -def list_presets(): + with gr.Row(): - result = [] + preview_button = gr.Button( + "Preview All Faces", + variant="primary" + ) - for file in os.listdir( - PRESET_DIR - ): + clear_source_button = gr.Button( + "Clear Source" + ) - if file.lower().endswith( - ".json" - ): + clear_target_button = gr.Button( + "Clear Target" + ) - result.append( - os.path.splitext( - file - )[0] - ) + # ======================================================== + # PREVIEW GALLERY + # ======================================================== - return sorted( - result - ) + source_gallery = gr.Gallery( + label="Source Face Preview", -# ============================================================ -# DELETE PRESET -# ============================================================ + columns=2, -def delete_mapping_preset( - preset_name -): + rows=2, - name = str( - preset_name or "" - ).strip() + height="auto", - if not name: - return gr.update( - choices=list_presets() - ) + object_fit="contain", - path = os.path.join( - PRESET_DIR, - f"{name}.json" + preview=True ) - if os.path.isfile( - path - ): - - os.remove( - path - ) + target_gallery = gr.Gallery( - return gr.update( - choices=list_presets(), - value=None - ) + label="Target Face Preview", + columns=2, -# ============================================================ -# CLEAR TARGET -# ============================================================ + rows=2, -def clear_target(): + height="auto", - clear_face_cache() + object_fit="contain", - return ( - [], - None, - gr.update( - choices=[], - value=None - ), - None, - gr.update( - choices=[], - value=None - ) + preview=True ) + # ======================================================== + # SELECTORS + # ======================================================== -# ============================================================ -# CLEAR SOURCE -# ============================================================ + with gr.Row(): -def clear_source(): + source_selector = gr.Dropdown( - clear_face_cache() + label="Source Image", - return ( - [], - None, - gr.update( choices=[], - value=None + + value=None, + + interactive=True ) - ) + target_selector = gr.Dropdown( -# ============================================================ -# UI -# ============================================================ + label="Target Image", -with gr.Blocks( - title=APP_TITLE, - theme=gr.themes.Soft() -) as app: + choices=[], - # ======================================================== - # SOURCE - # ======================================================== + value=None, + + interactive=True + ) with gr.Row(): - with gr.Column( - scale=1 - ): + source_face_selector = gr.Dropdown( - source_files = gr.File( - label="SOURCE", - file_count="multiple", - file_types=SUPPORTED_IMAGES, - type="filepath" - ) + label="Source Face", - source_selector = gr.Dropdown( - label="Source Image", - choices=[], - interactive=True - ) + choices=[], - source_preview = gr.Image( - label="Source Faces", - type="numpy", - interactive=False - ) + value=None, - source_face_selector = gr.Dropdown( - label="Source Face", - choices=[], - interactive=True - ) + interactive=True + ) - with gr.Column( - scale=1 - ): + target_face_selector = gr.Dropdown( - target_files = gr.File( - label="TARGET", - file_count="multiple", - file_types=SUPPORTED_TARGETS, - type="filepath" - ) + label="Target Face", - target_selector = gr.Dropdown( - label="Target Image", - choices=[], - interactive=True - ) + choices=[], - target_preview = gr.Image( - label="Target Faces", - type="numpy", - interactive=False - ) + value=None, - target_face_selector = gr.Dropdown( - label="Target Face", - choices=[], - interactive=True - ) + interactive=True + ) # ======================================================== # MAPPING # ======================================================== - with gr.Row(): + mapping_source_selector = gr.Dropdown( - mapping_source_selector = gr.Dropdown( - label="Mapping Source Face", - choices=[], - interactive=True - ) + label="Mapping Source Face", - mapping_target_image_selector = gr.Dropdown( - label="Mapping Target Image", - choices=[], - interactive=True - ) + choices=[], - mapping_target_face_selector = gr.Dropdown( - label="Mapping Target Face", - choices=[], - interactive=True - ) + value=None, + + interactive=True + ) + + mapping_target_selector = gr.Dropdown( + + label="Mapping Target Face", + + choices=[], + + value=None, + + interactive=True + ) with gr.Row(): @@ -3680,80 +3596,67 @@ with gr.Blocks( ) clear_mapping_button = gr.Button( - "Clear" + "Clear Mapping" ) default_mapping_button = gr.Button( - "Default" + "Default Mapping" + ) + + auto_mapping_button = gr.Button( + "Auto Mapping" ) mapping_text = gr.Textbox( + label="Face Mapping", + value=default_mapping(), + lines=8, + max_lines=30, + interactive=True ) # ======================================================== - # AUTO MAPPING + # MAPPING JSON # ======================================================== with gr.Row(): - auto_mapping_mode = gr.Dropdown( - - choices=[ - "Sequential", - "Round Robin", - "First Source → All Targets", - "Same Face Index" - ], - - value="Sequential", - - label="Auto Mapping Mode" - ) - - auto_mapping_button = gr.Button( - "Auto Mapping" - ) - - # ======================================================== - # PRESET - # ======================================================== + mapping_json_upload = gr.File( - with gr.Row(): + label="Load Mapping JSON", - preset_name = gr.Textbox( - label="Preset Name" - ) + file_count="single", - save_preset_button = gr.Button( - "Save Preset" - ) + file_types=[ + ".json" + ], - preset_selector = gr.Dropdown( - label="Preset", - choices=list_presets() + type="filepath" ) - load_preset_button = gr.Button( - "Load Preset" + save_mapping_button = gr.Button( + "Save Mapping JSON" ) - delete_preset_button = gr.Button( - "Delete Preset" + load_mapping_button = gr.Button( + "Load Mapping JSON" ) # ======================================================== - # SETTINGS + # MODELS # ======================================================== with gr.Row(): swap_model = gr.Dropdown( + label="Swap Model", + choices=[ "inswapper_128.onnx", "hyperswap_1a_256.onnx", @@ -3763,224 +3666,162 @@ with gr.Blocks( value=DEFAULT_SWAP_MODEL, - label="Swap Model" + interactive=True ) restore_model = gr.Dropdown( + label="Face Restore", + choices=[ "none", - DEFAULT_RESTORE_MODEL + "GPEN-BFR-512.onnx" ], value=DEFAULT_RESTORE_MODEL, - label="Restore Model" - ) - - restore_strength = gr.Slider( - - minimum=0.0, - - maximum=1.0, - - value=0.70, - - step=0.05, - - label="Restore Strength" - ) - - with gr.Row(): - - output_format = gr.Dropdown( - - choices=[ - "webp", - "png", - "jpg", - "gif" - ], - - value="webp", - - label="Output Format" + interactive=True ) - output_quality = gr.Slider( - - minimum=50, - - maximum=100, + restore_strength = gr.Slider( - value=90, + label="Restore Strength", - step=1, + minimum=0.0, - label="Output Quality" - ) + maximum=1.0, - skip_existing = gr.Checkbox( + value=DEFAULT_RESTORE_STRENGTH, - value=False, + step=0.05, - label="Skip Existing" - ) + interactive=True + ) # ======================================================== - # ACTION + # GENERATE # ======================================================== generate_button = gr.Button( + "GENERATE MULTI FACE SWAP", + variant="primary", + size="lg" ) # ======================================================== - # OUTPUT + # STATUS # ======================================================== - output_files = gr.Files( - label="Generated Results" - ) - - output_gallery = gr.Gallery( - label="Output Preview", - columns=3, - rows=2, - object_fit="contain", - height="auto" - ) - - use_output_button = gr.Button( - "Use Output As Target" - ) + status = gr.Textbox( - clear_target_button = gr.Button( - "Clear Target" - ) + label="Status", - clear_source_button = gr.Button( - "Clear Source" - ) + value="Ready.", - status = gr.Markdown( - "" + interactive=False ) # ======================================================== - # SOURCE EVENTS + # OUTPUT # ======================================================== - source_files.change( - - fn=update_source_selector, + output_files = gr.File( - inputs=[ - source_files - ], - - outputs=[ - source_selector - ] - ) + label="Generated Results", - source_files.change( + file_count="multiple", - fn=update_mapping_source_choices, - - inputs=[ - source_files - ], - - outputs=[ - mapping_source_selector - ] + interactive=False ) - source_files.change( - - fn=lambda files: show_source_preview( - files, - None - ), + output_gallery = gr.Gallery( - inputs=[ - source_files - ], + label="Output Preview", - outputs=[ - source_preview, - source_face_selector - ] - ) + columns=3, - source_selector.change( + rows=2, - fn=show_source_preview, + height="auto", - inputs=[ - source_files, - source_selector - ], + object_fit="contain", - outputs=[ - source_preview, - source_face_selector - ] + preview=True ) # ======================================================== - # TARGET EVENTS + # OUTPUT -> TARGET # ======================================================== - target_files.change( - - fn=update_target_selector, - - inputs=[ - target_files - ], - - outputs=[ - target_selector - ] + use_output_button = gr.Button( + + "Use Output As Target + Preview" ) - target_files.change( + # ======================================================== + # PREVIEW EVENT + # ======================================================== + # + # IMPORTANT: + # + # Only ONE preview job is created for all files. + # This prevents multiple .change() events from competing + # and causing BUSY on CPU. + # + # ======================================================== + + preview_button.click( - fn=update_mapping_target_choices, + fn=preview_source_target, inputs=[ + source_files, target_files ], outputs=[ - mapping_target_image_selector - ] + source_gallery, + target_gallery, + source_selector, + target_selector, + mapping_source_selector, + mapping_target_selector, + status + ], + + concurrency_limit=2 ) - target_files.change( + # ======================================================== + # SOURCE SELECTOR + # ======================================================== - fn=lambda files: show_target_preview( - files, - None - ), + source_selector.change( + + fn=source_face_choices_from_source, inputs=[ - target_files + source_files, + source_selector ], outputs=[ - target_preview, - target_face_selector - ] + source_face_selector + ], + + concurrency_limit=2 ) + # ======================================================== + # TARGET SELECTOR + # ======================================================== + target_selector.change( - fn=show_target_preview, + fn=target_face_choices_from_target, inputs=[ target_files, @@ -3988,43 +3829,14 @@ with gr.Blocks( ], outputs=[ - target_preview, target_face_selector - ] - ) - - mapping_target_image_selector.change( - - fn=update_mapping_target_faces, - - inputs=[ - target_files, - mapping_target_image_selector - ], - - outputs=[ - mapping_target_face_selector - ] - ) - - target_files.change( - - fn=lambda files: update_mapping_target_faces( - files, - None - ), - - inputs=[ - target_files ], - outputs=[ - mapping_target_face_selector - ] + concurrency_limit=2 ) # ======================================================== - # MAPPING + # ADD MAPPING # ======================================================== add_mapping_button.click( @@ -4034,14 +3846,20 @@ with gr.Blocks( inputs=[ mapping_text, mapping_source_selector, - mapping_target_face_selector + mapping_target_selector ], outputs=[ mapping_text - ] + ], + + concurrency_limit=2 ) + # ======================================================== + # REMOVE + # ======================================================== + remove_mapping_button.click( fn=remove_last_mapping, @@ -4052,9 +3870,15 @@ with gr.Blocks( outputs=[ mapping_text - ] + ], + + concurrency_limit=2 ) + # ======================================================== + # CLEAR + # ======================================================== + clear_mapping_button.click( fn=clear_mapping, @@ -4063,9 +3887,15 @@ with gr.Blocks( outputs=[ mapping_text - ] + ], + + concurrency_limit=2 ) + # ======================================================== + # DEFAULT + # ======================================================== + default_mapping_button.click( fn=default_mapping, @@ -4074,7 +3904,9 @@ with gr.Blocks( outputs=[ mapping_text - ] + ], + + concurrency_limit=2 ) # ======================================================== @@ -4087,152 +3919,61 @@ with gr.Blocks( inputs=[ source_files, - target_files, - auto_mapping_mode + target_files ], outputs=[ mapping_text - ] + ], + + concurrency_limit=2 ) # ======================================================== - # PRESETS + # SAVE MAPPING # ======================================================== - save_preset_button.click( + save_mapping_button.click( - fn=save_mapping_preset, + fn=save_mapping_json, inputs=[ - preset_name, mapping_text ], outputs=[ - status - ] - ) - - save_preset_button.click( - - fn=lambda: gr.update( - choices=list_presets() - ), - - inputs=[], + mapping_json_upload + ], - outputs=[ - preset_selector - ] + concurrency_limit=2 ) - load_preset_button.click( + # ======================================================== + # LOAD MAPPING + # ======================================================== - fn=load_mapping_preset, + load_mapping_button.click( + + fn=load_mapping_json, inputs=[ - preset_selector + mapping_json_upload ], outputs=[ mapping_text - ] - ) - - delete_preset_button.click( - - fn=delete_mapping_preset, - - inputs=[ - preset_selector ], - outputs=[ - preset_selector - ] + concurrency_limit=2 ) # ======================================================== # GENERATE # ======================================================== - def generate_ui( - source_files, - target_files, - mapping_text, - swap_model, - restore_model, - restore_strength, - output_format, - output_quality, - skip_existing, - progress=gr.Progress() - ): - - try: - - results = generate_pro( - - source_files, - - target_files, - - mapping_text, - - swap_model, - - restore_model, - - restore_strength, - - output_format, - - output_quality, - - skip_existing, - - progress - ) - - gallery = [] - - for path in results: - - if os.path.isfile(path): - - gallery.append( - path - ) - - return ( - results, - gallery, - ( - f"Done: " - f"{len(results)} output" - ) - ) - - except gr.Error: - raise - - except Exception as e: - - log( - "[GENERATE ERROR]", - repr(e) - ) - - gc.collect() - - raise gr.Error( - f"Generate failed: {e}" - ) - generate_button.click( - fn=generate_ui, + fn=generate_image, inputs=[ source_files, @@ -4240,17 +3981,27 @@ with gr.Blocks( mapping_text, swap_model, restore_model, - restore_strength, - output_format, - output_quality, - skip_existing + restore_strength ], outputs=[ - output_files, - output_gallery, - status - ] + output_files + ], + + concurrency_limit=2 + ).then( + + fn=lambda files: files, + + inputs=[ + output_files + ], + + outputs=[ + output_gallery + ], + + concurrency_limit=2 ) # ======================================================== @@ -4267,53 +4018,87 @@ with gr.Blocks( outputs=[ target_files - ] + ], + + concurrency_limit=2 + ).then( + + fn=preview_source_target, + + inputs=[ + source_files, + target_files + ], + + outputs=[ + source_gallery, + target_gallery, + source_selector, + target_selector, + mapping_source_selector, + mapping_target_selector, + status + ], + + concurrency_limit=2 ) # ======================================================== - # CLEAR TARGET + # CLEAR SOURCE # ======================================================== - clear_target_button.click( + clear_source_button.click( - fn=clear_target, + fn=clear_source, inputs=[], outputs=[ - target_files, - target_preview, - target_face_selector, - mapping_target_image_selector, - mapping_target_face_selector - ] + source_gallery, + target_gallery, + source_selector, + target_selector, + mapping_source_selector, + mapping_target_selector, + status + ], + + concurrency_limit=2 ) # ======================================================== - # CLEAR SOURCE + # CLEAR TARGET # ======================================================== - clear_source_button.click( + clear_target_button.click( - fn=clear_source, + fn=clear_target, inputs=[], outputs=[ - source_files, - source_preview, - source_face_selector - ] + source_gallery, + target_gallery, + source_selector, + target_selector, + mapping_source_selector, + mapping_target_selector, + status + ], + + concurrency_limit=2 ) # ============================================================ -# QUEUE +# GRADIO QUEUE # ============================================================ app.queue( - max_size=1, - default_concurrency_limit=1 + + max_size=GRADIO_QUEUE_SIZE, + + default_concurrency_limit=MAX_CONCURRENT_JOBS ) @@ -4321,76 +4106,86 @@ app.queue( # START # ============================================================ -if __name__ == "__main__": +log("=" * 70) - log("=" * 70) +log( + "[APP] Starting:", + APP_TITLE +) - log( - "[APP] Starting:", - APP_TITLE - ) +log( + "[APP] Device: CPU" +) - log( - "[APP] Device: CPU" - ) +log( + "[APP] Swap:", + DEFAULT_SWAP_MODEL +) - log( - "[APP] ComfyUI:", - COMFY_VERSION - ) +log( + "[APP] Restore:", + DEFAULT_RESTORE_MODEL +) - log( - "[APP] Swap:", - DEFAULT_SWAP_MODEL - ) +log( + "[APP] RAM profile: 16 GB" +) - log( - "[APP] Restore:", - DEFAULT_RESTORE_MODEL - ) +log( + "[APP] Concurrent jobs:", + MAX_CONCURRENT_JOBS +) - log( - "[APP] Multi Source Face: ENABLED" - ) +log( + "[APP] Concurrent inference:", + MAX_CONCURRENT_INFERENCE +) - log( - "[APP] Multi Target Face: ENABLED" - ) +log( + "[APP] Multi Source Face: ENABLED" +) - log( - "[APP] Face Mapping: ENABLED" - ) +log( + "[APP] Multi Target Face: ENABLED" +) - log( - "[APP] Auto Mapping: ENABLED" - ) +log( + "[APP] Face Mapping: ENABLED" +) - log( - "[APP] Mapping Preset: ENABLED" - ) +log( + "[APP] GIF: ENABLED" +) - log( - "[APP] GIF: ENABLED" - ) +log( + "[APP] Face Preview Labels: ENABLED" +) - log( - "[APP] GPEN Fallback: ENABLED" - ) +log( + "[APP] Preview Batch Mode: ENABLED" +) - log( - "[APP] Output Resume: ENABLED" - ) +log("=" * 70) - log("=" * 70) + +# ============================================================ +# LAUNCH +# ============================================================ + +if __name__ == "__main__": app.launch( + server_name="0.0.0.0", + server_port=int( os.environ.get( "PORT", "7860" ) ), + share=True, + show_error=True ) \ No newline at end of file