mr2along commited on
Commit
59a292b
·
verified ·
1 Parent(s): 409bb3b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +219 -240
app.py CHANGED
@@ -1,300 +1,279 @@
1
  import os
2
- import torch
3
- from comfy.model_management import CPUState # Импорт из того же файла
4
 
5
- # Отключаем CUDA, чтобы избежать инициализации
 
 
6
  os.environ["CUDA_VISIBLE_DEVICES"] = ""
7
  os.environ["PYTORCH_CUDA_ALLOC_CONF"] = ""
8
 
9
- # Принудительно устанавливаем CPU режим
10
- import comfy.model_management
11
- comfy.model_management.cpu_state = CPUState.CPU
12
-
13
- import random
14
  import sys
 
 
 
 
 
 
15
  from typing import Sequence, Mapping, Any, Union
16
- import torch
17
  from PIL import Image
18
  from huggingface_hub import hf_hub_download
19
- import spaces
20
 
21
- import subprocess, sys
 
 
22
 
23
- import gradio
24
- import gradio_client
25
- import gradio as gr
 
 
26
 
27
- print("gradio version:", gradio.__version__)
28
- print("gradio_client version:", gradio_client.__version__)
 
 
 
29
 
30
- hf_hub_download(repo_id="facefusion/models-3.3.0", filename="hyperswap_1a_256.onnx", local_dir="models/hyperswap")
31
- hf_hub_download(repo_id="facefusion/models-3.3.0", filename="hyperswap_1b_256.onnx", local_dir="models/hyperswap")
32
- hf_hub_download(repo_id="facefusion/models-3.3.0", filename="hyperswap_1c_256.onnx", local_dir="models/hyperswap")
33
-
34
- hf_hub_download(repo_id="martintomov/comfy", filename="facedetection/yolov5l-face.pth", local_dir="models")
35
- ###hf_hub_download(repo_id="darkeril/collection", filename="detection_Resnet50_Final.pth", local_dir="models/facedetection")
36
- hf_hub_download(repo_id="gmk123/GFPGAN", filename="parsing_parsenet.pth", local_dir="models/facedetection")
37
-
38
- hf_hub_download(repo_id="MonsterMMORPG/tools", filename="1k3d68.onnx", local_dir="models/insightface/models/buffalo_l")
39
- hf_hub_download(repo_id="MonsterMMORPG/tools", filename="2d106det.onnx", local_dir="models/insightface/models/buffalo_l")
40
- hf_hub_download(repo_id="maze/faceX", filename="det_10g.onnx", local_dir="models/insightface/models/buffalo_l")
41
- hf_hub_download(repo_id="typhoon01/aux_models", filename="genderage.onnx", local_dir="models/insightface/models/buffalo_l")
42
- hf_hub_download(repo_id="maze/faceX", filename="w600k_r50.onnx", local_dir="models/insightface/models/buffalo_l")
43
-
44
- hf_hub_download(repo_id="vladmandic/insightface-faceanalysis", filename="buffalo_l.zip", local_dir="models/insightface/models/buffalo_l")
45
 
 
 
 
46
 
47
  def get_value_at_index(obj: Union[Sequence, Mapping], index: int) -> Any:
48
- """Returns the value at the given index of a sequence or mapping.
49
- If the object is a sequence (like list or string), returns the value at the given index.
50
- If the object is a mapping (like a dictionary), returns the value at the index-th key.
51
- Some return a dictionary, in these cases, we look for the "results" key
52
- Args:
53
- obj (Union[Sequence, Mapping]): The object to retrieve the value from.
54
- index (int): The index of the value to retrieve.
55
- Returns:
56
- Any: The value at the given index.
57
- Raises:
58
- IndexError: If the index is out of bounds for the object and the object is not a mapping.
59
- """
60
  try:
61
  return obj[index]
62
- except KeyError:
63
  return obj["result"][index]
64
 
65
-
66
  def find_path(name: str, path: str = None) -> str:
67
- """
68
- Recursively looks at parent folders starting from the given path until it finds the given name.
69
- Returns the path as a Path object if found, or None otherwise.
70
- """
71
- # If no path is given, use the current working directory
72
  if path is None:
73
  path = os.getcwd()
74
 
75
- # Check if the current directory contains the name
76
  if name in os.listdir(path):
