cosmicweb98 commited on
Commit
81ebb6a
·
verified ·
1 Parent(s): 5de33df

Upload 7 files

Browse files
ui/globals.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ui_restart_server = False
2
+
3
+ SELECTION_FACES_DATA = None
4
+ ui_SELECTED_INPUT_FACE_INDEX = 0
5
+
6
+ ui_selected_enhancer = None
7
+ ui_upscale = None
8
+ ui_blend_ratio = None
9
+ ui_input_thumbs = []
10
+ ui_target_thumbs = []
11
+ ui_camera_frame = None
12
+
13
+
14
+
15
+
16
+
ui/main.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ import gradio as gr
4
+ import roop.globals
5
+ import roop.metadata
6
+ import roop.utilities as util
7
+ import ui.globals as uii
8
+
9
+ from ui.tabs.faceswap_tab import faceswap_tab
10
+ from ui.tabs.livecam_tab import livecam_tab
11
+ from ui.tabs.facemgr_tab import facemgr_tab
12
+ from ui.tabs.extras_tab import extras_tab
13
+ from ui.tabs.settings_tab import settings_tab
14
+
15
+ roop.globals.keep_fps = None
16
+ roop.globals.keep_frames = None
17
+ roop.globals.skip_audio = None
18
+ roop.globals.use_batch = None
19
+
20
+
21
+ def prepare_environment():
22
+ roop.globals.output_path = os.path.abspath(os.path.join(os.getcwd(), "output"))
23
+ os.makedirs(roop.globals.output_path, exist_ok=True)
24
+ if not roop.globals.CFG.use_os_temp_folder:
25
+ os.environ["TEMP"] = os.environ["TMP"] = os.path.abspath(os.path.join(os.getcwd(), "temp"))
26
+ os.makedirs(os.environ["TEMP"], exist_ok=True)
27
+ os.environ["GRADIO_TEMP_DIR"] = os.environ["TEMP"]
28
+ os.environ['GRADIO_ANALYTICS_ENABLED'] = '0'
29
+
30
+
31
+ def run():
32
+ from roop.core import decode_execution_providers, set_display_ui
33
+
34
+ prepare_environment()
35
+
36
+ set_display_ui(show_msg)
37
+ roop.globals.execution_providers = decode_execution_providers([roop.globals.CFG.provider])
38
+ print(f'Using provider {roop.globals.execution_providers} - Device:{util.get_device()}')
39
+
40
+ run_server = True
41
+ uii.ui_restart_server = False
42
+ mycss = """
43
+ span {color: var(--block-info-text-color)}
44
+ #fixedheight {
45
+ max-height: 238.4px;
46
+ overflow-y: auto !important;
47
+ }
48
+ .image-container.svelte-1l6wqyv {height: 100%}
49
+
50
+ """
51
+
52
+ while run_server:
53
+ server_name = roop.globals.CFG.server_name
54
+ if server_name is None or len(server_name) < 1:
55
+ server_name = None
56
+ server_port = roop.globals.CFG.server_port
57
+ if server_port <= 0:
58
+ server_port = None
59
+ ssl_verify = False if server_name == '0.0.0.0' else True
60
+ with gr.Blocks(title=f'{roop.metadata.name} {roop.metadata.version}', theme=roop.globals.CFG.selected_theme, css=mycss, delete_cache=(60, 86400)) as ui:
61
+ with gr.Row(variant='compact'):
62
+ gr.Markdown(f"### [{roop.metadata.name} {roop.metadata.version}](https://github.com/C0untFloyd/roop-unleashed)")
63
+ gr.HTML(util.create_version_html(), elem_id="versions")
64
+ faceswap_tab()
65
+ livecam_tab()
66
+ facemgr_tab()
67
+ extras_tab()
68
+ settings_tab()
69
+
70
+ uii.ui_restart_server = False
71
+ try:
72
+ ui.queue().launch(inbrowser=True, server_name=server_name, server_port=server_port, share=roop.globals.CFG.server_share, ssl_verify=ssl_verify, prevent_thread_lock=True, show_error=True)
73
+ except Exception as e:
74
+ print(f'Exception {e} when launching Gradio Server!')
75
+ uii.ui_restart_server = True
76
+ run_server = False
77
+ try:
78
+ while uii.ui_restart_server == False:
79
+ time.sleep(1.0)
80
+
81
+ except (KeyboardInterrupt, OSError):
82
+ print("Keyboard interruption in main thread... closing server.")
83
+ run_server = False
84
+ ui.close()
85
+
86
+
87
+ def show_msg(msg: str):
88
+ gr.Info(msg)
89
+
ui/tabs/extras_tab.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import shutil
4
+ import roop.utilities as util
5
+ import roop.util_ffmpeg as ffmpeg
6
+ import roop.globals
7
+
8
+ frame_filters_map = {
9
+ "Colorize B/W Images (Deoldify Artistic)" : {"colorizer" : {"subtype": "deoldify_artistic"}},
10
+ "Colorize B/W Images (Deoldify Stable)" : {"colorizer" : {"subtype": "deoldify_stable"}},
11
+ "Background remove" : {"removebg" : {"subtype": ""}},
12
+ "Filter Stylize" : {"filter_generic" : {"subtype" : "stylize" }},
13
+ "Filter Detail Enhance" : {"filter_generic" : {"subtype" : "detailenhance" }},
14
+ "Filter Pencil Sketch" : {"filter_generic" : {"subtype" : "pencil" }},
15
+ "Filter Cartoon" : {"filter_generic" : {"subtype" : "cartoon" }},
16
+ "Filter C64" : {"filter_generic" : {"subtype" : "C64" }}
17
+ }
18
+
19
+ frame_upscalers_map = {
20
+ "ESRGAN x2" : {"upscale" : {"subtype": "esrganx2"}},
21
+ "ESRGAN x4" : {"upscale" : {"subtype": "esrganx4"}},
22
+ "LSDIR x4" : {"upscale" : {"subtype": "lsdirx4"}}
23
+ }
24
+
25
+ def extras_tab():
26
+ filternames = ["None"]
27
+ for f in frame_filters_map.keys():
28
+ filternames.append(f)
29
+ upscalernames = ["None"]
30
+ for f in frame_upscalers_map.keys():
31
+ upscalernames.append(f)
32
+
33
+ with gr.Tab("🎉 Extras"):
34
+ with gr.Row():
35
+ files_to_process = gr.Files(label='File(s) to process', file_count="multiple", file_types=["image", "video"])
36
+ with gr.Row(variant='panel'):
37
+ with gr.Accordion(label="Video/GIF", open=False):
38
+ with gr.Row(variant='panel'):
39
+ with gr.Column():
40
+ gr.Markdown("""
41
+ # Poor man's video editor
42
+ Re-encoding uses your configuration from the Settings Tab.
43
+ """)
44
+ with gr.Column():
45
+ cut_start_time = gr.Slider(0, 1000000, value=0, label="Start Frame", step=1.0, interactive=True)
46
+ with gr.Column():
47
+ cut_end_time = gr.Slider(1, 1000000, value=1, label="End Frame", step=1.0, interactive=True)
48
+ with gr.Column():
49
+ extras_chk_encode = gr.Checkbox(label='Re-encode videos (necessary for videos with different codecs)', value=False)
50
+ start_cut_video = gr.Button("Cut video")
51
+ start_extract_frames = gr.Button("Extract frames")
52
+ start_join_videos = gr.Button("Join videos")
53
+
54
+ with gr.Row(variant='panel'):
55
+ with gr.Column():
56
+ gr.Markdown("""
57
+ # Create video/gif from images
58
+ """)
59
+ with gr.Column():
60
+ extras_fps = gr.Slider(minimum=0, maximum=120, value=30, label="Video FPS", step=1.0, interactive=True)
61
+ extras_images_folder = gr.Textbox(show_label=False, placeholder="/content/", interactive=True)
62
+ with gr.Column():
63
+ extras_chk_creategif = gr.Checkbox(label='Create GIF from video', value=False)
64
+ extras_create_video=gr.Button("Create")
65
+ with gr.Row(variant='panel'):
66
+ with gr.Accordion(label="Full frame processing", open=True):
67
+ with gr.Row(variant='panel'):
68
+ filterselection = gr.Dropdown(filternames, value="None", label="Colorizer/FilterFX", interactive=True)
69
+ upscalerselection = gr.Dropdown(upscalernames, value="None", label="Enhancer", interactive=True)
70
+ with gr.Row(variant='panel'):
71
+ start_frame_process=gr.Button("Start processing")
72
+
73
+ with gr.Row():
74
+ gr.Button("👀 Open Output Folder", size='sm').click(fn=lambda: util.open_folder(roop.globals.output_path))
75
+ with gr.Row():
76
+ extra_files_output = gr.Files(label='Resulting output files', file_count="multiple")
77
+
78
+ start_cut_video.click(fn=on_cut_video, inputs=[files_to_process, cut_start_time, cut_end_time, extras_chk_encode], outputs=[extra_files_output])
79
+ start_extract_frames.click(fn=on_extras_extract_frames, inputs=[files_to_process], outputs=[extra_files_output])
80
+ start_join_videos.click(fn=on_join_videos, inputs=[files_to_process, extras_chk_encode], outputs=[extra_files_output])
81
+ extras_create_video.click(fn=on_extras_create_video, inputs=[extras_images_folder, extras_fps, extras_chk_creategif], outputs=[extra_files_output])
82
+ start_frame_process.click(fn=on_frame_process, inputs=[files_to_process, filterselection, upscalerselection], outputs=[extra_files_output])
83
+
84
+
85
+ def on_cut_video(files, cut_start_frame, cut_end_frame, reencode):
86
+ if files is None:
87
+ return None
88
+
89
+ resultfiles = []
90
+ for tf in files:
91
+ f = tf.name
92
+ destfile = util.get_destfilename_from_path(f, roop.globals.output_path, '_cut')
93
+ ffmpeg.cut_video(f, destfile, cut_start_frame, cut_end_frame, reencode)
94
+ if os.path.isfile(destfile):
95
+ resultfiles.append(destfile)
96
+ else:
97
+ gr.Error('Cutting video failed!')
98
+ return resultfiles
99
+
100
+
101
+ def on_join_videos(files, chk_encode):
102
+ if files is None:
103
+ return None
104
+
105
+ filenames = []
106
+ for f in files:
107
+ filenames.append(f.name)
108
+ destfile = util.get_destfilename_from_path(filenames[0], roop.globals.output_path, '_join')
109
+ sorted_filenames = util.sort_filenames_ignore_path(filenames)
110
+ ffmpeg.join_videos(sorted_filenames, destfile, not chk_encode)
111
+ resultfiles = []
112
+ if os.path.isfile(destfile):
113
+ resultfiles.append(destfile)
114
+ else:
115
+ gr.Error('Joining videos failed!')
116
+ return resultfiles
117
+
118
+
119
+
120
+ def on_extras_create_video(images_path,fps, create_gif):
121
+ util.sort_rename_frames(os.path.dirname(images_path))
122
+ destfilename = os.path.join(roop.globals.output_path, "img2video." + roop.globals.CFG.output_video_format)
123
+ ffmpeg.create_video('', destfilename, fps, images_path)
124
+ resultfiles = []
125
+ if os.path.isfile(destfilename):
126
+ resultfiles.append(destfilename)
127
+ else:
128
+ return None
129
+ if create_gif:
130
+ gifname = util.get_destfilename_from_path(destfilename, './output', '.gif')
131
+ ffmpeg.create_gif_from_video(destfilename, gifname)
132
+ if os.path.isfile(destfilename):
133
+ resultfiles.append(gifname)
134
+ return resultfiles
135
+
136
+
137
+ def on_extras_extract_frames(files):
138
+ if files is None:
139
+ return None
140
+
141
+ resultfiles = []
142
+ for tf in files:
143
+ f = tf.name
144
+ resfolder = ffmpeg.extract_frames(f)
145
+ for file in os.listdir(resfolder):
146
+ outfile = os.path.join(resfolder, file)
147
+ if os.path.isfile(outfile):
148
+ resultfiles.append(outfile)
149
+ return resultfiles
150
+
151
+
152
+ def on_frame_process(files, filterselection, upscaleselection):
153
+ import pathlib
154
+ from roop.core import batch_process_with_options
155
+ from roop.ProcessEntry import ProcessEntry
156
+ from roop.ProcessOptions import ProcessOptions
157
+ from ui.main import prepare_environment
158
+
159
+
160
+ if files is None:
161
+ return None
162
+
163
+ if roop.globals.CFG.clear_output:
164
+ shutil.rmtree(roop.globals.output_path)
165
+ prepare_environment()
166
+ list_files_process : list[ProcessEntry] = []
167
+
168
+ for tf in files:
169
+ list_files_process.append(ProcessEntry(tf.name, 0,0, 0))
170
+
171
+ processoroptions = {}
172
+ filter = next((x for x in frame_filters_map.keys() if x == filterselection), None)
173
+ if filter is not None:
174
+ processoroptions.update(frame_filters_map[filter])
175
+ filter = next((x for x in frame_upscalers_map.keys() if x == upscaleselection), None)
176
+ if filter is not None:
177
+ processoroptions.update(frame_upscalers_map[filter])
178
+ options = ProcessOptions(processoroptions, 0, 0, "all", 0, None, None, 0, 128, False)
179
+ batch_process_with_options(list_files_process, options, None)
180
+ outdir = pathlib.Path(roop.globals.output_path)
181
+ outfiles = [str(item) for item in outdir.rglob("*") if item.is_file()]
182
+ return outfiles
183
+
184
+
ui/tabs/facemgr_tab.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ import cv2
4
+ import gradio as gr
5
+ import roop.utilities as util
6
+ import roop.globals
7
+ from roop.face_util import extract_face_images
8
+ from roop.capturer import get_video_frame, get_video_frame_total
9
+ from typing import List, Tuple, Optional
10
+ from roop.typing import Frame, Face, FaceSet
11
+
12
+ selected_face_index = -1
13
+ thumbs = []
14
+ images = []
15
+
16
+
17
+ def facemgr_tab() -> None:
18
+ with gr.Tab("👨‍👩‍👧‍👦 Face Management"):
19
+ with gr.Row():
20
+ gr.Markdown("""
21
+ # Create blending facesets
22
+ Add multiple reference images into a faceset file.
23
+ """)
24
+ with gr.Row():
25
+ videoimagefst = gr.Image(label="Cut face from video frame", height=576, interactive=False, visible=True)
26
+ with gr.Row():
27
+ frame_num_fst = gr.Slider(1, 1, value=1, label="Frame Number", info='0:00:00', step=1.0, interactive=False)
28
+ fb_cutfromframe = gr.Button("Use faces from this frame", variant='secondary', interactive=False)
29
+ with gr.Row():
30
+ fb_facesetfile = gr.Files(label='Faceset', file_count='single', file_types=['.fsz'], interactive=True)
31
+ fb_files = gr.Files(label='Input Files', file_count="multiple", file_types=["image", "video"], interactive=True)
32
+ with gr.Row():
33
+ with gr.Column():
34
+ gr.Button("👀 Open Output Folder", size='sm').click(fn=lambda: util.open_folder(roop.globals.output_path))
35
+ with gr.Column():
36
+ gr.Markdown(' ')
37
+ with gr.Row():
38
+ faces = gr.Gallery(label="Faces in this Faceset", allow_preview=True, preview=True, height=128, object_fit="scale-down")
39
+ with gr.Row():
40
+ fb_remove = gr.Button("Remove selected", variant='secondary')
41
+ fb_update = gr.Button("Create/Update Faceset file", variant='primary')
42
+ fb_clear = gr.Button("Clear all", variant='stop')
43
+
44
+ fb_facesetfile.change(fn=on_faceset_changed, inputs=[fb_facesetfile], outputs=[faces])
45
+ fb_files.change(fn=on_fb_files_changed, inputs=[fb_files], outputs=[faces, videoimagefst, frame_num_fst, fb_cutfromframe])
46
+ fb_update.click(fn=on_update_clicked, outputs=[fb_facesetfile])
47
+ fb_remove.click(fn=on_remove_clicked, outputs=[faces])
48
+ fb_clear.click(fn=on_clear_clicked, outputs=[faces, fb_files, fb_facesetfile])
49
+ fb_cutfromframe.click(fn=on_cutfromframe_clicked, inputs=[fb_files, frame_num_fst], outputs=[faces])
50
+ frame_num_fst.release(fn=on_frame_num_fst_changed, inputs=[fb_files, frame_num_fst], outputs=[videoimagefst])
51
+ faces.select(fn=on_face_selected)
52
+
53
+
54
+ def on_faceset_changed(faceset, progress=gr.Progress()) -> List[Frame]:
55
+ global thumbs, images
56
+
57
+ if faceset is None:
58
+ return thumbs
59
+
60
+ thumbs.clear()
61
+ filename = faceset.name
62
+
63
+ if filename.lower().endswith('fsz'):
64
+ progress(0, desc="Retrieving faces from Faceset File", )
65
+ unzipfolder = os.path.join(os.environ["TEMP"], 'faceset')
66
+ if os.path.isdir(unzipfolder):
67
+ shutil.rmtree(unzipfolder)
68
+ util.mkdir_with_umask(unzipfolder)
69
+ util.unzip(filename, unzipfolder)
70
+ for file in os.listdir(unzipfolder):
71
+ if file.endswith(".png"):
72
+ SELECTION_FACES_DATA = extract_face_images(os.path.join(unzipfolder,file), (False, 0), 0.5)
73
+ if len(SELECTION_FACES_DATA) < 1:
74
+ gr.Warning(f"No face detected in {file}!")
75
+ for f in SELECTION_FACES_DATA:
76
+ image = f[1]
77
+ images.append(image)
78
+ thumbs.append(util.convert_to_gradio(image))
79
+
80
+ return thumbs
81
+
82
+
83
+ def on_fb_files_changed(inputfiles, progress=gr.Progress()) -> Tuple[List[Frame], Optional[gr.Image], Optional[gr.Slider], Optional[gr.Button]]:
84
+ global thumbs, images, total_frames, current_video_fps
85
+
86
+ if inputfiles is None or len(inputfiles) < 1:
87
+ return thumbs, None, None, None
88
+
89
+ progress(0, desc="Retrieving faces from images", )
90
+ slider = None
91
+ video_image = None
92
+ cut_button = None
93
+ for f in inputfiles:
94
+ source_path = f.name
95
+ if util.has_image_extension(source_path):
96
+ slider = gr.Slider(interactive=False)
97
+ video_image = gr.Image(interactive=False)
98
+ cut_button = gr.Button(interactive=False)
99
+ roop.globals.source_path = source_path
100
+ SELECTION_FACES_DATA = extract_face_images(roop.globals.source_path, (False, 0), 0.5)
101
+ for f in SELECTION_FACES_DATA:
102
+ image = f[1]
103
+ images.append(image)
104
+ thumbs.append(util.convert_to_gradio(image))
105
+ elif util.is_video(source_path) or source_path.lower().endswith('gif'):
106
+ total_frames = get_video_frame_total(source_path)
107
+ current_video_fps = util.detect_fps(source_path)
108
+ cut_button = gr.Button(interactive=True)
109
+ video_image, slider = display_video_frame(source_path, 1, total_frames)
110
+
111
+ return thumbs, video_image, slider, cut_button
112
+
113
+
114
+ def display_video_frame(filename: str, frame_num: int, total: int=0) -> Tuple[gr.Image, gr.Slider]:
115
+ global current_video_fps
116
+
117
+ current_frame = get_video_frame(filename, frame_num)
118
+ if current_video_fps == 0:
119
+ current_video_fps = 1
120
+ secs = (frame_num - 1) / current_video_fps
121
+ minutes = secs / 60
122
+ secs = secs % 60
123
+ hours = minutes / 60
124
+ minutes = minutes % 60
125
+ milliseconds = (secs - int(secs)) * 1000
126
+ timeinfo = f"{int(hours):0>2}:{int(minutes):0>2}:{int(secs):0>2}.{int(milliseconds):0>3}"
127
+ if total > 0:
128
+ return gr.Image(value=util.convert_to_gradio(current_frame), interactive=True), gr.Slider(info=timeinfo, minimum=1, maximum=total, interactive=True)
129
+ return gr.Image(value=util.convert_to_gradio(current_frame), interactive=True), gr.Slider(info=timeinfo, interactive=True)
130
+
131
+
132
+ def on_face_selected(evt: gr.SelectData) -> None:
133
+ global selected_face_index
134
+
135
+ if evt is not None:
136
+ selected_face_index = evt.index
137
+
138
+ def on_frame_num_fst_changed(inputfiles: List[gr.Files], frame_num: int) -> Frame:
139
+ filename = inputfiles[0].name
140
+ video_image, _ = display_video_frame(filename, frame_num, 0)
141
+ return video_image
142
+
143
+
144
+ def on_cutfromframe_clicked(inputfiles: List[gr.Files], frame_num: int) -> List[Frame]:
145
+ global thumbs
146
+
147
+ filename = inputfiles[0].name
148
+ SELECTION_FACES_DATA = extract_face_images(filename, (True, frame_num), 0.5)
149
+ for f in SELECTION_FACES_DATA:
150
+ image = f[1]
151
+ images.append(image)
152
+ thumbs.append(util.convert_to_gradio(image))
153
+ return thumbs
154
+
155
+
156
+ def on_remove_clicked() -> List[Frame]:
157
+ global thumbs, images, selected_face_index
158
+
159
+ if len(thumbs) > selected_face_index:
160
+ f = thumbs.pop(selected_face_index)
161
+ del f
162
+ f = images.pop(selected_face_index)
163
+ del f
164
+ return thumbs
165
+
166
+ def on_clear_clicked() -> Tuple[List[Frame], None, None]:
167
+ global thumbs, images
168
+
169
+ thumbs.clear()
170
+ images.clear()
171
+ return thumbs, None, None
172
+
173
+
174
+ def on_update_clicked() -> Optional[str]:
175
+ if len(images) < 1:
176
+ gr.Warning(f"No faces to create faceset from!")
177
+ return None
178
+
179
+ imgnames = []
180
+ for index,img in enumerate(images):
181
+ filename = os.path.join(roop.globals.output_path, f'{index}.png')
182
+ cv2.imwrite(filename, img)
183
+ imgnames.append(filename)
184
+
185
+ finalzip = os.path.join(roop.globals.output_path, 'faceset.fsz')
186
+ util.zip(imgnames, finalzip)
187
+ return finalzip
ui/tabs/faceswap_tab.py ADDED
@@ -0,0 +1,722 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ import pathlib
4
+ import gradio as gr
5
+ import roop.utilities as util
6
+ import roop.globals
7
+ import ui.globals
8
+ from roop.face_util import extract_face_images, create_blank_image
9
+ from roop.capturer import get_video_frame, get_video_frame_total, get_image_frame
10
+ from roop.ProcessEntry import ProcessEntry
11
+ from roop.ProcessOptions import ProcessOptions
12
+ from roop.FaceSet import FaceSet
13
+
14
+ last_image = None
15
+
16
+
17
+ IS_INPUT = True
18
+ SELECTED_FACE_INDEX = 0
19
+
20
+ SELECTED_INPUT_FACE_INDEX = 0
21
+ SELECTED_TARGET_FACE_INDEX = 0
22
+
23
+ input_faces = None
24
+ target_faces = None
25
+ face_selection = None
26
+ previewimage = None
27
+
28
+ selected_preview_index = 0
29
+
30
+ is_processing = False
31
+
32
+ list_files_process : list[ProcessEntry] = []
33
+ no_face_choices = ["Use untouched original frame","Retry rotated", "Skip Frame", "Skip Frame if no similar face"]
34
+
35
+ current_video_fps = 50
36
+
37
+ manual_masking = False
38
+
39
+
40
+ def faceswap_tab():
41
+ global no_face_choices, previewimage
42
+
43
+ with gr.Tab("🎭 Face Swap"):
44
+ with gr.Row(variant='panel'):
45
+ with gr.Column(scale=2):
46
+ with gr.Row():
47
+ with gr.Column(min_width=160):
48
+ input_faces = gr.Gallery(label="Input faces", allow_preview=False, preview=False, height=128, object_fit="scale-down", columns=8)
49
+ with gr.Accordion(label="Advanced Masking", open=False):
50
+ chk_showmaskoffsets = gr.Checkbox(label="Show mask overlay in preview", value=False, interactive=True)
51
+ mask_top = gr.Slider(0, 1.0, value=0, label="Offset Face Top", step=0.01, interactive=True)
52
+ mask_bottom = gr.Slider(0, 1.0, value=0, label="Offset Face Bottom", step=0.01, interactive=True)
53
+ mask_left = gr.Slider(0, 1.0, value=0, label="Offset Face Left", step=0.01, interactive=True)
54
+ mask_right = gr.Slider(0, 1.0, value=0, label="Offset Face Right", step=0.01, interactive=True)
55
+ mask_erosion = gr.Slider(1.0, 3.0, value=1.0, label="Erosion Iterations", step=1.00, interactive=True)
56
+ mask_blur = gr.Slider(10.0, 50.0, value=20.0, label="Blur size", step=1.00, interactive=True)
57
+ bt_toggle_masking = gr.Button("Toggle manual masking", variant='secondary', size='sm')
58
+ selected_mask_engine = gr.Dropdown(["None", "Clip2Seg", "DFL XSeg"], value="None", label="Face masking engine")
59
+ clip_text = gr.Textbox(label="List of objects to mask and restore back on fake face", value="cup,hands,hair,banana", interactive=False)
60
+ bt_preview_mask = gr.Button("👥 Show Mask Preview", variant='secondary')
61
+ bt_remove_selected_input_face = gr.Button("❌ Remove selected", size='sm')
62
+ bt_clear_input_faces = gr.Button("💥 Clear all", variant='stop', size='sm')
63
+ with gr.Column(min_width=160):
64
+ target_faces = gr.Gallery(label="Target faces", allow_preview=False, preview=False, height=128, object_fit="scale-down", columns=8)
65
+ bt_remove_selected_target_face = gr.Button("❌ Remove selected", size='sm')
66
+ bt_add_local = gr.Button('Add local files from', size='sm')
67
+ local_folder = gr.Textbox(show_label=False, placeholder="/content/", interactive=True)
68
+ with gr.Row(variant='panel'):
69
+ bt_srcfiles = gr.Files(label='Source File(s)', file_count="multiple", file_types=["image", ".fsz"], elem_id='filelist', height=233)
70
+ bt_destfiles = gr.Files(label='Target File(s)', file_count="multiple", file_types=["image", "video"], elem_id='filelist', height=233)
71
+ with gr.Row(variant='panel'):
72
+ gr.Markdown('')
73
+ forced_fps = gr.Slider(minimum=0, maximum=120, value=0, label="Video FPS", info='Overrides detected fps if not 0', step=1.0, interactive=True, container=True)
74
+
75
+ with gr.Column(scale=2):
76
+ previewimage = gr.Image(label="Preview Image", height=576, interactive=False, visible=True)
77
+ maskimage = gr.ImageEditor(label="Manual mask Image", sources=["clipboard"], transforms="", type="numpy",
78
+ brush=gr.Brush(color_mode="fixed", colors=["rgba(255, 255, 255, 1"]), interactive=True, visible=False)
79
+ with gr.Row(variant='panel'):
80
+ fake_preview = gr.Checkbox(label="Face swap frames", value=False)
81
+ bt_refresh_preview = gr.Button("🔄 Refresh", variant='secondary', size='sm')
82
+ bt_use_face_from_preview = gr.Button("Use Face from this Frame", variant='primary', size='sm')
83
+ with gr.Row():
84
+ preview_frame_num = gr.Slider(1, 1, value=1, label="Frame Number", info='0:00:00', step=1.0, interactive=True)
85
+ with gr.Row():
86
+ text_frame_clip = gr.Markdown('Processing frame range [0 - 0]')
87
+ set_frame_start = gr.Button("⬅ Set as Start", size='sm')
88
+ set_frame_end = gr.Button("➡ Set as End", size='sm')
89
+ with gr.Row(visible=False) as dynamic_face_selection:
90
+ with gr.Column(scale=2):
91
+ face_selection = gr.Gallery(label="Detected faces", allow_preview=False, preview=False, height=256, object_fit="cover", columns=8)
92
+ with gr.Column():
93
+ bt_faceselect = gr.Button("☑ Use selected face", size='sm')
94
+ bt_cancelfaceselect = gr.Button("Done", size='sm')
95
+ with gr.Column():
96
+ gr.Markdown(' ')
97
+
98
+ with gr.Row(variant='panel'):
99
+ with gr.Column(scale=1):
100
+ selected_face_detection = gr.Dropdown(["First found", "All female", "All male", "All faces", "Selected face"], value="First found", label="Specify face selection for swapping")
101
+ with gr.Column(scale=1):
102
+ num_swap_steps = gr.Slider(1, 5, value=1, step=1.0, label="Number of swapping steps", info="More steps may increase likeness")
103
+ with gr.Column(scale=2):
104
+ ui.globals.ui_selected_enhancer = gr.Dropdown(["None", "Codeformer", "DMDNet", "GFPGAN", "GPEN", "Restoreformer++"], value="None", label="Select post-processing")
105
+
106
+ with gr.Row(variant='panel'):
107
+ with gr.Column(scale=1):
108
+ max_face_distance = gr.Slider(0.01, 1.0, value=0.65, label="Max Face Similarity Threshold", info="0.0 = identical 1.0 = no similarity")
109
+ with gr.Column(scale=1):
110
+ ui.globals.ui_upscale = gr.Dropdown(["128px", "256px", "512px"], value="128px", label="Subsample upscale to", interactive=True)
111
+ with gr.Column(scale=2):
112
+ ui.globals.ui_blend_ratio = gr.Slider(0.0, 1.0, value=0.65, label="Original/Enhanced image blend ratio", info="Only used with active post-processing")
113
+
114
+
115
+ with gr.Row(variant='panel'):
116
+ with gr.Column(scale=1):
117
+ video_swapping_method = gr.Dropdown(["Extract Frames to media","In-Memory processing"], value="In-Memory processing", label="Select video processing method", interactive=True)
118
+ no_face_action = gr.Dropdown(choices=no_face_choices, value=no_face_choices[0], label="Action on no face detected", interactive=True)
119
+ vr_mode = gr.Checkbox(label="VR Mode", value=False)
120
+ with gr.Column(scale=1):
121
+ with gr.Group():
122
+ autorotate = gr.Checkbox(label="Auto rotate horizontal Faces", value=True)
123
+ roop.globals.skip_audio = gr.Checkbox(label="Skip audio", value=False)
124
+ roop.globals.keep_frames = gr.Checkbox(label="Keep Frames (relevant only when extracting frames)", value=False)
125
+ roop.globals.wait_after_extraction = gr.Checkbox(label="Wait for user key press before creating video ", value=False)
126
+
127
+
128
+
129
+ with gr.Row(variant='panel'):
130
+ with gr.Column():
131
+ bt_start = gr.Button("▶ Start", variant='primary')
132
+ gr.Button("👀 Open Output Folder", size='sm').click(fn=lambda: util.open_folder(roop.globals.output_path))
133
+ with gr.Column():
134
+ bt_stop = gr.Button("⏹ Stop", variant='secondary', interactive=False)
135
+ with gr.Column(scale=2):
136
+ gr.Markdown(' ')
137
+ with gr.Row(variant='panel'):
138
+ with gr.Column():
139
+ resultfiles = gr.Files(label='Processed File(s)', interactive=False)
140
+ with gr.Column():
141
+ resultimage = gr.Image(type='filepath', label='Final Image', interactive=False )
142
+ resultvideo = gr.Video(label='Final Video', interactive=False, visible=False)
143
+
144
+ previewinputs = [preview_frame_num, bt_destfiles, fake_preview, ui.globals.ui_selected_enhancer, selected_face_detection,
145
+ max_face_distance, ui.globals.ui_blend_ratio, selected_mask_engine, clip_text, no_face_action, vr_mode, autorotate, maskimage, chk_showmaskoffsets, num_swap_steps, ui.globals.ui_upscale]
146
+ previewoutputs = [previewimage, maskimage, preview_frame_num]
147
+ input_faces.select(on_select_input_face, None, None).then(fn=on_preview_frame_changed, inputs=previewinputs, outputs=previewoutputs)
148
+ bt_remove_selected_input_face.click(fn=remove_selected_input_face, outputs=[input_faces])
149
+ bt_srcfiles.change(fn=on_srcfile_changed, show_progress='full', inputs=bt_srcfiles, outputs=[dynamic_face_selection, face_selection, input_faces])
150
+
151
+ mask_top.release(fn=on_mask_top_changed, inputs=[mask_top], show_progress='hidden')
152
+ mask_bottom.release(fn=on_mask_bottom_changed, inputs=[mask_bottom], show_progress='hidden')
153
+ mask_left.release(fn=on_mask_left_changed, inputs=[mask_left], show_progress='hidden')
154
+ mask_right.release(fn=on_mask_right_changed, inputs=[mask_right], show_progress='hidden')
155
+ mask_erosion.release(fn=on_mask_erosion_changed, inputs=[mask_erosion], show_progress='hidden')
156
+ mask_blur.release(fn=on_mask_blur_changed, inputs=[mask_blur], show_progress='hidden')
157
+ selected_mask_engine.change(fn=on_mask_engine_changed, inputs=[selected_mask_engine], outputs=[clip_text], show_progress='hidden')
158
+
159
+
160
+ target_faces.select(on_select_target_face, None, None)
161
+ bt_remove_selected_target_face.click(fn=remove_selected_target_face, outputs=[target_faces])
162
+
163
+ forced_fps.change(fn=on_fps_changed, inputs=[forced_fps], show_progress='hidden')
164
+ bt_destfiles.change(fn=on_destfiles_changed, inputs=[bt_destfiles], outputs=[preview_frame_num, text_frame_clip], show_progress='hidden').then(fn=on_preview_frame_changed, inputs=previewinputs, outputs=previewoutputs, show_progress='hidden')
165
+ bt_destfiles.select(fn=on_destfiles_selected, outputs=[preview_frame_num, text_frame_clip, forced_fps], show_progress='hidden').then(fn=on_preview_frame_changed, inputs=previewinputs, outputs=previewoutputs, show_progress='hidden')
166
+ bt_destfiles.clear(fn=on_clear_destfiles, outputs=[target_faces, selected_face_detection])
167
+ resultfiles.select(fn=on_resultfiles_selected, inputs=[resultfiles], outputs=[resultimage, resultvideo])
168
+
169
+ face_selection.select(on_select_face, None, None)
170
+ bt_faceselect.click(fn=on_selected_face, outputs=[input_faces, target_faces, selected_face_detection])
171
+ bt_cancelfaceselect.click(fn=on_end_face_selection, outputs=[dynamic_face_selection, face_selection])
172
+
173
+ bt_clear_input_faces.click(fn=on_clear_input_faces, outputs=[input_faces])
174
+
175
+
176
+ bt_add_local.click(fn=on_add_local_folder, inputs=[local_folder], outputs=[bt_destfiles])
177
+ bt_preview_mask.click(fn=on_preview_mask, inputs=[preview_frame_num, bt_destfiles, clip_text, selected_mask_engine], outputs=[previewimage])
178
+
179
+ start_event = bt_start.click(fn=start_swap,
180
+ inputs=[ui.globals.ui_selected_enhancer, selected_face_detection, roop.globals.keep_frames, roop.globals.wait_after_extraction,
181
+ roop.globals.skip_audio, max_face_distance, ui.globals.ui_blend_ratio, selected_mask_engine, clip_text,video_swapping_method, no_face_action, vr_mode, autorotate, num_swap_steps, ui.globals.ui_upscale, maskimage],
182
+ outputs=[bt_start, bt_stop, resultfiles], show_progress='full')
183
+ after_swap_event = start_event.then(fn=on_resultfiles_finished, inputs=[resultfiles], outputs=[resultimage, resultvideo])
184
+
185
+ bt_stop.click(fn=stop_swap, cancels=[start_event, after_swap_event], outputs=[bt_start, bt_stop], queue=False)
186
+
187
+ bt_refresh_preview.click(fn=on_preview_frame_changed, inputs=previewinputs, outputs=previewoutputs)
188
+ bt_toggle_masking.click(fn=on_toggle_masking, inputs=[previewimage, maskimage], outputs=[previewimage, maskimage])
189
+ fake_preview.change(fn=on_preview_frame_changed, inputs=previewinputs, outputs=previewoutputs)
190
+ preview_frame_num.release(fn=on_preview_frame_changed, inputs=previewinputs, outputs=previewoutputs, show_progress='hidden', )
191
+ bt_use_face_from_preview.click(fn=on_use_face_from_selected, show_progress='full', inputs=[bt_destfiles, preview_frame_num], outputs=[dynamic_face_selection, face_selection, target_faces, selected_face_detection])
192
+ set_frame_start.click(fn=on_set_frame, inputs=[set_frame_start, preview_frame_num], outputs=[text_frame_clip])
193
+ set_frame_end.click(fn=on_set_frame, inputs=[set_frame_end, preview_frame_num], outputs=[text_frame_clip])
194
+
195
+
196
+
197
+ def on_mask_top_changed(mask_offset):
198
+ set_mask_offset(0, mask_offset)
199
+
200
+ def on_mask_bottom_changed(mask_offset):
201
+ set_mask_offset(1, mask_offset)
202
+
203
+ def on_mask_left_changed(mask_offset):
204
+ set_mask_offset(2, mask_offset)
205
+
206
+ def on_mask_right_changed(mask_offset):
207
+ set_mask_offset(3, mask_offset)
208
+
209
+ def on_mask_erosion_changed(mask_offset):
210
+ set_mask_offset(4, mask_offset)
211
+ def on_mask_blur_changed(mask_offset):
212
+ set_mask_offset(5, mask_offset)
213
+
214
+
215
+ def set_mask_offset(index, mask_offset):
216
+ global SELECTED_INPUT_FACE_INDEX
217
+
218
+ if len(roop.globals.INPUT_FACESETS) > SELECTED_INPUT_FACE_INDEX:
219
+ offs = roop.globals.INPUT_FACESETS[SELECTED_INPUT_FACE_INDEX].faces[0].mask_offsets
220
+ offs[index] = mask_offset
221
+ if offs[0] + offs[1] > 0.99:
222
+ offs[0] = 0.99
223
+ offs[1] = 0.0
224
+ if offs[2] + offs[3] > 0.99:
225
+ offs[2] = 0.99
226
+ offs[3] = 0.0
227
+ roop.globals.INPUT_FACESETS[SELECTED_INPUT_FACE_INDEX].faces[0].mask_offsets = offs
228
+
229
+ def on_mask_engine_changed(mask_engine):
230
+ if mask_engine == "Clip2Seg":
231
+ return gr.Textbox(interactive=True)
232
+ return gr.Textbox(interactive=False)
233
+
234
+
235
+
236
+ def on_add_local_folder(folder):
237
+ files = util.get_local_files_from_folder(folder)
238
+ if files is None:
239
+ gr.Warning("Empty folder or folder not found!")
240
+ return files
241
+
242
+
243
+ def on_srcfile_changed(srcfiles, progress=gr.Progress()):
244
+ global SELECTION_FACES_DATA, IS_INPUT, input_faces, face_selection, last_image
245
+
246
+ IS_INPUT = True
247
+
248
+ if srcfiles is None or len(srcfiles) < 1:
249
+ return gr.Column(visible=False), None, ui.globals.ui_input_thumbs
250
+
251
+ thumbs = []
252
+ for f in srcfiles:
253
+ source_path = f.name
254
+ if source_path.lower().endswith('fsz'):
255
+ progress(0, desc="Retrieving faces from Faceset File")
256
+ unzipfolder = os.path.join(os.environ["TEMP"], 'faceset')
257
+ if os.path.isdir(unzipfolder):
258
+ files = os.listdir(unzipfolder)
259
+ for file in files:
260
+ os.remove(os.path.join(unzipfolder, file))
261
+ else:
262
+ os.makedirs(unzipfolder)
263
+ util.mkdir_with_umask(unzipfolder)
264
+ util.unzip(source_path, unzipfolder)
265
+ is_first = True
266
+ face_set = FaceSet()
267
+ for file in os.listdir(unzipfolder):
268
+ if file.endswith(".png"):
269
+ filename = os.path.join(unzipfolder,file)
270
+ progress(0, desc="Extracting faceset")
271
+ SELECTION_FACES_DATA = extract_face_images(filename, (False, 0))
272
+ for f in SELECTION_FACES_DATA:
273
+ face = f[0]
274
+ face.mask_offsets = (0,0,0,0,1,20)
275
+ face_set.faces.append(face)
276
+ if is_first:
277
+ image = util.convert_to_gradio(f[1])
278
+ ui.globals.ui_input_thumbs.append(image)
279
+ is_first = False
280
+ face_set.ref_images.append(get_image_frame(filename))
281
+ if len(face_set.faces) > 0:
282
+ if len(face_set.faces) > 1:
283
+ face_set.AverageEmbeddings()
284
+ roop.globals.INPUT_FACESETS.append(face_set)
285
+
286
+ elif util.has_image_extension(source_path):
287
+ progress(0, desc="Retrieving faces from image")
288
+ roop.globals.source_path = source_path
289
+ SELECTION_FACES_DATA = extract_face_images(roop.globals.source_path, (False, 0))
290
+ progress(0.5, desc="Retrieving faces from image")
291
+ for f in SELECTION_FACES_DATA:
292
+ face_set = FaceSet()
293
+ face = f[0]
294
+ face.mask_offsets = (0,0,0,0,1,20)
295
+ face_set.faces.append(face)
296
+ image = util.convert_to_gradio(f[1])
297
+ ui.globals.ui_input_thumbs.append(image)
298
+ roop.globals.INPUT_FACESETS.append(face_set)
299
+
300
+ progress(1.0)
301
+
302
+ # old style with selecting input faces commented out
303
+ # if len(thumbs) < 1:
304
+ # return gr.Column(visible=False), None, ui.globals.ui_input_thumbs
305
+ # return gr.Column(visible=True), thumbs, gr.Gallery(visible=True)
306
+
307
+ return gr.Column(visible=False), None, ui.globals.ui_input_thumbs
308
+
309
+
310
+ def on_select_input_face(evt: gr.SelectData):
311
+ global SELECTED_INPUT_FACE_INDEX
312
+
313
+ SELECTED_INPUT_FACE_INDEX = evt.index
314
+
315
+
316
+ def remove_selected_input_face():
317
+ global SELECTED_INPUT_FACE_INDEX
318
+
319
+ if len(roop.globals.INPUT_FACESETS) > SELECTED_INPUT_FACE_INDEX:
320
+ f = roop.globals.INPUT_FACESETS.pop(SELECTED_INPUT_FACE_INDEX)
321
+ del f
322
+ if len(ui.globals.ui_input_thumbs) > SELECTED_INPUT_FACE_INDEX:
323
+ f = ui.globals.ui_input_thumbs.pop(SELECTED_INPUT_FACE_INDEX)
324
+ del f
325
+
326
+ return ui.globals.ui_input_thumbs
327
+
328
+ def on_select_target_face(evt: gr.SelectData):
329
+ global SELECTED_TARGET_FACE_INDEX
330
+
331
+ SELECTED_TARGET_FACE_INDEX = evt.index
332
+
333
+ def remove_selected_target_face():
334
+ if len(roop.globals.TARGET_FACES) > SELECTED_TARGET_FACE_INDEX:
335
+ f = roop.globals.TARGET_FACES.pop(SELECTED_TARGET_FACE_INDEX)
336
+ del f
337
+ if len(ui.globals.ui_target_thumbs) > SELECTED_TARGET_FACE_INDEX:
338
+ f = ui.globals.ui_target_thumbs.pop(SELECTED_TARGET_FACE_INDEX)
339
+ del f
340
+ return ui.globals.ui_target_thumbs
341
+
342
+
343
+
344
+
345
+
346
+ def on_use_face_from_selected(files, frame_num):
347
+ global IS_INPUT, SELECTION_FACES_DATA
348
+
349
+ IS_INPUT = False
350
+ thumbs = []
351
+
352
+ roop.globals.target_path = files[selected_preview_index].name
353
+ if util.is_image(roop.globals.target_path) and not roop.globals.target_path.lower().endswith(('gif')):
354
+ SELECTION_FACES_DATA = extract_face_images(roop.globals.target_path, (False, 0))
355
+ if len(SELECTION_FACES_DATA) > 0:
356
+ for f in SELECTION_FACES_DATA:
357
+ image = util.convert_to_gradio(f[1])
358
+ thumbs.append(image)
359
+ else:
360
+ gr.Info('No faces detected!')
361
+ roop.globals.target_path = None
362
+
363
+ elif util.is_video(roop.globals.target_path) or roop.globals.target_path.lower().endswith(('gif')):
364
+ selected_frame = frame_num
365
+ SELECTION_FACES_DATA = extract_face_images(roop.globals.target_path, (True, selected_frame))
366
+ if len(SELECTION_FACES_DATA) > 0:
367
+ for f in SELECTION_FACES_DATA:
368
+ image = util.convert_to_gradio(f[1])
369
+ thumbs.append(image)
370
+ else:
371
+ gr.Info('No faces detected!')
372
+ roop.globals.target_path = None
373
+
374
+ if len(thumbs) == 1:
375
+ roop.globals.TARGET_FACES.append(SELECTION_FACES_DATA[0][0])
376
+ ui.globals.ui_target_thumbs.append(thumbs[0])
377
+ return gr.Row(visible=False), None, ui.globals.ui_target_thumbs, gr.Dropdown(value='Selected face')
378
+
379
+ return gr.Row(visible=True), thumbs, gr.Gallery(visible=True), gr.Dropdown(visible=True)
380
+
381
+
382
+
383
+ def on_select_face(evt: gr.SelectData): # SelectData is a subclass of EventData
384
+ global SELECTED_FACE_INDEX
385
+ SELECTED_FACE_INDEX = evt.index
386
+
387
+
388
+ def on_selected_face():
389
+ global IS_INPUT, SELECTED_FACE_INDEX, SELECTION_FACES_DATA
390
+
391
+ fd = SELECTION_FACES_DATA[SELECTED_FACE_INDEX]
392
+ image = util.convert_to_gradio(fd[1])
393
+ if IS_INPUT:
394
+ face_set = FaceSet()
395
+ fd[0].mask_offsets = (0,0,0,0,1,20)
396
+ face_set.faces.append(fd[0])
397
+ roop.globals.INPUT_FACESETS.append(face_set)
398
+ ui.globals.ui_input_thumbs.append(image)
399
+ return ui.globals.ui_input_thumbs, gr.Gallery(visible=True), gr.Dropdown(visible=True)
400
+ else:
401
+ roop.globals.TARGET_FACES.append(fd[0])
402
+ ui.globals.ui_target_thumbs.append(image)
403
+ return gr.Gallery(visible=True), ui.globals.ui_target_thumbs, gr.Dropdown(value='Selected face')
404
+
405
+ # bt_faceselect.click(fn=on_selected_face, outputs=[dynamic_face_selection, face_selection, input_faces, target_faces])
406
+
407
+ def on_end_face_selection():
408
+ return gr.Column(visible=False), None
409
+
410
+
411
+ def on_preview_frame_changed(frame_num, files, fake_preview, enhancer, detection, face_distance, blend_ratio,
412
+ selected_mask_engine, clip_text, no_face_action, vr_mode, auto_rotate, maskimage, show_face_area, num_steps, upsample):
413
+ global SELECTED_INPUT_FACE_INDEX, manual_masking, current_video_fps
414
+
415
+ from roop.core import live_swap, get_processing_plugins
416
+
417
+ manual_masking = False
418
+ mask_offsets = (0,0,0,0)
419
+ if len(roop.globals.INPUT_FACESETS) > SELECTED_INPUT_FACE_INDEX:
420
+ if not hasattr(roop.globals.INPUT_FACESETS[SELECTED_INPUT_FACE_INDEX].faces[0], 'mask_offsets'):
421
+ roop.globals.INPUT_FACESETS[SELECTED_INPUT_FACE_INDEX].faces[0].mask_offsets = mask_offsets
422
+ mask_offsets = roop.globals.INPUT_FACESETS[SELECTED_INPUT_FACE_INDEX].faces[0].mask_offsets
423
+
424
+ timeinfo = '0:00:00'
425
+ if files is None or selected_preview_index >= len(files) or frame_num is None:
426
+ return None,None, gr.Slider(info=timeinfo)
427
+
428
+ filename = files[selected_preview_index].name
429
+ if util.is_video(filename) or filename.lower().endswith('gif'):
430
+ current_frame = get_video_frame(filename, frame_num)
431
+ if current_video_fps == 0:
432
+ current_video_fps = 1
433
+ secs = (frame_num - 1) / current_video_fps
434
+ minutes = secs / 60
435
+ secs = secs % 60
436
+ hours = minutes / 60
437
+ minutes = minutes % 60
438
+ milliseconds = (secs - int(secs)) * 1000
439
+ timeinfo = f"{int(hours):0>2}:{int(minutes):0>2}:{int(secs):0>2}.{int(milliseconds):0>3}"
440
+ else:
441
+ current_frame = get_image_frame(filename)
442
+ if current_frame is None:
443
+ return None, None, gr.Slider(info=timeinfo)
444
+
445
+ layers = None
446
+ if maskimage is not None:
447
+ layers = maskimage["layers"]
448
+
449
+ if not fake_preview or len(roop.globals.INPUT_FACESETS) < 1:
450
+ return gr.Image(value=util.convert_to_gradio(current_frame), visible=True), gr.ImageEditor(visible=False), gr.Slider(info=timeinfo)
451
+
452
+ roop.globals.face_swap_mode = translate_swap_mode(detection)
453
+ roop.globals.selected_enhancer = enhancer
454
+ roop.globals.distance_threshold = face_distance
455
+ roop.globals.blend_ratio = blend_ratio
456
+ roop.globals.no_face_action = index_of_no_face_action(no_face_action)
457
+ roop.globals.vr_mode = vr_mode
458
+ roop.globals.autorotate_faces = auto_rotate
459
+ roop.globals.subsample_size = int(upsample[:3])
460
+
461
+
462
+ mask_engine = map_mask_engine(selected_mask_engine, clip_text)
463
+
464
+ roop.globals.execution_threads = roop.globals.CFG.max_threads
465
+ mask = layers[0] if layers is not None else None
466
+ face_index = SELECTED_INPUT_FACE_INDEX
467
+ if len(roop.globals.INPUT_FACESETS) <= face_index:
468
+ face_index = 0
469
+
470
+ options = ProcessOptions(get_processing_plugins(mask_engine), roop.globals.distance_threshold, roop.globals.blend_ratio,
471
+ roop.globals.face_swap_mode, face_index, clip_text, maskimage, num_steps, roop.globals.subsample_size, show_face_area)
472
+
473
+ current_frame = live_swap(current_frame, options)
474
+ if current_frame is None:
475
+ return gr.Image(visible=True), None, gr.Slider(info=timeinfo)
476
+ return gr.Image(value=util.convert_to_gradio(current_frame), visible=True), gr.ImageEditor(visible=False), gr.Slider(info=timeinfo)
477
+
478
+ def map_mask_engine(selected_mask_engine, clip_text):
479
+ if selected_mask_engine == "Clip2Seg":
480
+ mask_engine = "mask_clip2seg"
481
+ if clip_text is None or len(clip_text) < 1:
482
+ mask_engine = None
483
+ elif selected_mask_engine == "DFL XSeg":
484
+ mask_engine = "mask_xseg"
485
+ else:
486
+ mask_engine = None
487
+ return mask_engine
488
+
489
+
490
+
491
+ def on_toggle_masking(previewimage, mask):
492
+ global manual_masking
493
+
494
+ manual_masking = not manual_masking
495
+ if manual_masking:
496
+ layers = mask["layers"]
497
+ if len(layers) == 1:
498
+ layers = [create_blank_image(previewimage.shape[1],previewimage.shape[0])]
499
+ return gr.Image(visible=False), gr.ImageEditor(value={"background": previewimage, "layers": layers, "composite": None}, visible=True)
500
+ return gr.Image(visible=True), gr.ImageEditor(visible=False)
501
+
502
+ def gen_processing_text(start, end):
503
+ return f'Processing frame range [{start} - {end}]'
504
+
505
+ def on_set_frame(sender:str, frame_num):
506
+ global selected_preview_index, list_files_process
507
+
508
+ idx = selected_preview_index
509
+ if list_files_process[idx].endframe == 0:
510
+ return gen_processing_text(0,0)
511
+
512
+ start = list_files_process[idx].startframe
513
+ end = list_files_process[idx].endframe
514
+ if sender.lower().endswith('start'):
515
+ list_files_process[idx].startframe = min(frame_num, end)
516
+ else:
517
+ list_files_process[idx].endframe = max(frame_num, start)
518
+
519
+ return gen_processing_text(list_files_process[idx].startframe,list_files_process[idx].endframe)
520
+
521
+
522
+
523
+ def on_preview_mask(frame_num, files, clip_text, mask_engine):
524
+ from roop.core import live_swap, get_processing_plugins
525
+ global is_processing
526
+
527
+ if is_processing or files is None or selected_preview_index >= len(files) or clip_text is None or frame_num is None:
528
+ return None
529
+
530
+ filename = files[selected_preview_index].name
531
+ if util.is_video(filename) or filename.lower().endswith('gif'):
532
+ current_frame = get_video_frame(filename, frame_num
533
+ )
534
+ else:
535
+ current_frame = get_image_frame(filename)
536
+ if current_frame is None or mask_engine is None:
537
+ return None
538
+ if mask_engine == "Clip2Seg":
539
+ mask_engine = "mask_clip2seg"
540
+ if clip_text is None or len(clip_text) < 1:
541
+ mask_engine = None
542
+ elif mask_engine == "DFL XSeg":
543
+ mask_engine = "mask_xseg"
544
+ options = ProcessOptions(get_processing_plugins(mask_engine), roop.globals.distance_threshold, roop.globals.blend_ratio,
545
+ "all", 0, clip_text, None, 0, 128, False, True)
546
+
547
+ current_frame = live_swap(current_frame, options)
548
+ return util.convert_to_gradio(current_frame)
549
+
550
+
551
+
552
+ def on_clear_input_faces():
553
+ ui.globals.ui_input_thumbs.clear()
554
+ roop.globals.INPUT_FACESETS.clear()
555
+ return ui.globals.ui_input_thumbs
556
+
557
+ def on_clear_destfiles():
558
+ roop.globals.TARGET_FACES.clear()
559
+ ui.globals.ui_target_thumbs.clear()
560
+ return ui.globals.ui_target_thumbs, gr.Dropdown(value="First found")
561
+
562
+
563
+ def index_of_no_face_action(dropdown_text):
564
+ global no_face_choices
565
+
566
+ return no_face_choices.index(dropdown_text)
567
+
568
+ def translate_swap_mode(dropdown_text):
569
+ if dropdown_text == "Selected face":
570
+ return "selected"
571
+ elif dropdown_text == "First found":
572
+ return "first"
573
+ elif dropdown_text == "All female":
574
+ return "all_female"
575
+ elif dropdown_text == "All male":
576
+ return "all_male"
577
+
578
+ return "all"
579
+
580
+
581
+
582
+ def start_swap( enhancer, detection, keep_frames, wait_after_extraction, skip_audio, face_distance, blend_ratio,
583
+ selected_mask_engine, clip_text, processing_method, no_face_action, vr_mode, autorotate, num_swap_steps, upsample, imagemask, progress=gr.Progress()):
584
+ from ui.main import prepare_environment
585
+ from roop.core import batch_process_regular
586
+ global is_processing, list_files_process
587
+
588
+ if list_files_process is None or len(list_files_process) <= 0:
589
+ return gr.Button(variant="primary"), None, None
590
+
591
+ if roop.globals.CFG.clear_output:
592
+ shutil.rmtree(roop.globals.output_path)
593
+
594
+ if not util.is_installed("ffmpeg"):
595
+ msg = "ffmpeg is not installed! No video processing possible."
596
+ gr.Warning(msg)
597
+
598
+ prepare_environment()
599
+
600
+ roop.globals.selected_enhancer = enhancer
601
+ roop.globals.target_path = None
602
+ roop.globals.distance_threshold = face_distance
603
+ roop.globals.blend_ratio = blend_ratio
604
+ roop.globals.keep_frames = keep_frames
605
+ roop.globals.wait_after_extraction = wait_after_extraction
606
+ roop.globals.skip_audio = skip_audio
607
+ roop.globals.face_swap_mode = translate_swap_mode(detection)
608
+ roop.globals.no_face_action = index_of_no_face_action(no_face_action)
609
+ roop.globals.vr_mode = vr_mode
610
+ roop.globals.autorotate_faces = autorotate
611
+ roop.globals.subsample_size = int(upsample[:3])
612
+ mask_engine = map_mask_engine(selected_mask_engine, clip_text)
613
+
614
+ if roop.globals.face_swap_mode == 'selected':
615
+ if len(roop.globals.TARGET_FACES) < 1:
616
+ gr.Error('No Target Face selected!')
617
+ return gr.Button(variant="primary"), None, None
618
+
619
+ is_processing = True
620
+ yield gr.Button(variant="secondary", interactive=False), gr.Button(variant="primary", interactive=True), None
621
+ roop.globals.execution_threads = roop.globals.CFG.max_threads
622
+ roop.globals.video_encoder = roop.globals.CFG.output_video_codec
623
+ roop.globals.video_quality = roop.globals.CFG.video_quality
624
+ roop.globals.max_memory = roop.globals.CFG.memory_limit if roop.globals.CFG.memory_limit > 0 else None
625
+
626
+ batch_process_regular(list_files_process, mask_engine, clip_text, processing_method == "In-Memory processing", imagemask, num_swap_steps, progress, SELECTED_INPUT_FACE_INDEX)
627
+ is_processing = False
628
+ outdir = pathlib.Path(roop.globals.output_path)
629
+ outfiles = [str(item) for item in outdir.rglob("*") if item.is_file()]
630
+ if len(outfiles) > 0:
631
+ yield gr.Button(variant="primary", interactive=True),gr.Button(variant="secondary", interactive=False),gr.Files(value=outfiles)
632
+ else:
633
+ yield gr.Button(variant="primary", interactive=True),gr.Button(variant="secondary", interactive=False),None
634
+
635
+
636
+ def stop_swap():
637
+ roop.globals.processing = False
638
+ gr.Info('Aborting processing - please wait for the remaining threads to be stopped')
639
+ return gr.Button(variant="primary", interactive=True),gr.Button(variant="secondary", interactive=False),None
640
+
641
+
642
+ def on_fps_changed(fps):
643
+ global selected_preview_index, list_files_process
644
+
645
+ if len(list_files_process) < 1 or list_files_process[selected_preview_index].endframe < 1:
646
+ return
647
+ list_files_process[selected_preview_index].fps = fps
648
+
649
+
650
+ def on_destfiles_changed(destfiles):
651
+ global selected_preview_index, list_files_process, current_video_fps
652
+
653
+ if destfiles is None or len(destfiles) < 1:
654
+ list_files_process.clear()
655
+ return gr.Slider(value=1, maximum=1, info='0:00:00'), ''
656
+
657
+ for f in destfiles:
658
+ list_files_process.append(ProcessEntry(f.name, 0,0, 0))
659
+
660
+ selected_preview_index = 0
661
+ idx = selected_preview_index
662
+
663
+ filename = list_files_process[idx].filename
664
+
665
+ if util.is_video(filename) or filename.lower().endswith('gif'):
666
+ total_frames = get_video_frame_total(filename)
667
+ current_video_fps = util.detect_fps(filename)
668
+ else:
669
+ total_frames = 1
670
+ list_files_process[idx].endframe = total_frames
671
+ if total_frames > 1:
672
+ return gr.Slider(value=1, maximum=total_frames, info='0:00:00'), gen_processing_text(list_files_process[idx].startframe,list_files_process[idx].endframe)
673
+ return gr.Slider(value=1, maximum=total_frames, info='0:00:00'), ''
674
+
675
+
676
+
677
+
678
+ def on_destfiles_selected(evt: gr.SelectData):
679
+ global selected_preview_index, list_files_process, current_video_fps
680
+
681
+ if evt is not None:
682
+ selected_preview_index = evt.index
683
+ idx = selected_preview_index
684
+ filename = list_files_process[idx].filename
685
+ fps = list_files_process[idx].fps
686
+ if util.is_video(filename) or filename.lower().endswith('gif'):
687
+ total_frames = get_video_frame_total(filename)
688
+ current_video_fps = util.detect_fps(filename)
689
+ if list_files_process[idx].endframe == 0:
690
+ list_files_process[idx].endframe = total_frames
691
+ else:
692
+ total_frames = 1
693
+
694
+ if total_frames > 1:
695
+ return gr.Slider(value=list_files_process[idx].startframe, maximum=total_frames, info='0:00:00'), gen_processing_text(list_files_process[idx].startframe,list_files_process[idx].endframe), fps
696
+ return gr.Slider(value=1, maximum=total_frames, info='0:00:00'), gen_processing_text(0,0), fps
697
+
698
+
699
+
700
+ def on_resultfiles_selected(evt: gr.SelectData, files):
701
+ selected_index = evt.index
702
+ filename = files[selected_index].name
703
+ return display_output(filename)
704
+
705
+ def on_resultfiles_finished(files):
706
+ selected_index = 0
707
+ if files is None or len(files) < 1:
708
+ return None, None
709
+
710
+ filename = files[selected_index].name
711
+ return display_output(filename)
712
+
713
+
714
+ def display_output(filename):
715
+ if util.is_video(filename) and roop.globals.CFG.output_show_video:
716
+ return gr.Image(visible=False), gr.Video(visible=True, value=filename)
717
+ else:
718
+ if util.is_video(filename) or filename.lower().endswith('gif'):
719
+ current_frame = get_video_frame(filename)
720
+ else:
721
+ current_frame = get_image_frame(filename)
722
+ return gr.Image(visible=True, value=util.convert_to_gradio(current_frame)), gr.Video(visible=False)
ui/tabs/livecam_tab.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import roop.globals
3
+ import ui.globals
4
+
5
+
6
+ camera_frame = None
7
+
8
+ def livecam_tab():
9
+ with gr.Tab("🎥 Live Cam"):
10
+ with gr.Row(variant='panel'):
11
+ gr.Markdown("""
12
+ This feature will allow you to use your physical webcam and apply the selected faces to the stream.
13
+ You can also forward the stream to a virtual camera, which can be used in video calls or streaming software.<br />
14
+ Supported are: v4l2loopback (linux), OBS Virtual Camera (macOS/Windows) and unitycapture (Windows).<br />
15
+ **Please note:** to change the face or any other settings you need to stop and restart a running live cam.
16
+ """)
17
+
18
+ with gr.Row(variant='panel'):
19
+ with gr.Column():
20
+ bt_start = gr.Button("▶ Start", variant='primary')
21
+ with gr.Column():
22
+ bt_stop = gr.Button("⏹ Stop", variant='secondary', interactive=False)
23
+ with gr.Column():
24
+ camera_num = gr.Slider(0, 8, value=0, label="Camera Number", step=1.0, interactive=True)
25
+ cb_obs = gr.Checkbox(label="Forward stream to virtual camera", interactive=True)
26
+ with gr.Column():
27
+ dd_reso = gr.Dropdown(choices=["640x480","1280x720", "1920x1080"], value="1280x720", label="Fake Camera Resolution", interactive=True)
28
+
29
+ with gr.Row():
30
+ fake_cam_image = gr.Image(label='Fake Camera Output', interactive=False)
31
+
32
+ start_event = bt_start.click(fn=start_cam, inputs=[cb_obs, camera_num, dd_reso, ui.globals.ui_selected_enhancer, ui.globals.ui_blend_ratio, ui.globals.ui_upscale],outputs=[bt_start, bt_stop,fake_cam_image])
33
+ bt_stop.click(fn=stop_swap, cancels=[start_event], outputs=[bt_start, bt_stop], queue=False)
34
+
35
+
36
+ def start_cam(stream_to_obs, cam, reso, enhancer, blend_ratio, upscale):
37
+ from roop.virtualcam import start_virtual_cam
38
+ from roop.utilities import convert_to_gradio
39
+
40
+ start_virtual_cam(stream_to_obs, cam, reso)
41
+ roop.globals.selected_enhancer = enhancer
42
+ roop.globals.blend_ratio = blend_ratio
43
+ roop.globals.subsample_size = int(upscale[:3])
44
+ while True:
45
+ yield gr.Button(interactive=False), gr.Button(interactive=True), convert_to_gradio(ui.globals.ui_camera_frame)
46
+
47
+
48
+ def stop_swap():
49
+ from roop.virtualcam import stop_virtual_cam
50
+ stop_virtual_cam()
51
+ return gr.Button(interactive=True), gr.Button(interactive=False)
52
+
53
+
54
+
55
+
ui/tabs/settings_tab.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import shutil
2
+ import os
3
+ import gradio as gr
4
+ import roop.globals
5
+ import ui.globals
6
+
7
+ available_themes = ["Default", "gradio/glass", "gradio/monochrome", "gradio/seafoam", "gradio/soft", "gstaff/xkcd", "freddyaboulton/dracula_revamped", "ysharma/steampunk"]
8
+ image_formats = ['jpg','png', 'webp']
9
+ video_formats = ['avi','mkv', 'mp4', 'webm']
10
+ video_codecs = ['libx264', 'libx265', 'libvpx-vp9', 'h264_nvenc', 'hevc_nvenc']
11
+ providerlist = None
12
+
13
+ settings_controls = []
14
+
15
+ def settings_tab():
16
+ from roop.core import suggest_execution_providers
17
+ global providerlist
18
+
19
+ providerlist = suggest_execution_providers()
20
+ with gr.Tab("⚙ Settings"):
21
+ with gr.Row():
22
+ with gr.Column():
23
+ themes = gr.Dropdown(available_themes, label="Theme", info="Change needs complete restart", value=roop.globals.CFG.selected_theme)
24
+ with gr.Column():
25
+ settings_controls.append(gr.Checkbox(label="Public Server", value=roop.globals.CFG.server_share, elem_id='server_share', interactive=True))
26
+ settings_controls.append(gr.Checkbox(label='Clear output folder before each run', value=roop.globals.CFG.clear_output, elem_id='clear_output', interactive=True))
27
+ output_template = gr.Textbox(label="Filename Output Template", info="(file extension is added automatically)", lines=1, placeholder='{file}_{time}', value=roop.globals.CFG.output_template)
28
+ with gr.Column():
29
+ input_server_name = gr.Textbox(label="Server Name", lines=1, info="Leave blank to run locally", value=roop.globals.CFG.server_name)
30
+ with gr.Column():
31
+ input_server_port = gr.Number(label="Server Port", precision=0, info="Leave at 0 to use default", value=roop.globals.CFG.server_port)
32
+ with gr.Row():
33
+ with gr.Column():
34
+ settings_controls.append(gr.Dropdown(providerlist, label="Provider", value=roop.globals.CFG.provider, elem_id='provider', interactive=True))
35
+ chk_det_size = gr.Checkbox(label="Use default Det-Size", value=True, elem_id='default_det_size', interactive=True)
36
+ settings_controls.append(gr.Checkbox(label="Force CPU for Face Analyser", value=roop.globals.CFG.force_cpu, elem_id='force_cpu', interactive=True))
37
+ max_threads = gr.Slider(1, 32, value=roop.globals.CFG.max_threads, label="Max. Number of Threads", info='default: 3', step=1.0, interactive=True)
38
+ with gr.Column():
39
+ memory_limit = gr.Slider(0, 128, value=roop.globals.CFG.memory_limit, label="Max. Memory to use (Gb)", info='0 meaning no limit', step=1.0, interactive=True)
40
+ settings_controls.append(gr.Dropdown(image_formats, label="Image Output Format", info='default: png', value=roop.globals.CFG.output_image_format, elem_id='output_image_format', interactive=True))
41
+ with gr.Column():
42
+ settings_controls.append(gr.Dropdown(video_codecs, label="Video Codec", info='default: libx264', value=roop.globals.CFG.output_video_codec, elem_id='output_video_codec', interactive=True))
43
+ settings_controls.append(gr.Dropdown(video_formats, label="Video Output Format", info='default: mp4', value=roop.globals.CFG.output_video_format, elem_id='output_video_format', interactive=True))
44
+ video_quality = gr.Slider(0, 100, value=roop.globals.CFG.video_quality, label="Video Quality (crf)", info='default: 14', step=1.0, interactive=True)
45
+ with gr.Column():
46
+ with gr.Group():
47
+ settings_controls.append(gr.Checkbox(label='Use OS temp folder', value=roop.globals.CFG.use_os_temp_folder, elem_id='use_os_temp_folder', interactive=True))
48
+ settings_controls.append(gr.Checkbox(label='Show video in browser (re-encodes output)', value=roop.globals.CFG.output_show_video, elem_id='output_show_video', interactive=True))
49
+ button_apply_restart = gr.Button("Restart Server", variant='primary')
50
+ button_clean_temp = gr.Button("Clean temp folder")
51
+ button_apply_settings = gr.Button("Apply Settings")
52
+
53
+ chk_det_size.select(fn=on_option_changed)
54
+
55
+ # Settings
56
+ for s in settings_controls:
57
+ s.select(fn=on_settings_changed)
58
+ max_threads.input(fn=lambda a,b='max_threads':on_settings_changed_misc(a,b), inputs=[max_threads])
59
+ memory_limit.input(fn=lambda a,b='memory_limit':on_settings_changed_misc(a,b), inputs=[memory_limit])
60
+ video_quality.input(fn=lambda a,b='video_quality':on_settings_changed_misc(a,b), inputs=[video_quality])
61
+
62
+ # button_clean_temp.click(fn=clean_temp, outputs=[bt_srcfiles, input_faces, target_faces, bt_destfiles])
63
+ button_clean_temp.click(fn=clean_temp)
64
+ button_apply_settings.click(apply_settings, inputs=[themes, input_server_name, input_server_port, output_template])
65
+ button_apply_restart.click(restart)
66
+
67
+
68
+ def on_option_changed(evt: gr.SelectData):
69
+ attribname = evt.target.elem_id
70
+ if isinstance(evt.target, gr.Checkbox):
71
+ if hasattr(roop.globals, attribname):
72
+ setattr(roop.globals, attribname, evt.selected)
73
+ return
74
+ elif isinstance(evt.target, gr.Dropdown):
75
+ if hasattr(roop.globals, attribname):
76
+ setattr(roop.globals, attribname, evt.value)
77
+ return
78
+ raise gr.Error(f'Unhandled Setting for {evt.target}')
79
+
80
+
81
+ def on_settings_changed_misc(new_val, attribname):
82
+ if hasattr(roop.globals.CFG, attribname):
83
+ setattr(roop.globals.CFG, attribname, new_val)
84
+ else:
85
+ print("Didn't find attrib!")
86
+
87
+
88
+
89
+ def on_settings_changed(evt: gr.SelectData):
90
+ attribname = evt.target.elem_id
91
+ if isinstance(evt.target, gr.Checkbox):
92
+ if hasattr(roop.globals.CFG, attribname):
93
+ setattr(roop.globals.CFG, attribname, evt.selected)
94
+ return
95
+ elif isinstance(evt.target, gr.Dropdown):
96
+ if hasattr(roop.globals.CFG, attribname):
97
+ setattr(roop.globals.CFG, attribname, evt.value)
98
+ return
99
+
100
+ raise gr.Error(f'Unhandled Setting for {evt.target}')
101
+
102
+ def clean_temp():
103
+ from ui.main import prepare_environment
104
+
105
+ ui.globals.ui_input_thumbs.clear()
106
+ roop.globals.INPUT_FACESETS.clear()
107
+ roop.globals.TARGET_FACES.clear()
108
+ ui.globals.ui_target_thumbs = []
109
+ if not roop.globals.CFG.use_os_temp_folder:
110
+ shutil.rmtree(os.environ["TEMP"])
111
+ prepare_environment()
112
+ gr.Info('Temp Files removed')
113
+ return None,None,None,None
114
+
115
+
116
+ def apply_settings(themes, input_server_name, input_server_port, output_template):
117
+ from ui.main import show_msg
118
+
119
+ roop.globals.CFG.selected_theme = themes
120
+ roop.globals.CFG.server_name = input_server_name
121
+ roop.globals.CFG.server_port = input_server_port
122
+ roop.globals.CFG.output_template = output_template
123
+ roop.globals.CFG.save()
124
+ show_msg('Settings saved')
125
+
126
+
127
+ def restart():
128
+ ui.globals.ui_restart_server = True