-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathsdcpp_webui.py
More file actions
388 lines (324 loc) · 12.1 KB
/
sdcpp_webui.py
File metadata and controls
388 lines (324 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
#!/usr/bin/env python3
"""sd.cpp-webui - Main module"""
import os
import sys
import json
import argparse
import gradio as gr
from modules.interfaces.cli.txt2img_tab import (
txt2img_block, txt2img_params
)
from modules.interfaces.server.txt2img_tab import (
txt2img_server_block, txt2img_server_params
)
from modules.interfaces.cli.img2img_tab import (
img2img_block, img2img_params, img_inp_img2img
)
from modules.interfaces.server.img2img_tab import (
img2img_server_block, img2img_server_params,
img_inp_img2img_server
)
from modules.interfaces.cli.imgedit_tab import (
imgedit_block, width_imgedit, height_imgedit,
ref_img_imgedit
)
from modules.interfaces.server.imgedit_tab import (
imgedit_server_block, width_imgedit_server,
height_imgedit_server, ref_img_imgedit_server
)
from modules.interfaces.cli.any2video_tab import (
any2video_block, any2video_params
)
from modules.interfaces.cli.upscale_tab import (
upscale_block, img_inp_upscale
)
from modules.interfaces.common.gallery_tab import (
gallery_block, cpy_2_txt2img_btn, cpy_2_img2img_btn, cpy_2_imgedit_btn,
cpy_2_any2video_btn, cpy_2_upscale_btn, info_params, path_info,
gallery, gallery_manager, def_page, txt2img_ctrl, page_num_select
)
from modules.interfaces.cli.convert_tab import convert_block
from modules.interfaces.common.options_tab import (
options_block, restart_btn
)
from modules.config import ConfigManager
from modules.ui.constants import FIELDS, SAMPLERS, SCHEDULERS
DARK_MODE_JS = """
function refresh() {
const url = new URL(window.location);
if (url.searchParams.get('__theme') !== 'dark') {
url.searchParams.set('__theme', 'dark');
window.location.href = url.href;
}
}
"""
os.environ['GRADIO_ANALYTICS_ENABLED'] = 'False'
config = ConfigManager()
theme = config.get('def_theme')
def create_copy_fn(tab_id: str, fields: list = None) -> callable:
"""
Creates a function that switches to a specific tab
and passes through its arguments.
Args:
tab_id (str): The ID of the selected tab.
Returns:
A function suitable for a Gradio .click() event.
"""
def copy_fn(*args):
# The first return value switches the tab,
# the rest are the passed-through arguments.
values = args
if fields:
values = []
for name, value in zip(fields, args):
if name == 'sampling' and value not in SAMPLERS:
value = config.get('def_sampling')
elif name == 'scheduler' and value not in SCHEDULERS:
value = config.get('def_scheduler')
values.append(value)
return [gr.Tabs(selected=tab_id), *values]
return copy_fn
def lazy_load_gallery(is_loaded, page, ctrl):
if is_loaded:
# If already loaded, return existing values (do nothing)
return (
gr.skip(), gr.skip(), True
)
results = gallery_manager.reload_gallery(page, ctrl)
return *results, True
def get_allowed_paths(config_data, base_path: str) -> list:
"""Parses config to find allowed external or linked directories."""
allowed_paths = []
dirs = [
val for key, val in config.data.items()
if key.endswith('_dir') and isinstance(val, str) and val
]
for path in dirs:
# Expand user tildes
expanded_path = os.path.expanduser(path)
abs_path = os.path.abspath(expanded_path)
# Check if it's a symlink (STRIP TRAILING SLASHES)
# os.path.islink() returns False if the path ends with a separator
is_link = os.path.islink(abs_path.rstrip(os.sep))
# Check if it is physically outside the base path
real_path = os.path.realpath(abs_path)
is_external = not real_path.startswith(base_path)
if is_link or is_external:
if is_link:
allowed_paths.append(real_path)
if abs_path != real_path:
allowed_paths.append(abs_path)
elif not is_link:
allowed_paths.append(abs_path)
unique_paths = list(set(allowed_paths))
if unique_paths:
print("Allowing external/linked directories:")
for path in unique_paths:
print(f" - {path}")
print()
return unique_paths
def load_credentials(filepath: str = "credentials.json"):
"""
Loads usernames and passwords from a JSON file.
Expected format: {"username1": "password1", "username2": "password2"}
"""
try:
if os.path.exists(filepath):
with open(filepath, 'r') as file:
data = json.load(file)
# Gradio expects auth to be a list of tuples:
# [("user", "pass"), ...]
return list(data.items())
else:
print(f"Credentials file '{filepath}' not found. Skipping password protection.")
return None
except Exception as e:
print(f"Error reading credentials: {e}. Skipping password protection.")
return None
def build_launch_args(
listen: bool, autostart: bool, credentials: bool
) -> dict:
launch_args = {}
if listen:
launch_args["server_name"] = "0.0.0.0"
if autostart:
launch_args["inbrowser"] = True
if credentials:
auth_data = load_credentials()
if auth_data:
print(f"Secure mode enabled with {len(auth_data)} users.")
launch_args["auth"] = auth_data
else:
print("Secure mode requested but failed to load credentials. Launching without auth.")
return launch_args
def render_server_ui():
gr.Markdown("# <center>sd.cpp-webui - server</center>")
with gr.Tabs() as tabs:
with gr.TabItem("txt2img", id="txt2img"):
txt2img_server_block.render()
with gr.TabItem("img2img", id="img2img"):
img2img_server_block.render()
with gr.TabItem("imgedit", id="imgedit"):
imgedit_server_block.render()
with gr.TabItem("Gallery", id="gallery") as gallery_tab:
cpy_2_any2video_btn.visible = False
cpy_2_upscale_btn.visible = False
gallery_block.render()
with gr.TabItem("Options", id="options"):
options_block.render()
return tabs, gallery_tab
def render_cli_ui():
gr.Markdown("# <center>sd.cpp-webui - cli</center>")
with gr.Tabs() as tabs:
with gr.TabItem("txt2img", id="txt2img"):
txt2img_block.render()
with gr.TabItem("img2img", id="img2img"):
img2img_block.render()
with gr.TabItem("imgedit", id="imgedit"):
imgedit_block.render()
with gr.TabItem("any2video", id="any2video"):
any2video_block.render()
with gr.TabItem("Gallery", id="gallery") as gallery_tab:
gallery_block.render()
with gr.TabItem("Upscaler", id="upscale"):
upscale_block.render()
with gr.TabItem("Checkpoint Converter", id="convert"):
convert_block.render()
with gr.TabItem("Options", id="options"):
options_block.render()
return tabs, gallery_tab
def restart_server():
"""
Restarts the sdcpp-webui.
"""
print("\nRestarting server...")
os.environ['SDCPP_IS_RESTART'] = 'true'
python = sys.executable
new_args = [arg for arg in sys.argv if arg != '--autostart']
os.execv(python, [python] + new_args)
def bind_ui_events(server: bool, tabs, gallery_tab, gallery_loaded_state):
common_inputs = [info_params[f] for f in FIELDS]
gallery_tab.select(
fn=lazy_load_gallery,
inputs=[gallery_loaded_state, def_page, txt2img_ctrl],
outputs=[
gallery, page_num_select, gallery_loaded_state
]
)
t2i_params = txt2img_server_params if server else txt2img_params
i2i_params = img2img_server_params if server else img2img_params
i2i_inp = img_inp_img2img_server if server else img_inp_img2img
ie_width = width_imgedit_server if server else width_imgedit
ie_height = height_imgedit_server if server else height_imgedit
ie_ref = ref_img_imgedit_server if server else ref_img_imgedit
# Copy data from gallery image to txt2img.
cpy_2_txt2img_btn.click(
create_copy_fn("txt2img", FIELDS),
inputs=common_inputs,
outputs=[tabs] + [t2i_params[f] for f in FIELDS]
)
# Copy data from gallery image to img2img.
cpy_2_img2img_btn.click(
create_copy_fn("img2img", FIELDS + ['input_image']),
inputs=common_inputs + [path_info],
outputs=[tabs] + [i2i_params[f] for f in FIELDS] + [i2i_inp]
)
# Copy data from gallery image to imgedit
cpy_2_imgedit_btn.click(
create_copy_fn("imgedit"),
inputs=[info_params['width'], info_params['height'], path_info],
outputs=[tabs, ie_width, ie_height, ie_ref]
)
if not server:
# Copy data from gallery image to any2video.
cpy_2_any2video_btn.click(
create_copy_fn("any2video", FIELDS),
inputs=common_inputs + [path_info],
outputs=[tabs] + [any2video_params[f] for f in FIELDS]
)
cpy_2_upscale_btn.click(
create_copy_fn("upscale"),
inputs=[path_info],
outputs=[tabs, img_inp_upscale]
)
restart_btn.click(
fn=restart_server,
inputs=[],
outputs=[]
)
def sdcpp_launch(
server: bool = False, listen: bool = False,
autostart: bool = False, darkmode: bool = False,
credentials: bool = False, insecure_dir: bool = False
):
"""Logic for launching sdcpp based on arguments"""
launch_args = build_launch_args(listen, autostart, credentials)
dark_js = DARK_MODE_JS if darkmode else None
if insecure_dir:
launch_args["allowed_paths"] = get_allowed_paths(
config.data, os.path.abspath(os.getcwd())
)
with gr.Blocks(
title="sd.cpp-webui"
) as sdcpp:
gallery_loaded_state = gr.State(value=False)
if server:
tabs, gallery_tab = render_server_ui()
else:
tabs, gallery_tab = render_cli_ui()
bind_ui_events(server, tabs, gallery_tab, gallery_loaded_state)
# Pass the arguments to sdcpp.launch with argument unpacking
sdcpp.launch(
css="footer {visibility: hidden}",
theme="default", js=dark_js,
**launch_args
)
def main():
"""Main"""
if os.environ.get('SDCPP_IS_RESTART') == 'true':
print("\n" + "="*60)
print(" SERVER RESTARTED SUCCESSFULLY")
print(" Please refresh your web browser to apply the changes.")
print("="*60 + "\n")
del os.environ['SDCPP_IS_RESTART']
parser = argparse.ArgumentParser(description='Process optional arguments')
parser.add_argument(
'--server',
action='store_true',
help='Run stable-diffusion.cpp\'s server mode'
)
parser.add_argument(
'--listen',
action='store_true',
help='Listen on 0.0.0.0'
)
parser.add_argument(
'--autostart',
action='store_true',
help='Automatically launch in a new browser tab'
)
parser.add_argument(
'--darkmode',
action='store_true',
help='Enable dark mode for the web interface'
)
parser.add_argument(
'--credentials',
action='store_true',
help='Enable password protection using credentials.json'
)
parser.add_argument(
'--allow-insecure-dir',
action='store_true',
help='Allows the usage of external or linked directories based on config.json'
)
args = parser.parse_args()
sdcpp_launch(
args.server, args.listen, args.autostart, args.darkmode,
args.credentials, args.allow_insecure_dir
)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
sys.exit(0)