File size: 14,492 Bytes
0070fce |
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 |
"""
This script installs necessary requirements and launches main program in webui.py
"""
import importlib.metadata
import importlib.util
import json
import logging
import os
import re
import subprocess
import sys
from pathlib import Path
from dataclasses import dataclass
from modules import cmd_args, errors, logging_config
from modules.paths_internal import extensions_builtin_dir, extensions_dir, script_path
from modules.timer import startup_timer
from modules_forge.config import always_disabled_extensions
from modules_forge.forge_version import version
args, _ = cmd_args.parser.parse_known_args()
logging_config.setup_logging(args.loglevel)
python = sys.executable
git = os.environ.get("GIT", "git")
index_url = os.environ.get("INDEX_URL")
dir_repos = "repositories"
default_command_live = os.environ.get("WEBUI_LAUNCH_LIVE_OUTPUT") == "1"
os.environ.setdefault("GRADIO_ANALYTICS_ENABLED", "False")
def check_python_version():
major = sys.version_info.major
minor = sys.version_info.minor
micro = sys.version_info.micro
if not (major == 3 and minor == 11):
import modules.errors
modules.errors.print_error_explanation(
f"""
This program is tested with 3.11.9 Python, but you have {major}.{minor}.{micro}.
If you encounter any error regarding unsuccessful package/library installation,
please downgrade (or upgrade) to the latest version of 3.11 Python,
and delete the current Python "venv" folder in WebUI's directory.
Use --skip-python-version-check to suppress this warning
"""
)
def git_tag():
return version
def run(command, desc=None, errdesc=None, custom_env=None, live=default_command_live) -> str:
if desc is not None:
print(desc)
run_kwargs = {
"args": command,
"shell": True,
"env": os.environ if custom_env is None else custom_env,
"encoding": "utf8",
"errors": "ignore",
}
if not live:
run_kwargs["stdout"] = run_kwargs["stderr"] = subprocess.PIPE
result = subprocess.run(**run_kwargs)
if result.returncode != 0:
error_bits = [
f"{errdesc or 'Error running command'}.",
f"Command: {command}",
f"Error code: {result.returncode}",
]
if result.stdout:
error_bits.append(f"stdout: {result.stdout}")
if result.stderr:
error_bits.append(f"stderr: {result.stderr}")
raise RuntimeError("\n".join(error_bits))
return result.stdout or ""
def is_installed(package):
try:
dist = importlib.metadata.distribution(package)
except importlib.metadata.PackageNotFoundError:
try:
spec = importlib.util.find_spec(package)
except ModuleNotFoundError:
return False
return spec is not None
return dist is not None
def repo_dir(name):
return os.path.join(script_path, dir_repos, name)
def run_pip(command, desc=None, live=default_command_live):
if args.skip_install:
return
index_url_line = f" --index-url {index_url}" if index_url is not None else ""
return run(f'"{python}" -m pip {command} --prefer-binary{index_url_line}', desc=f"Installing {desc}", errdesc=f"Couldn't install {desc}", live=live)
def check_run_python(code: str) -> bool:
result = subprocess.run([python, "-c", code], capture_output=True, shell=False)
return result.returncode == 0
def git_fix_workspace(*args, **kwargs):
raise NotImplementedError
def run_git(*args, **kwargs):
raise NotImplementedError
def git_clone(*args, **kwargs):
raise NotImplementedError
def git_pull_recursive(dir):
for subdir, _, _ in os.walk(dir):
if os.path.exists(os.path.join(subdir, ".git")):
try:
output = subprocess.check_output([git, "-C", subdir, "pull", "--autostash"])
print(f"Pulled changes for repository in '{subdir}':\n{output.decode('utf-8').strip()}\n")
except subprocess.CalledProcessError as e:
print(f"Couldn't perform 'git pull' on repository in '{subdir}':\n{e.output.decode('utf-8').strip()}\n")
def run_extension_installer(extension_dir):
path_installer = os.path.join(extension_dir, "install.py")
if not os.path.isfile(path_installer):
return
try:
env = os.environ.copy()
env["PYTHONPATH"] = f"{os.path.abspath('.')}{os.pathsep}{env.get('PYTHONPATH', '')}"
stdout = run(f'"{python}" "{path_installer}"', errdesc=f"Error running install.py for extension {extension_dir}", custom_env=env).strip()
if stdout:
print(stdout)
except Exception as e:
errors.report(str(e))
def list_extensions(settings_file):
settings = {}
try:
with open(settings_file, "r", encoding="utf8") as file:
settings = json.load(file)
except FileNotFoundError:
pass
except Exception:
errors.report(f'\nCould not load settings\nThe config file "{settings_file}" is likely corrupted\nIt has been moved to the "tmp/config.json"\nReverting config to default\n\n', exc_info=True)
os.replace(settings_file, os.path.join(script_path, "tmp", "config.json"))
disabled_extensions = set(settings.get("disabled_extensions", []) + always_disabled_extensions)
disable_all_extensions = settings.get("disable_all_extensions", "none")
if disable_all_extensions != "none" or args.disable_extra_extensions or args.disable_all_extensions or not os.path.isdir(extensions_dir):
return []
return [x for x in os.listdir(extensions_dir) if x not in disabled_extensions]
def list_extensions_builtin(settings_file):
settings = {}
try:
with open(settings_file, "r", encoding="utf8") as file:
settings = json.load(file)
except FileNotFoundError:
pass
except Exception:
errors.report(f'\nCould not load settings\nThe config file "{settings_file}" is likely corrupted\nIt has been moved to the "tmp/config.json"\nReverting config to default\n\n', exc_info=True)
os.replace(settings_file, os.path.join(script_path, "tmp", "config.json"))
disabled_extensions = set(settings.get("disabled_extensions", []))
disable_all_extensions = settings.get("disable_all_extensions", "none")
if disable_all_extensions != "none" or args.disable_extra_extensions or args.disable_all_extensions or not os.path.isdir(extensions_builtin_dir):
return []
return [x for x in os.listdir(extensions_builtin_dir) if x not in disabled_extensions]
def run_extensions_installers(settings_file):
if not os.path.isdir(extensions_dir):
return
with startup_timer.subcategory("run extensions installers"):
for dirname_extension in list_extensions(settings_file):
logging.debug(f"Installing {dirname_extension}")
path = os.path.join(extensions_dir, dirname_extension)
if os.path.isdir(path):
run_extension_installer(path)
startup_timer.record(dirname_extension)
if not os.path.isdir(extensions_builtin_dir):
return
with startup_timer.subcategory("run extensions_builtin installers"):
for dirname_extension in list_extensions_builtin(settings_file):
logging.debug(f"Installing {dirname_extension}")
path = os.path.join(extensions_builtin_dir, dirname_extension)
if os.path.isdir(path):
run_extension_installer(path)
startup_timer.record(dirname_extension)
return
re_requirement = re.compile(r"\s*([-_a-zA-Z0-9]+)\s*(?:==\s*([-+_.a-zA-Z0-9]+))?\s*")
def requirements_met(requirements_file):
"""
Does a simple parse of a requirements.txt file to determine if all rerqirements in it
are already installed. Returns True if so, False if not installed or parsing fails.
"""
import importlib.metadata
import packaging.version
with open(requirements_file, "r", encoding="utf8") as file:
for line in file:
if line.strip() == "":
continue
m = re.match(re_requirement, line)
if m is None:
return False
package = m.group(1).strip()
version_required = (m.group(2) or "").strip()
if version_required == "":
continue
try:
version_installed = importlib.metadata.version(package)
except Exception:
return False
if packaging.version.parse(version_required) != packaging.version.parse(version_installed):
return False
return True
def prepare_environment():
torch_index_url = os.environ.get("TORCH_INDEX_URL", "https://download.pytorch.org/whl/cu128")
torch_command = os.environ.get("TORCH_COMMAND", f"pip install torch==2.7.0+cu128 torchvision==0.22.0+cu128 --extra-index-url {torch_index_url}")
xformers_package = os.environ.get("XFORMERS_PACKAGE", f"xformers==0.0.30 --extra-index-url {torch_index_url}")
sage_package = os.environ.get("SAGE_PACKAGE", "sageattention==1.0.6")
clip_package = os.environ.get("CLIP_PACKAGE", "https://github.com/openai/CLIP/archive/d50d76daa670286dd6cacf3bcd80b5e4823fc8e1.zip")
packaging_package = os.environ.get("PACKAGING_PACKAGE", "packaging==24.2")
gradio_package = os.environ.get("GRADIO_PACKAGE", "gradio==3.43.2")
insightface_package = os.environ.get("INSIGHT_PACKAGE", "insightface==0.7.3")
requirements_file = os.environ.get("REQS_FILE", "requirements.txt")
try:
# the existence of this file is a signal to webui.sh/bat that webui needs to be restarted when it stops execution
os.remove(os.path.join(script_path, "tmp", "restart"))
os.environ.setdefault("SD_WEBUI_RESTARTING", "1")
except OSError:
pass
if not args.skip_python_version_check:
check_python_version()
startup_timer.record("checks")
tag = git_tag()
print(f"Python {sys.version}")
print(f"Version: {tag}")
if not is_installed("torch") or not is_installed("torchvision") or args.reinstall_torch:
run(f'"{python}" -m {torch_command}', "Installing torch and torchvision", "Couldn't install torch", live=True)
startup_timer.record("install torch")
if not args.skip_torch_cuda_test:
if not check_run_python("import torch; assert torch.cuda.is_available()"):
raise RuntimeError("PyTorch is not able to access CUDA")
startup_timer.record("torch GPU test")
if not is_installed("clip"):
run_pip(f"install {clip_package}", "clip")
startup_timer.record("install clip")
if args.xformers and (not is_installed("xformers") or args.reinstall_xformers):
run_pip(f"install -U --no-deps {xformers_package}", "xformers")
startup_timer.record("install xformers")
if args.sage and not is_installed("sageattention"):
run_pip(f"install -U --no-deps {sage_package}", "sageattention")
startup_timer.record("install sageattention")
if args.ngrok and not is_installed("ngrok"):
run_pip("install ngrok", "ngrok")
startup_timer.record("install ngrok")
if not os.path.isfile(requirements_file):
requirements_file = os.path.join(script_path, requirements_file)
if not is_installed("packaging"):
run_pip(f"install {packaging_package}", "packaging")
if not is_installed("gradio"):
run_pip(f"install {gradio_package}", "gradio")
if not requirements_met(requirements_file):
run_pip(f'install -r "{requirements_file}"', "requirements")
startup_timer.record("install requirements")
if not is_installed("insightface"):
run(
f'"{python}" -m pip install {insightface_package} --no-deps',
desc="Installing insightface",
errdesc="Failed to install insightface; please manually install C++ build tools first",
live=False,
)
if not args.skip_install:
run_extensions_installers(settings_file=args.ui_settings_file)
if args.update_all_extensions:
git_pull_recursive(extensions_dir)
startup_timer.record("update extensions")
if not requirements_met(requirements_file):
run_pip(f'install -r "{requirements_file}"', "requirements")
startup_timer.record("enforce requirements")
if "--exit" in sys.argv:
print("Exiting because of --exit argument")
exit(0)
def configure_forge_reference_checkout(model_ref: Path):
"""Set model paths based on an existing A1111 setup"""
@dataclass
class ModelRef:
flag: str
relative_path: str
refs = [
ModelRef("--embeddings-dir", "embeddings"),
ModelRef("--ckpt-dir", "models/Stable-diffusion"),
ModelRef("--lora-dir", "models/Lora"),
ModelRef("--vae-dir", "models/VAE"),
ModelRef("--controlnet-dir", "models/ControlNet"),
ModelRef("--controlnet-preprocessor-models-dir", "models/ControlNetPreprocessor"),
]
for ref in refs:
target_path = model_ref.joinpath(ref.relative_path)
if not target_path.exists():
print(f'Path "{target_path}" does not exist. Skipping "{ref.flag}" flag')
continue
if ref.flag not in sys.argv:
sys.argv.extend([ref.flag, str(target_path)])
def start():
print(f"Launching {'API server' if '--nowebui' in sys.argv else 'Web UI'} with arguments: {' '.join(sys.argv[1:])}")
import webui
if "--nowebui" in sys.argv:
webui.api_only()
else:
webui.webui()
from modules_forge import main_thread
main_thread.loop()
return
def dump_sysinfo():
import datetime
from modules import sysinfo
text = sysinfo.get()
filename = f"sysinfo-{datetime.datetime.utcnow().strftime('%Y-%m-%d-%H-%M')}.json"
with open(filename, "w", encoding="utf8") as file:
file.write(text)
return filename
|