Spaces:
Running
on
Zero
Running
on
Zero
Upload nodes.py
Browse files
custom_nodes/comfyui-reactor-node/nodes.py
CHANGED
|
@@ -2,8 +2,7 @@ import os, glob, sys
|
|
| 2 |
import logging
|
| 3 |
|
| 4 |
import torch
|
| 5 |
-
import torch.nn.functional as
|
| 6 |
-
import torchvision.transforms as T
|
| 7 |
from torchvision.transforms.functional import normalize
|
| 8 |
from torchvision.ops import masks_to_boxes
|
| 9 |
|
|
@@ -12,7 +11,6 @@ import cv2
|
|
| 12 |
import math
|
| 13 |
from typing import List
|
| 14 |
from PIL import Image
|
| 15 |
-
import io
|
| 16 |
from scipy import stats
|
| 17 |
from insightface.app.common import Face
|
| 18 |
from segment_anything import sam_model_registry
|
|
@@ -23,6 +21,7 @@ from modules.shared import state
|
|
| 23 |
import comfy.model_management as model_management
|
| 24 |
import comfy.utils
|
| 25 |
import folder_paths
|
|
|
|
| 26 |
|
| 27 |
import scripts.reactor_version
|
| 28 |
from r_chainner import model_loading
|
|
@@ -51,9 +50,7 @@ from reactor_utils import (
|
|
| 51 |
prepare_cropped_face,
|
| 52 |
normalize_cropped_face,
|
| 53 |
add_folder_path_and_extensions,
|
| 54 |
-
rgba2rgb_tensor
|
| 55 |
-
progress_bar,
|
| 56 |
-
progress_bar_reset
|
| 57 |
)
|
| 58 |
from reactor_patcher import apply_patch
|
| 59 |
from r_facelib.utils.face_restoration_helper import FaceRestoreHelper
|
|
@@ -63,19 +60,39 @@ import scripts.r_masking.subcore as subcore
|
|
| 63 |
import scripts.r_masking.core as core
|
| 64 |
import scripts.r_masking.segs as masking_segs
|
| 65 |
|
| 66 |
-
|
| 67 |
models_dir = folder_paths.models_dir
|
| 68 |
REACTOR_MODELS_PATH = os.path.join(models_dir, "reactor")
|
| 69 |
FACE_MODELS_PATH = os.path.join(REACTOR_MODELS_PATH, "faces")
|
| 70 |
|
|
|
|
|
|
|
|
|
|
| 71 |
if not os.path.exists(REACTOR_MODELS_PATH):
|
| 72 |
os.makedirs(REACTOR_MODELS_PATH)
|
| 73 |
if not os.path.exists(FACE_MODELS_PATH):
|
| 74 |
os.makedirs(FACE_MODELS_PATH)
|
| 75 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
dir_facerestore_models = os.path.join(models_dir, "facerestore_models")
|
| 77 |
os.makedirs(dir_facerestore_models, exist_ok=True)
|
| 78 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
|
| 80 |
BLENDED_FACE_MODEL = None
|
| 81 |
FACE_SIZE: int = 512
|
|
@@ -155,8 +172,7 @@ class reactor:
|
|
| 155 |
"hidden": {"faces_order": "FACES_ORDER"},
|
| 156 |
}
|
| 157 |
|
| 158 |
-
RETURN_TYPES = ("IMAGE","FACE_MODEL"
|
| 159 |
-
RETURN_NAMES = ("SWAPPED_IMAGE","FACE_MODEL","ORIGINAL_IMAGE")
|
| 160 |
FUNCTION = "execute"
|
| 161 |
CATEGORY = "🌌 ReActor"
|
| 162 |
|
|
@@ -170,37 +186,24 @@ class reactor:
|
|
| 170 |
self.interpolation = "Bicubic"
|
| 171 |
self.boost_model_visibility = 1
|
| 172 |
self.boost_cf_weight = 0.5
|
| 173 |
-
|
|
|
|
| 174 |
def restore_face(
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
sort_by="area",
|
| 183 |
-
descending=True,
|
| 184 |
-
min_x_position=0.0,
|
| 185 |
-
max_x_position=1.0,
|
| 186 |
-
min_y_position=0.0,
|
| 187 |
-
max_y_position=1.0,
|
| 188 |
-
take_start=0,
|
| 189 |
-
take_count=1,
|
| 190 |
-
face_index=0,
|
| 191 |
-
):
|
| 192 |
-
|
| 193 |
-
# >>>>> ПРИНУДИТЕЛЬНЫЙ ВЫВОД ОТЛАДКИ <<<<<
|
| 194 |
-
# print(f"\n--- [ReActor Debug] Face selection: {face_selection}, Sort by: {sort_by}, Descending: {descending}")
|
| 195 |
-
|
| 196 |
result = input_image
|
| 197 |
|
| 198 |
if face_restore_model != "none" and not model_management.processing_interrupted():
|
| 199 |
-
|
| 200 |
global FACE_SIZE, FACE_HELPER
|
| 201 |
|
| 202 |
self.face_helper = FACE_HELPER
|
| 203 |
|
|
|
|
| 204 |
faceSize = 512
|
| 205 |
if "1024" in face_restore_model.lower():
|
| 206 |
faceSize = 1024
|
|
@@ -209,9 +212,30 @@ class reactor:
|
|
| 209 |
|
| 210 |
logger.status(f"Restoring with {face_restore_model} | Face Size is set to {faceSize}")
|
| 211 |
|
|
|
|
| 212 |
model_path = folder_paths.get_full_path("facerestore_models", face_restore_model)
|
| 213 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 214 |
device = model_management.get_torch_device()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 215 |
|
| 216 |
if "codeformer" in face_restore_model.lower():
|
| 217 |
|
|
@@ -243,19 +267,16 @@ class reactor:
|
|
| 243 |
FACE_SIZE = faceSize
|
| 244 |
FACE_HELPER = self.face_helper
|
| 245 |
|
| 246 |
-
|
| 247 |
-
image_np = 255. * result.cpu().numpy()
|
| 248 |
|
| 249 |
total_images = image_np.shape[0]
|
| 250 |
|
| 251 |
out_images = []
|
| 252 |
|
| 253 |
-
pbar = progress_bar(total_images)
|
| 254 |
-
|
| 255 |
for i in range(total_images):
|
| 256 |
|
| 257 |
-
|
| 258 |
-
|
| 259 |
|
| 260 |
cur_image_np = image_np[i,:, :, ::-1]
|
| 261 |
|
|
@@ -269,110 +290,16 @@ class reactor:
|
|
| 269 |
self.face_helper.get_face_landmarks_5(only_center_face=False, resize=640, eye_dist_threshold=5)
|
| 270 |
self.face_helper.align_warp_face()
|
| 271 |
|
| 272 |
-
# Фильтрация лиц
|
| 273 |
-
if face_selection != "all" and self.face_helper.cropped_faces:
|
| 274 |
-
# Собираем информацию о лицах для фильтрации
|
| 275 |
-
face_info = []
|
| 276 |
-
img_height, img_width = cur_image_np.shape[0:2]
|
| 277 |
-
|
| 278 |
-
for j, face in enumerate(self.face_helper.cropped_faces):
|
| 279 |
-
# Используем центр лица вместо левого верхнего угла
|
| 280 |
-
if hasattr(self.face_helper, 'det_faces') and len(self.face_helper.det_faces) > j:
|
| 281 |
-
bbox = self.face_helper.det_faces[j]
|
| 282 |
-
# Вычисляем центр лица для более точного позиционирования
|
| 283 |
-
x1 = ((bbox[0] + bbox[2]) / 2) / img_width # центр x
|
| 284 |
-
y1 = ((bbox[1] + bbox[3]) / 2) / img_height # центр y
|
| 285 |
-
area = face.shape[0] * face.shape[1]
|
| 286 |
-
confidence = bbox[4] if len(bbox) > 4 else 1.0
|
| 287 |
-
else:
|
| 288 |
-
# Если информация о bbox недоступна, используем приблизительные данные
|
| 289 |
-
area = face.shape[0] * face.shape[1]
|
| 290 |
-
x1, y1 = 0.5, 0.5 # центр изображения
|
| 291 |
-
confidence = 1.0
|
| 292 |
-
|
| 293 |
-
face_info.append({
|
| 294 |
-
'index': j,
|
| 295 |
-
'area': area,
|
| 296 |
-
'x_position': x1,
|
| 297 |
-
'y_position': y1,
|
| 298 |
-
'detection_confidence': confidence
|
| 299 |
-
})
|
| 300 |
-
|
| 301 |
-
# Сначала сортируем все лица по выбранному критерию
|
| 302 |
-
all_indices = list(range(len(self.face_helper.cropped_faces)))
|
| 303 |
-
|
| 304 |
-
# Отладочный вывод перед сортировкой
|
| 305 |
-
# print(f"--- [ReActor Debug] Sorting all faces by {sort_by}, descending={descending}")
|
| 306 |
-
|
| 307 |
-
# Вывод для x_position и y_position
|
| 308 |
-
if sort_by == "y_position":
|
| 309 |
-
all_positions = [(idx, face_info[idx]['y_position']) for idx in all_indices]
|
| 310 |
-
# print(f"--- [ReActor Debug] All positions before sort: {all_positions}")
|
| 311 |
-
elif sort_by == "x_position":
|
| 312 |
-
all_positions = [(idx, face_info[idx]['x_position']) for idx in all_indices]
|
| 313 |
-
# print(f"--- [ReActor Debug] All X positions before sort: {all_positions}")
|
| 314 |
-
|
| 315 |
-
# Сортировка по выбранному критерию
|
| 316 |
-
sorted_indices = sorted(
|
| 317 |
-
all_indices,
|
| 318 |
-
key=lambda idx: face_info[idx][sort_by],
|
| 319 |
-
reverse=descending
|
| 320 |
-
)
|
| 321 |
-
|
| 322 |
-
# Отладочный вывод после сортировки
|
| 323 |
-
if sort_by == "y_position":
|
| 324 |
-
sorted_positions = [(idx, face_info[idx]['y_position']) for idx in sorted_indices]
|
| 325 |
-
# print(f"--- [ReActor Debug] All positions after sort: {sorted_positions}")
|
| 326 |
-
elif sort_by == "x_position":
|
| 327 |
-
sorted_positions = [(idx, face_info[idx]['x_position']) for idx in sorted_indices]
|
| 328 |
-
# print(f"--- [ReActor Debug] All X positions after sort: {sorted_positions}")
|
| 329 |
-
|
| 330 |
-
# Применяем фильтрацию в зависимости от режима
|
| 331 |
-
if face_selection == "filter":
|
| 332 |
-
# Фильтрация по координатам
|
| 333 |
-
filtered_indices = [
|
| 334 |
-
idx for idx in sorted_indices
|
| 335 |
-
if min_x_position <= face_info[idx]['x_position'] <= max_x_position and
|
| 336 |
-
min_y_position <= face_info[idx]['y_position'] <= max_y_position
|
| 337 |
-
]
|
| 338 |
-
|
| 339 |
-
# print(f"--- [ReActor Debug] Filtered faces: {len(filtered_indices)}")
|
| 340 |
-
|
| 341 |
-
# Выборка по take_start и take_count
|
| 342 |
-
selected_indices = filtered_indices[take_start:take_start + take_count]
|
| 343 |
-
|
| 344 |
-
elif face_selection == "largest":
|
| 345 |
-
# При выборе "largest" просто берем take_count лиц с наибольшей площадью, начиная с take_start
|
| 346 |
-
selected_indices = sorted_indices[take_start:take_start + take_count]
|
| 347 |
-
# print(f"--- [ReActor Debug] Selected {take_count} face(s) starting from {take_start}: {selected_indices}")
|
| 348 |
-
|
| 349 |
-
elif face_selection == "index":
|
| 350 |
-
# В режиме "index" просто берем лица, начиная с take_start
|
| 351 |
-
selected_indices = sorted_indices[take_start:take_start + take_count]
|
| 352 |
-
# print(f"--- [ReActor Debug] Selected {take_count} face(s) starting from {take_start}: {selected_indices}")
|
| 353 |
-
|
| 354 |
-
# Дополнительная отладочная информация
|
| 355 |
-
# for i, idx in enumerate(selected_indices):
|
| 356 |
-
# if sort_by == "x_position":
|
| 357 |
-
# print(f"--- [ReActor Debug] Selected face {i}: X position = {face_info[idx]['x_position']}")
|
| 358 |
-
# elif sort_by == "y_position":
|
| 359 |
-
# print(f"--- [ReActor Debug] Selected face {i}: Y position = {face_info[idx]['y_position']}")
|
| 360 |
-
|
| 361 |
-
# Применяем фильтрацию ко всем спискам
|
| 362 |
-
# print(f"--- [ReActor Debug] Final selected indices: {selected_indices}")
|
| 363 |
-
if selected_indices:
|
| 364 |
-
self.face_helper.cropped_faces = [self.face_helper.cropped_faces[j] for j in selected_indices]
|
| 365 |
-
if hasattr(self.face_helper, 'restored_faces'):
|
| 366 |
-
self.face_helper.restored_faces = []
|
| 367 |
-
if hasattr(self.face_helper, 'affine_matrices'):
|
| 368 |
-
self.face_helper.affine_matrices = [self.face_helper.affine_matrices[j] for j in selected_indices]
|
| 369 |
-
if hasattr(self.face_helper, 'det_faces'):
|
| 370 |
-
self.face_helper.det_faces = [self.face_helper.det_faces[j] for j in selected_indices]
|
| 371 |
-
|
| 372 |
restored_face = None
|
| 373 |
|
|
|
|
| 374 |
for idx, cropped_face in enumerate(self.face_helper.cropped_faces):
|
| 375 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 376 |
# if ".pth" in face_restore_model:
|
| 377 |
cropped_face_t = img2tensor(cropped_face / 255., bgr2rgb=True, float32=True)
|
| 378 |
normalize(cropped_face_t, (0.5, 0.5, 0.5), (0.5, 0.5, 0.5), inplace=True)
|
|
@@ -381,33 +308,43 @@ class reactor:
|
|
| 381 |
try:
|
| 382 |
|
| 383 |
with torch.no_grad():
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
ort_session_inputs[
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
output = ort_session.run(None, ort_session_inputs)[0][0]
|
|
|
|
| 396 |
restored_face = normalize_cropped_face(output)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 397 |
|
| 398 |
-
else: # PTH models
|
| 399 |
-
|
| 400 |
-
output = facerestore_model(cropped_face_t, w=codeformer_weight)[0] if "codeformer" in face_restore_model.lower() else facerestore_model(cropped_face_t)[0]
|
| 401 |
restored_face = tensor2img(output, rgb2bgr=True, min_max=(-1, 1))
|
| 402 |
-
|
|
|
|
|
|
|
| 403 |
del output
|
| 404 |
torch.cuda.empty_cache()
|
| 405 |
|
| 406 |
except Exception as error:
|
| 407 |
-
|
| 408 |
print(f"\tFailed inference: {error}", file=sys.stderr)
|
| 409 |
restored_face = tensor2img(cropped_face_t, rgb2bgr=True, min_max=(-1, 1))
|
| 410 |
|
|
|
|
| 411 |
if face_restore_visibility < 1:
|
| 412 |
restored_face = cropped_face * (1 - face_restore_visibility) + restored_face * face_restore_visibility
|
| 413 |
|
|
@@ -430,24 +367,15 @@ class reactor:
|
|
| 430 |
if state.interrupted or model_management.processing_interrupted():
|
| 431 |
logger.status("Interrupted by User")
|
| 432 |
return input_image
|
| 433 |
-
|
| 434 |
-
pbar.update(1)
|
| 435 |
|
| 436 |
restored_img_np = np.array(out_images).astype(np.float32) / 255.0
|
| 437 |
restored_img_tensor = torch.from_numpy(restored_img_np)
|
| 438 |
|
| 439 |
result = restored_img_tensor
|
| 440 |
|
| 441 |
-
progress_bar_reset(pbar)
|
| 442 |
-
|
| 443 |
return result
|
| 444 |
-
|
| 445 |
-
def execute(self, enabled, input_image, swap_model, detect_gender_source, detect_gender_input, source_faces_index, input_faces_index, console_log_level, face_restore_model,
|
| 446 |
-
|
| 447 |
-
device = model_management.get_torch_device()
|
| 448 |
-
|
| 449 |
-
if isinstance(input_image, torch.Tensor) and input_image.device != device:
|
| 450 |
-
input_image = input_image.to(device)
|
| 451 |
|
| 452 |
if face_boost is not None:
|
| 453 |
self.face_boost_enabled = face_boost["enabled"]
|
|
@@ -473,35 +401,8 @@ class reactor:
|
|
| 473 |
if face_model == "none":
|
| 474 |
face_model = None
|
| 475 |
|
| 476 |
-
# Сохраняем параметры для последующего использования при restore
|
| 477 |
-
target_indices = []
|
| 478 |
-
if input_faces_index == "0" or input_faces_index == "":
|
| 479 |
-
target_indices = [0]
|
| 480 |
-
else:
|
| 481 |
-
try:
|
| 482 |
-
target_indices = [int(x.strip()) for x in input_faces_index.split(",") if x.strip()]
|
| 483 |
-
except:
|
| 484 |
-
target_indices = [0]
|
| 485 |
-
|
| 486 |
-
# Определяем параметры сортировки
|
| 487 |
-
sort_by = "area"
|
| 488 |
-
descending = True
|
| 489 |
-
if faces_order is not None:
|
| 490 |
-
input_order = faces_order[0]
|
| 491 |
-
if input_order in ["left-right", "right-left"]:
|
| 492 |
-
sort_by = "x_position"
|
| 493 |
-
descending = (input_order == "right-left")
|
| 494 |
-
elif input_order in ["top-bottom", "bottom-top"]:
|
| 495 |
-
sort_by = "y_position"
|
| 496 |
-
descending = (input_order == "bottom-top")
|
| 497 |
-
elif input_order in ["small-large", "large-small"]:
|
| 498 |
-
sort_by = "area"
|
| 499 |
-
descending = (input_order == "large-small")
|
| 500 |
-
|
| 501 |
-
# Выполняем face swap
|
| 502 |
script = FaceSwapScript()
|
| 503 |
pil_images = batch_tensor_to_pil(input_image)
|
| 504 |
-
|
| 505 |
if source_image is not None:
|
| 506 |
source = tensor_to_pil(source_image)
|
| 507 |
else:
|
|
@@ -527,8 +428,7 @@ class reactor:
|
|
| 527 |
codeformer_weight=self.boost_cf_weight,
|
| 528 |
interpolation=self.interpolation,
|
| 529 |
)
|
| 530 |
-
|
| 531 |
-
original_image = batched_pil_to_tensor(pil_images)
|
| 532 |
|
| 533 |
if face_model is None:
|
| 534 |
current_face_model = get_current_faces_model()
|
|
@@ -536,100 +436,11 @@ class reactor:
|
|
| 536 |
else:
|
| 537 |
face_model_to_provide = face_model
|
| 538 |
|
| 539 |
-
# Применяем restore face к результату face swap
|
| 540 |
if self.restore or not self.face_boost_enabled:
|
| 541 |
-
|
| 542 |
-
|
| 543 |
-
|
| 544 |
-
|
| 545 |
-
swapped_img_tensor = swapped_result[0].cpu()
|
| 546 |
-
swapped_img_np = (255 * swapped_img_tensor.numpy()).astype(np.uint8)
|
| 547 |
-
swapped_img_pil = Image.fromarray(swapped_img_np)
|
| 548 |
-
swapped_img_cv = cv2.cvtColor(np.array(swapped_img_pil), cv2.COLOR_RGB2BGR)
|
| 549 |
-
|
| 550 |
-
# Определяем лица после face swap
|
| 551 |
-
face_analyser = get_current_faces_model()
|
| 552 |
-
detected_faces = analyze_faces(swapped_img_cv, (640, 640))
|
| 553 |
-
|
| 554 |
-
if not detected_faces:
|
| 555 |
-
# Пробуем с меньшим размером детекции
|
| 556 |
-
detected_faces = analyze_faces(swapped_img_cv, (320, 320))
|
| 557 |
-
|
| 558 |
-
if detected_faces:
|
| 559 |
-
# Сортируем лица тем же способом, что и в face swap
|
| 560 |
-
if sort_by == "x_position":
|
| 561 |
-
detected_faces.sort(key=lambda x: (x.bbox[0] + x.bbox[2])/2, reverse=descending)
|
| 562 |
-
elif sort_by == "y_position":
|
| 563 |
-
detected_faces.sort(key=lambda x: (x.bbox[1] + x.bbox[3])/2, reverse=descending)
|
| 564 |
-
elif sort_by == "area":
|
| 565 |
-
detected_faces.sort(key=lambda x: (x.bbox[2]-x.bbox[0])*(x.bbox[3]-x.bbox[1]), reverse=descending)
|
| 566 |
-
|
| 567 |
-
# Выбираем лица по тем же индексам, что и для face swap
|
| 568 |
-
for idx in target_indices:
|
| 569 |
-
if idx < len(detected_faces):
|
| 570 |
-
face = detected_faces[idx]
|
| 571 |
-
# Сохраняем координаты центра лица
|
| 572 |
-
center_x = (face.bbox[0] + face.bbox[2]) / 2 / swapped_img_cv.shape[1] # нормализуем
|
| 573 |
-
center_y = (face.bbox[1] + face.bbox[3]) / 2 / swapped_img_cv.shape[0] # нормализуем
|
| 574 |
-
target_faces_coords.append((center_x, center_y))
|
| 575 |
-
|
| 576 |
-
# print(f"--- [ReActor Debug] Detected face coordinates after swap: {target_faces_coords}")
|
| 577 |
-
# else:
|
| 578 |
-
# print("--- [ReActor Debug] No faces detected after face swap")
|
| 579 |
-
|
| 580 |
-
except Exception as e:
|
| 581 |
-
# print(f"--- [ReActor Debug] Error analyzing faces after swap: {str(e)}")
|
| 582 |
-
target_faces_coords = []
|
| 583 |
-
|
| 584 |
-
# Если определены координаты лиц, применяем restore только к ним
|
| 585 |
-
if target_faces_coords:
|
| 586 |
-
# Используем небольшой отступ вокруг каждого лица
|
| 587 |
-
margin = 0.15 # 15% от размера изображения
|
| 588 |
-
|
| 589 |
-
restored_result = swapped_result
|
| 590 |
-
for center_x, center_y in target_faces_coords:
|
| 591 |
-
min_x = max(0.0, center_x - margin)
|
| 592 |
-
max_x = min(1.0, center_x + margin)
|
| 593 |
-
min_y = max(0.0, center_y - margin)
|
| 594 |
-
max_y = min(1.0, center_y + margin)
|
| 595 |
-
|
| 596 |
-
# print(f"--- [ReActor Debug] Restoring faces in region: x={min_x:.2f}-{max_x:.2f}, y={min_y:.2f}-{max_y:.2f}")
|
| 597 |
-
|
| 598 |
-
# Применяем restore_face к указанной области
|
| 599 |
-
restored_result = reactor.restore_face(
|
| 600 |
-
self,
|
| 601 |
-
restored_result,
|
| 602 |
-
face_restore_model,
|
| 603 |
-
face_restore_visibility,
|
| 604 |
-
codeformer_weight,
|
| 605 |
-
facedetection,
|
| 606 |
-
"filter", # Используем filter для выбора по координатам
|
| 607 |
-
sort_by,
|
| 608 |
-
descending,
|
| 609 |
-
min_x,
|
| 610 |
-
max_x,
|
| 611 |
-
min_y,
|
| 612 |
-
max_y,
|
| 613 |
-
0, # take_start
|
| 614 |
-
10 # take_count - берем больше лиц для надежности
|
| 615 |
-
)
|
| 616 |
-
|
| 617 |
-
return (restored_result, face_model_to_provide, original_image)
|
| 618 |
-
else:
|
| 619 |
-
# Если координаты не определены, восстанавливаем все лица
|
| 620 |
-
# print("--- [ReActor Debug] Falling back to restoring all faces")
|
| 621 |
-
restored_result = reactor.restore_face(
|
| 622 |
-
self,
|
| 623 |
-
swapped_result,
|
| 624 |
-
face_restore_model,
|
| 625 |
-
face_restore_visibility,
|
| 626 |
-
codeformer_weight,
|
| 627 |
-
facedetection
|
| 628 |
-
)
|
| 629 |
-
return (restored_result, face_model_to_provide, original_image)
|
| 630 |
-
else:
|
| 631 |
-
# Если restore не требуется
|
| 632 |
-
return (swapped_result, face_model_to_provide, original_image)
|
| 633 |
|
| 634 |
class ReActorPlusOpt:
|
| 635 |
@classmethod
|
|
@@ -652,8 +463,7 @@ class ReActorPlusOpt:
|
|
| 652 |
}
|
| 653 |
}
|
| 654 |
|
| 655 |
-
RETURN_TYPES = ("IMAGE","FACE_MODEL"
|
| 656 |
-
RETURN_NAMES = ("SWAPPED_IMAGE","FACE_MODEL","ORIGINAL_IMAGE")
|
| 657 |
FUNCTION = "execute"
|
| 658 |
CATEGORY = "🌌 ReActor"
|
| 659 |
|
|
@@ -1010,44 +820,40 @@ class RestoreFace:
|
|
| 1010 |
"model": (get_model_names(get_restorers),),
|
| 1011 |
"visibility": ("FLOAT", {"default": 1, "min": 0.0, "max": 1, "step": 0.05}),
|
| 1012 |
"codeformer_weight": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1, "step": 0.05}),
|
| 1013 |
-
"face_selection": (["all", "filter", "largest"],{"default": "all"}), # ["all", "filter", "largest", "index"]
|
| 1014 |
},
|
| 1015 |
-
"optional": {
|
| 1016 |
-
"sort_by": (["area", "x_position", "y_position", "detection_confidence"],{"default": "area"}),
|
| 1017 |
-
"descending": ("BOOLEAN", {"default": True}),
|
| 1018 |
-
# "min_x_position": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.01}),
|
| 1019 |
-
# "max_x_position": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
|
| 1020 |
-
# "min_y_position": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.01}),
|
| 1021 |
-
# "max_y_position": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
|
| 1022 |
-
"take_start": ("INT", {"default": 0, "min": 0, "max": 100, "step": 1}),
|
| 1023 |
-
"take_count": ("INT", {"default": 1, "min": 1, "max": 100, "step": 1}),
|
| 1024 |
-
# "face_index": ("INT", {"default": 0, "min": 0, "max": 100, "step": 1}),
|
| 1025 |
-
}
|
| 1026 |
}
|
| 1027 |
-
|
| 1028 |
RETURN_TYPES = ("IMAGE",)
|
| 1029 |
FUNCTION = "execute"
|
| 1030 |
CATEGORY = "🌌 ReActor"
|
| 1031 |
|
| 1032 |
-
def
|
| 1033 |
-
|
| 1034 |
-
|
| 1035 |
-
|
| 1036 |
-
|
| 1037 |
-
|
| 1038 |
-
min_y_position, max_y_position, take_start, take_count, face_index
|
| 1039 |
-
)
|
| 1040 |
return (result,)
|
| 1041 |
|
| 1042 |
|
| 1043 |
class MaskHelper:
|
| 1044 |
def __init__(self):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1045 |
self.labels = "all"
|
| 1046 |
self.detailer_hook = None
|
| 1047 |
self.device_mode = "AUTO"
|
| 1048 |
self.detection_hint = "center-1"
|
| 1049 |
-
self.
|
| 1050 |
-
self.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1051 |
|
| 1052 |
@classmethod
|
| 1053 |
def INPUT_TYPES(s):
|
|
@@ -1085,114 +891,82 @@ class MaskHelper:
|
|
| 1085 |
CATEGORY = "🌌 ReActor"
|
| 1086 |
|
| 1087 |
def execute(self, image, swapped_image, bbox_model_name, bbox_threshold, bbox_dilation, bbox_crop_factor, bbox_drop_size, sam_model_name, sam_dilation, sam_threshold, bbox_expansion, mask_hint_threshold, mask_hint_use_negative, morphology_operation, morphology_distance, blur_radius, sigma_factor, mask_optional=None):
|
| 1088 |
-
device = model_management.get_torch_device()
|
| 1089 |
|
| 1090 |
# images = [image[i:i + 1, ...] for i in range(image.shape[0])]
|
| 1091 |
-
# Оптимально перемещаем тензоры
|
| 1092 |
-
if isinstance(image, torch.Tensor) and image.device != device:
|
| 1093 |
-
image = image.to(device)
|
| 1094 |
|
| 1095 |
images = image
|
| 1096 |
|
| 1097 |
-
if mask_optional is
|
| 1098 |
-
|
| 1099 |
-
|
| 1100 |
-
|
| 1101 |
-
|
| 1102 |
-
|
| 1103 |
-
|
| 1104 |
-
|
| 1105 |
-
|
| 1106 |
-
|
| 1107 |
-
|
| 1108 |
-
|
| 1109 |
-
|
| 1110 |
-
|
| 1111 |
-
|
| 1112 |
-
|
| 1113 |
-
|
| 1114 |
-
|
| 1115 |
-
|
| 1116 |
-
|
| 1117 |
-
|
| 1118 |
-
|
| 1119 |
-
|
| 1120 |
-
else:
|
| 1121 |
-
model_kind = 'vit_b'
|
| 1122 |
-
sam = sam_model_registry[model_kind](checkpoint=sam_model_path)
|
| 1123 |
-
size = os.path.getsize(sam_model_path)
|
| 1124 |
-
sam.safe_to = core.SafeToGPU(size)
|
| 1125 |
-
sam.safe_to.to_device(sam, device)
|
| 1126 |
-
sam.is_auto_mode = self.device_mode == "AUTO"
|
| 1127 |
-
self._sam_cache[sam_model_name] = sam
|
| 1128 |
-
else:
|
| 1129 |
-
sam = self._sam_cache[sam_model_name]
|
| 1130 |
-
|
| 1131 |
-
# Handle batched input
|
| 1132 |
-
if image.ndim == 4:
|
| 1133 |
-
combined_masks = []
|
| 1134 |
-
for i in range(image.shape[0]):
|
| 1135 |
-
segs_i = segs_all[i] if i < len(segs_all) else []
|
| 1136 |
-
segs_tuple = ([segs_i], seg_labels) if isinstance(segs_i, dict) else (segs_i, seg_labels)
|
| 1137 |
-
image_device = image.to(device) if image.device != device else image
|
| 1138 |
-
image_i = image_device[i]
|
| 1139 |
-
mask_i, _ = core.make_sam_mask_segmented(
|
| 1140 |
-
sam, segs_tuple, image_i, self.detection_hint,
|
| 1141 |
-
sam_dilation, sam_threshold, bbox_expansion,
|
| 1142 |
-
mask_hint_threshold, mask_hint_use_negative
|
| 1143 |
-
)
|
| 1144 |
-
combined_masks.append(mask_i)
|
| 1145 |
-
combined_mask = torch.stack(combined_masks)
|
| 1146 |
else:
|
| 1147 |
-
|
| 1148 |
-
|
| 1149 |
-
|
| 1150 |
-
|
| 1151 |
-
|
| 1152 |
-
|
|
|
|
| 1153 |
|
| 1154 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1155 |
|
| 1156 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1157 |
|
| 1158 |
-
#
|
| 1159 |
|
| 1160 |
-
|
| 1161 |
|
| 1162 |
-
# Morph operations
|
| 1163 |
if morphology_operation == "dilate":
|
| 1164 |
-
|
| 1165 |
elif morphology_operation == "erode":
|
| 1166 |
-
|
| 1167 |
elif morphology_operation == "open":
|
| 1168 |
-
|
|
|
|
| 1169 |
elif morphology_operation == "close":
|
| 1170 |
-
|
|
|
|
| 1171 |
|
| 1172 |
-
#
|
| 1173 |
|
| 1174 |
-
|
| 1175 |
-
|
| 1176 |
-
# Gaussian blur
|
| 1177 |
-
|
| 1178 |
-
if blur_radius > 0:
|
| 1179 |
-
blur = T.GaussianBlur(kernel_size=blur_radius * 2 + 1, sigma=sigma_factor)
|
| 1180 |
-
mask_blurred = blur(combined_mask.unsqueeze(1)).squeeze(1)
|
| 1181 |
-
else:
|
| 1182 |
-
mask_blurred = combined_mask
|
| 1183 |
|
| 1184 |
-
|
| 1185 |
-
|
| 1186 |
-
|
| 1187 |
-
|
| 1188 |
-
|
| 1189 |
-
|
| 1190 |
-
|
| 1191 |
-
# Apply mask to swapped image (basic RGBA composite)
|
| 1192 |
-
swapped_image = swapped_image.to(device) if swapped_image.device != device else swapped_image
|
| 1193 |
-
swapped_rgba = core.tensor2rgba(swapped_image)
|
| 1194 |
-
|
| 1195 |
-
mask_image_final = mask_blurred
|
| 1196 |
|
| 1197 |
# *** CUT BY MASK ***:
|
| 1198 |
|
|
@@ -1231,11 +1005,15 @@ class MaskHelper:
|
|
| 1231 |
use_width = int(torch.max(width).item())
|
| 1232 |
use_height = int(torch.max(height).item())
|
| 1233 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1234 |
alpha_mask = torch.ones((B, H, W, 4))
|
| 1235 |
alpha_mask[:,:,:,3] = mask
|
| 1236 |
|
| 1237 |
-
alpha_mask = alpha_mask.to(device) if alpha_mask.device != device else alpha_mask
|
| 1238 |
-
|
| 1239 |
swapped_image = swapped_image * alpha_mask
|
| 1240 |
|
| 1241 |
cutted_image = torch.zeros((B, use_height, use_width, 4))
|
|
@@ -1257,7 +1035,7 @@ class MaskHelper:
|
|
| 1257 |
|
| 1258 |
# *** PASTE BY MASK ***:
|
| 1259 |
|
| 1260 |
-
image_base = core.tensor2rgba(
|
| 1261 |
image_to_paste = core.tensor2rgba(cutted_image)
|
| 1262 |
mask = core.tensor2mask(mask_image_final)
|
| 1263 |
|
|
@@ -1307,18 +1085,35 @@ class MaskHelper:
|
|
| 1307 |
continue
|
| 1308 |
else:
|
| 1309 |
image_index = i
|
| 1310 |
-
|
| 1311 |
SB, SH, SW, _ = image_to_paste.shape
|
| 1312 |
|
| 1313 |
# Figure out the desired size
|
| 1314 |
width = int(target_width[i].item())
|
| 1315 |
height = int(target_height[i].item())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1316 |
|
| 1317 |
width = SW
|
| 1318 |
height = SH
|
| 1319 |
|
| 1320 |
# Resize the image we're pasting if needed
|
| 1321 |
resized_image = image_to_paste[i].unsqueeze(0)
|
|
|
|
|
|
|
| 1322 |
|
| 1323 |
pasting = torch.ones([H, W, C])
|
| 1324 |
ymid = float(mid_y[i].item())
|
|
@@ -1350,11 +1145,12 @@ class MaskHelper:
|
|
| 1350 |
pasting_alpha = torch.zeros([H, W])
|
| 1351 |
pasting_alpha[ymin:ymax, xmin:xmax] = resized_image[0, source_ymin:source_ymax, source_xmin:source_xmax, 3]
|
| 1352 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1353 |
paste_mask = torch.min(pasting_alpha, mask[i]).unsqueeze(2).repeat(1, 1, 4)
|
| 1354 |
-
|
| 1355 |
-
pasting = pasting.to(device) if pasting.device != device else pasting
|
| 1356 |
-
paste_mask = paste_mask.to(device) if paste_mask.device != device else paste_mask
|
| 1357 |
-
|
| 1358 |
result[image_index] = pasting * paste_mask + result[image_index] * (1. - paste_mask)
|
| 1359 |
|
| 1360 |
face_segment = result
|
|
@@ -1363,24 +1159,44 @@ class MaskHelper:
|
|
| 1363 |
|
| 1364 |
result = rgba2rgb_tensor(result)
|
| 1365 |
|
| 1366 |
-
|
| 1367 |
-
|
| 1368 |
-
|
| 1369 |
-
|
| 1370 |
-
|
| 1371 |
-
|
| 1372 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1373 |
|
| 1374 |
-
def
|
| 1375 |
-
|
| 1376 |
-
|
| 1377 |
-
|
| 1378 |
-
|
| 1379 |
-
|
| 1380 |
-
|
| 1381 |
-
|
| 1382 |
-
|
| 1383 |
-
return image.squeeze(1)
|
| 1384 |
|
| 1385 |
|
| 1386 |
class ImageDublicator:
|
|
|
|
| 2 |
import logging
|
| 3 |
|
| 4 |
import torch
|
| 5 |
+
import torch.nn.functional as torchfn
|
|
|
|
| 6 |
from torchvision.transforms.functional import normalize
|
| 7 |
from torchvision.ops import masks_to_boxes
|
| 8 |
|
|
|
|
| 11 |
import math
|
| 12 |
from typing import List
|
| 13 |
from PIL import Image
|
|
|
|
| 14 |
from scipy import stats
|
| 15 |
from insightface.app.common import Face
|
| 16 |
from segment_anything import sam_model_registry
|
|
|
|
| 21 |
import comfy.model_management as model_management
|
| 22 |
import comfy.utils
|
| 23 |
import folder_paths
|
| 24 |
+
# from folder_paths import add_folder_path_and_extensions # ← добавили (не работает - вызывает ошибку ImportError: cannot import name 'add_folder_path_and_extensions' from 'folder_paths' (/home/user/app/folder_paths.py))
|
| 25 |
|
| 26 |
import scripts.reactor_version
|
| 27 |
from r_chainner import model_loading
|
|
|
|
| 50 |
prepare_cropped_face,
|
| 51 |
normalize_cropped_face,
|
| 52 |
add_folder_path_and_extensions,
|
| 53 |
+
rgba2rgb_tensor
|
|
|
|
|
|
|
| 54 |
)
|
| 55 |
from reactor_patcher import apply_patch
|
| 56 |
from r_facelib.utils.face_restoration_helper import FaceRestoreHelper
|
|
|
|
| 60 |
import scripts.r_masking.core as core
|
| 61 |
import scripts.r_masking.segs as masking_segs
|
| 62 |
|
| 63 |
+
# … сервисные константы …
|
| 64 |
models_dir = folder_paths.models_dir
|
| 65 |
REACTOR_MODELS_PATH = os.path.join(models_dir, "reactor")
|
| 66 |
FACE_MODELS_PATH = os.path.join(REACTOR_MODELS_PATH, "faces")
|
| 67 |
|
| 68 |
+
os.makedirs(REACTOR_MODELS_PATH, exist_ok=True)
|
| 69 |
+
os.makedirs(FACE_MODELS_PATH, exist_ok=True)
|
| 70 |
+
|
| 71 |
if not os.path.exists(REACTOR_MODELS_PATH):
|
| 72 |
os.makedirs(REACTOR_MODELS_PATH)
|
| 73 |
if not os.path.exists(FACE_MODELS_PATH):
|
| 74 |
os.makedirs(FACE_MODELS_PATH)
|
| 75 |
|
| 76 |
+
# ——————————————————————————————————————————————————————————————
|
| 77 |
+
# Настраиваем папку facerestore_models, чтобы туда «виделось» расширение .onnx
|
| 78 |
+
# Вместо старого куска:
|
| 79 |
+
# dir_facerestore_models = os.path.join(models_dir, "facerestore_models")
|
| 80 |
+
# os.makedirs(dir_facerestore_models, exist_ok=True)
|
| 81 |
+
# folder_paths.folder_names_and_paths["facerestore_models"] = (
|
| 82 |
+
# [dir_facerestore_models],
|
| 83 |
+
# folder_paths.supported_pt_extensions
|
| 84 |
+
# )
|
| 85 |
+
#
|
| 86 |
+
# Делаем так:
|
| 87 |
dir_facerestore_models = os.path.join(models_dir, "facerestore_models")
|
| 88 |
os.makedirs(dir_facerestore_models, exist_ok=True)
|
| 89 |
+
|
| 90 |
+
add_folder_path_and_extensions(
|
| 91 |
+
"facerestore_models", # ключ, как мы потом будем доставать
|
| 92 |
+
[dir_facerestore_models], # список директорий
|
| 93 |
+
[".pth", ".pt", ".onnx"] # ← явно указываем .onnx
|
| 94 |
+
)
|
| 95 |
+
# ——————————————————————————————————————————————————————————————
|
| 96 |
|
| 97 |
BLENDED_FACE_MODEL = None
|
| 98 |
FACE_SIZE: int = 512
|
|
|
|
| 172 |
"hidden": {"faces_order": "FACES_ORDER"},
|
| 173 |
}
|
| 174 |
|
| 175 |
+
RETURN_TYPES = ("IMAGE","FACE_MODEL")
|
|
|
|
| 176 |
FUNCTION = "execute"
|
| 177 |
CATEGORY = "🌌 ReActor"
|
| 178 |
|
|
|
|
| 186 |
self.interpolation = "Bicubic"
|
| 187 |
self.boost_model_visibility = 1
|
| 188 |
self.boost_cf_weight = 0.5
|
| 189 |
+
|
| 190 |
+
# Начинаем restore face
|
| 191 |
def restore_face(
|
| 192 |
+
self,
|
| 193 |
+
input_image,
|
| 194 |
+
face_restore_model,
|
| 195 |
+
face_restore_visibility,
|
| 196 |
+
codeformer_weight,
|
| 197 |
+
facedetection,
|
| 198 |
+
):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 199 |
result = input_image
|
| 200 |
|
| 201 |
if face_restore_model != "none" and not model_management.processing_interrupted():
|
|
|
|
| 202 |
global FACE_SIZE, FACE_HELPER
|
| 203 |
|
| 204 |
self.face_helper = FACE_HELPER
|
| 205 |
|
| 206 |
+
# Подготавливаем размер лица
|
| 207 |
faceSize = 512
|
| 208 |
if "1024" in face_restore_model.lower():
|
| 209 |
faceSize = 1024
|
|
|
|
| 212 |
|
| 213 |
logger.status(f"Restoring with {face_restore_model} | Face Size is set to {faceSize}")
|
| 214 |
|
| 215 |
+
# пытаемся найти путь через папки
|
| 216 |
model_path = folder_paths.get_full_path("facerestore_models", face_restore_model)
|
| 217 |
+
|
| 218 |
+
# если по какой-то причине не нашли — склеиваем вручную
|
| 219 |
+
if model_path is None or not os.path.isfile(model_path):
|
| 220 |
+
model_path = os.path.join(dir_facerestore_models, face_restore_model)
|
| 221 |
+
|
| 222 |
+
# И вот здесь, если model_path всё ещё неправильный, мы сразу бросим понятную ошибку
|
| 223 |
+
if not os.path.isfile(model_path):
|
| 224 |
+
raise FileNotFoundError(f"ONNX-модель не найдена: {model_path}")
|
| 225 |
+
|
| 226 |
device = model_management.get_torch_device()
|
| 227 |
+
|
| 228 |
+
# Единственный блок для .onnx — гарантируем, что сюда попадает только он
|
| 229 |
+
if face_restore_model.lower().endswith(".onnx"):
|
| 230 |
+
ort_session = set_ort_session(model_path, providers=providers)
|
| 231 |
+
ort_session_inputs = {}
|
| 232 |
+
facerestore_model = ort_session
|
| 233 |
+
|
| 234 |
+
if ".onnx" in face_restore_model.lower():
|
| 235 |
+
# в этом месте model_path уже точно строка, а не None
|
| 236 |
+
ort_session = set_ort_session(model_path, providers=providers)
|
| 237 |
+
ort_session_inputs = {}
|
| 238 |
+
facerestore_model = ort_session
|
| 239 |
|
| 240 |
if "codeformer" in face_restore_model.lower():
|
| 241 |
|
|
|
|
| 267 |
FACE_SIZE = faceSize
|
| 268 |
FACE_HELPER = self.face_helper
|
| 269 |
|
| 270 |
+
image_np = 255. * result.numpy()
|
|
|
|
| 271 |
|
| 272 |
total_images = image_np.shape[0]
|
| 273 |
|
| 274 |
out_images = []
|
| 275 |
|
|
|
|
|
|
|
| 276 |
for i in range(total_images):
|
| 277 |
|
| 278 |
+
if total_images > 1:
|
| 279 |
+
logger.status(f"Restoring {i+1}")
|
| 280 |
|
| 281 |
cur_image_np = image_np[i,:, :, ::-1]
|
| 282 |
|
|
|
|
| 290 |
self.face_helper.get_face_landmarks_5(only_center_face=False, resize=640, eye_dist_threshold=5)
|
| 291 |
self.face_helper.align_warp_face()
|
| 292 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 293 |
restored_face = None
|
| 294 |
|
| 295 |
+
# после подготовки self.face_helper и выравнивания лица начинается цикл по всем фрагментам:
|
| 296 |
for idx, cropped_face in enumerate(self.face_helper.cropped_faces):
|
| 297 |
+
|
| 298 |
+
# если у вас несколько лиц, логируем прогресс
|
| 299 |
+
if len(self.face_helper.cropped_faces) > 1:
|
| 300 |
+
logger.status(f"Restoring face {idx+1}")
|
| 301 |
+
|
| 302 |
+
# превращаем PIL→tensor и нормализуем (для PTH-моделей):
|
| 303 |
# if ".pth" in face_restore_model:
|
| 304 |
cropped_face_t = img2tensor(cropped_face / 255., bgr2rgb=True, float32=True)
|
| 305 |
normalize(cropped_face_t, (0.5, 0.5, 0.5), (0.5, 0.5, 0.5), inplace=True)
|
|
|
|
| 308 |
try:
|
| 309 |
|
| 310 |
with torch.no_grad():
|
| 311 |
+
|
| 312 |
+
# ────── 🚩 МЕСТО ВСТАВКИ SNIPPET-а for ONNX ──────
|
| 313 |
+
if face_restore_model.lower().endswith(".onnx"):
|
| 314 |
+
# тут мы готовим входы для onnxruntime
|
| 315 |
+
for inp in ort_session.get_inputs():
|
| 316 |
+
if inp.name == "input":
|
| 317 |
+
ort_session_inputs[inp.name] = prepare_cropped_face(cropped_face)
|
| 318 |
+
elif inp.name == "weight":
|
| 319 |
+
ort_session_inputs[inp.name] = np.array([1], dtype=np.double)
|
| 320 |
+
|
| 321 |
+
# собственно, инференс
|
| 322 |
output = ort_session.run(None, ort_session_inputs)[0][0]
|
| 323 |
+
# возвращаем в изображение
|
| 324 |
restored_face = normalize_cropped_face(output)
|
| 325 |
+
|
| 326 |
+
else:
|
| 327 |
+
# ────── ВЕТКА ДЛЯ PTH / CODEFORMER ──────
|
| 328 |
+
# если CodeFormer
|
| 329 |
+
if "codeformer" in face_restore_model.lower():
|
| 330 |
+
output = facerestore_model(cropped_face_t, w=codeformer_weight)[0]
|
| 331 |
+
else:
|
| 332 |
+
# обычная PTH-модель (GFPGAN и т.п.)
|
| 333 |
+
output = facerestore_model(cropped_face_t)[0]
|
| 334 |
|
|
|
|
|
|
|
|
|
|
| 335 |
restored_face = tensor2img(output, rgb2bgr=True, min_max=(-1, 1))
|
| 336 |
+
# ─────────────────────────────────────────────────
|
| 337 |
+
|
| 338 |
+
# освобождаем память
|
| 339 |
del output
|
| 340 |
torch.cuda.empty_cache()
|
| 341 |
|
| 342 |
except Exception as error:
|
| 343 |
+
# на случай краха инференса — возвращаем «сырой» кроп
|
| 344 |
print(f"\tFailed inference: {error}", file=sys.stderr)
|
| 345 |
restored_face = tensor2img(cropped_face_t, rgb2bgr=True, min_max=(-1, 1))
|
| 346 |
|
| 347 |
+
# далее вы накладываете прозрачность и собираете кадр:
|
| 348 |
if face_restore_visibility < 1:
|
| 349 |
restored_face = cropped_face * (1 - face_restore_visibility) + restored_face * face_restore_visibility
|
| 350 |
|
|
|
|
| 367 |
if state.interrupted or model_management.processing_interrupted():
|
| 368 |
logger.status("Interrupted by User")
|
| 369 |
return input_image
|
|
|
|
|
|
|
| 370 |
|
| 371 |
restored_img_np = np.array(out_images).astype(np.float32) / 255.0
|
| 372 |
restored_img_tensor = torch.from_numpy(restored_img_np)
|
| 373 |
|
| 374 |
result = restored_img_tensor
|
| 375 |
|
|
|
|
|
|
|
| 376 |
return result
|
| 377 |
+
|
| 378 |
+
def execute(self, enabled, input_image, swap_model, detect_gender_source, detect_gender_input, source_faces_index, input_faces_index, console_log_level, face_restore_model,face_restore_visibility, codeformer_weight, facedetection, source_image=None, face_model=None, faces_order=None, face_boost=None):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 379 |
|
| 380 |
if face_boost is not None:
|
| 381 |
self.face_boost_enabled = face_boost["enabled"]
|
|
|
|
| 401 |
if face_model == "none":
|
| 402 |
face_model = None
|
| 403 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 404 |
script = FaceSwapScript()
|
| 405 |
pil_images = batch_tensor_to_pil(input_image)
|
|
|
|
| 406 |
if source_image is not None:
|
| 407 |
source = tensor_to_pil(source_image)
|
| 408 |
else:
|
|
|
|
| 428 |
codeformer_weight=self.boost_cf_weight,
|
| 429 |
interpolation=self.interpolation,
|
| 430 |
)
|
| 431 |
+
result = batched_pil_to_tensor(p.init_images)
|
|
|
|
| 432 |
|
| 433 |
if face_model is None:
|
| 434 |
current_face_model = get_current_faces_model()
|
|
|
|
| 436 |
else:
|
| 437 |
face_model_to_provide = face_model
|
| 438 |
|
|
|
|
| 439 |
if self.restore or not self.face_boost_enabled:
|
| 440 |
+
result = reactor.restore_face(self,result,face_restore_model,face_restore_visibility,codeformer_weight,facedetection)
|
| 441 |
+
|
| 442 |
+
return (result,face_model_to_provide)
|
| 443 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 444 |
|
| 445 |
class ReActorPlusOpt:
|
| 446 |
@classmethod
|
|
|
|
| 463 |
}
|
| 464 |
}
|
| 465 |
|
| 466 |
+
RETURN_TYPES = ("IMAGE","FACE_MODEL")
|
|
|
|
| 467 |
FUNCTION = "execute"
|
| 468 |
CATEGORY = "🌌 ReActor"
|
| 469 |
|
|
|
|
| 820 |
"model": (get_model_names(get_restorers),),
|
| 821 |
"visibility": ("FLOAT", {"default": 1, "min": 0.0, "max": 1, "step": 0.05}),
|
| 822 |
"codeformer_weight": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1, "step": 0.05}),
|
|
|
|
| 823 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 824 |
}
|
| 825 |
+
|
| 826 |
RETURN_TYPES = ("IMAGE",)
|
| 827 |
FUNCTION = "execute"
|
| 828 |
CATEGORY = "🌌 ReActor"
|
| 829 |
|
| 830 |
+
# def __init__(self):
|
| 831 |
+
# self.face_helper = None
|
| 832 |
+
# self.face_size = 512
|
| 833 |
+
|
| 834 |
+
def execute(self, image, model, visibility, codeformer_weight, facedetection):
|
| 835 |
+
result = reactor.restore_face(self,image,model,visibility,codeformer_weight,facedetection)
|
|
|
|
|
|
|
| 836 |
return (result,)
|
| 837 |
|
| 838 |
|
| 839 |
class MaskHelper:
|
| 840 |
def __init__(self):
|
| 841 |
+
# self.threshold = 0.5
|
| 842 |
+
# self.dilation = 10
|
| 843 |
+
# self.crop_factor = 3.0
|
| 844 |
+
# self.drop_size = 1
|
| 845 |
self.labels = "all"
|
| 846 |
self.detailer_hook = None
|
| 847 |
self.device_mode = "AUTO"
|
| 848 |
self.detection_hint = "center-1"
|
| 849 |
+
# self.sam_dilation = 0
|
| 850 |
+
# self.sam_threshold = 0.93
|
| 851 |
+
# self.bbox_expansion = 0
|
| 852 |
+
# self.mask_hint_threshold = 0.7
|
| 853 |
+
# self.mask_hint_use_negative = "False"
|
| 854 |
+
# self.force_resize_width = 0
|
| 855 |
+
# self.force_resize_height = 0
|
| 856 |
+
# self.resize_behavior = "source_size"
|
| 857 |
|
| 858 |
@classmethod
|
| 859 |
def INPUT_TYPES(s):
|
|
|
|
| 891 |
CATEGORY = "🌌 ReActor"
|
| 892 |
|
| 893 |
def execute(self, image, swapped_image, bbox_model_name, bbox_threshold, bbox_dilation, bbox_crop_factor, bbox_drop_size, sam_model_name, sam_dilation, sam_threshold, bbox_expansion, mask_hint_threshold, mask_hint_use_negative, morphology_operation, morphology_distance, blur_radius, sigma_factor, mask_optional=None):
|
|
|
|
| 894 |
|
| 895 |
# images = [image[i:i + 1, ...] for i in range(image.shape[0])]
|
|
|
|
|
|
|
|
|
|
| 896 |
|
| 897 |
images = image
|
| 898 |
|
| 899 |
+
if mask_optional is None:
|
| 900 |
+
|
| 901 |
+
bbox_model_path = folder_paths.get_full_path("ultralytics", bbox_model_name)
|
| 902 |
+
bbox_model = subcore.load_yolo(bbox_model_path)
|
| 903 |
+
bbox_detector = subcore.UltraBBoxDetector(bbox_model)
|
| 904 |
+
|
| 905 |
+
segs = bbox_detector.detect(images, bbox_threshold, bbox_dilation, bbox_crop_factor, bbox_drop_size, self.detailer_hook)
|
| 906 |
+
|
| 907 |
+
if isinstance(self.labels, list):
|
| 908 |
+
self.labels = str(self.labels[0])
|
| 909 |
+
|
| 910 |
+
if self.labels is not None and self.labels != '':
|
| 911 |
+
self.labels = self.labels.split(',')
|
| 912 |
+
if len(self.labels) > 0:
|
| 913 |
+
segs, _ = masking_segs.filter(segs, self.labels)
|
| 914 |
+
# segs, _ = masking_segs.filter(segs, "all")
|
| 915 |
+
|
| 916 |
+
sam_modelname = folder_paths.get_full_path("sams", sam_model_name)
|
| 917 |
+
|
| 918 |
+
if 'vit_h' in sam_model_name:
|
| 919 |
+
model_kind = 'vit_h'
|
| 920 |
+
elif 'vit_l' in sam_model_name:
|
| 921 |
+
model_kind = 'vit_l'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 922 |
else:
|
| 923 |
+
model_kind = 'vit_b'
|
| 924 |
+
|
| 925 |
+
sam = sam_model_registry[model_kind](checkpoint=sam_modelname)
|
| 926 |
+
size = os.path.getsize(sam_modelname)
|
| 927 |
+
sam.safe_to = core.SafeToGPU(size)
|
| 928 |
+
|
| 929 |
+
device = model_management.get_torch_device()
|
| 930 |
|
| 931 |
+
sam.safe_to.to_device(sam, device)
|
| 932 |
+
|
| 933 |
+
sam.is_auto_mode = self.device_mode == "AUTO"
|
| 934 |
+
|
| 935 |
+
combined_mask, _ = core.make_sam_mask_segmented(sam, segs, images, self.detection_hint, sam_dilation, sam_threshold, bbox_expansion, mask_hint_threshold, mask_hint_use_negative)
|
| 936 |
|
| 937 |
+
else:
|
| 938 |
+
combined_mask = mask_optional
|
| 939 |
+
|
| 940 |
+
# *** MASK TO IMAGE ***:
|
| 941 |
+
|
| 942 |
+
mask_image = combined_mask.reshape((-1, 1, combined_mask.shape[-2], combined_mask.shape[-1])).movedim(1, -1).expand(-1, -1, -1, 3)
|
| 943 |
|
| 944 |
+
# *** MASK MORPH ***:
|
| 945 |
|
| 946 |
+
mask_image = core.tensor2mask(mask_image)
|
| 947 |
|
|
|
|
| 948 |
if morphology_operation == "dilate":
|
| 949 |
+
mask_image = self.dilate(mask_image, morphology_distance)
|
| 950 |
elif morphology_operation == "erode":
|
| 951 |
+
mask_image = self.erode(mask_image, morphology_distance)
|
| 952 |
elif morphology_operation == "open":
|
| 953 |
+
mask_image = self.erode(mask_image, morphology_distance)
|
| 954 |
+
mask_image = self.dilate(mask_image, morphology_distance)
|
| 955 |
elif morphology_operation == "close":
|
| 956 |
+
mask_image = self.dilate(mask_image, morphology_distance)
|
| 957 |
+
mask_image = self.erode(mask_image, morphology_distance)
|
| 958 |
|
| 959 |
+
# *** MASK BLUR ***:
|
| 960 |
|
| 961 |
+
if len(mask_image.size()) == 3:
|
| 962 |
+
mask_image = mask_image.unsqueeze(3)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 963 |
|
| 964 |
+
mask_image = mask_image.permute(0, 3, 1, 2)
|
| 965 |
+
kernel_size = blur_radius * 2 + 1
|
| 966 |
+
sigma = sigma_factor * (0.6 * blur_radius - 0.3)
|
| 967 |
+
mask_image_final = self.gaussian_blur(mask_image, kernel_size, sigma).permute(0, 2, 3, 1)
|
| 968 |
+
if mask_image_final.size()[3] == 1:
|
| 969 |
+
mask_image_final = mask_image_final[:, :, :, 0]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 970 |
|
| 971 |
# *** CUT BY MASK ***:
|
| 972 |
|
|
|
|
| 1005 |
use_width = int(torch.max(width).item())
|
| 1006 |
use_height = int(torch.max(height).item())
|
| 1007 |
|
| 1008 |
+
# if self.force_resize_width > 0:
|
| 1009 |
+
# use_width = self.force_resize_width
|
| 1010 |
+
|
| 1011 |
+
# if self.force_resize_height > 0:
|
| 1012 |
+
# use_height = self.force_resize_height
|
| 1013 |
+
|
| 1014 |
alpha_mask = torch.ones((B, H, W, 4))
|
| 1015 |
alpha_mask[:,:,:,3] = mask
|
| 1016 |
|
|
|
|
|
|
|
| 1017 |
swapped_image = swapped_image * alpha_mask
|
| 1018 |
|
| 1019 |
cutted_image = torch.zeros((B, use_height, use_width, 4))
|
|
|
|
| 1035 |
|
| 1036 |
# *** PASTE BY MASK ***:
|
| 1037 |
|
| 1038 |
+
image_base = core.tensor2rgba(images)
|
| 1039 |
image_to_paste = core.tensor2rgba(cutted_image)
|
| 1040 |
mask = core.tensor2mask(mask_image_final)
|
| 1041 |
|
|
|
|
| 1085 |
continue
|
| 1086 |
else:
|
| 1087 |
image_index = i
|
| 1088 |
+
source_size = image_to_paste.size()
|
| 1089 |
SB, SH, SW, _ = image_to_paste.shape
|
| 1090 |
|
| 1091 |
# Figure out the desired size
|
| 1092 |
width = int(target_width[i].item())
|
| 1093 |
height = int(target_height[i].item())
|
| 1094 |
+
# if self.resize_behavior == "keep_ratio_fill":
|
| 1095 |
+
# target_ratio = width / height
|
| 1096 |
+
# actual_ratio = SW / SH
|
| 1097 |
+
# if actual_ratio > target_ratio:
|
| 1098 |
+
# width = int(height * actual_ratio)
|
| 1099 |
+
# elif actual_ratio < target_ratio:
|
| 1100 |
+
# height = int(width / actual_ratio)
|
| 1101 |
+
# elif self.resize_behavior == "keep_ratio_fit":
|
| 1102 |
+
# target_ratio = width / height
|
| 1103 |
+
# actual_ratio = SW / SH
|
| 1104 |
+
# if actual_ratio > target_ratio:
|
| 1105 |
+
# height = int(width / actual_ratio)
|
| 1106 |
+
# elif actual_ratio < target_ratio:
|
| 1107 |
+
# width = int(height * actual_ratio)
|
| 1108 |
+
# elif self.resize_behavior == "source_size" or self.resize_behavior == "source_size_unmasked":
|
| 1109 |
|
| 1110 |
width = SW
|
| 1111 |
height = SH
|
| 1112 |
|
| 1113 |
# Resize the image we're pasting if needed
|
| 1114 |
resized_image = image_to_paste[i].unsqueeze(0)
|
| 1115 |
+
# if SH != height or SW != width:
|
| 1116 |
+
# resized_image = torch.nn.functional.interpolate(resized_image.permute(0, 3, 1, 2), size=(height,width), mode='bicubic').permute(0, 2, 3, 1)
|
| 1117 |
|
| 1118 |
pasting = torch.ones([H, W, C])
|
| 1119 |
ymid = float(mid_y[i].item())
|
|
|
|
| 1145 |
pasting_alpha = torch.zeros([H, W])
|
| 1146 |
pasting_alpha[ymin:ymax, xmin:xmax] = resized_image[0, source_ymin:source_ymax, source_xmin:source_xmax, 3]
|
| 1147 |
|
| 1148 |
+
# if self.resize_behavior == "keep_ratio_fill" or self.resize_behavior == "source_size_unmasked":
|
| 1149 |
+
# # If we explicitly want to fill the area, we are ok with extending outside
|
| 1150 |
+
# paste_mask = pasting_alpha.unsqueeze(2).repeat(1, 1, 4)
|
| 1151 |
+
# else:
|
| 1152 |
+
# paste_mask = torch.min(pasting_alpha, mask[i]).unsqueeze(2).repeat(1, 1, 4)
|
| 1153 |
paste_mask = torch.min(pasting_alpha, mask[i]).unsqueeze(2).repeat(1, 1, 4)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1154 |
result[image_index] = pasting * paste_mask + result[image_index] * (1. - paste_mask)
|
| 1155 |
|
| 1156 |
face_segment = result
|
|
|
|
| 1159 |
|
| 1160 |
result = rgba2rgb_tensor(result)
|
| 1161 |
|
| 1162 |
+
return (result,combined_mask,mask_image_final,face_segment,)
|
| 1163 |
+
|
| 1164 |
+
def gaussian_blur(self, image, kernel_size, sigma):
|
| 1165 |
+
kernel = torch.Tensor(kernel_size, kernel_size).to(device=image.device)
|
| 1166 |
+
center = kernel_size // 2
|
| 1167 |
+
variance = sigma**2
|
| 1168 |
+
for i in range(kernel_size):
|
| 1169 |
+
for j in range(kernel_size):
|
| 1170 |
+
x = i - center
|
| 1171 |
+
y = j - center
|
| 1172 |
+
kernel[i, j] = math.exp(-(x**2 + y**2)/(2*variance))
|
| 1173 |
+
kernel /= kernel.sum()
|
| 1174 |
+
|
| 1175 |
+
# Pad the input tensor
|
| 1176 |
+
padding = (kernel_size - 1) // 2
|
| 1177 |
+
input_pad = torch.nn.functional.pad(image, (padding, padding, padding, padding), mode='reflect')
|
| 1178 |
+
|
| 1179 |
+
# Reshape the padded input tensor for batched convolution
|
| 1180 |
+
batch_size, num_channels, height, width = image.shape
|
| 1181 |
+
input_reshaped = input_pad.reshape(batch_size*num_channels, 1, height+padding*2, width+padding*2)
|
| 1182 |
+
|
| 1183 |
+
# Perform batched convolution with the Gaussian kernel
|
| 1184 |
+
output_reshaped = torch.nn.functional.conv2d(input_reshaped, kernel.unsqueeze(0).unsqueeze(0))
|
| 1185 |
+
|
| 1186 |
+
# Reshape the output tensor to its original shape
|
| 1187 |
+
output_tensor = output_reshaped.reshape(batch_size, num_channels, height, width)
|
| 1188 |
+
|
| 1189 |
+
return output_tensor
|
| 1190 |
|
| 1191 |
+
def erode(self, image, distance):
|
| 1192 |
+
return 1. - self.dilate(1. - image, distance)
|
| 1193 |
+
|
| 1194 |
+
def dilate(self, image, distance):
|
| 1195 |
+
kernel_size = 1 + distance * 2
|
| 1196 |
+
# Add the channels dimension
|
| 1197 |
+
image = image.unsqueeze(1)
|
| 1198 |
+
out = torchfn.max_pool2d(image, kernel_size=kernel_size, stride=1, padding=kernel_size // 2).squeeze(1)
|
| 1199 |
+
return out
|
|
|
|
| 1200 |
|
| 1201 |
|
| 1202 |
class ImageDublicator:
|