Skip to content

Commit c545d80

Browse files
authored
Merge pull request #290 from thygate/standalone-interface
Standalone interface
2 parents 88e11b8 + 1d217ce commit c545d80

File tree

8 files changed

+757
-584
lines changed

8 files changed

+757
-584
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@ video by [@graemeniedermayer](https://github.com/graemeniedermayer), more exampl
2121
images generated by [@semjon00](https://github.com/semjon00) from CC0 photos, more examples [here](https://github.com/thygate/stable-diffusion-webui-depthmap-script/pull/56#issuecomment-1367596463).
2222

2323
## Changelog
24+
* v0.4.1 standalone mode
25+
* ability to run DepthMap without WebUI (Use main.py. Make sure all the dependencies are installed. The support is not feature-complete.)
2426
* v0.4.0 large code refactor
2527
* UI improvements
2628
* improved Batch from Directory, Clip and renormalize DepthMap

main.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# This launches DepthMap without the AUTOMATIC1111/stable-diffusion-webui
2+
# If DepthMap is installed as an extension,
3+
# you may want to change the working directory to the stable-diffusion-webui root.
4+
5+
import argparse
6+
import os
7+
import pathlib
8+
import builtins
9+
10+
import src.misc
11+
12+
def maybe_chdir():
13+
"""Detects if DepthMap was installed as a stable-diffusion-webui script, but run without current directory set to
14+
the stable-diffusion-webui root. Changes current directory if needed, to aviod clutter."""
15+
try:
16+
file_path = pathlib.Path(__file__)
17+
path = file_path.parts
18+
while len(path) > 0 and path[-1] != src.misc.REPOSITORY_NAME:
19+
path = path[:-1]
20+
if len(path) >= 2 and path[-1] == src.misc.REPOSITORY_NAME and path[-2] == "extensions":
21+
path = path[:-2]
22+
listdir = os.listdir(str(pathlib.Path(*path)))
23+
if 'launch.py' in listdir and 'webui.py':
24+
os.chdir(str(pathlib.Path(**path)))
25+
except:
26+
pass
27+
28+
29+
if __name__ == '__main__':
30+
parser = argparse.ArgumentParser()
31+
parser.add_argument("--listen", help="Create public link")
32+
parser.add_argument("--no_chdir", help="Do not try to use the root of stable-diffusion-webui")
33+
args = parser.parse_args()
34+
35+
print(f"{src.misc.SCRIPT_FULL_NAME} running in standalone mode!")
36+
import src.common_ui
37+
if not args.no_chdir:
38+
maybe_chdir()
39+
src.common_ui.on_ui_tabs().launch(share=args.listen)

scripts/depthmap.py

Lines changed: 21 additions & 493 deletions
Large diffs are not rendered by default.

src/backbone.py

Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
# DepthMap can be run inside stable-duiffusion-webui, but also separately.
2+
# All the stable-duiffusion-webui stuff that the DepthMap relies on
3+
# must be resided in this file (or in the scripts folder).
4+
import pathlib
5+
from datetime import datetime
6+
7+
try:
8+
# stable-duiffusion-webui backbone
9+
from modules.images import save_image # Should fail if not on stable-duiffusion-webui
10+
from modules.devices import torch_gc # TODO: is this really sufficient?
11+
from modules.images import get_next_sequence_number
12+
from modules.call_queue import wrap_gradio_gpu_call
13+
from modules.shared import listfiles
14+
15+
def get_opt(name, default):
16+
from modules.shared import opts
17+
if hasattr(opts, name):
18+
return opts.__getattr__(name)
19+
return default
20+
21+
def get_cmd_opt(name, default):
22+
"""Get command line argument"""
23+
from modules.shared import cmd_opts
24+
if hasattr(cmd_opts, name):
25+
return cmd_opts.__getattribute__(name)
26+
return default
27+
28+
def gather_ops():
29+
"""Parameters for depthmap generation"""
30+
from modules.shared import cmd_opts
31+
ops = {}
32+
if get_opt('depthmap_script_boost_rmax', None) is not None:
33+
ops['boost_whole_size_threshold'] = get_opt('depthmap_script_boost_rmax', None)
34+
ops['precision'] = cmd_opts.precision
35+
ops['no_half'] = cmd_opts.no_half
36+
return ops
37+
38+
39+
def get_outpath():
40+
"""Get path where results are saved by default"""
41+
path = get_opt('outdir_samples', None)
42+
if path is None or len(path) == 0:
43+
path = get_opt('outdir_extras_samples', None)
44+
assert path is not None and len(path) > 0
45+
return path
46+
47+
48+
def unload_sd_model():
49+
from modules import shared, devices
50+
if shared.sd_model is not None:
51+
shared.sd_model.cond_stage_model.to(devices.cpu)
52+
shared.sd_model.first_stage_model.to(devices.cpu)
53+
54+
55+
def reload_sd_model():
56+
from modules import shared, devices
57+
if shared.sd_model is not None:
58+
shared.sd_model.cond_stage_model.to(devices.device)
59+
shared.sd_model.first_stage_model.to(devices.device)
60+
61+
def get_hide_dirs():
62+
import modules.shared
63+
return modules.shared.hide_dirs
64+
except:
65+
# Standalone backbone
66+
print( # " DepthMap did not detect stable-duiffusion-webui; launching with the standalone backbone.\n"
67+
" The standalone mode is not on par with the stable-duiffusion-webui mode.\n"
68+
" Some features may be missing or work differently. Please report bugs.\n")
69+
70+
def save_image(image, path, basename, **kwargs):
71+
import os
72+
os.makedirs(path, exist_ok=True)
73+
if 'suffix' not in kwargs or len(kwargs['suffix']) == 0:
74+
kwargs['suffix'] = ''
75+
else:
76+
kwargs['suffix'] = f"-{kwargs['suffix']}"
77+
format = get_opt('samples_format', kwargs['extension'])
78+
fullfn = os.path.join(
79+
path, f"{basename}-{get_next_sequence_number(path, basename)}{kwargs['suffix']}.{format}")
80+
image.save(fullfn, format=format)
81+
82+
def torch_gc():
83+
# TODO: is this really sufficient?
84+
import torch
85+
if torch.cuda.is_available():
86+
with torch.cuda.device('cuda'):
87+
torch.cuda.empty_cache()
88+
torch.cuda.ipc_collect()
89+
90+
launched_at = int(datetime.now().timestamp())
91+
backbone_current_seq_number = 0
92+
93+
def get_next_sequence_number(outpath=None, basename=None):
94+
global backbone_current_seq_number
95+
backbone_current_seq_number += 1
96+
return int(f"{launched_at}{backbone_current_seq_number:04}")
97+
98+
def wrap_gradio_gpu_call(f): return f # Displaying various stats is not supported
99+
100+
def listfiles(dirname):
101+
import os
102+
filenames = [os.path.join(dirname, x) for x in sorted(os.listdir(dirname)) if not x.startswith(".")]
103+
return [file for file in filenames if os.path.isfile(file)]
104+
105+
def get_opt(name, default): return default # Configuring is not supported
106+
107+
108+
def get_cmd_opt(name, default): return default # Configuring is not supported
109+
110+
def gather_ops(): return {} # Configuring is not supported
111+
112+
def get_outpath(): return str(pathlib.Path('.', 'outputs'))
113+
114+
def unload_sd_model(): pass # Not needed
115+
116+
def reload_sd_model(): pass # Not needed
117+
118+
def get_hide_dirs(): return {} # Directories will not be hidden from traversal (except when starts with the dot)

0 commit comments

Comments
 (0)