77
- path_name = os.path.join(path, name)
78
- print(f"{name} found: {path_name}")
79
- return path_name
80
 
81
- # Get the parent directory
82
- parent_directory = os.path.dirname(path)
83
-
84
- # If the parent directory is the same as the current directory, we've reached the root and stop the search
85
- if parent_directory == path:
86
  return None
87
 
88
- # Recursively call the function with the parent directory
89
- return find_path(name, parent_directory)
90
-
91
 
92
- def add_comfyui_directory_to_sys_path() -> None:
93
- """
94
- Add 'ComfyUI' to the sys.path
95
- """
96
  comfyui_path = find_path("ComfyUI")
97
- if comfyui_path is not None and os.path.isdir(comfyui_path):
98
  sys.path.append(comfyui_path)
99
- print(f"'{comfyui_path}' added to sys.path")
100
 
 
101
 
102
- def add_extra_model_paths() -> None:
103
- """
104
- Parse the optional extra_model_paths.yaml file and add the parsed paths to the sys.path.
105
- """
106
  try:
107
  from main import load_extra_path_config
108
  except ImportError:
109
- print(
110
- "Could not import load_extra_path_config from main.py. Looking in utils.extra_config instead."
111
- )
112
  from utils.extra_config import load_extra_path_config
113
 
114
  extra_model_paths = find_path("extra_model_paths.yaml")
115
-
116
- if extra_model_paths is not None:
117
  load_extra_path_config(extra_model_paths)
118
- else:
119
- print("Could not find the extra_model_paths config file.")
120
-
121
 
122
- add_comfyui_directory_to_sys_path()
123
  add_extra_model_paths()
124
 
125
-
126
- def import_custom_nodes() -> None:
127
- """Find all custom nodes in the custom_nodes folder and add those node objects to NODE_CLASS_MAPPINGS
128
- This function sets up a new asyncio event loop, initializes the PromptServer,
129
- creates a PromptQueue, and initializes the custom nodes.
130
- """
131
- import asyncio
132
  import execution
133
  from nodes import init_extra_nodes
134
  import server
135
 
136
- # Creating a new event loop and setting it as the default loop
137
  loop = asyncio.new_event_loop()
138
  asyncio.set_event_loop(loop)
139
 
140
- # Creating an instance of PromptServer with the loop
141
  server_instance = server.PromptServer(loop)
142
  execution.PromptQueue(server_instance)
143
-
144
- # Initializing custom nodes
145
- # Запускаем корутину и ждём её завершения
146
  loop.run_until_complete(init_extra_nodes())
147
 
148
  import_custom_nodes()
 
149
  from nodes import NODE_CLASS_MAPPINGS
150
 
151
- # --- Глобальная загрузка моделей (один раз при старте) ---
152
  loadimage = NODE_CLASS_MAPPINGS["LoadImage"]()
153
- vhs_loadvideo = NODE_CLASS_MAPPINGS["VHS_LoadVideo"]()
154
- reactoroptions = NODE_CLASS_MAPPINGS["ReActorOptions"]()
155
- vhs_videoinfoloaded = NODE_CLASS_MAPPINGS["VHS_VideoInfoLoaded"]()
156
- reactorfaceswapopt = NODE_CLASS_MAPPINGS["ReActorFaceSwapOpt"]()
157
- vhs_videocombine = NODE_CLASS_MAPPINGS["VHS_VideoCombine"]()
158
-
159
- # @spaces.GPU(duration=60)
160
- def generate_image(source_image, input_video, input_index, input_faces_order, swap_model, pingpong, loop_count, select_every_nth, use_audio):
 
 
 
 
 
 
 
161
  with torch.inference_mode():
