Skip to content

Standalone interface #290

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Jul 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ video by [@graemeniedermayer](https://github.com/graemeniedermayer), more exampl
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).

## Changelog
* v0.4.1 standalone mode
* ability to run DepthMap without WebUI (Use main.py. Make sure all the dependencies are installed. The support is not feature-complete.)
* v0.4.0 large code refactor
* UI improvements
* improved Batch from Directory, Clip and renormalize DepthMap
Expand Down
39 changes: 39 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# This launches DepthMap without the AUTOMATIC1111/stable-diffusion-webui
# If DepthMap is installed as an extension,
# you may want to change the working directory to the stable-diffusion-webui root.

import argparse
import os
import pathlib
import builtins

import src.misc

def maybe_chdir():
"""Detects if DepthMap was installed as a stable-diffusion-webui script, but run without current directory set to
the stable-diffusion-webui root. Changes current directory if needed, to aviod clutter."""
try:
file_path = pathlib.Path(__file__)
path = file_path.parts
while len(path) > 0 and path[-1] != src.misc.REPOSITORY_NAME:
path = path[:-1]
if len(path) >= 2 and path[-1] == src.misc.REPOSITORY_NAME and path[-2] == "extensions":
path = path[:-2]
listdir = os.listdir(str(pathlib.Path(*path)))
if 'launch.py' in listdir and 'webui.py':
os.chdir(str(pathlib.Path(**path)))
except:
pass


if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("--listen", help="Create public link")
parser.add_argument("--no_chdir", help="Do not try to use the root of stable-diffusion-webui")
args = parser.parse_args()

print(f"{src.misc.SCRIPT_FULL_NAME} running in standalone mode!")
import src.common_ui
if not args.no_chdir:
maybe_chdir()
src.common_ui.on_ui_tabs().launch(share=args.listen)
514 changes: 21 additions & 493 deletions scripts/depthmap.py

Large diffs are not rendered by default.

118 changes: 118 additions & 0 deletions src/backbone.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
# DepthMap can be run inside stable-duiffusion-webui, but also separately.
# All the stable-duiffusion-webui stuff that the DepthMap relies on
# must be resided in this file (or in the scripts folder).
import pathlib
from datetime import datetime

try:
# stable-duiffusion-webui backbone
from modules.images import save_image # Should fail if not on stable-duiffusion-webui
from modules.devices import torch_gc # TODO: is this really sufficient?
from modules.images import get_next_sequence_number
from modules.call_queue import wrap_gradio_gpu_call
from modules.shared import listfiles

def get_opt(name, default):
from modules.shared import opts
if hasattr(opts, name):
return opts.__getattr__(name)
return default

def get_cmd_opt(name, default):
"""Get command line argument"""
from modules.shared import cmd_opts
if hasattr(cmd_opts, name):
return cmd_opts.__getattribute__(name)
return default

def gather_ops():
"""Parameters for depthmap generation"""
from modules.shared import cmd_opts
ops = {}
if get_opt('depthmap_script_boost_rmax', None) is not None:
ops['boost_whole_size_threshold'] = get_opt('depthmap_script_boost_rmax', None)
ops['precision'] = cmd_opts.precision
ops['no_half'] = cmd_opts.no_half
return ops


def get_outpath():
"""Get path where results are saved by default"""
path = get_opt('outdir_samples', None)
if path is None or len(path) == 0:
path = get_opt('outdir_extras_samples', None)
assert path is not None and len(path) > 0
return path


def unload_sd_model():
from modules import shared, devices
if shared.sd_model is not None:
shared.sd_model.cond_stage_model.to(devices.cpu)
shared.sd_model.first_stage_model.to(devices.cpu)


def reload_sd_model():
from modules import shared, devices
if shared.sd_model is not None:
shared.sd_model.cond_stage_model.to(devices.device)
shared.sd_model.first_stage_model.to(devices.device)

def get_hide_dirs():
import modules.shared
return modules.shared.hide_dirs
except:
# Standalone backbone
print( # " DepthMap did not detect stable-duiffusion-webui; launching with the standalone backbone.\n"
" The standalone mode is not on par with the stable-duiffusion-webui mode.\n"
" Some features may be missing or work differently. Please report bugs.\n")

def save_image(image, path, basename, **kwargs):
import os
os.makedirs(path, exist_ok=True)
if 'suffix' not in kwargs or len(kwargs['suffix']) == 0:
kwargs['suffix'] = ''
else:
kwargs['suffix'] = f"-{kwargs['suffix']}"
format = get_opt('samples_format', kwargs['extension'])
fullfn = os.path.join(
path, f"{basename}-{get_next_sequence_number(path, basename)}{kwargs['suffix']}.{format}")
image.save(fullfn, format=format)

def torch_gc():
# TODO: is this really sufficient?
import torch
if torch.cuda.is_available():
with torch.cuda.device('cuda'):
torch.cuda.empty_cache()
torch.cuda.ipc_collect()

launched_at = int(datetime.now().timestamp())
backbone_current_seq_number = 0

def get_next_sequence_number(outpath=None, basename=None):
global backbone_current_seq_number
backbone_current_seq_number += 1
return int(f"{launched_at}{backbone_current_seq_number:04}")

def wrap_gradio_gpu_call(f): return f # Displaying various stats is not supported

def listfiles(dirname):
import os
filenames = [os.path.join(dirname, x) for x in sorted(os.listdir(dirname)) if not x.startswith(".")]
return [file for file in filenames if os.path.isfile(file)]

def get_opt(name, default): return default # Configuring is not supported


def get_cmd_opt(name, default): return default # Configuring is not supported

def gather_ops(): return {} # Configuring is not supported

def get_outpath(): return str(pathlib.Path('.', 'outputs'))

def unload_sd_model(): pass # Not needed

def reload_sd_model(): pass # Not needed

def get_hide_dirs(): return {} # Directories will not be hidden from traversal (except when starts with the dot)
Loading