Spaces:
Running
on
Zero
Running
on
Zero
Initial commit hyperswap
Browse files- 20250929213116_OPTIM-FAIL_app.py +0 -270
- app.py +10 -12
20250929213116_OPTIM-FAIL_app.py
DELETED
@@ -1,270 +0,0 @@
|
|
1 |
-
import os
|
2 |
-
import random
|
3 |
-
import sys
|
4 |
-
from typing import Sequence, Mapping, Any, Union
|
5 |
-
import torch
|
6 |
-
from PIL import Image
|
7 |
-
from huggingface_hub import hf_hub_download
|
8 |
-
import spaces
|
9 |
-
|
10 |
-
import subprocess, sys
|
11 |
-
|
12 |
-
# ---------------------------------------------------------------------------------
|
13 |
-
# 🛠️ Monkey-patch для gradio_client: игнорируем булевы схемы и не падаем на TypeError
|
14 |
-
# ---------------------------------------------------------------------------------
|
15 |
-
import gradio_client.utils as _gc_utils
|
16 |
-
|
17 |
-
# Сохраняем оригинальные функции
|
18 |
-
_orig_js2pt = _gc_utils._json_schema_to_python_type
|
19 |
-
_orig_get_type = _gc_utils.get_type
|
20 |
-
|
21 |
-
def _safe_json_schema_to_python_type(schema, defs=None):
|
22 |
-
"""
|
23 |
-
Если schema — bool (True/False), возвращаем 'Any',
|
24 |
-
иначе — вызываем оригинальный код.
|
25 |
-
"""
|
26 |
-
if isinstance(schema, bool):
|
27 |
-
return "Any"
|
28 |
-
return _orig_js2pt(schema, defs)
|
29 |
-
|
30 |
-
def _safe_get_type(schema):
|
31 |
-
"""
|
32 |
-
Если schema — bool, возвращаем 'Any',
|
33 |
-
иначе — вызываем оригинальную функцию get_type.
|
34 |
-
"""
|
35 |
-
if isinstance(schema, bool):
|
36 |
-
return "Any"
|
37 |
-
return _orig_get_type(schema)
|
38 |
-
|
39 |
-
# Заменяем в модуле
|
40 |
-
_gc_utils._json_schema_to_python_type = _safe_json_schema_to_python_type
|
41 |
-
_gc_utils.get_type = _safe_get_type
|
42 |
-
# ---------------------------------------------------------------------------------
|
43 |
-
|
44 |
-
# Дальше уже можно безопасно импортировать Gradio
|
45 |
-
|
46 |
-
import gradio
|
47 |
-
import gradio_client
|
48 |
-
import gradio as gr
|
49 |
-
|
50 |
-
print("gradio version:", gradio.__version__)
|
51 |
-
print("gradio_client version:", gradio_client.__version__)
|
52 |
-
|
53 |
-
hf_hub_download(repo_id="ezioruan/inswapper_128.onnx", filename="inswapper_128.onnx", local_dir="models/insightface")
|
54 |
-
hf_hub_download(repo_id="martintomov/comfy", filename="facerestore_models/GPEN-BFR-512.onnx", local_dir="models")
|
55 |
-
|
56 |
-
hf_hub_download(repo_id="facefusion/models-3.3.0", filename="hyperswap_1a_256.onnx", local_dir="models/hyperswap")
|
57 |
-
hf_hub_download(repo_id="facefusion/models-3.3.0", filename="hyperswap_1b_256.onnx", local_dir="models/hyperswap")
|
58 |
-
hf_hub_download(repo_id="facefusion/models-3.3.0", filename="hyperswap_1c_256.onnx", local_dir="models/hyperswap")
|
59 |
-
|
60 |
-
hf_hub_download(repo_id="martintomov/comfy", filename="facedetection/yolov5l-face.pth", local_dir="models")
|
61 |
-
###hf_hub_download(repo_id="darkeril/collection", filename="detection_Resnet50_Final.pth", local_dir="models/facedetection")
|
62 |
-
hf_hub_download(repo_id="gmk123/GFPGAN", filename="parsing_parsenet.pth", local_dir="models/facedetection")
|
63 |
-
|
64 |
-
hf_hub_download(repo_id="MonsterMMORPG/tools", filename="1k3d68.onnx", local_dir="models/insightface/models/buffalo_l")
|
65 |
-
hf_hub_download(repo_id="MonsterMMORPG/tools", filename="2d106det.onnx", local_dir="models/insightface/models/buffalo_l")
|
66 |
-
hf_hub_download(repo_id="maze/faceX", filename="det_10g.onnx", local_dir="models/insightface/models/buffalo_l")
|
67 |
-
hf_hub_download(repo_id="typhoon01/aux_models", filename="genderage.onnx", local_dir="models/insightface/models/buffalo_l")
|
68 |
-
hf_hub_download(repo_id="maze/faceX", filename="w600k_r50.onnx", local_dir="models/insightface/models/buffalo_l")
|
69 |
-
|
70 |
-
hf_hub_download(repo_id="vladmandic/insightface-faceanalysis", filename="buffalo_l.zip", local_dir="models/insightface/models/buffalo_l")
|
71 |
-
|
72 |
-
|
73 |
-
def get_value_at_index(obj: Union[Sequence, Mapping], index: int) -> Any:
|
74 |
-
"""Returns the value at the given index of a sequence or mapping.
|
75 |
-
|
76 |
-
If the object is a sequence (like list or string), returns the value at the given index.
|
77 |
-
If the object is a mapping (like a dictionary), returns the value at the index-th key.
|
78 |
-
|
79 |
-
Some return a dictionary, in these cases, we look for the "results" key
|
80 |
-
|
81 |
-
Args:
|
82 |
-
obj (Union[Sequence, Mapping]): The object to retrieve the value from.
|
83 |
-
index (int): The index of the value to retrieve.
|
84 |
-
|
85 |
-
Returns:
|
86 |
-
Any: The value at the given index.
|
87 |
-
|
88 |
-
Raises:
|
89 |
-
IndexError: If the index is out of bounds for the object and the object is not a mapping.
|
90 |
-
"""
|
91 |
-
try:
|
92 |
-
return obj[index]
|
93 |
-
except KeyError:
|
94 |
-
return obj["result"][index]
|
95 |
-
|
96 |
-
|
97 |
-
def find_path(name: str, path: str = None) -> str:
|
98 |
-
"""
|
99 |
-
Recursively looks at parent folders starting from the given path until it finds the given name.
|
100 |
-
Returns the path as a Path object if found, or None otherwise.
|
101 |
-
"""
|
102 |
-
# If no path is given, use the current working directory
|
103 |
-
if path is None:
|
104 |
-
path = os.getcwd()
|
105 |
-
|
106 |
-
# Check if the current directory contains the name
|
107 |
-
if name in os.listdir(path):
|
108 |
-
path_name = os.path.join(path, name)
|
109 |
-
print(f"{name} found: {path_name}")
|
110 |
-
return path_name
|
111 |
-
|
112 |
-
# Get the parent directory
|
113 |
-
parent_directory = os.path.dirname(path)
|
114 |
-
|
115 |
-
# If the parent directory is the same as the current directory, we've reached the root and stop the search
|
116 |
-
if parent_directory == path:
|
117 |
-
return None
|
118 |
-
|
119 |
-
# Recursively call the function with the parent directory
|
120 |
-
return find_path(name, parent_directory)
|
121 |
-
|
122 |
-
|
123 |
-
def add_comfyui_directory_to_sys_path() -> None:
|
124 |
-
"""
|
125 |
-
Add 'ComfyUI' to the sys.path
|
126 |
-
"""
|
127 |
-
comfyui_path = find_path("ComfyUI")
|
128 |
-
if comfyui_path is not None and os.path.isdir(comfyui_path):
|
129 |
-
sys.path.append(comfyui_path)
|
130 |
-
print(f"'{comfyui_path}' added to sys.path")
|
131 |
-
|
132 |
-
|
133 |
-
def add_extra_model_paths() -> None:
|
134 |
-
"""
|
135 |
-
Parse the optional extra_model_paths.yaml file and add the parsed paths to the sys.path.
|
136 |
-
"""
|
137 |
-
try:
|
138 |
-
from main import load_extra_path_config
|
139 |
-
except ImportError:
|
140 |
-
print(
|
141 |
-
"Could not import load_extra_path_config from main.py. Looking in utils.extra_config instead."
|
142 |
-
)
|
143 |
-
from utils.extra_config import load_extra_path_config
|
144 |
-
|
145 |
-
extra_model_paths = find_path("extra_model_paths.yaml")
|
146 |
-
|
147 |
-
if extra_model_paths is not None:
|
148 |
-
load_extra_path_config(extra_model_paths)
|
149 |
-
else:
|
150 |
-
print("Could not find the extra_model_paths config file.")
|
151 |
-
|
152 |
-
|
153 |
-
add_comfyui_directory_to_sys_path()
|
154 |
-
add_extra_model_paths()
|
155 |
-
|
156 |
-
|
157 |
-
def import_custom_nodes() -> None:
|
158 |
-
"""Find all custom nodes in the custom_nodes folder and add those node objects to NODE_CLASS_MAPPINGS
|
159 |
-
|
160 |
-
This function sets up a new asyncio event loop, initializes the PromptServer,
|
161 |
-
creates a PromptQueue, and initializes the custom nodes.
|
162 |
-
"""
|
163 |
-
import asyncio
|
164 |
-
import execution
|
165 |
-
from nodes import init_extra_nodes
|
166 |
-
import server
|
167 |
-
|
168 |
-
# Creating a new event loop and setting it as the default loop
|
169 |
-
loop = asyncio.new_event_loop()
|
170 |
-
asyncio.set_event_loop(loop)
|
171 |
-
|
172 |
-
# Creating an instance of PromptServer with the loop
|
173 |
-
server_instance = server.PromptServer(loop)
|
174 |
-
execution.PromptQueue(server_instance)
|
175 |
-
|
176 |
-
# Initializing custom nodes
|
177 |
-
# Запускаем корутину и ждём её завершения
|
178 |
-
loop.run_until_complete(init_extra_nodes())
|
179 |
-
|
180 |
-
import_custom_nodes()
|
181 |
-
from nodes import NODE_CLASS_MAPPINGS
|
182 |
-
|
183 |
-
# --- Глобальная загрузка моделей (один раз при старте) ---
|
184 |
-
loadimage = NODE_CLASS_MAPPINGS["LoadImage"]()
|
185 |
-
reactorfaceswap = NODE_CLASS_MAPPINGS["ReActorFaceSwap"]()
|
186 |
-
saveimage = NODE_CLASS_MAPPINGS["SaveImage"]()
|
187 |
-
|
188 |
-
@spaces.GPU(duration=20)
|
189 |
-
def generate_image(source_image, target_image, target_index, swap_model, face_restore_model, restore_strength):
|
190 |
-
with torch.inference_mode():
|
191 |
-
loadimage_2 = loadimage.load_image(image=source_image)
|
192 |
-
loadimage_3 = loadimage.load_image(image=target_image)
|
193 |
-
|
194 |
-
reactorfaceswap_76 = reactorfaceswap.execute(
|
195 |
-
enabled=True,
|
196 |
-
swap_model=swap_model, # Используем выбранную модель
|
197 |
-
facedetection="YOLOv5l",
|
198 |
-
face_restore_model=face_restore_model,
|
199 |
-
face_restore_visibility=restore_strength,
|
200 |
-
codeformer_weight=0.5,
|
201 |
-
detect_gender_input="no",
|
202 |
-
detect_gender_source="no",
|
203 |
-
input_faces_index=str(target_index), # Преобразуем в строку
|
204 |
-
source_faces_index="0",
|
205 |
-
console_log_level=1,
|
206 |
-
input_image=get_value_at_index(loadimage_3, 0),
|
207 |
-
source_image=get_value_at_index(loadimage_2, 0),
|
208 |
-
)
|
209 |
-
|
210 |
-
saveimage_77 = saveimage.save_images(
|
211 |
-
filename_prefix="ComfyUI",
|
212 |
-
images=get_value_at_index(reactorfaceswap_76, 0),
|
213 |
-
)
|
214 |
-
|
215 |
-
saved_path = f"output/{saveimage_77['ui']['images'][0]['filename']}"
|
216 |
-
return saved_path
|
217 |
-
|
218 |
-
if __name__ == "__main__":
|
219 |
-
with gr.Blocks() as app:
|
220 |
-
# Заголовок
|
221 |
-
gr.Markdown("# ComfyUI Reactor Fast Face Swap Hyperswap")
|
222 |
-
|
223 |
-
with gr.Row():
|
224 |
-
with gr.Column():
|
225 |
-
# Вложенный Row для групп
|
226 |
-
with gr.Row():
|
227 |
-
# Первая группа
|
228 |
-
with gr.Group():
|
229 |
-
source_image = gr.Image(label="Source Image (Face)", type="filepath")
|
230 |
-
swap_model = gr.Dropdown(
|
231 |
-
choices=["inswapper_128.onnx", "hyperswap_1a_256.onnx", "hyperswap_1b_256.onnx", "hyperswap_1c_256.onnx"],
|
232 |
-
value="hyperswap_1b_256.onnx",
|
233 |
-
label="Swap Model"
|
234 |
-
)
|
235 |
-
face_restore_model = gr.Dropdown(choices=["none", "GPEN-BFR-512.onnx"], value="none", label="Face Restore Model")
|
236 |
-
restore_strength = gr.Slider(minimum=0, maximum=1, step=0.05, value=0.7, label="Face Restore Strength")
|
237 |
-
|
238 |
-
# Вторая группа (обратите внимание — она должна быть на том же уровне, что и первая)
|
239 |
-
with gr.Group():
|
240 |
-
target_image = gr.Image(label="Target Image (Body)", type="filepath")
|
241 |
-
# restore_strength = gr.Slider(minimum=0, maximum=1, step=0.05, value=0.7, label="Face Restore Strength")
|
242 |
-
target_index = gr.Dropdown(choices=[0, 1, 2, 3, 4], value=0, label="Target Face Index")
|
243 |
-
gr.Markdown("Index_0 = Largest Face. To switch for another target face - switch to Index_1, Index_2, e.t.c")
|
244 |
-
|
245 |
-
# Кнопка генерации
|
246 |
-
generate_btn = gr.Button("Generate")
|
247 |
-
gr.Markdown(
|
248 |
-
"***Hyperswap_1b_256.onnx is the best (in most cases) - but sometimes model produce FAIL swap (do not do any swapping). It's known inner bug."
|
249 |
-
)
|
250 |
-
gr.Markdown(
|
251 |
-
"***Hyperswap models do not need Face Restorer - use it with None. Inswapper_128 need Face Restorer - use it with GPEN-BFR-512 at strenght 0.7-0.8."
|
252 |
-
)
|
253 |
-
gr.Markdown(
|
254 |
-
"***ComfyUI Reactor Fast Face Swap Hyperswap running directly on Gradio. - "
|
255 |
-
"[How to convert your any ComfyUI workflow to Gradio]"
|
256 |
-
"(https://huggingface.co/blog/run-comfyui-workflows-on-spaces)"
|
257 |
-
)
|
258 |
-
|
259 |
-
with gr.Column():
|
260 |
-
# Вывод изображения
|
261 |
-
output_image = gr.Image(label="Generated Image")
|
262 |
-
|
263 |
-
# Связываем клик кнопки с функцией
|
264 |
-
generate_btn.click(
|
265 |
-
fn=generate_image,
|
266 |
-
inputs=[source_image, target_image, target_index, swap_model, face_restore_model, restore_strength],
|
267 |
-
outputs=[output_image]
|
268 |
-
)
|
269 |
-
|
270 |
-
app.launch(share=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
app.py
CHANGED
@@ -142,21 +142,21 @@ def import_custom_nodes() -> None:
|
|
142 |
# Initializing custom nodes
|
143 |
# Запускаем корутину и ждём её завершения
|
144 |
loop.run_until_complete(init_extra_nodes())
|
145 |
-
# init_extra_nodes()
|
146 |
|
147 |
import_custom_nodes()
|
148 |
from nodes import NODE_CLASS_MAPPINGS
|
149 |
|
150 |
-
|
|
|
|
|
|
|
|
|
|
|
151 |
def generate_image(source_image, target_image, target_index, swap_model, face_restore_model, restore_strength):
|
152 |
with torch.inference_mode():
|
153 |
-
loadimage = NODE_CLASS_MAPPINGS["LoadImage"]()
|
154 |
loadimage_2 = loadimage.load_image(image=source_image)
|
155 |
loadimage_3 = loadimage.load_image(image=target_image)
|
156 |
|
157 |
-
reactorfaceswap = NODE_CLASS_MAPPINGS["ReActorFaceSwap"]()
|
158 |
-
saveimage = NODE_CLASS_MAPPINGS["SaveImage"]()
|
159 |
-
|
160 |
reactorfaceswap_76 = reactorfaceswap.execute(
|
161 |
enabled=True,
|
162 |
swap_model=swap_model, # Используем выбранную модель
|
@@ -210,12 +210,10 @@ if __name__ == "__main__":
|
|
210 |
|
211 |
# Кнопка генерации
|
212 |
generate_btn = gr.Button("Generate")
|
213 |
-
gr.Markdown(
|
214 |
-
|
215 |
-
|
216 |
-
gr.Markdown(
|
217 |
-
"***Hyperswap models do not need Face Restorer - use it with None. Inswapper_128 need Face Restorer - use it with GPEN-BFR-512 at strenght 0.7-0.8."
|
218 |
-
)
|
219 |
gr.Markdown(
|
220 |
"***ComfyUI Reactor Fast Face Swap Hyperswap running directly on Gradio. - "
|
221 |
"[How to convert your any ComfyUI workflow to Gradio]"
|
|
|
142 |
# Initializing custom nodes
|
143 |
# Запускаем корутину и ждём её завершения
|
144 |
loop.run_until_complete(init_extra_nodes())
|
|
|
145 |
|
146 |
import_custom_nodes()
|
147 |
from nodes import NODE_CLASS_MAPPINGS
|
148 |
|
149 |
+
# --- Глобальная загрузка моделей (один раз при старте) ---
|
150 |
+
loadimage = NODE_CLASS_MAPPINGS["LoadImage"]()
|
151 |
+
reactorfaceswap = NODE_CLASS_MAPPINGS["ReActorFaceSwap"]()
|
152 |
+
saveimage = NODE_CLASS_MAPPINGS["SaveImage"]()
|
153 |
+
|
154 |
+
@spaces.GPU
|
155 |
def generate_image(source_image, target_image, target_index, swap_model, face_restore_model, restore_strength):
|
156 |
with torch.inference_mode():
|
|
|
157 |
loadimage_2 = loadimage.load_image(image=source_image)
|
158 |
loadimage_3 = loadimage.load_image(image=target_image)
|
159 |
|
|
|
|
|
|
|
160 |
reactorfaceswap_76 = reactorfaceswap.execute(
|
161 |
enabled=True,
|
162 |
swap_model=swap_model, # Используем выбранную модель
|
|
|
210 |
|
211 |
# Кнопка генерации
|
212 |
generate_btn = gr.Button("Generate")
|
213 |
+
gr.Markdown("***Hyperswap_1b_256.onnx is the best (in most cases) - but sometimes model produce FAIL swap (do not do any swapping). It's known inner bug.")
|
214 |
+
gr.Markdown("***Hyperswap models do not need Face Restorer - use it with None. Inswapper_128 need Face Restorer - use it with GPEN-BFR-512 at strenght 0.7-0.8.")
|
215 |
+
# gr.Markdown("***Standard time of one generation - 23 sec per image.")
|
216 |
+
gr.Markdown("***Use Private window in your browser (this clear coockies) and SoftEther VPN (this change your IP) - for expand your limit.")
|
|
|
|
|
217 |
gr.Markdown(
|
218 |
"***ComfyUI Reactor Fast Face Swap Hyperswap running directly on Gradio. - "
|
219 |
"[How to convert your any ComfyUI workflow to Gradio]"
|