162
- loadimage_29 = loadimage.load_image(image=source_image)
163
-
164
- vhs_loadvideo_51 = vhs_loadvideo.load_video(
165
- video=input_video,
166
- force_rate=0,
167
- custom_width=0,
168
- custom_height=0,
169
- frame_load_cap=0,
170
- skip_first_frames=0,
171
- select_every_nth=select_every_nth,
172
- format="AnimateDiff",
173
- unique_id=17765013700631265033,
174
- )
175
-
176
- reactoroptions_107 = reactoroptions.execute(
177
- input_faces_order=input_faces_order,
178
- input_faces_index=str(input_index), # Преобразуем в строку
179
- detect_gender_input="no",
180
- source_faces_order="large-small",
181
- source_faces_index="0",
182
- detect_gender_source="no",
183
- console_log_level=1,
184
- )
185
-
186
- for q in range(1):
187
- vhs_videoinfoloaded_105 = vhs_videoinfoloaded.get_video_info(
188
- video_info=get_value_at_index(vhs_loadvideo_51, 3)
189
- )
190
-
191
- reactorfaceswapopt_106 = reactorfaceswapopt.execute(
192
- enabled=True,
193
- swap_model=swap_model, # Используем выбранную модель
194
- facedetection="YOLOv5l",
195
- face_restore_model="none",
196
- face_restore_visibility=1,
197
- codeformer_weight=0.5,
198
- input_image=get_value_at_index(vhs_loadvideo_51, 0),
199
- source_image=get_value_at_index(loadimage_29, 0),
200
- options=get_value_at_index(reactoroptions_107, 0),
201
- )
202
-
203
- # Формируем аргументы для combine_video
204
- combine_kwargs = dict(
205
- frame_rate=get_value_at_index(vhs_videoinfoloaded_105, 0),
206
- loop_count=loop_count,
207
- filename_prefix="vidswap",
208
- format="video/h264-mp4",
209
- pix_fmt="yuv420p",
210
- crf=20,
211
- save_metadata=False,
212
- trim_to_audio=False,
213
- pingpong=pingpong,
214
- save_output=True,
215
- images=get_value_at_index(reactorfaceswapopt_106, 0),
216
- unique_id=17889577966051683261,
217
- )
218
-
219
- if use_audio:
220
- combine_kwargs["audio"] = get_value_at_index(vhs_loadvideo_51, 2)
221
-
222
- vhs_videocombine_28 = vhs_videocombine.combine_video(**combine_kwargs)
223
-
224
- saved_path = f"output/{vhs_videocombine_28['ui']['gifs'][0]['filename']}"
225
- return saved_path
226
-
227
- if __name__ == "__main__":
228
- with gr.Blocks() as app:
229
- with gr.Row():
230
- with gr.Column():
231
- # Вложенный Row для групп
232
- with gr.Row():
233
- # Первая группа
234
- with gr.Group():
235
- source_image = gr.Image(label="Source Image (Face)", type="filepath")
236
- swap_model = gr.Dropdown(
237
- choices=["hyperswap_1a_256.onnx", "hyperswap_1b_256.onnx", "hyperswap_1c_256.onnx"],
238
- value="hyperswap_1b_256.onnx",
239
- label="Swap Model"
240
  )
