Repository navigation
Expand file tree
/
Copy pathsdcpp_webui.py
More file actions
453 lines (383 loc) · 14.6 KB
/
Copy pathsdcpp_webui.py
File metadata and controls
453 lines (383 loc) · 14.6 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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
#!/usr/bin/env python3
"""sd.cpp-webui - Main module"""
import os
import sys
import json
import argparse
import warnings
import gradio as gr
from modules.extensions.loader import load_extensions
from modules.extensions.ui import render_extension_tabs, render_extensions_info
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, img_inp_any2video
)
from modules.interfaces.server.any2video_tab import (
any2video_server_block, any2video_server_params,
img_inp_any2video_server
)
from modules.interfaces.server.upscale_tab import (
upscale_server_block, img_inp_upscale_server
)
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.models_tab import models_block
from modules.interfaces.common.settings_tab import (
settings_block, restart_btn
)
from modules.settings import ConfigManager
from modules.ui.constants import FIELDS, SAMPLERS, SCHEDULERS
from modules.utils.sdcpp_utils import restart_server
from modules.utils.ui_events import RESYNC_JS, GALLERY_CSS
def _is_within(real_path: str, base_real_path: str) -> bool:
"""Return True iff `real_path` equals or is a descendant of `base_real_path`.
Compares inode identity (st_dev, st_ino) of each ancestor rather than
string prefixes, so it is correct on case-insensitive filesystems
(macOS APFS, Windows NTFS), case-sensitive filesystems (Linux ext4,
case-sensitive APFS), across Unicode NFD/NFC differences, through
symlinks, across bind mounts and mount points, across Windows drive
letters, with trailing separators, and with non-existent suffixes.
`real_path` and `base_real_path` are expected to be absolute and
already passed through os.path.realpath.
"""
try:
base_stat = os.stat(base_real_path)
except OSError:
# Base does not exist: nothing can be within it.
return False
current = real_path
while True:
try:
if os.path.samestat(os.stat(current), base_stat):
return True
except OSError:
# Component absent or unreadable; keep walking upward —
# a shallower ancestor may still match.
pass
parent = os.path.dirname(current)
if parent == current: # reached the root / drive root
return False
current = parent
def build_page_js(scheme: str):
"""On-page-load JS: forces the color scheme and resyncs the
generation outputs when the page becomes visible again.
Gradio dark mode is a 'dark' class on <body> (light/dark CSS vars
are both served), so no reload is needed."""
scheme = str(scheme or 'system').lower()
if scheme == 'dark':
action = "document.body.classList.add('dark');"
elif scheme == 'light':
action = "document.body.classList.remove('dark');"
else:
action = ""
return f"function refresh() {{\n {action}\n{RESYNC_JS}}}"
warnings.filterwarnings("ignore", message=".*HTTP_422_UNPROCESSABLE_ENTITY.*")
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 copy_to_imgedit(width, height, path_info):
gallery_path = [path_info] if path_info else []
return [gr.Tabs(selected="imgedit"), width, height, gallery_path]
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 key != 'ext_dir'
and isinstance(val, str) and val
]
base_real_path = os.path.realpath(base_path)
for path in dirs:
expanded_path = os.path.expanduser(path)
abs_path = os.path.abspath(expanded_path)
# STRIP TRAILING SLASHES: islink() is False for paths ending in a separator
is_link = os.path.islink(abs_path.rstrip(os.sep))
real_path = os.path.realpath(abs_path)
is_external = not _is_within(real_path, base_real_path)
if is_link or is_external:
allowed_paths.append(abs_path)
if real_path != abs_path:
allowed_paths.append(real_path)
unique_paths = list(set(allowed_paths))
if unique_paths:
print("Allowing external/linked directories:")
for p in unique_paths:
print(f" - {p}")
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.")
return None
except Exception as e:
print(f"Error reading credentials: {e}")
return None
def build_launch_args(
listen: bool, share: bool, autostart: bool, credentials: bool
) -> dict:
launch_args = {}
if listen:
launch_args["server_name"] = "0.0.0.0"
if share:
launch_args["share"] = True
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("ERROR: Secure mode requested but no valid credentials were loaded.")
print("Refusing to launch without authentication. Fix or create credentials.json and retry.")
sys.exit(1)
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("any2video", id="any2video"):
any2video_server_block.render()
with gr.TabItem("Gallery", id="gallery") as gallery_tab:
gallery_block.render()
with gr.TabItem("Upscaler", id="upscale"):
upscale_server_block.render()
with gr.TabItem("Models", id="models"):
models_block.render()
render_extension_tabs()
with gr.TabItem("Settings", id="settings"):
settings_block.render()
render_extensions_info()
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("Models", id="models"):
models_block.render()
render_extension_tabs()
with gr.TabItem("Settings", id="settings"):
settings_block.render()
render_extensions_info()
return tabs, gallery_tab
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
v2v_params = any2video_server_params if server else any2video_params
v2v_inp = img_inp_any2video_server if server else img_inp_any2video
# 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(
copy_to_imgedit,
inputs=[info_params['width'], info_params['height'], path_info],
outputs=[tabs, ie_width, ie_height, ie_ref]
)
# Copy data from gallery image to any2video.
cpy_2_any2video_btn.click(
create_copy_fn("any2video", FIELDS + ['input_image']),
inputs=common_inputs + [path_info],
outputs=[tabs] + [v2v_params[f] for f in FIELDS] + [v2v_inp]
)
cpy_2_upscale_btn.click(
create_copy_fn("upscale"),
inputs=[path_info],
outputs=[tabs, img_inp_upscale_server if server else img_inp_upscale]
)
restart_btn.click(
fn=restart_server,
inputs=[],
outputs=[]
)
def sdcpp_launch(
server: bool = False, listen: bool = False,
share: bool = False, autostart: bool = False,
credentials: bool = False, insecure_dir: bool = False
):
"""Logic for launching sdcpp based on arguments"""
launch_args = build_launch_args(listen, share, autostart, credentials)
page_js = build_page_js(config.get('def_color_scheme'))
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}" + GALLERY_CSS,
theme=theme or "default", js=page_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(
'--share',
action='store_true',
help="Share sd.cpp-webui online with a link"
)
parser.add_argument(
'--autostart',
action='store_true',
help='Automatically launch in a new browser tab'
)
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'
)
parser.add_argument(
'--extensions',
action='store_true',
help='Enable extensions: install their requirements and load '
'them from the extensions folder'
)
args = parser.parse_args()
load_extensions(config)
sdcpp_launch(
args.server, args.listen, args.share, args.autostart,
args.credentials, args.allow_insecure_dir
)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
sys.exit(0)