241
- input_index = gr.Dropdown(choices=[0, 1, 2, 3, 4], value=0, label="Target Face Index")
242
- input_faces_order_dropdown = gr.Dropdown(
243
- choices=[
244
- "left-right",
245
- "right-left",
246
- "top-bottom",
247
- "bottom-top",
248
- "large-small"
249
- ],
250
- value="large-small", # значение по умолчанию
251
- label="Target Faces Order")
252
-
253
- # Вторая группа (обратите внимание — она должна быть на том же уровне, что и первая)
254
- with gr.Group():
255
- input_video = gr.File(label="Target Video (Body)",file_types=[".mp4", ".gif"],type="filepath")
256
- select_every_nth = gr.Dropdown(choices=[1, 2], value=1, label='"1" = choose every frame, "2" - every second frame')
257
- loop_count = gr.Dropdown(choices=[0, 1, 2, 3, 4], value=0, label='"Loop_Count" = repeat loop append to your video')
258
- pingpong_checkbox = gr.Checkbox(label='"Pingpong" = reverse append to your video', value=False)
259
- audio_checkbox = gr.Checkbox(label='"Audio" = enable audio', value=False)
260
-
261
- # Кнопка генерации
262
- generate_btn = gr.Button("Check: Audio? Loop Count? Pingpong? Generate!")
263
-
264
- with gr.Column():
265
- # Вывод результата
266
- output_video = gr.Video(label="Generated Video")
267
- # with gr.Accordion("Notes (click to open)", open=False):
268
- # gr.Markdown("Added text here")
269
-
270
- with gr.Row():
271
- with gr.Column(scale=1):
272
- text = """
273
- ***Hyperswap_1b_256.onnx is the best (in most cases) - but model has inner bug - sometimes they produce "FAIL" swap (working, but do not do any swapping - on SOME faces. So, for stability - do test image to image face swap on one screenshot from your video first). Most stable version is Hyperswap_1a_256.onnx.
274
-
275
- ***Target_Face_Index: Index_0 = First Face. To switch for another target face - switch to Index_1, Index_2, e.t.c.
276
- ***Note: "1" or "2" - 'every frame' or 'every second frame' - if you have video 60fps or 48 fps - you can choose "2" to select every 2nd frame - for two time reduce total number of frames in video (got 30 fps and 24 fps video, accordingly).
277
- ***Video 05 sec * 24 fps = 120 frames/720p = takes 275 sec (4.5 min) for generating. Overall: SECONDS --> MINUTES.
278
- ***To cancel job - just close your browser's page.
279
-
280
- ***If needed, use AdvancedLivePortrait to correct faces on video before swapping. Here is [workflow](https://openart.ai/workflows/ocelot_vibrant_0/advanced-liveportrait-for-video-as-source/hV07PExjpK3JEd6kNnkr) for ComfyUI.
281
-
282
- ***Use Avidemux - simple but powerful freeware video editor. [Download](https://www.avidemux.org/nightly/) - choose win64 v2.8.2 for Windows 10.
283
-
284
- ***Use MediaInfo (freeware) to get information about video file - [Download](https://mediaarea.net/en/MediaInfo)
285
-
286
- ***Free and easy hosting for short mp4 files - [https://sendvid.com/](https://sendvid.com/)
287
-
288
- ***"ComfyUI Reactor Video Face Swap Hyperswap running directly on Gradio. - [How to convert your any ComfyUI workflow to Gradio](https://huggingface.co/blog/run-comfyui-workflows-on-spaces)
289
-
290
- """
291
- gr.Markdown(text)
292
-
293
- # Связываем клик кнопки с функцией
294
- generate_btn.click(
295
- fn=generate_image,
296
- inputs=[source_image, input_video, input_index, input_faces_order_dropdown, swap_model, pingpong_checkbox, loop_count, select_every_nth, audio_checkbox],
297
- outputs=[output_video]
298
- )
299
-
300
- app.launch(server_name="0.0.0.0",server_port=7860,ssr_mode=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
 
 
2
 
3
+ # =========================
4
+ # FORCE CPU MODE
5
+ # =========================
6
  os.environ["CUDA_VISIBLE_DEVICES"] = ""
7
  os.environ["PYTORCH_CUDA_ALLOC_CONF"] = ""
8
 
9
+ import torch
 
 
 
 
10
  import sys
11
+ import asyncio
12
+ import imageio
13
+ import tempfile
14
+ import numpy as np
15
+ import gradio as gr
16
+
17
  from typing import Sequence, Mapping, Any, Union
 
18
  from PIL import Image
19
  from huggingface_hub import hf_hub_download
 
20
 
21
+ # =========================
22
+ # DOWNLOAD MODELS (ONLY IF NOT EXISTS)
23
+ # =========================
24
 
25
+ def download_if_not_exists(repo, filename, local_dir):
26
+ path = os.path.join(local_dir, filename)
27
+ if not os.path.exists(path):
28
+ os.makedirs(local_dir, exist_ok=True)
29
+ hf_hub_download(repo_id=repo, filename=filename, local_dir=local_dir)
30
 
31
+ download_if_not_exists("ezioruan/inswapper_128.onnx", "inswapper_128.onnx", "models/insightface")
32
+ download_if_not_exists("martintomov/comfy", "facerestore_models/GPEN-BFR-512.onnx", "models")
33
+ download_if_not_exists("facefusion/models-3.3.0", "hyperswap_1a_256.onnx", "models/hyperswap")
34
+ download_if_not_exists("facefusion/models-3.3.0", "hyperswap_1b_256.onnx", "models/hyperswap")
35
+ download_if_not_exists("facefusion/models-3.3.0", "hyperswap_1c_256.onnx", "models/hyperswap")
36
 
37
+ # =========================
38
+ # COMFY INIT (GIỮ NGUYÊN)
39
+ # =========================
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
+ from comfy.model_management import CPUState
42
+ import comfy.model_management
43
+ comfy.model_management.cpu_state = CPUState.CPU
44
 
45
  def get_value_at_index(obj: Union[Sequence, Mapping], index: int) -> Any:
 
 
 
 
 
 
 
 
 
 
 
 
46
  try:
47
  return obj[index]
48
+ except Exception:
49
  return obj["result"][index]
50
 
 
51
  def find_path(name: str, path: str = None) -> str:
 
 
 
 
 
52
  if path is None:
53
  path = os.getcwd()
54
 
 
55
  if name in os.listdir(path):
56
+ return os.path.join(path, name)
 
 
57
 
58
+ parent = os.path.dirname(path)
59
+ if parent == path:
 
 
 
60
  return None
61
 
62
+ return find_path(name, parent)
 
 
63
 
64
+ def add_comfyui_directory_to_sys_path():
 
 
 
65
  comfyui_path = find_path("ComfyUI")
66
+ if comfyui_path and os.path.isdir(comfyui_path):
67
  sys.path.append(comfyui_path)
 
68
 
69
+ add_comfyui_directory_to_sys_path()
70
 
71
+ def add_extra_model_paths():
 
 
 
72
  try:
73
  from main import load_extra_path_config
74
  except ImportError:
 
 
 
75
  from utils.extra_config import load_extra_path_config
76
 
77
  extra_model_paths = find_path("extra_model_paths.yaml")
78
+ if extra_model_paths:
 
79
  load_extra_path_config(extra_model_paths)
 
 
 
80
 
 
81
  add_extra_model_paths()
82
 
83
+ def import_custom_nodes():
 
 
 
 
 
 
84
  import execution
85
  from nodes import init_extra_nodes
86
  import server
87
 
 
88
  loop = asyncio.new_event_loop()
89
  asyncio.set_event_loop(loop)
90
 
 
91
  server_instance = server.PromptServer(loop)
92
  execution.PromptQueue(server_instance)
 
 
 
93
  loop.run_until_complete(init_extra_nodes())
94
 
95
  import_custom_nodes()
96
+
97
  from nodes import NODE_CLASS_MAPPINGS
98
 
 
99
  loadimage = NODE_CLASS_MAPPINGS["LoadImage"]()
100
+ reactorfaceswap = NODE_CLASS_MAPPINGS["ReActorFaceSwap"]()
101
+
102
+ # =========================
103
+ # MAIN FUNCTION
104
+ # =========================
105
+
106
+ def generate_image(source_files, target_files, target_index,
107
+ swap_model, face_restore_model, restore_strength):
108
+
109
+ os.makedirs("output", exist_ok=True)
110
+ output_paths = []
111
+
112
+ if not source_files or not target_files:
113
+ return []
114
+
115
  with torch.inference_mode():
116
+
117
+ for s in source_files:
118
+
119
+ source_path = s.name
120
+ loadimage_source = loadimage.load_image(image=source_path)
121
+ source_tensor = get_value_at_index(loadimage_source, 0)
122
+ source_base = os.path.splitext(os.path.basename(source_path))[0]
123
+
124
+ for t in target_files:
125
+
126
+ target_path = t.name
127
+ target_base = os.path.splitext(os.path.basename(target_path))[0]
128
+
129
+ # ================= GIF =================
130
+ if target_path.lower().endswith(".gif"):
131
+
132
+ reader = imageio.get_reader(target_path)
133
+ frames = []
134
+ durations = []
135
+
136
+ for i, frame in enumerate(reader):
137
+ frame_rgb = Image.fromarray(frame).convert("RGB")
138
+ frames.append(np.array(frame_rgb))
139
+ meta = reader.get_meta_data(index=i)
140
+ durations.append(meta.get("duration", 100))
141
+
142
+ reader.close()
143
+
144
+ output_frames = []
145
+
146
+ for frame in frames:
147
+
148
+ with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
149
+ Image.fromarray(frame).save(tmp.name)
150
+ temp_path = tmp.name
151
+
152
+ loadimage_target = loadimage.load_image(image=temp_path)
153
+ target_tensor = get_value_at_index(loadimage_target, 0)
154
+
155
+ result = reactorfaceswap.execute(
156
+ enabled=True,
157
+ swap_model=swap_model,
158
+ facedetection="YOLOv5l",
159
+ face_restore_model=face_restore_model,
160
+ face_restore_visibility=restore_strength,
161
+ codeformer_weight=0.5,
162
+ detect_gender_input="no",
163
+ detect_gender_source="no",
164
+ input_faces_index=str(target_index),
165
+ source_faces_index="0",
166
+ console_log_level=1,
167
+ input_image=target_tensor,
168
+ source_image=source_tensor,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
169
  )
170
+
171
+ swapped = get_value_at_index(result, 0)[0]
172
+
173
+ if isinstance(swapped, torch.Tensor):
174
+ swapped = swapped.detach().cpu().float().numpy()
175
+
176
+ if swapped.max() <= 1.0:
177
+ swapped *= 255.0
178
+
179
+ swapped = np.clip(swapped, 0, 255).astype(np.uint8)
180
+
181
+ output_frames.append(Image.fromarray(swapped).convert("RGB"))
182
+ os.remove(temp_path)
183
+
184
+ output_path = f"output/{source_base}_to_{target_base}.webp"
185
+
186
+ output_frames[0].save(
187
+ output_path,
188
+ save_all=True,
189
+ append_images=output_frames[1:],
190
+ duration=durations,
191
+ loop=0,
192
+ format="WEBP",
193
+ quality=90,
194
+ method=6
195
+ )
196
+
197
+ # ================= IMAGE =================
198
+ else:
199
+
200
+ loadimage_target = loadimage.load_image(image=target_path)
201
+ target_tensor = get_value_at_index(loadimage_target, 0)
202
+
203
+ result = reactorfaceswap.execute(
204
+ enabled=True,
205
+ swap_model=swap_model,
206
+ facedetection="YOLOv5l",
207
+ face_restore_model=face_restore_model,
208
+ face_restore_visibility=restore_strength,
209
+ codeformer_weight=0.5,
210
+ detect_gender_input="no",
211
+ detect_gender_source="no",
212
+ input_faces_index=str(target_index),
213
+ source_faces_index="0",
214
+ console_log_level=1,
215
+ input_image=target_tensor,
216
+ source_image=source_tensor,
217
+ )
218
+
219
+ swapped = get_value_at_index(result, 0)[0]
220
+
221
+ if isinstance(swapped, torch.Tensor):
222
+ swapped = swapped.detach().cpu().float().numpy()
223
+
224
+ if swapped.max() <= 1.0:
225
+ swapped *= 255.0
226
+
227
+ swapped = np.clip(swapped, 0, 255).astype(np.uint8)
228
+
229
+ output_path = f"output/{source_base}_to_{target_base}.webp"
230
+
231
+ Image.fromarray(swapped).save(
232
+ output_path,
233
+ format="WEBP",
234
+ quality=90,
235
+ method=6
236
+ )
237
+
238
+ output_paths.append(output_path)
239
+
240
+ return output_paths
241
+
242
+ # =========================
243
+ # GRADIO UI
244
+ # =========================
245
+
246
+ with gr.Blocks() as app:
247
+
248
+ source_files = gr.File(label="Source Faces", file_count="multiple", interactive=True)
249
+ target_files = gr.File(label="Target Images / GIFs", file_count="multiple", interactive=True)
250
+
251
+ swap_model = gr.Dropdown(
252
+ choices=["inswapper_128.onnx",
253
+ "hyperswap_1a_256.onnx",
254
+ "hyperswap_1b_256.onnx",
255
+ "hyperswap_1c_256.onnx"],
256
+ value="hyperswap_1b_256.onnx",
257
+ label="Swap Model"
258
+ )
259
+
260
+ face_restore_model = gr.Dropdown(
261
+ choices=["none", "GPEN-BFR-512.onnx"],
262
+ value="none",
263
+ label="Face Restore Model"
264
+ )
265
+
266
+ restore_strength = gr.Slider(0, 1, 0.7, step=0.05)
267
+ target_index = gr.Dropdown([0,1,2,3,4], value=0)
268
+
269
+ generate_btn = gr.Button("Generate")
270
+ output_files = gr.Files(label="Output WebPs")
271
+
272
+ generate_btn.click(
273
+ fn=generate_image,
274
+ inputs=[source_files, target_files, target_index,
275
+ swap_model, face_restore_model, restore_strength],
276
+ outputs=output_files
277
+ )
278
+
279
+ app.launch(share=True)