Upload 124 files
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +1 -0
- modules/Roboto-Regular.ttf +3 -0
- modules/api/api.py +835 -0
- modules/api/models.py +325 -0
- modules/cache.py +80 -0
- modules/call_queue.py +133 -0
- modules/cmd_args.py +94 -0
- modules/codeformer_model.py +55 -0
- modules/config_states.py +198 -0
- modules/devices.py +101 -0
- modules/errors.py +140 -0
- modules/esrgan_model.py +75 -0
- modules/extensions.py +311 -0
- modules/extra_networks.py +207 -0
- modules/extras.py +317 -0
- modules/face_restoration.py +19 -0
- modules/face_restoration_utils.py +182 -0
- modules/fifo_lock.py +37 -0
- modules/gfpgan_model.py +61 -0
- modules/gitpython_hack.py +42 -0
- modules/gradio_extensions.py +178 -0
- modules/hashes.py +92 -0
- modules/images.py +972 -0
- modules/img2img.py +287 -0
- modules/infotext_utils.py +626 -0
- modules/infotext_versions.py +46 -0
- modules/initialize.py +162 -0
- modules/initialize_util.py +202 -0
- modules/launch_utils.py +529 -0
- modules/localization.py +37 -0
- modules/logging_config.py +58 -0
- modules/masking.py +96 -0
- modules/memmon.py +92 -0
- modules/modelloader.py +125 -0
- modules/ngrok.py +30 -0
- modules/options.py +343 -0
- modules/patches.py +64 -0
- modules/paths.py +8 -0
- modules/paths_internal.py +33 -0
- modules/postprocessing.py +141 -0
- modules/processing.py +1900 -0
- modules/processing_scripts/comments.py +68 -0
- modules/processing_scripts/mahiro.py +62 -0
- modules/processing_scripts/refiner.py +55 -0
- modules/processing_scripts/rescale_cfg.py +78 -0
- modules/processing_scripts/sampler.py +39 -0
- modules/processing_scripts/seed.py +100 -0
- modules/profiling.py +45 -0
- modules/progress.py +157 -0
- modules/prompt_parser.py +490 -0
.gitattributes
CHANGED
|
@@ -57,3 +57,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 57 |
# Video files - compressed
|
| 58 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 59 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 57 |
# Video files - compressed
|
| 58 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 59 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
| 60 |
+
modules/Roboto-Regular.ttf filter=lfs diff=lfs merge=lfs -text
|
modules/Roboto-Regular.ttf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:797e35f7f5d6020a5c6ea13b42ecd668bcfb3bbc4baa0e74773527e5b6cb3174
|
| 3 |
+
size 305608
|
modules/api/api.py
ADDED
|
@@ -0,0 +1,835 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
import datetime
|
| 3 |
+
import io
|
| 4 |
+
import ipaddress
|
| 5 |
+
import os
|
| 6 |
+
import time
|
| 7 |
+
from contextlib import closing
|
| 8 |
+
from io import BytesIO
|
| 9 |
+
from secrets import compare_digest
|
| 10 |
+
from threading import Lock
|
| 11 |
+
from typing import Any, Union, get_args, get_origin
|
| 12 |
+
|
| 13 |
+
import gradio as gr
|
| 14 |
+
import piexif
|
| 15 |
+
import piexif.helper
|
| 16 |
+
import requests
|
| 17 |
+
import uvicorn
|
| 18 |
+
from fastapi import APIRouter, Depends, FastAPI, Request, Response
|
| 19 |
+
from fastapi.encoders import jsonable_encoder
|
| 20 |
+
from fastapi.exceptions import HTTPException
|
| 21 |
+
from fastapi.responses import JSONResponse
|
| 22 |
+
from fastapi.security import HTTPBasic, HTTPBasicCredentials
|
| 23 |
+
from PIL import PngImagePlugin
|
| 24 |
+
|
| 25 |
+
import modules.shared as shared
|
| 26 |
+
import modules.textual_inversion.textual_inversion
|
| 27 |
+
from modules import errors, images, infotext_utils, postprocessing, restart, script_callbacks, scripts, sd_models, sd_samplers, sd_schedulers, shared_items, ui
|
| 28 |
+
from modules.api import models
|
| 29 |
+
from modules.processing import StableDiffusionProcessingImg2Img, StableDiffusionProcessingTxt2Img, process_extra_images, process_images
|
| 30 |
+
from modules.progress import add_task_to_queue, create_task_id, current_task, finish_task, start_task
|
| 31 |
+
from modules.shared import cmd_opts, opts
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def script_name_to_index(name, scripts):
|
| 35 |
+
try:
|
| 36 |
+
return [script.title().lower() for script in scripts].index(name.lower())
|
| 37 |
+
except Exception as e:
|
| 38 |
+
raise HTTPException(status_code=422, detail=f"Script '{name}' not found") from e
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def validate_sampler_name(name):
|
| 42 |
+
config = sd_samplers.all_samplers_map.get(name, None)
|
| 43 |
+
if config is None:
|
| 44 |
+
raise HTTPException(status_code=400, detail="Sampler not found")
|
| 45 |
+
|
| 46 |
+
return name
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def setUpscalers(req: dict):
|
| 50 |
+
reqDict = vars(req)
|
| 51 |
+
reqDict["extras_upscaler_1"] = reqDict.pop("upscaler_1", None)
|
| 52 |
+
reqDict["extras_upscaler_2"] = reqDict.pop("upscaler_2", None)
|
| 53 |
+
return reqDict
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def verify_url(url):
|
| 57 |
+
"""Returns True if the url refers to a global resource."""
|
| 58 |
+
|
| 59 |
+
import socket
|
| 60 |
+
from urllib.parse import urlparse
|
| 61 |
+
|
| 62 |
+
try:
|
| 63 |
+
parsed_url = urlparse(url)
|
| 64 |
+
domain_name = parsed_url.netloc
|
| 65 |
+
host = socket.gethostbyname_ex(domain_name)
|
| 66 |
+
for ip in host[2]:
|
| 67 |
+
ip_addr = ipaddress.ip_address(ip)
|
| 68 |
+
if not ip_addr.is_global:
|
| 69 |
+
return False
|
| 70 |
+
except Exception:
|
| 71 |
+
return False
|
| 72 |
+
|
| 73 |
+
return True
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def decode_base64_to_image(encoding):
|
| 77 |
+
if encoding.startswith("http://") or encoding.startswith("https://"):
|
| 78 |
+
if not opts.api_enable_requests:
|
| 79 |
+
raise HTTPException(status_code=500, detail="Requests not allowed")
|
| 80 |
+
|
| 81 |
+
if opts.api_forbid_local_requests and not verify_url(encoding):
|
| 82 |
+
raise HTTPException(status_code=500, detail="Request to local resource not allowed")
|
| 83 |
+
|
| 84 |
+
headers = {"user-agent": opts.api_useragent} if opts.api_useragent else {}
|
| 85 |
+
response = requests.get(encoding, timeout=30, headers=headers)
|
| 86 |
+
try:
|
| 87 |
+
image = images.read(BytesIO(response.content))
|
| 88 |
+
return image
|
| 89 |
+
except Exception as e:
|
| 90 |
+
raise HTTPException(status_code=500, detail="Invalid image url") from e
|
| 91 |
+
|
| 92 |
+
if encoding.startswith("data:image/"):
|
| 93 |
+
encoding = encoding.split(";")[1].split(",")[1]
|
| 94 |
+
try:
|
| 95 |
+
image = images.read(BytesIO(base64.b64decode(encoding)))
|
| 96 |
+
return image
|
| 97 |
+
except Exception as e:
|
| 98 |
+
raise HTTPException(status_code=500, detail="Invalid encoded image") from e
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def encode_pil_to_base64(image):
|
| 102 |
+
with io.BytesIO() as output_bytes:
|
| 103 |
+
if isinstance(image, str):
|
| 104 |
+
return image
|
| 105 |
+
if opts.samples_format.lower() == "png":
|
| 106 |
+
use_metadata = False
|
| 107 |
+
metadata = PngImagePlugin.PngInfo()
|
| 108 |
+
for key, value in image.info.items():
|
| 109 |
+
if isinstance(key, str) and isinstance(value, str):
|
| 110 |
+
metadata.add_text(key, value)
|
| 111 |
+
use_metadata = True
|
| 112 |
+
image.save(output_bytes, format="PNG", pnginfo=(metadata if use_metadata else None), quality=opts.jpeg_quality)
|
| 113 |
+
|
| 114 |
+
elif opts.samples_format.lower() in ("jpg", "jpeg", "webp"):
|
| 115 |
+
if image.mode in ("RGBA", "P"):
|
| 116 |
+
image = image.convert("RGB")
|
| 117 |
+
parameters = image.info.get("parameters", None)
|
| 118 |
+
exif_bytes = piexif.dump({"Exif": {piexif.ExifIFD.UserComment: piexif.helper.UserComment.dump(parameters or "", encoding="unicode")}})
|
| 119 |
+
if opts.samples_format.lower() in ("jpg", "jpeg"):
|
| 120 |
+
image.save(output_bytes, format="JPEG", exif=exif_bytes, quality=opts.jpeg_quality)
|
| 121 |
+
else:
|
| 122 |
+
image.save(output_bytes, format="WEBP", exif=exif_bytes, quality=opts.jpeg_quality, lossless=opts.webp_lossless)
|
| 123 |
+
|
| 124 |
+
else:
|
| 125 |
+
raise HTTPException(status_code=500, detail="Invalid image format")
|
| 126 |
+
|
| 127 |
+
bytes_data = output_bytes.getvalue()
|
| 128 |
+
|
| 129 |
+
return base64.b64encode(bytes_data)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def api_middleware(app: FastAPI):
|
| 133 |
+
rich_available = False
|
| 134 |
+
try:
|
| 135 |
+
if os.environ.get("WEBUI_RICH_EXCEPTIONS", None) is not None:
|
| 136 |
+
import anyio # importing just so it can be placed on silent list
|
| 137 |
+
import starlette # importing just so it can be placed on silent list
|
| 138 |
+
from rich.console import Console
|
| 139 |
+
|
| 140 |
+
console = Console()
|
| 141 |
+
rich_available = True
|
| 142 |
+
except Exception:
|
| 143 |
+
pass
|
| 144 |
+
|
| 145 |
+
@app.middleware("http")
|
| 146 |
+
async def log_and_time(req: Request, call_next):
|
| 147 |
+
ts = time.time()
|
| 148 |
+
res: Response = await call_next(req)
|
| 149 |
+
duration = str(round(time.time() - ts, 4))
|
| 150 |
+
res.headers["X-Process-Time"] = duration
|
| 151 |
+
endpoint = req.scope.get("path", "err")
|
| 152 |
+
if shared.cmd_opts.api_log and endpoint.startswith("/sdapi"):
|
| 153 |
+
print(
|
| 154 |
+
"API {t} {code} {prot}/{ver} {method} {endpoint} {cli} {duration}".format(
|
| 155 |
+
t=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"),
|
| 156 |
+
code=res.status_code,
|
| 157 |
+
ver=req.scope.get("http_version", "0.0"),
|
| 158 |
+
cli=req.scope.get("client", ("0:0.0.0", 0))[0],
|
| 159 |
+
prot=req.scope.get("scheme", "err"),
|
| 160 |
+
method=req.scope.get("method", "err"),
|
| 161 |
+
endpoint=endpoint,
|
| 162 |
+
duration=duration,
|
| 163 |
+
)
|
| 164 |
+
)
|
| 165 |
+
return res
|
| 166 |
+
|
| 167 |
+
def handle_exception(request: Request, e: Exception):
|
| 168 |
+
err = {
|
| 169 |
+
"error": type(e).__name__,
|
| 170 |
+
"detail": vars(e).get("detail", ""),
|
| 171 |
+
"body": vars(e).get("body", ""),
|
| 172 |
+
"errors": str(e),
|
| 173 |
+
}
|
| 174 |
+
if not isinstance(e, HTTPException): # do not print backtrace on known httpexceptions
|
| 175 |
+
message = f"API error: {request.method}: {request.url} {err}"
|
| 176 |
+
if rich_available:
|
| 177 |
+
print(message)
|
| 178 |
+
console.print_exception(show_locals=True, max_frames=2, extra_lines=1, suppress=[anyio, starlette], word_wrap=False, width=min([console.width, 200]))
|
| 179 |
+
else:
|
| 180 |
+
errors.report(message, exc_info=True)
|
| 181 |
+
return JSONResponse(status_code=vars(e).get("status_code", 500), content=jsonable_encoder(err))
|
| 182 |
+
|
| 183 |
+
@app.middleware("http")
|
| 184 |
+
async def exception_handling(request: Request, call_next):
|
| 185 |
+
try:
|
| 186 |
+
return await call_next(request)
|
| 187 |
+
except Exception as e:
|
| 188 |
+
return handle_exception(request, e)
|
| 189 |
+
|
| 190 |
+
@app.exception_handler(Exception)
|
| 191 |
+
async def fastapi_exception_handler(request: Request, e: Exception):
|
| 192 |
+
return handle_exception(request, e)
|
| 193 |
+
|
| 194 |
+
@app.exception_handler(HTTPException)
|
| 195 |
+
async def http_exception_handler(request: Request, e: HTTPException):
|
| 196 |
+
return handle_exception(request, e)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
class Api:
|
| 200 |
+
def __init__(self, app: FastAPI, queue_lock: Lock):
|
| 201 |
+
if shared.cmd_opts.api_auth:
|
| 202 |
+
self.credentials = {}
|
| 203 |
+
for auth in shared.cmd_opts.api_auth.split(","):
|
| 204 |
+
user, password = auth.split(":")
|
| 205 |
+
self.credentials[user] = password
|
| 206 |
+
|
| 207 |
+
self.router = APIRouter()
|
| 208 |
+
self.app = app
|
| 209 |
+
self.queue_lock = queue_lock
|
| 210 |
+
# api_middleware(self.app) # FIXME: (legacy) this will have to be fixed
|
| 211 |
+
self.add_api_route("/sdapi/v1/txt2img", self.text2imgapi, methods=["POST"], response_model=models.TextToImageResponse)
|
| 212 |
+
self.add_api_route("/sdapi/v1/img2img", self.img2imgapi, methods=["POST"], response_model=models.ImageToImageResponse)
|
| 213 |
+
self.add_api_route("/sdapi/v1/extra-single-image", self.extras_single_image_api, methods=["POST"], response_model=models.ExtrasSingleImageResponse)
|
| 214 |
+
self.add_api_route("/sdapi/v1/extra-batch-images", self.extras_batch_images_api, methods=["POST"], response_model=models.ExtrasBatchImagesResponse)
|
| 215 |
+
self.add_api_route("/sdapi/v1/png-info", self.pnginfoapi, methods=["POST"], response_model=models.PNGInfoResponse)
|
| 216 |
+
self.add_api_route("/sdapi/v1/progress", self.progressapi, methods=["GET"], response_model=models.ProgressResponse)
|
| 217 |
+
self.add_api_route("/sdapi/v1/interrupt", self.interruptapi, methods=["POST"])
|
| 218 |
+
self.add_api_route("/sdapi/v1/skip", self.skip, methods=["POST"])
|
| 219 |
+
self.add_api_route("/sdapi/v1/options", self.get_config, methods=["GET"], response_model=models.OptionsModel)
|
| 220 |
+
self.add_api_route("/sdapi/v1/options", self.set_config, methods=["POST"])
|
| 221 |
+
self.add_api_route("/sdapi/v1/cmd-flags", self.get_cmd_flags, methods=["GET"], response_model=models.FlagsModel)
|
| 222 |
+
self.add_api_route("/sdapi/v1/samplers", self.get_samplers, methods=["GET"], response_model=list[models.SamplerItem])
|
| 223 |
+
self.add_api_route("/sdapi/v1/schedulers", self.get_schedulers, methods=["GET"], response_model=list[models.SchedulerItem])
|
| 224 |
+
self.add_api_route("/sdapi/v1/upscalers", self.get_upscalers, methods=["GET"], response_model=list[models.UpscalerItem])
|
| 225 |
+
self.add_api_route("/sdapi/v1/latent-upscale-modes", self.get_latent_upscale_modes, methods=["GET"], response_model=list[models.LatentUpscalerModeItem])
|
| 226 |
+
self.add_api_route("/sdapi/v1/sd-models", self.get_sd_models, methods=["GET"], response_model=list[models.SDModelItem])
|
| 227 |
+
self.add_api_route("/sdapi/v1/sd-modules", self.get_sd_vaes_and_text_encoders, methods=["GET"], response_model=list[models.SDModuleItem])
|
| 228 |
+
self.add_api_route("/sdapi/v1/face-restorers", self.get_face_restorers, methods=["GET"], response_model=list[models.FaceRestorerItem])
|
| 229 |
+
self.add_api_route("/sdapi/v1/prompt-styles", self.get_prompt_styles, methods=["GET"], response_model=list[models.PromptStyleItem])
|
| 230 |
+
self.add_api_route("/sdapi/v1/embeddings", self.get_embeddings, methods=["GET"], response_model=models.EmbeddingsResponse)
|
| 231 |
+
self.add_api_route("/sdapi/v1/refresh-embeddings", self.refresh_embeddings, methods=["POST"])
|
| 232 |
+
self.add_api_route("/sdapi/v1/refresh-checkpoints", self.refresh_checkpoints, methods=["POST"])
|
| 233 |
+
self.add_api_route("/sdapi/v1/refresh-vae", self.refresh_vae, methods=["POST"])
|
| 234 |
+
self.add_api_route("/sdapi/v1/memory", self.get_memory, methods=["GET"], response_model=models.MemoryResponse)
|
| 235 |
+
self.add_api_route("/sdapi/v1/unload-checkpoint", self.unloadapi, methods=["POST"])
|
| 236 |
+
self.add_api_route("/sdapi/v1/scripts", self.get_scripts_list, methods=["GET"], response_model=models.ScriptsList)
|
| 237 |
+
self.add_api_route("/sdapi/v1/script-info", self.get_script_info, methods=["GET"], response_model=list[models.ScriptInfo])
|
| 238 |
+
self.add_api_route("/sdapi/v1/extensions", self.get_extensions_list, methods=["GET"], response_model=list[models.ExtensionItem])
|
| 239 |
+
|
| 240 |
+
if shared.cmd_opts.api_server_stop:
|
| 241 |
+
self.add_api_route("/sdapi/v1/server-kill", self.kill_webui, methods=["POST"])
|
| 242 |
+
self.add_api_route("/sdapi/v1/server-restart", self.restart_webui, methods=["POST"])
|
| 243 |
+
self.add_api_route("/sdapi/v1/server-stop", self.stop_webui, methods=["POST"])
|
| 244 |
+
|
| 245 |
+
self.default_script_arg_txt2img = []
|
| 246 |
+
self.default_script_arg_img2img = []
|
| 247 |
+
|
| 248 |
+
txt2img_script_runner = scripts.scripts_txt2img
|
| 249 |
+
img2img_script_runner = scripts.scripts_img2img
|
| 250 |
+
|
| 251 |
+
if not txt2img_script_runner.scripts or not img2img_script_runner.scripts:
|
| 252 |
+
ui.create_ui()
|
| 253 |
+
|
| 254 |
+
if not txt2img_script_runner.scripts:
|
| 255 |
+
txt2img_script_runner.initialize_scripts(False)
|
| 256 |
+
if not self.default_script_arg_txt2img:
|
| 257 |
+
self.default_script_arg_txt2img = self.init_default_script_args(txt2img_script_runner)
|
| 258 |
+
|
| 259 |
+
if not img2img_script_runner.scripts:
|
| 260 |
+
img2img_script_runner.initialize_scripts(True)
|
| 261 |
+
if not self.default_script_arg_img2img:
|
| 262 |
+
self.default_script_arg_img2img = self.init_default_script_args(img2img_script_runner)
|
| 263 |
+
|
| 264 |
+
self.embedding_db = modules.textual_inversion.textual_inversion.EmbeddingDatabase()
|
| 265 |
+
self.embedding_db.add_embedding_dir(cmd_opts.embeddings_dir)
|
| 266 |
+
self.embedding_db.load_textual_inversion_embeddings(force_reload=True, sync_with_sd_model=False)
|
| 267 |
+
|
| 268 |
+
def add_api_route(self, path: str, endpoint, **kwargs):
|
| 269 |
+
if shared.cmd_opts.api_auth:
|
| 270 |
+
return self.app.add_api_route(path, endpoint, dependencies=[Depends(self.auth)], **kwargs)
|
| 271 |
+
return self.app.add_api_route(path, endpoint, **kwargs)
|
| 272 |
+
|
| 273 |
+
def auth(self, credentials: HTTPBasicCredentials = Depends(HTTPBasic())):
|
| 274 |
+
if credentials.username in self.credentials:
|
| 275 |
+
if compare_digest(credentials.password, self.credentials[credentials.username]):
|
| 276 |
+
return True
|
| 277 |
+
|
| 278 |
+
raise HTTPException(status_code=401, detail="Incorrect username or password", headers={"WWW-Authenticate": "Basic"})
|
| 279 |
+
|
| 280 |
+
def get_selectable_script(self, script_name, script_runner):
|
| 281 |
+
if script_name is None or script_name == "":
|
| 282 |
+
return None, None
|
| 283 |
+
|
| 284 |
+
script_idx = script_name_to_index(script_name, script_runner.selectable_scripts)
|
| 285 |
+
script = script_runner.selectable_scripts[script_idx]
|
| 286 |
+
return script, script_idx
|
| 287 |
+
|
| 288 |
+
def get_scripts_list(self):
|
| 289 |
+
t2ilist = [script.name for script in scripts.scripts_txt2img.scripts if script.name is not None]
|
| 290 |
+
i2ilist = [script.name for script in scripts.scripts_img2img.scripts if script.name is not None]
|
| 291 |
+
|
| 292 |
+
return models.ScriptsList(txt2img=t2ilist, img2img=i2ilist)
|
| 293 |
+
|
| 294 |
+
def get_script_info(self):
|
| 295 |
+
res = []
|
| 296 |
+
|
| 297 |
+
for script_list in [scripts.scripts_txt2img.scripts, scripts.scripts_img2img.scripts]:
|
| 298 |
+
res += [script.api_info for script in script_list if script.api_info is not None]
|
| 299 |
+
|
| 300 |
+
return res
|
| 301 |
+
|
| 302 |
+
def get_script(self, script_name, script_runner):
|
| 303 |
+
if script_name is None or script_name == "":
|
| 304 |
+
return None, None
|
| 305 |
+
|
| 306 |
+
script_idx = script_name_to_index(script_name, script_runner.scripts)
|
| 307 |
+
return script_runner.scripts[script_idx]
|
| 308 |
+
|
| 309 |
+
def init_default_script_args(self, script_runner):
|
| 310 |
+
# find max idx from the scripts in runner and generate a none array to init script_args
|
| 311 |
+
last_arg_index = 1
|
| 312 |
+
for script in script_runner.scripts:
|
| 313 |
+
if last_arg_index < script.args_to:
|
| 314 |
+
last_arg_index = script.args_to
|
| 315 |
+
# None everywhere except position 0 to initialize script args
|
| 316 |
+
script_args = [None] * last_arg_index
|
| 317 |
+
script_args[0] = 0
|
| 318 |
+
|
| 319 |
+
# get default values
|
| 320 |
+
with gr.Blocks(): # will throw errors calling ui function without this
|
| 321 |
+
for script in script_runner.scripts:
|
| 322 |
+
if script.ui(script.is_img2img):
|
| 323 |
+
ui_default_values = []
|
| 324 |
+
for elem in script.ui(script.is_img2img):
|
| 325 |
+
ui_default_values.append(elem.value)
|
| 326 |
+
script_args[script.args_from : script.args_to] = ui_default_values
|
| 327 |
+
return script_args
|
| 328 |
+
|
| 329 |
+
def init_script_args(self, request, default_script_args, selectable_scripts, selectable_idx, script_runner, *, input_script_args=None):
|
| 330 |
+
script_args = default_script_args.copy()
|
| 331 |
+
|
| 332 |
+
if input_script_args is not None:
|
| 333 |
+
for index, value in input_script_args.items():
|
| 334 |
+
script_args[index] = value
|
| 335 |
+
|
| 336 |
+
# position 0 in script_arg is the idx+1 of the selectable script that is going to be run when using scripts.scripts_*2img.run()
|
| 337 |
+
if selectable_scripts:
|
| 338 |
+
script_args[selectable_scripts.args_from : selectable_scripts.args_to] = request.script_args
|
| 339 |
+
script_args[0] = selectable_idx + 1
|
| 340 |
+
|
| 341 |
+
# Now check for always on scripts
|
| 342 |
+
if request.alwayson_scripts:
|
| 343 |
+
for alwayson_script_name in request.alwayson_scripts.keys():
|
| 344 |
+
alwayson_script = self.get_script(alwayson_script_name, script_runner)
|
| 345 |
+
if alwayson_script is None:
|
| 346 |
+
raise HTTPException(status_code=422, detail=f"always on script {alwayson_script_name} not found")
|
| 347 |
+
# Selectable script in always on script param check
|
| 348 |
+
if alwayson_script.alwayson is False:
|
| 349 |
+
raise HTTPException(status_code=422, detail="Cannot have a selectable script in the always on scripts params")
|
| 350 |
+
# always on script with no arg should always run so you don't really need to add them to the requests
|
| 351 |
+
if "args" in request.alwayson_scripts[alwayson_script_name]:
|
| 352 |
+
# min between arg length in scriptrunner and arg length in the request
|
| 353 |
+
for idx in range(0, min((alwayson_script.args_to - alwayson_script.args_from), len(request.alwayson_scripts[alwayson_script_name]["args"]))):
|
| 354 |
+
script_args[alwayson_script.args_from + idx] = request.alwayson_scripts[alwayson_script_name]["args"][idx]
|
| 355 |
+
return script_args
|
| 356 |
+
|
| 357 |
+
def apply_infotext(self, request, tabname, *, script_runner=None, mentioned_script_args=None):
|
| 358 |
+
"""Processes `infotext` field from the `request`, and sets other fields of the `request` according to what's in infotext.
|
| 359 |
+
|
| 360 |
+
If request already has a field set, and that field is encountered in infotext too, the value from infotext is ignored.
|
| 361 |
+
|
| 362 |
+
Additionally, fills `mentioned_script_args` dict with index: value pairs for script arguments read from infotext.
|
| 363 |
+
"""
|
| 364 |
+
|
| 365 |
+
if not request.infotext:
|
| 366 |
+
return {}
|
| 367 |
+
|
| 368 |
+
possible_fields = infotext_utils.paste_fields[tabname]["fields"]
|
| 369 |
+
set_fields = request.model_dump(exclude_unset=True) if hasattr(request, "request") else request.dict(exclude_unset=True) # pydantic v1/v2 have different names for this
|
| 370 |
+
params = infotext_utils.parse_generation_parameters(request.infotext)
|
| 371 |
+
|
| 372 |
+
def get_base_type(annotation):
|
| 373 |
+
origin = get_origin(annotation)
|
| 374 |
+
|
| 375 |
+
if origin is Union: # represents Optional
|
| 376 |
+
args = get_args(annotation) # filter out NoneType
|
| 377 |
+
non_none_args = [arg for arg in args if arg is not type(None)]
|
| 378 |
+
if len(non_none_args) == 1: # annotation was Optional[X]
|
| 379 |
+
return non_none_args[0]
|
| 380 |
+
|
| 381 |
+
return annotation
|
| 382 |
+
|
| 383 |
+
def get_field_value(field, params):
|
| 384 |
+
value = field.function(params) if field.function else params.get(field.label)
|
| 385 |
+
if value is None:
|
| 386 |
+
return None
|
| 387 |
+
|
| 388 |
+
if field.api in request.__fields__:
|
| 389 |
+
target_type = get_base_type(request.__fields__[field.api].annotation) # extract type from Optional[X]
|
| 390 |
+
else:
|
| 391 |
+
target_type = type(field.component.value)
|
| 392 |
+
|
| 393 |
+
if target_type == type(None):
|
| 394 |
+
return None
|
| 395 |
+
|
| 396 |
+
if isinstance(value, dict) and value.get("__type__") == "generic_update": # this is a gradio.update rather than a value
|
| 397 |
+
value = value.get("value")
|
| 398 |
+
|
| 399 |
+
if value is not None and not isinstance(value, target_type):
|
| 400 |
+
value = target_type(value)
|
| 401 |
+
|
| 402 |
+
return value
|
| 403 |
+
|
| 404 |
+
for field in possible_fields:
|
| 405 |
+
if not field.api:
|
| 406 |
+
continue
|
| 407 |
+
|
| 408 |
+
if field.api in set_fields:
|
| 409 |
+
continue
|
| 410 |
+
|
| 411 |
+
value = get_field_value(field, params)
|
| 412 |
+
if value is not None:
|
| 413 |
+
setattr(request, field.api, value)
|
| 414 |
+
|
| 415 |
+
if request.override_settings is None:
|
| 416 |
+
request.override_settings = {}
|
| 417 |
+
|
| 418 |
+
overridden_settings = infotext_utils.get_override_settings(params)
|
| 419 |
+
for _, setting_name, value in overridden_settings:
|
| 420 |
+
if setting_name not in request.override_settings:
|
| 421 |
+
request.override_settings[setting_name] = value
|
| 422 |
+
|
| 423 |
+
if script_runner is not None and mentioned_script_args is not None:
|
| 424 |
+
indexes = {v: i for i, v in enumerate(script_runner.inputs)}
|
| 425 |
+
script_fields = ((field, indexes[field.component]) for field in possible_fields if field.component in indexes)
|
| 426 |
+
|
| 427 |
+
for field, index in script_fields:
|
| 428 |
+
value = get_field_value(field, params)
|
| 429 |
+
|
| 430 |
+
if value is None:
|
| 431 |
+
continue
|
| 432 |
+
|
| 433 |
+
mentioned_script_args[index] = value
|
| 434 |
+
|
| 435 |
+
return params
|
| 436 |
+
|
| 437 |
+
def text2imgapi(self, txt2imgreq: models.StableDiffusionTxt2ImgProcessingAPI):
|
| 438 |
+
task_id = txt2imgreq.force_task_id or create_task_id("txt2img")
|
| 439 |
+
|
| 440 |
+
script_runner = scripts.scripts_txt2img
|
| 441 |
+
|
| 442 |
+
infotext_script_args = {}
|
| 443 |
+
self.apply_infotext(txt2imgreq, "txt2img", script_runner=script_runner, mentioned_script_args=infotext_script_args)
|
| 444 |
+
|
| 445 |
+
selectable_scripts, selectable_script_idx = self.get_selectable_script(txt2imgreq.script_name, script_runner)
|
| 446 |
+
sampler, scheduler = sd_samplers.get_sampler_and_scheduler(txt2imgreq.sampler_name or txt2imgreq.sampler_index, txt2imgreq.scheduler)
|
| 447 |
+
|
| 448 |
+
populate = txt2imgreq.copy(
|
| 449 |
+
update={ # Override __init__ params
|
| 450 |
+
"sampler_name": validate_sampler_name(sampler),
|
| 451 |
+
"do_not_save_samples": not txt2imgreq.save_images,
|
| 452 |
+
"do_not_save_grid": not txt2imgreq.save_images,
|
| 453 |
+
}
|
| 454 |
+
)
|
| 455 |
+
if populate.sampler_name:
|
| 456 |
+
populate.sampler_index = None # prevent a warning later on
|
| 457 |
+
|
| 458 |
+
if not populate.scheduler and scheduler != "Automatic":
|
| 459 |
+
populate.scheduler = scheduler
|
| 460 |
+
|
| 461 |
+
args = vars(populate)
|
| 462 |
+
args.pop("script_name", None)
|
| 463 |
+
args.pop("script_args", None) # will refeed them to the pipeline directly after initializing them
|
| 464 |
+
args.pop("alwayson_scripts", None)
|
| 465 |
+
args.pop("infotext", None)
|
| 466 |
+
|
| 467 |
+
script_args = self.init_script_args(txt2imgreq, self.default_script_arg_txt2img, selectable_scripts, selectable_script_idx, script_runner, input_script_args=infotext_script_args)
|
| 468 |
+
|
| 469 |
+
send_images = args.pop("send_images", True)
|
| 470 |
+
args.pop("save_images", None)
|
| 471 |
+
|
| 472 |
+
add_task_to_queue(task_id)
|
| 473 |
+
|
| 474 |
+
with self.queue_lock:
|
| 475 |
+
with closing(StableDiffusionProcessingTxt2Img(sd_model=shared.sd_model, **args)) as p:
|
| 476 |
+
p.is_api = True
|
| 477 |
+
p.scripts = script_runner
|
| 478 |
+
p.outpath_grids = opts.outdir_txt2img_grids
|
| 479 |
+
p.outpath_samples = opts.outdir_txt2img_samples
|
| 480 |
+
|
| 481 |
+
try:
|
| 482 |
+
shared.state.begin(job="scripts_txt2img")
|
| 483 |
+
start_task(task_id)
|
| 484 |
+
if selectable_scripts is not None:
|
| 485 |
+
p.script_args = script_args
|
| 486 |
+
processed = scripts.scripts_txt2img.run(p, *p.script_args) # Need to pass args as list here
|
| 487 |
+
else:
|
| 488 |
+
p.script_args = tuple(script_args) # Need to pass args as tuple here
|
| 489 |
+
processed = process_images(p)
|
| 490 |
+
process_extra_images(processed)
|
| 491 |
+
finish_task(task_id)
|
| 492 |
+
finally:
|
| 493 |
+
shared.state.end()
|
| 494 |
+
shared.total_tqdm.clear()
|
| 495 |
+
|
| 496 |
+
b64images = list(map(encode_pil_to_base64, processed.images + processed.extra_images)) if send_images else []
|
| 497 |
+
|
| 498 |
+
return models.TextToImageResponse(images=b64images, parameters=vars(txt2imgreq), info=processed.js())
|
| 499 |
+
|
| 500 |
+
def img2imgapi(self, img2imgreq: models.StableDiffusionImg2ImgProcessingAPI):
|
| 501 |
+
task_id = img2imgreq.force_task_id or create_task_id("img2img")
|
| 502 |
+
|
| 503 |
+
init_images = img2imgreq.init_images
|
| 504 |
+
if init_images is None:
|
| 505 |
+
raise HTTPException(status_code=404, detail="Init image not found")
|
| 506 |
+
|
| 507 |
+
mask = img2imgreq.mask
|
| 508 |
+
if mask:
|
| 509 |
+
mask = decode_base64_to_image(mask)
|
| 510 |
+
|
| 511 |
+
script_runner = scripts.scripts_img2img
|
| 512 |
+
|
| 513 |
+
infotext_script_args = {}
|
| 514 |
+
self.apply_infotext(img2imgreq, "img2img", script_runner=script_runner, mentioned_script_args=infotext_script_args)
|
| 515 |
+
|
| 516 |
+
selectable_scripts, selectable_script_idx = self.get_selectable_script(img2imgreq.script_name, script_runner)
|
| 517 |
+
sampler, scheduler = sd_samplers.get_sampler_and_scheduler(img2imgreq.sampler_name or img2imgreq.sampler_index, img2imgreq.scheduler)
|
| 518 |
+
|
| 519 |
+
populate = img2imgreq.copy(
|
| 520 |
+
update={ # Override __init__ params
|
| 521 |
+
"sampler_name": validate_sampler_name(sampler),
|
| 522 |
+
"do_not_save_samples": not img2imgreq.save_images,
|
| 523 |
+
"do_not_save_grid": not img2imgreq.save_images,
|
| 524 |
+
"mask": mask,
|
| 525 |
+
}
|
| 526 |
+
)
|
| 527 |
+
if populate.sampler_name:
|
| 528 |
+
populate.sampler_index = None # prevent a warning later on
|
| 529 |
+
|
| 530 |
+
if not populate.scheduler and scheduler != "Automatic":
|
| 531 |
+
populate.scheduler = scheduler
|
| 532 |
+
|
| 533 |
+
args = vars(populate)
|
| 534 |
+
args.pop("include_init_images", None) # this is meant to be done by "exclude": True in model, but it's for a reason that I cannot determine.
|
| 535 |
+
args.pop("script_name", None)
|
| 536 |
+
args.pop("script_args", None) # will refeed them to the pipeline directly after initializing them
|
| 537 |
+
args.pop("alwayson_scripts", None)
|
| 538 |
+
args.pop("infotext", None)
|
| 539 |
+
|
| 540 |
+
script_args = self.init_script_args(img2imgreq, self.default_script_arg_img2img, selectable_scripts, selectable_script_idx, script_runner, input_script_args=infotext_script_args)
|
| 541 |
+
|
| 542 |
+
send_images = args.pop("send_images", True)
|
| 543 |
+
args.pop("save_images", None)
|
| 544 |
+
|
| 545 |
+
add_task_to_queue(task_id)
|
| 546 |
+
|
| 547 |
+
with self.queue_lock:
|
| 548 |
+
with closing(StableDiffusionProcessingImg2Img(sd_model=shared.sd_model, **args)) as p:
|
| 549 |
+
p.init_images = [decode_base64_to_image(x) for x in init_images]
|
| 550 |
+
p.is_api = True
|
| 551 |
+
p.scripts = script_runner
|
| 552 |
+
p.outpath_grids = opts.outdir_img2img_grids
|
| 553 |
+
p.outpath_samples = opts.outdir_img2img_samples
|
| 554 |
+
|
| 555 |
+
try:
|
| 556 |
+
shared.state.begin(job="scripts_img2img")
|
| 557 |
+
start_task(task_id)
|
| 558 |
+
if selectable_scripts is not None:
|
| 559 |
+
p.script_args = script_args
|
| 560 |
+
processed = scripts.scripts_img2img.run(p, *p.script_args) # Need to pass args as list here
|
| 561 |
+
else:
|
| 562 |
+
p.script_args = tuple(script_args) # Need to pass args as tuple here
|
| 563 |
+
processed = process_images(p)
|
| 564 |
+
process_extra_images(processed)
|
| 565 |
+
finish_task(task_id)
|
| 566 |
+
finally:
|
| 567 |
+
shared.state.end()
|
| 568 |
+
shared.total_tqdm.clear()
|
| 569 |
+
|
| 570 |
+
b64images = list(map(encode_pil_to_base64, processed.images + processed.extra_images)) if send_images else []
|
| 571 |
+
|
| 572 |
+
if not img2imgreq.include_init_images:
|
| 573 |
+
img2imgreq.init_images = None
|
| 574 |
+
img2imgreq.mask = None
|
| 575 |
+
|
| 576 |
+
return models.ImageToImageResponse(images=b64images, parameters=vars(img2imgreq), info=processed.js())
|
| 577 |
+
|
| 578 |
+
def extras_single_image_api(self, req: models.ExtrasSingleImageRequest):
|
| 579 |
+
reqDict = setUpscalers(req)
|
| 580 |
+
|
| 581 |
+
reqDict["image"] = decode_base64_to_image(reqDict["image"])
|
| 582 |
+
|
| 583 |
+
with self.queue_lock:
|
| 584 |
+
result = postprocessing.run_extras(extras_mode=0, image_folder="", input_dir="", output_dir="", save_output=False, **reqDict)
|
| 585 |
+
|
| 586 |
+
return models.ExtrasSingleImageResponse(image=encode_pil_to_base64(result[0][0]), html_info=result[1])
|
| 587 |
+
|
| 588 |
+
def extras_batch_images_api(self, req: models.ExtrasBatchImagesRequest):
|
| 589 |
+
reqDict = setUpscalers(req)
|
| 590 |
+
|
| 591 |
+
image_list = reqDict.pop("imageList", [])
|
| 592 |
+
image_folder = [decode_base64_to_image(x.data) for x in image_list]
|
| 593 |
+
|
| 594 |
+
with self.queue_lock:
|
| 595 |
+
result = postprocessing.run_extras(extras_mode=1, image_folder=image_folder, image="", input_dir="", output_dir="", save_output=False, **reqDict)
|
| 596 |
+
|
| 597 |
+
return models.ExtrasBatchImagesResponse(images=list(map(encode_pil_to_base64, result[0])), html_info=result[1])
|
| 598 |
+
|
| 599 |
+
def pnginfoapi(self, req: models.PNGInfoRequest):
|
| 600 |
+
image = decode_base64_to_image(req.image.strip())
|
| 601 |
+
if image is None:
|
| 602 |
+
return models.PNGInfoResponse(info="")
|
| 603 |
+
|
| 604 |
+
geninfo, items = images.read_info_from_image(image)
|
| 605 |
+
if geninfo is None:
|
| 606 |
+
geninfo = ""
|
| 607 |
+
|
| 608 |
+
params = infotext_utils.parse_generation_parameters(geninfo)
|
| 609 |
+
script_callbacks.infotext_pasted_callback(geninfo, params)
|
| 610 |
+
|
| 611 |
+
return models.PNGInfoResponse(info=geninfo, items=items, parameters=params)
|
| 612 |
+
|
| 613 |
+
def progressapi(self, req: models.ProgressRequest = Depends()):
|
| 614 |
+
# copy from check_progress_call of ui.py
|
| 615 |
+
|
| 616 |
+
if shared.state.job_count == 0:
|
| 617 |
+
return models.ProgressResponse(progress=0, eta_relative=0, state=shared.state.dict(), textinfo=shared.state.textinfo)
|
| 618 |
+
|
| 619 |
+
# avoid dividing zero
|
| 620 |
+
progress = 0.01
|
| 621 |
+
|
| 622 |
+
if shared.state.job_count > 0:
|
| 623 |
+
progress += shared.state.job_no / shared.state.job_count
|
| 624 |
+
if shared.state.sampling_steps > 0:
|
| 625 |
+
progress += 1 / shared.state.job_count * shared.state.sampling_step / shared.state.sampling_steps
|
| 626 |
+
|
| 627 |
+
time_since_start = time.time() - shared.state.time_start
|
| 628 |
+
eta = time_since_start / progress
|
| 629 |
+
eta_relative = eta - time_since_start
|
| 630 |
+
|
| 631 |
+
progress = min(progress, 1)
|
| 632 |
+
|
| 633 |
+
shared.state.set_current_image()
|
| 634 |
+
|
| 635 |
+
current_image = None
|
| 636 |
+
if shared.state.current_image and not req.skip_current_image:
|
| 637 |
+
current_image = encode_pil_to_base64(shared.state.current_image)
|
| 638 |
+
|
| 639 |
+
return models.ProgressResponse(progress=progress, eta_relative=eta_relative, state=shared.state.dict(), current_image=current_image, textinfo=shared.state.textinfo, current_task=current_task)
|
| 640 |
+
|
| 641 |
+
def interruptapi(self):
|
| 642 |
+
shared.state.interrupt()
|
| 643 |
+
|
| 644 |
+
return {}
|
| 645 |
+
|
| 646 |
+
def unloadapi(self):
|
| 647 |
+
sd_models.unload_model_weights()
|
| 648 |
+
|
| 649 |
+
return {}
|
| 650 |
+
|
| 651 |
+
def skip(self):
|
| 652 |
+
shared.state.skip()
|
| 653 |
+
|
| 654 |
+
def get_config(self):
|
| 655 |
+
from modules.sysinfo import get_config
|
| 656 |
+
|
| 657 |
+
return get_config()
|
| 658 |
+
|
| 659 |
+
def set_config(self, req: dict[str, Any]):
|
| 660 |
+
from modules.sysinfo import set_config
|
| 661 |
+
|
| 662 |
+
set_config(req)
|
| 663 |
+
|
| 664 |
+
def get_cmd_flags(self):
|
| 665 |
+
return vars(shared.cmd_opts)
|
| 666 |
+
|
| 667 |
+
def get_samplers(self):
|
| 668 |
+
return [{"name": sampler[0], "aliases": sampler[2], "options": sampler[3]} for sampler in sd_samplers.all_samplers]
|
| 669 |
+
|
| 670 |
+
def get_schedulers(self):
|
| 671 |
+
return [
|
| 672 |
+
{
|
| 673 |
+
"name": scheduler.name,
|
| 674 |
+
"label": scheduler.label,
|
| 675 |
+
"aliases": scheduler.aliases,
|
| 676 |
+
"default_rho": scheduler.default_rho,
|
| 677 |
+
"need_inner_model": scheduler.need_inner_model,
|
| 678 |
+
}
|
| 679 |
+
for scheduler in sd_schedulers.schedulers
|
| 680 |
+
]
|
| 681 |
+
|
| 682 |
+
def get_upscalers(self):
|
| 683 |
+
return [
|
| 684 |
+
{
|
| 685 |
+
"name": upscaler.name,
|
| 686 |
+
"model_name": upscaler.scaler.model_name,
|
| 687 |
+
"model_path": upscaler.data_path,
|
| 688 |
+
"model_url": None,
|
| 689 |
+
"scale": upscaler.scale,
|
| 690 |
+
}
|
| 691 |
+
for upscaler in shared.sd_upscalers
|
| 692 |
+
]
|
| 693 |
+
|
| 694 |
+
def get_latent_upscale_modes(self):
|
| 695 |
+
return [
|
| 696 |
+
{
|
| 697 |
+
"name": upscale_mode,
|
| 698 |
+
}
|
| 699 |
+
for upscale_mode in [*(shared.latent_upscale_modes or {})]
|
| 700 |
+
]
|
| 701 |
+
|
| 702 |
+
def get_sd_models(self):
|
| 703 |
+
import modules.sd_models as sd_models
|
| 704 |
+
|
| 705 |
+
return [{"title": x.title, "model_name": x.model_name, "hash": x.shorthash, "sha256": x.sha256, "filename": x.filename, "config": getattr(x, "config", None)} for x in sd_models.checkpoints_list.values()]
|
| 706 |
+
|
| 707 |
+
def get_sd_vaes_and_text_encoders(self):
|
| 708 |
+
from modules_forge.main_entry import module_list
|
| 709 |
+
|
| 710 |
+
return [{"model_name": x, "filename": module_list[x]} for x in module_list.keys()]
|
| 711 |
+
|
| 712 |
+
def get_face_restorers(self):
|
| 713 |
+
return [{"name": x.name(), "cmd_dir": getattr(x, "cmd_dir", None)} for x in shared.face_restorers]
|
| 714 |
+
|
| 715 |
+
def get_prompt_styles(self):
|
| 716 |
+
styleList = []
|
| 717 |
+
for k in shared.prompt_styles.styles:
|
| 718 |
+
style = shared.prompt_styles.styles[k]
|
| 719 |
+
styleList.append({"name": style[0], "prompt": style[1], "negative_prompt": style[2]})
|
| 720 |
+
|
| 721 |
+
return styleList
|
| 722 |
+
|
| 723 |
+
def get_embeddings(self):
|
| 724 |
+
def convert_embedding(embedding):
|
| 725 |
+
return {
|
| 726 |
+
"step": embedding.step,
|
| 727 |
+
"sd_checkpoint": embedding.sd_checkpoint,
|
| 728 |
+
"sd_checkpoint_name": embedding.sd_checkpoint_name,
|
| 729 |
+
"shape": embedding.shape,
|
| 730 |
+
"vectors": embedding.vectors,
|
| 731 |
+
}
|
| 732 |
+
|
| 733 |
+
def convert_embeddings(embeddings):
|
| 734 |
+
return {embedding.name: convert_embedding(embedding) for embedding in embeddings.values()}
|
| 735 |
+
|
| 736 |
+
return {
|
| 737 |
+
"loaded": convert_embeddings(self.embedding_db.word_embeddings),
|
| 738 |
+
"skipped": convert_embeddings(self.embedding_db.skipped_embeddings),
|
| 739 |
+
}
|
| 740 |
+
|
| 741 |
+
def refresh_embeddings(self):
|
| 742 |
+
with self.queue_lock:
|
| 743 |
+
self.embedding_db.load_textual_inversion_embeddings(force_reload=True, sync_with_sd_model=False)
|
| 744 |
+
|
| 745 |
+
def refresh_checkpoints(self):
|
| 746 |
+
with self.queue_lock:
|
| 747 |
+
shared.refresh_checkpoints()
|
| 748 |
+
|
| 749 |
+
def refresh_vae(self):
|
| 750 |
+
with self.queue_lock:
|
| 751 |
+
shared_items.refresh_vae_list()
|
| 752 |
+
|
| 753 |
+
def get_memory(self):
|
| 754 |
+
try:
|
| 755 |
+
import os
|
| 756 |
+
|
| 757 |
+
import psutil
|
| 758 |
+
|
| 759 |
+
process = psutil.Process(os.getpid())
|
| 760 |
+
res = process.memory_info() # only rss is cross-platform guaranteed so we dont rely on other values
|
| 761 |
+
ram_total = 100 * res.rss / process.memory_percent() # and total memory is calculated as actual value is not cross-platform safe
|
| 762 |
+
ram = {"free": ram_total - res.rss, "used": res.rss, "total": ram_total}
|
| 763 |
+
except Exception as err:
|
| 764 |
+
ram = {"error": f"{err}"}
|
| 765 |
+
try:
|
| 766 |
+
import torch
|
| 767 |
+
|
| 768 |
+
if torch.cuda.is_available():
|
| 769 |
+
s = torch.cuda.mem_get_info()
|
| 770 |
+
system = {"free": s[0], "used": s[1] - s[0], "total": s[1]}
|
| 771 |
+
s = dict(torch.cuda.memory_stats(shared.device))
|
| 772 |
+
allocated = {"current": s["allocated_bytes.all.current"], "peak": s["allocated_bytes.all.peak"]}
|
| 773 |
+
reserved = {"current": s["reserved_bytes.all.current"], "peak": s["reserved_bytes.all.peak"]}
|
| 774 |
+
active = {"current": s["active_bytes.all.current"], "peak": s["active_bytes.all.peak"]}
|
| 775 |
+
inactive = {"current": s["inactive_split_bytes.all.current"], "peak": s["inactive_split_bytes.all.peak"]}
|
| 776 |
+
warnings = {"retries": s["num_alloc_retries"], "oom": s["num_ooms"]}
|
| 777 |
+
cuda = {
|
| 778 |
+
"system": system,
|
| 779 |
+
"active": active,
|
| 780 |
+
"allocated": allocated,
|
| 781 |
+
"reserved": reserved,
|
| 782 |
+
"inactive": inactive,
|
| 783 |
+
"events": warnings,
|
| 784 |
+
}
|
| 785 |
+
else:
|
| 786 |
+
cuda = {"error": "unavailable"}
|
| 787 |
+
except Exception as err:
|
| 788 |
+
cuda = {"error": f"{err}"}
|
| 789 |
+
return models.MemoryResponse(ram=ram, cuda=cuda)
|
| 790 |
+
|
| 791 |
+
def get_extensions_list(self):
|
| 792 |
+
from modules import extensions
|
| 793 |
+
|
| 794 |
+
extensions.list_extensions()
|
| 795 |
+
ext_list = []
|
| 796 |
+
for ext in extensions.extensions:
|
| 797 |
+
ext: extensions.Extension
|
| 798 |
+
ext.read_info_from_repo()
|
| 799 |
+
if ext.remote is not None:
|
| 800 |
+
ext_list.append(
|
| 801 |
+
{
|
| 802 |
+
"name": ext.name,
|
| 803 |
+
"remote": ext.remote,
|
| 804 |
+
"branch": ext.branch,
|
| 805 |
+
"commit_hash": ext.commit_hash,
|
| 806 |
+
"commit_date": ext.commit_date,
|
| 807 |
+
"version": ext.version,
|
| 808 |
+
"enabled": ext.enabled,
|
| 809 |
+
}
|
| 810 |
+
)
|
| 811 |
+
return ext_list
|
| 812 |
+
|
| 813 |
+
def launch(self, server_name, port, root_path):
|
| 814 |
+
self.app.include_router(self.router)
|
| 815 |
+
uvicorn.run(
|
| 816 |
+
self.app,
|
| 817 |
+
host=server_name,
|
| 818 |
+
port=port,
|
| 819 |
+
timeout_keep_alive=shared.cmd_opts.timeout_keep_alive,
|
| 820 |
+
root_path=root_path,
|
| 821 |
+
ssl_keyfile=shared.cmd_opts.tls_keyfile,
|
| 822 |
+
ssl_certfile=shared.cmd_opts.tls_certfile,
|
| 823 |
+
)
|
| 824 |
+
|
| 825 |
+
def kill_webui(self):
|
| 826 |
+
restart.stop_program()
|
| 827 |
+
|
| 828 |
+
def restart_webui(self):
|
| 829 |
+
if restart.is_restartable():
|
| 830 |
+
restart.restart_program()
|
| 831 |
+
return Response(status_code=501)
|
| 832 |
+
|
| 833 |
+
def stop_webui(request):
|
| 834 |
+
shared.state.server_command = "stop"
|
| 835 |
+
return Response("Stopping.")
|
modules/api/models.py
ADDED
|
@@ -0,0 +1,325 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import inspect
|
| 2 |
+
from typing import Any, Literal, Optional
|
| 3 |
+
|
| 4 |
+
from inflection import underscore
|
| 5 |
+
from pydantic import BaseModel, ConfigDict, Field, create_model
|
| 6 |
+
|
| 7 |
+
from modules.processing import StableDiffusionProcessingImg2Img, StableDiffusionProcessingTxt2Img
|
| 8 |
+
from modules.shared import opts, parser, sd_upscalers
|
| 9 |
+
|
| 10 |
+
API_NOT_ALLOWED = {
|
| 11 |
+
"self",
|
| 12 |
+
"kwargs",
|
| 13 |
+
"sd_model",
|
| 14 |
+
"outpath_samples",
|
| 15 |
+
"outpath_grids",
|
| 16 |
+
"sampler_index",
|
| 17 |
+
"extra_generation_params",
|
| 18 |
+
"overlay_images",
|
| 19 |
+
"do_not_reload_embeddings",
|
| 20 |
+
"seed_enable_extras",
|
| 21 |
+
"prompt_for_display",
|
| 22 |
+
"sampler_noise_scheduler_override",
|
| 23 |
+
"ddim_discretize",
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class ModelDef(BaseModel):
|
| 28 |
+
"""Assistance Class for Pydantic Dynamic Model Generation"""
|
| 29 |
+
|
| 30 |
+
field: str
|
| 31 |
+
field_alias: str
|
| 32 |
+
field_type: Any
|
| 33 |
+
field_value: Any
|
| 34 |
+
field_exclude: bool = False
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class PydanticModelGenerator:
|
| 38 |
+
"""
|
| 39 |
+
Takes in created classes and stubs them out in a way FastAPI/Pydantic is happy about:
|
| 40 |
+
source_data is a snapshot of the default values produced by the class
|
| 41 |
+
params are the names of the actual keys required by __init__
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
def __init__(
|
| 45 |
+
self,
|
| 46 |
+
model_name: str = None,
|
| 47 |
+
class_instance=None,
|
| 48 |
+
additional_fields=None,
|
| 49 |
+
):
|
| 50 |
+
def field_type_generator(k, v):
|
| 51 |
+
field_type = v.annotation
|
| 52 |
+
|
| 53 |
+
if field_type == "Image":
|
| 54 |
+
# images are sent as base64 strings via API
|
| 55 |
+
field_type = "str"
|
| 56 |
+
|
| 57 |
+
return Optional[field_type]
|
| 58 |
+
|
| 59 |
+
def merge_class_params(class_):
|
| 60 |
+
all_classes = list(filter(lambda x: x is not object, inspect.getmro(class_)))
|
| 61 |
+
parameters = {}
|
| 62 |
+
for classes in all_classes:
|
| 63 |
+
parameters = {**parameters, **inspect.signature(classes.__init__).parameters}
|
| 64 |
+
return parameters
|
| 65 |
+
|
| 66 |
+
self._model_name = model_name
|
| 67 |
+
self._class_data = merge_class_params(class_instance)
|
| 68 |
+
|
| 69 |
+
self._model_def = [ModelDef(field=underscore(k), field_alias=k, field_type=field_type_generator(k, v), field_value=None if isinstance(v.default, property) else v.default) for (k, v) in self._class_data.items() if k not in API_NOT_ALLOWED]
|
| 70 |
+
|
| 71 |
+
for fields in additional_fields:
|
| 72 |
+
self._model_def.append(ModelDef(field=underscore(fields["key"]), field_alias=fields["key"], field_type=fields["type"], field_value=fields["default"], field_exclude=fields["exclude"] if "exclude" in fields else False))
|
| 73 |
+
|
| 74 |
+
def generate_model(self):
|
| 75 |
+
"""
|
| 76 |
+
Creates a pydantic BaseModel
|
| 77 |
+
from the json and overrides provided at initialization
|
| 78 |
+
"""
|
| 79 |
+
fields = {d.field: (d.field_type, Field(default=d.field_value, alias=d.field_alias, exclude=d.field_exclude)) for d in self._model_def}
|
| 80 |
+
DynamicModel = create_model(self._model_name, __config__=ConfigDict(populate_by_name=True, frozen=False), **fields)
|
| 81 |
+
return DynamicModel
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
StableDiffusionTxt2ImgProcessingAPI = PydanticModelGenerator(
|
| 85 |
+
"StableDiffusionProcessingTxt2Img",
|
| 86 |
+
StableDiffusionProcessingTxt2Img,
|
| 87 |
+
[
|
| 88 |
+
{"key": "sampler_index", "type": str, "default": "Euler"},
|
| 89 |
+
{"key": "script_name", "type": str | None, "default": None},
|
| 90 |
+
{"key": "script_args", "type": list, "default": []},
|
| 91 |
+
{"key": "send_images", "type": bool, "default": True},
|
| 92 |
+
{"key": "save_images", "type": bool, "default": False},
|
| 93 |
+
{"key": "alwayson_scripts", "type": dict, "default": {}},
|
| 94 |
+
{"key": "force_task_id", "type": str | None, "default": None},
|
| 95 |
+
{"key": "infotext", "type": str | None, "default": None},
|
| 96 |
+
],
|
| 97 |
+
).generate_model()
|
| 98 |
+
|
| 99 |
+
StableDiffusionImg2ImgProcessingAPI = PydanticModelGenerator(
|
| 100 |
+
"StableDiffusionProcessingImg2Img",
|
| 101 |
+
StableDiffusionProcessingImg2Img,
|
| 102 |
+
[
|
| 103 |
+
{"key": "sampler_index", "type": str, "default": "Euler"},
|
| 104 |
+
{"key": "init_images", "type": list | None, "default": None},
|
| 105 |
+
{"key": "denoising_strength", "type": float, "default": 0.75},
|
| 106 |
+
{"key": "mask", "type": str | None, "default": None},
|
| 107 |
+
{"key": "include_init_images", "type": bool, "default": False, "exclude": True},
|
| 108 |
+
{"key": "script_name", "type": str | None, "default": None},
|
| 109 |
+
{"key": "script_args", "type": list, "default": []},
|
| 110 |
+
{"key": "send_images", "type": bool, "default": True},
|
| 111 |
+
{"key": "save_images", "type": bool, "default": False},
|
| 112 |
+
{"key": "alwayson_scripts", "type": dict, "default": {}},
|
| 113 |
+
{"key": "force_task_id", "type": str | None, "default": None},
|
| 114 |
+
{"key": "infotext", "type": str | None, "default": None},
|
| 115 |
+
],
|
| 116 |
+
).generate_model()
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
class TextToImageResponse(BaseModel):
|
| 120 |
+
images: list[str] | None = Field(default=None, title="Image", description="The generated image in base64 format.")
|
| 121 |
+
parameters: dict
|
| 122 |
+
info: str
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
class ImageToImageResponse(BaseModel):
|
| 126 |
+
images: list[str] | None = Field(default=None, title="Image", description="The generated image in base64 format.")
|
| 127 |
+
parameters: dict
|
| 128 |
+
info: str
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
class ExtrasBaseRequest(BaseModel):
|
| 132 |
+
resize_mode: Literal[0, 1] = Field(default=0, title="Resize Mode", description="Sets the resize mode: 0 to upscale by upscaling_resize amount, 1 to upscale up to upscaling_resize_h x upscaling_resize_w.")
|
| 133 |
+
show_extras_results: bool = Field(default=True, title="Show results", description="Should the backend return the generated image?")
|
| 134 |
+
gfpgan_visibility: float = Field(default=0, title="GFPGAN Visibility", ge=0, le=1, allow_inf_nan=False, description="Sets the visibility of GFPGAN, values should be between 0 and 1.")
|
| 135 |
+
codeformer_visibility: float = Field(default=0, title="CodeFormer Visibility", ge=0, le=1, allow_inf_nan=False, description="Sets the visibility of CodeFormer, values should be between 0 and 1.")
|
| 136 |
+
codeformer_weight: float = Field(default=0, title="CodeFormer Weight", ge=0, le=1, allow_inf_nan=False, description="Sets the weight of CodeFormer, values should be between 0 and 1.")
|
| 137 |
+
upscaling_resize: float = Field(default=2, title="Upscaling Factor", gt=0, description="By how much to upscale the image, only used when resize_mode=0.")
|
| 138 |
+
upscaling_resize_w: int = Field(default=512, title="Target Width", ge=1, description="Target width for the upscaler to hit. Only used when resize_mode=1.")
|
| 139 |
+
upscaling_resize_h: int = Field(default=512, title="Target Height", ge=1, description="Target height for the upscaler to hit. Only used when resize_mode=1.")
|
| 140 |
+
upscaling_crop: bool = Field(default=True, title="Crop to fit", description="Should the upscaler crop the image to fit in the chosen size?")
|
| 141 |
+
upscaler_1: str = Field(default="None", title="Main upscaler", description=f"The name of the main upscaler to use, it has to be one of this list: {' , '.join([x.name for x in sd_upscalers])}")
|
| 142 |
+
upscaler_2: str = Field(default="None", title="Secondary upscaler", description=f"The name of the secondary upscaler to use, it has to be one of this list: {' , '.join([x.name for x in sd_upscalers])}")
|
| 143 |
+
extras_upscaler_2_visibility: float = Field(default=0, title="Secondary upscaler visibility", ge=0, le=1, allow_inf_nan=False, description="Sets the visibility of secondary upscaler, values should be between 0 and 1.")
|
| 144 |
+
upscale_first: bool = Field(default=False, title="Upscale first", description="Should the upscaler run before restoring faces?")
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
class ExtraBaseResponse(BaseModel):
|
| 148 |
+
html_info: str = Field(title="HTML info", description="A series of HTML tags containing the process info.")
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
class ExtrasSingleImageRequest(ExtrasBaseRequest):
|
| 152 |
+
image: str = Field(default="", title="Image", description="Image to work on, must be a Base64 string containing the image's data.")
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
class ExtrasSingleImageResponse(ExtraBaseResponse):
|
| 156 |
+
image: str | None = Field(default=None, title="Image", description="The generated image in base64 format.")
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
class FileData(BaseModel):
|
| 160 |
+
data: str = Field(title="File data", description="Base64 representation of the file")
|
| 161 |
+
name: str = Field(title="File name")
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
class ExtrasBatchImagesRequest(ExtrasBaseRequest):
|
| 165 |
+
imageList: list[FileData] = Field(title="Images", description="List of images to work on. Must be Base64 strings")
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
class ExtrasBatchImagesResponse(ExtraBaseResponse):
|
| 169 |
+
images: list[str] = Field(title="Images", description="The generated images in base64 format.")
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
class PNGInfoRequest(BaseModel):
|
| 173 |
+
image: str = Field(title="Image", description="The base64 encoded PNG image")
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
class PNGInfoResponse(BaseModel):
|
| 177 |
+
info: str = Field(title="Image info", description="A string with the parameters used to generate the image")
|
| 178 |
+
items: dict = Field(title="Items", description="A dictionary containing all the other fields the image had")
|
| 179 |
+
parameters: dict = Field(title="Parameters", description="A dictionary with parsed generation info fields")
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
class ProgressRequest(BaseModel):
|
| 183 |
+
skip_current_image: bool = Field(default=False, title="Skip current image", description="Skip current image serialization")
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
class ProgressResponse(BaseModel):
|
| 187 |
+
progress: float = Field(title="Progress", description="The progress with a range of 0 to 1")
|
| 188 |
+
eta_relative: float = Field(title="ETA in secs")
|
| 189 |
+
state: dict = Field(title="State", description="The current state snapshot")
|
| 190 |
+
current_image: str | None = Field(default=None, title="Current image", description="The current image in base64 format. opts.show_progress_every_n_steps is required for this to work.")
|
| 191 |
+
textinfo: str | None = Field(default=None, title="Info text", description="Info text used by WebUI.")
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
fields = {}
|
| 195 |
+
for key, metadata in opts.data_labels.items():
|
| 196 |
+
value = opts.data.get(key)
|
| 197 |
+
optType = opts.typemap.get(type(metadata.default), type(metadata.default)) if metadata.default else Any
|
| 198 |
+
|
| 199 |
+
if metadata is not None:
|
| 200 |
+
fields.update({key: (Optional[optType], Field(default=metadata.default, description=metadata.label))})
|
| 201 |
+
else:
|
| 202 |
+
fields.update({key: (Optional[optType], Field())})
|
| 203 |
+
|
| 204 |
+
OptionsModel = create_model("Options", **fields)
|
| 205 |
+
|
| 206 |
+
flags = {}
|
| 207 |
+
_options = vars(parser)["_option_string_actions"]
|
| 208 |
+
for key in _options:
|
| 209 |
+
if _options[key].dest != "help":
|
| 210 |
+
flag = _options[key]
|
| 211 |
+
_type = str | None
|
| 212 |
+
if _options[key].default is not None:
|
| 213 |
+
_type = type(_options[key].default)
|
| 214 |
+
flags.update({flag.dest: (_type, Field(default=flag.default, description=flag.help))})
|
| 215 |
+
|
| 216 |
+
FlagsModel = create_model("Flags", **flags)
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
class SamplerItem(BaseModel):
|
| 220 |
+
name: str = Field(title="Name")
|
| 221 |
+
aliases: list[str] = Field(title="Aliases")
|
| 222 |
+
options: dict[str, Any] = Field(title="Options")
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
class SchedulerItem(BaseModel):
|
| 226 |
+
name: str = Field(title="Name")
|
| 227 |
+
label: str = Field(title="Label")
|
| 228 |
+
aliases: Optional[list[str]] = Field(title="Aliases")
|
| 229 |
+
default_rho: Optional[float] = Field(title="Default Rho")
|
| 230 |
+
need_inner_model: Optional[bool] = Field(title="Needs Inner Model")
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
class UpscalerItem(BaseModel):
|
| 234 |
+
class Config:
|
| 235 |
+
protected_namespaces = ()
|
| 236 |
+
|
| 237 |
+
name: str = Field(title="Name")
|
| 238 |
+
model_name: Optional[str] = Field(title="Model Name")
|
| 239 |
+
model_path: Optional[str] = Field(title="Path")
|
| 240 |
+
model_url: Optional[str] = Field(title="URL")
|
| 241 |
+
scale: Optional[float] = Field(title="Scale")
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
class LatentUpscalerModeItem(BaseModel):
|
| 245 |
+
name: str = Field(title="Name")
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
class SDModelItem(BaseModel):
|
| 249 |
+
class Config:
|
| 250 |
+
protected_namespaces = ()
|
| 251 |
+
|
| 252 |
+
title: str = Field(title="Title")
|
| 253 |
+
model_name: str = Field(title="Model Name")
|
| 254 |
+
hash: Optional[str] = Field(title="Short hash")
|
| 255 |
+
sha256: Optional[str] = Field(title="sha256 hash")
|
| 256 |
+
filename: str = Field(title="Filename")
|
| 257 |
+
config: Optional[str] = Field(default=None, title="Config file")
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
class SDModuleItem(BaseModel):
|
| 261 |
+
class Config:
|
| 262 |
+
protected_namespaces = ()
|
| 263 |
+
|
| 264 |
+
model_name: str = Field(title="Model Name")
|
| 265 |
+
filename: str = Field(title="Filename")
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
class FaceRestorerItem(BaseModel):
|
| 269 |
+
name: str = Field(title="Name")
|
| 270 |
+
cmd_dir: Optional[str] = Field(title="Path")
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
class PromptStyleItem(BaseModel):
|
| 274 |
+
name: str = Field(title="Name")
|
| 275 |
+
prompt: Optional[str] = Field(title="Prompt")
|
| 276 |
+
negative_prompt: Optional[str] = Field(title="Negative Prompt")
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
class EmbeddingItem(BaseModel):
|
| 280 |
+
step: Optional[int] = Field(title="Step", description="The number of steps that were used to train this embedding, if available")
|
| 281 |
+
sd_checkpoint: Optional[str] = Field(title="SD Checkpoint", description="The hash of the checkpoint this embedding was trained on, if available")
|
| 282 |
+
sd_checkpoint_name: Optional[str] = Field(title="SD Checkpoint Name", description="The name of the checkpoint this embedding was trained on, if available. Note that this is the name that was used by the trainer; for a stable identifier, use `sd_checkpoint` instead")
|
| 283 |
+
shape: int = Field(title="Shape", description="The length of each individual vector in the embedding")
|
| 284 |
+
vectors: int = Field(title="Vectors", description="The number of vectors in the embedding")
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
class EmbeddingsResponse(BaseModel):
|
| 288 |
+
loaded: dict[str, EmbeddingItem] = Field(title="Loaded", description="Embeddings loaded for the current model")
|
| 289 |
+
skipped: dict[str, EmbeddingItem] = Field(title="Skipped", description="Embeddings skipped for the current model (likely due to architecture incompatibility)")
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
class MemoryResponse(BaseModel):
|
| 293 |
+
ram: dict = Field(title="RAM", description="System memory stats")
|
| 294 |
+
cuda: dict = Field(title="CUDA", description="nVidia CUDA memory stats")
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
class ScriptsList(BaseModel):
|
| 298 |
+
txt2img: list | None = Field(default=None, title="Txt2img", description="Titles of scripts (txt2img)")
|
| 299 |
+
img2img: list | None = Field(default=None, title="Img2img", description="Titles of scripts (img2img)")
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
class ScriptArg(BaseModel):
|
| 303 |
+
label: str | None = Field(default=None, title="Label", description="Name of the argument in UI")
|
| 304 |
+
value: Optional[Any] = Field(default=None, title="Value", description="Default value of the argument")
|
| 305 |
+
minimum: Optional[Any] = Field(default=None, title="Minimum", description="Minimum allowed value for the argumentin UI")
|
| 306 |
+
maximum: Optional[Any] = Field(default=None, title="Minimum", description="Maximum allowed value for the argumentin UI")
|
| 307 |
+
step: Optional[Any] = Field(default=None, title="Minimum", description="Step for changing value of the argumentin UI")
|
| 308 |
+
choices: Optional[list[str]] = Field(default=None, title="Choices", description="Possible values for the argument")
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
class ScriptInfo(BaseModel):
|
| 312 |
+
name: str | None = Field(default=None, title="Name", description="Script name")
|
| 313 |
+
is_alwayson: bool | None = Field(default=None, title="IsAlwayson", description="Flag specifying whether this script is an alwayson script")
|
| 314 |
+
is_img2img: bool | None = Field(default=None, title="IsImg2img", description="Flag specifying whether this script is an img2img script")
|
| 315 |
+
args: list[ScriptArg] = Field(title="Arguments", description="List of script's arguments")
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
class ExtensionItem(BaseModel):
|
| 319 |
+
name: str = Field(title="Name", description="Extension name")
|
| 320 |
+
remote: str = Field(title="Remote", description="Extension Repository URL")
|
| 321 |
+
branch: str = Field(title="Branch", description="Extension Repository Branch")
|
| 322 |
+
commit_hash: str = Field(title="Commit Hash", description="Extension Repository Commit Hash")
|
| 323 |
+
version: str = Field(title="Version", description="Extension Version")
|
| 324 |
+
commit_date: int = Field(title="Commit Date", description="Extension Repository Commit Date")
|
| 325 |
+
enabled: bool = Field(title="Enabled", description="Flag specifying whether this extension is enabled")
|
modules/cache.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import threading
|
| 2 |
+
import diskcache
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
from modules.paths import data_path
|
| 6 |
+
|
| 7 |
+
cache_lock = threading.Lock()
|
| 8 |
+
cache_dir = os.environ.get("SD_WEBUI_CACHE_DIR", os.path.join(data_path, "cache"))
|
| 9 |
+
caches = {}
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
dump_cache = lambda: None
|
| 13 |
+
"""does nothing since diskcache"""
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def cache(subsection):
|
| 17 |
+
"""
|
| 18 |
+
Retrieves or initializes a cache for a specific subsection.
|
| 19 |
+
|
| 20 |
+
Parameters:
|
| 21 |
+
subsection (str): The subsection identifier for the cache.
|
| 22 |
+
|
| 23 |
+
Returns:
|
| 24 |
+
diskcache.Cache: The cache data for the specified subsection.
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
cache_obj = caches.get(subsection)
|
| 28 |
+
if not cache_obj:
|
| 29 |
+
with cache_lock:
|
| 30 |
+
cache_obj = caches.get(subsection)
|
| 31 |
+
if not cache_obj:
|
| 32 |
+
cache_obj = diskcache.Cache(os.path.join(cache_dir, subsection))
|
| 33 |
+
caches[subsection] = cache_obj
|
| 34 |
+
|
| 35 |
+
return cache_obj
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def cached_data_for_file(subsection, title, filename, func):
|
| 39 |
+
"""
|
| 40 |
+
Retrieves or generates data for a specific file, using a caching mechanism.
|
| 41 |
+
|
| 42 |
+
Parameters:
|
| 43 |
+
subsection (str): The subsection of the cache to use.
|
| 44 |
+
title (str): The title of the data entry in the subsection of the cache.
|
| 45 |
+
filename (str): The path to the file to be checked for modifications.
|
| 46 |
+
func (callable): A function that generates the data if it is not available in the cache.
|
| 47 |
+
|
| 48 |
+
Returns:
|
| 49 |
+
dict or None: The cached or generated data, or None if data generation fails.
|
| 50 |
+
|
| 51 |
+
The function implements a caching mechanism for data stored in files.
|
| 52 |
+
It checks if the data associated with the given `title` is present in the cache and compares the
|
| 53 |
+
modification time of the file with the cached modification time. If the file has been modified,
|
| 54 |
+
the cache is considered invalid and the data is regenerated using the provided `func`.
|
| 55 |
+
Otherwise, the cached data is returned.
|
| 56 |
+
|
| 57 |
+
If the data generation fails, None is returned to indicate the failure. Otherwise, the generated
|
| 58 |
+
or cached data is returned as a dictionary.
|
| 59 |
+
"""
|
| 60 |
+
|
| 61 |
+
existing_cache = cache(subsection)
|
| 62 |
+
ondisk_mtime = os.path.getmtime(filename)
|
| 63 |
+
|
| 64 |
+
entry = existing_cache.get(title)
|
| 65 |
+
if entry:
|
| 66 |
+
cached_mtime = entry.get("mtime", 0)
|
| 67 |
+
if ondisk_mtime > cached_mtime:
|
| 68 |
+
entry = None
|
| 69 |
+
|
| 70 |
+
if not entry or "value" not in entry:
|
| 71 |
+
value = func()
|
| 72 |
+
if value is None:
|
| 73 |
+
return None
|
| 74 |
+
|
| 75 |
+
entry = {"mtime": ondisk_mtime, "value": value}
|
| 76 |
+
existing_cache[title] = entry
|
| 77 |
+
|
| 78 |
+
dump_cache()
|
| 79 |
+
|
| 80 |
+
return entry["value"]
|
modules/call_queue.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os.path
|
| 2 |
+
from functools import wraps
|
| 3 |
+
import html
|
| 4 |
+
import time
|
| 5 |
+
import traceback
|
| 6 |
+
|
| 7 |
+
from modules_forge import main_thread
|
| 8 |
+
from modules import shared, progress, errors, devices, fifo_lock, profiling
|
| 9 |
+
|
| 10 |
+
queue_lock = fifo_lock.FIFOLock()
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def wrap_queued_call(func):
|
| 14 |
+
def f(*args, **kwargs):
|
| 15 |
+
with queue_lock:
|
| 16 |
+
res = func(*args, **kwargs)
|
| 17 |
+
|
| 18 |
+
return res
|
| 19 |
+
|
| 20 |
+
return f
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def wrap_gradio_gpu_call(func, extra_outputs=None):
|
| 24 |
+
@wraps(func)
|
| 25 |
+
def f(*args, **kwargs):
|
| 26 |
+
|
| 27 |
+
# if the first argument is a string that says "task(...)", it is treated as a job id
|
| 28 |
+
if args and type(args[0]) == str and args[0].startswith("task(") and args[0].endswith(")"):
|
| 29 |
+
id_task = args[0]
|
| 30 |
+
progress.add_task_to_queue(id_task)
|
| 31 |
+
else:
|
| 32 |
+
id_task = None
|
| 33 |
+
|
| 34 |
+
with queue_lock:
|
| 35 |
+
shared.state.begin(job=id_task)
|
| 36 |
+
progress.start_task(id_task)
|
| 37 |
+
|
| 38 |
+
try:
|
| 39 |
+
res = func(*args, **kwargs)
|
| 40 |
+
progress.record_results(id_task, res)
|
| 41 |
+
finally:
|
| 42 |
+
progress.finish_task(id_task)
|
| 43 |
+
|
| 44 |
+
shared.state.end()
|
| 45 |
+
|
| 46 |
+
return res
|
| 47 |
+
|
| 48 |
+
return wrap_gradio_call(f, extra_outputs=extra_outputs, add_stats=True)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def wrap_gradio_call(func, extra_outputs=None, add_stats=False):
|
| 52 |
+
@wraps(func)
|
| 53 |
+
def f(*args, **kwargs):
|
| 54 |
+
try:
|
| 55 |
+
res = func(*args, **kwargs)
|
| 56 |
+
finally:
|
| 57 |
+
shared.state.skipped = False
|
| 58 |
+
shared.state.interrupted = False
|
| 59 |
+
shared.state.stopping_generation = False
|
| 60 |
+
shared.state.job_count = 0
|
| 61 |
+
shared.state.job = ""
|
| 62 |
+
return res
|
| 63 |
+
|
| 64 |
+
return wrap_gradio_call_no_job(f, extra_outputs, add_stats)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def wrap_gradio_call_no_job(func, extra_outputs=None, add_stats=False):
|
| 68 |
+
@wraps(func)
|
| 69 |
+
def f(*args, extra_outputs_array=extra_outputs, **kwargs):
|
| 70 |
+
run_memmon = shared.opts.memmon_poll_rate > 0 and not shared.mem_mon.disabled and add_stats
|
| 71 |
+
if run_memmon:
|
| 72 |
+
shared.mem_mon.monitor()
|
| 73 |
+
t = time.perf_counter()
|
| 74 |
+
|
| 75 |
+
try:
|
| 76 |
+
res = list(func(*args, **kwargs))
|
| 77 |
+
except Exception as e:
|
| 78 |
+
if main_thread.last_exception is not None:
|
| 79 |
+
e = main_thread.last_exception
|
| 80 |
+
else:
|
| 81 |
+
traceback.print_exc()
|
| 82 |
+
print(e)
|
| 83 |
+
|
| 84 |
+
if extra_outputs_array is None:
|
| 85 |
+
extra_outputs_array = [None, '']
|
| 86 |
+
|
| 87 |
+
error_message = f'{type(e).__name__}: {e}'
|
| 88 |
+
res = extra_outputs_array + [f"<div class='error'>{html.escape(error_message)}</div>"]
|
| 89 |
+
|
| 90 |
+
devices.torch_gc()
|
| 91 |
+
|
| 92 |
+
if not add_stats:
|
| 93 |
+
return tuple(res)
|
| 94 |
+
|
| 95 |
+
elapsed = time.perf_counter() - t
|
| 96 |
+
elapsed_m = int(elapsed // 60)
|
| 97 |
+
elapsed_s = elapsed % 60
|
| 98 |
+
elapsed_text = f"{elapsed_s:.1f} sec."
|
| 99 |
+
if elapsed_m > 0:
|
| 100 |
+
elapsed_text = f"{elapsed_m} min. "+elapsed_text
|
| 101 |
+
|
| 102 |
+
if run_memmon:
|
| 103 |
+
mem_stats = {k: -(v//-(1024*1024)) for k, v in shared.mem_mon.stop().items()}
|
| 104 |
+
active_peak = mem_stats['active_peak']
|
| 105 |
+
reserved_peak = mem_stats['reserved_peak']
|
| 106 |
+
sys_peak = mem_stats['system_peak']
|
| 107 |
+
sys_total = mem_stats['total']
|
| 108 |
+
sys_pct = sys_peak/max(sys_total, 1) * 100
|
| 109 |
+
|
| 110 |
+
toltip_a = "Active: peak amount of video memory used during generation (excluding cached data)"
|
| 111 |
+
toltip_r = "Reserved: total amount of video memory allocated by the Torch library "
|
| 112 |
+
toltip_sys = "System: peak amount of video memory allocated by all running programs, out of total capacity"
|
| 113 |
+
|
| 114 |
+
text_a = f"<abbr title='{toltip_a}'>A</abbr>: <span class='measurement'>{active_peak/1024:.2f} GB</span>"
|
| 115 |
+
text_r = f"<abbr title='{toltip_r}'>R</abbr>: <span class='measurement'>{reserved_peak/1024:.2f} GB</span>"
|
| 116 |
+
text_sys = f"<abbr title='{toltip_sys}'>Sys</abbr>: <span class='measurement'>{sys_peak/1024:.1f}/{sys_total/1024:g} GB</span> ({sys_pct:.1f}%)"
|
| 117 |
+
|
| 118 |
+
vram_html = f"<p class='vram'>{text_a}, <wbr>{text_r}, <wbr>{text_sys}</p>"
|
| 119 |
+
else:
|
| 120 |
+
vram_html = ''
|
| 121 |
+
|
| 122 |
+
if shared.opts.profiling_enable and os.path.exists(shared.opts.profiling_filename):
|
| 123 |
+
profiling_html = f"<p class='profile'> [ <a href='{profiling.webpath()}' download>Profile</a> ] </p>"
|
| 124 |
+
else:
|
| 125 |
+
profiling_html = ''
|
| 126 |
+
|
| 127 |
+
# last item is always HTML
|
| 128 |
+
res[-1] += f"<div class='performance'><p class='time'>Time taken: <wbr><span class='measurement'>{elapsed_text}</span></p>{vram_html}{profiling_html}</div>"
|
| 129 |
+
|
| 130 |
+
return tuple(res)
|
| 131 |
+
|
| 132 |
+
return f
|
| 133 |
+
|
modules/cmd_args.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
from modules.paths_internal import data_path, extensions_builtin_dir, extensions_dir, models_path, normalized_filepath, parser, script_path # noqa: F401
|
| 7 |
+
|
| 8 |
+
parser.add_argument("-f", action="store_true", help=argparse.SUPPRESS)
|
| 9 |
+
|
| 10 |
+
parser.add_argument("--update-all-extensions", action="store_true", help="launch.py argument: download updates for all extensions when starting the program")
|
| 11 |
+
parser.add_argument("--skip-python-version-check", action="store_true", help="launch.py argument: do not check python version")
|
| 12 |
+
parser.add_argument("--skip-torch-cuda-test", action="store_true", help="launch.py argument: do not check if CUDA is able to work properly")
|
| 13 |
+
parser.add_argument("--reinstall-xformers", action="store_true", help="launch.py argument: install the appropriate version of xformers even if you have some version already installed")
|
| 14 |
+
parser.add_argument("--reinstall-torch", action="store_true", help="launch.py argument: install the appropriate version of torch even if you have some version already installed")
|
| 15 |
+
parser.add_argument("--log-startup", action="store_true", help="launch.py argument: print a detailed log of what's happening at startup")
|
| 16 |
+
parser.add_argument("--skip-prepare-environment", action="store_true", help="launch.py argument: skip all environment preparation")
|
| 17 |
+
parser.add_argument("--skip-install", action="store_true", help="launch.py argument: skip installation of packages")
|
| 18 |
+
parser.add_argument("--dump-sysinfo", action="store_true", help="launch.py argument: dump limited sysinfo file (without information about extensions, options) to disk and quit")
|
| 19 |
+
parser.add_argument("--loglevel", type=str, help="log level; one of: CRITICAL, ERROR, WARNING, INFO, DEBUG", default=None)
|
| 20 |
+
parser.add_argument("--share", action="store_true", help="use share=True for gradio and make the UI accessible through their site")
|
| 21 |
+
parser.add_argument("--ngrok", type=str, help="ngrok authtoken, alternative to gradio --share", default=None)
|
| 22 |
+
parser.add_argument("--ngrok-region", type=str, help="does not do anything.", default="")
|
| 23 |
+
parser.add_argument("--ngrok-options", type=json.loads, help='The options to pass to ngrok in JSON format, e.g.: \'{"authtoken_from_env":true, "basic_auth":"user:password", "oauth_provider":"google", "oauth_allow_emails":"user@asdf.com"}\'', default=dict())
|
| 24 |
+
parser.add_argument("--enable-insecure-extension-access", action="store_true", help="enable extensions tab regardless of other options")
|
| 25 |
+
parser.add_argument("--listen", action="store_true", help="launch gradio with 0.0.0.0 as server name, allowing to respond to network requests")
|
| 26 |
+
parser.add_argument("--port", type=int, help="launch gradio with given server port, you need root/admin rights for ports < 1024, defaults to 7860 if available", default=None)
|
| 27 |
+
parser.add_argument("--ui-config-file", type=str, help="filename to use for ui configuration", default=os.path.join(data_path, "ui-config.json"))
|
| 28 |
+
parser.add_argument("--hide-ui-dir-config", action="store_true", help="hide directory configuration from webui", default=False)
|
| 29 |
+
parser.add_argument("--freeze-settings", action="store_true", help="disable editing of all settings globally", default=False)
|
| 30 |
+
parser.add_argument("--freeze-settings-in-sections", type=str, help='disable editing settings in specific sections of the settings page by specifying a comma-delimited list such like "saving-images,upscaling". The list of setting names can be found in the modules/shared_options.py file', default=None)
|
| 31 |
+
parser.add_argument("--freeze-specific-settings", type=str, help='disable editing of individual settings by specifying a comma-delimited list like "samples_save,samples_format". The list of setting names can be found in the config.json file', default=None)
|
| 32 |
+
parser.add_argument("--ui-settings-file", type=str, help="filename to use for ui settings", default=os.path.join(data_path, "config.json"))
|
| 33 |
+
parser.add_argument("--gradio-debug", action="store_true", help="launch gradio with --debug option")
|
| 34 |
+
parser.add_argument("--gradio-auth", type=str, help='set gradio authentication like "username:password"; or comma-delimit multiple like "u1:p1,u2:p2,u3:p3"', default=None)
|
| 35 |
+
parser.add_argument("--gradio-auth-path", type=normalized_filepath, help='set gradio authentication file path ex. "/path/to/auth/file" same auth format as --gradio-auth', default=None)
|
| 36 |
+
parser.add_argument("--gradio-allowed-path", action="append", help="add path to gradio's allowed_paths, make it possible to serve files from it", default=[data_path])
|
| 37 |
+
parser.add_argument("--styles-file", type=str, action="append", help="path or wildcard path of styles files, allow multiple entries.", default=[])
|
| 38 |
+
parser.add_argument("--autolaunch", action="store_true", help="open the webui URL in the system's default browser upon launch", default=False)
|
| 39 |
+
parser.add_argument("--theme", type=str, help="launches the UI with light or dark theme", default=None)
|
| 40 |
+
parser.add_argument("--use-textbox-seed", action="store_true", help="use textbox for seeds in UI (no up/down, but possible to input long seeds)", default=False)
|
| 41 |
+
parser.add_argument("--disable-console-progressbars", action="store_true", help="do not output progressbars to console", default=False)
|
| 42 |
+
parser.add_argument("--enable-console-prompts", action="store_true", help="does not do anything", default=False) # Legacy compatibility, use as default value shared.opts.enable_console_prompts
|
| 43 |
+
parser.add_argument("--disable-safe-unpickle", action="store_true", help="disable checking pytorch models for malicious code", default=False)
|
| 44 |
+
parser.add_argument("--api", action="store_true", help="use api=True to launch the API together with the webui (use --nowebui instead for only the API)")
|
| 45 |
+
parser.add_argument("--api-auth", type=str, help='Set authentication for API like "username:password"; or comma-delimit multiple like "u1:p1,u2:p2,u3:p3"', default=None)
|
| 46 |
+
parser.add_argument("--api-log", action="store_true", help="use api-log=True to enable logging of all API requests")
|
| 47 |
+
parser.add_argument("--nowebui", action="store_true", help="use api=True to launch the API instead of the webui")
|
| 48 |
+
parser.add_argument("--ui-debug-mode", action="store_true", help="Don't load model to quickly launch UI")
|
| 49 |
+
parser.add_argument("--device-id", type=str, help="Select the default CUDA device to use (export CUDA_VISIBLE_DEVICES=0,1,etc might be needed before)", default=None)
|
| 50 |
+
parser.add_argument("--administrator", action="store_true", help="Administrator rights", default=False)
|
| 51 |
+
parser.add_argument("--cors-allow-origins", type=str, help="Allowed CORS origin(s) in the form of a comma-separated list (no spaces)", default=None)
|
| 52 |
+
parser.add_argument("--cors-allow-origins-regex", type=str, help="Allowed CORS origin(s) in the form of a single regular expression", default=None)
|
| 53 |
+
parser.add_argument("--tls-keyfile", type=str, help="Partially enables TLS, requires --tls-certfile to fully function", default=None)
|
| 54 |
+
parser.add_argument("--tls-certfile", type=str, help="Partially enables TLS, requires --tls-keyfile to fully function", default=None)
|
| 55 |
+
parser.add_argument("--disable-tls-verify", action="store_false", help="When passed, enables the use of self-signed certificates.", default=None)
|
| 56 |
+
parser.add_argument("--server-name", type=str, help="Sets hostname of server", default=None)
|
| 57 |
+
parser.add_argument("--no-gradio-queue", action="store_true", help="Disables gradio queue; causes the webpage to use http requests instead of websockets; was the default in earlier versions")
|
| 58 |
+
parser.add_argument("--skip-version-check", action="store_true", help="Do not check versions of torch and xformers")
|
| 59 |
+
parser.add_argument("--no-hashing", action="store_true", help="disable sha256 hashing of checkpoints to help loading performance", default=False)
|
| 60 |
+
parser.add_argument("--subpath", type=str, help="customize the subpath for gradio, use with reverse proxy")
|
| 61 |
+
parser.add_argument("--add-stop-route", action="store_true", help="does not do anything")
|
| 62 |
+
parser.add_argument("--api-server-stop", action="store_true", help="enable server stop/restart/kill via api")
|
| 63 |
+
parser.add_argument("--timeout-keep-alive", type=int, default=30, help="set timeout_keep_alive for uvicorn")
|
| 64 |
+
parser.add_argument("--disable-all-extensions", action="store_true", help="prevent all extensions from running regardless of any other settings", default=False)
|
| 65 |
+
parser.add_argument("--disable-extra-extensions", action="store_true", help="prevent all extensions except built-in from running regardless of any other settings", default=False)
|
| 66 |
+
parser.add_argument("--unix-filenames-sanitization", action="store_true", help="allow any symbols except '/' in filenames. May conflict with your browser and file system")
|
| 67 |
+
parser.add_argument("--filenames-max-length", type=int, default=128, help="maximal length of filenames of saved images. If you override it, it can conflict with your file system")
|
| 68 |
+
parser.add_argument("--no-prompt-history", action="store_true", help="disable read prompt from last generation feature; settings this argument will not create '--data_path/params.txt' file")
|
| 69 |
+
|
| 70 |
+
# Paths
|
| 71 |
+
parser.add_argument("--ckpt-dirs", type=normalized_filepath, action="append", help="Directories for Checkpoint model(s)", default=[])
|
| 72 |
+
parser.add_argument("--lora-dirs", type=normalized_filepath, action="append", help="Directories for LoRA(s)", default=[])
|
| 73 |
+
parser.add_argument("--vae-dirs", type=normalized_filepath, action="append", help="Directories for VAE model(s)", default=[])
|
| 74 |
+
parser.add_argument("--text-encoder-dirs", type=normalized_filepath, action="append", help="Directories for Text Encoder model(s)", default=[])
|
| 75 |
+
parser.add_argument("--embeddings-dir", type=normalized_filepath, help="Directory for Textual Inversion model(s)", default=os.path.join(models_path, "embeddings"))
|
| 76 |
+
parser.add_argument("--localizations-dir", type=normalized_filepath, help="Directory for localization file(s)", default=os.path.join(script_path, "localizations"))
|
| 77 |
+
|
| 78 |
+
parser.add_argument("--codeformer-models-path", type=normalized_filepath, help="Directory for CodeFormer model file(s)", default=os.path.join(models_path, "Codeformer"))
|
| 79 |
+
parser.add_argument("--gfpgan-models-path", type=normalized_filepath, help="Directory for GFPGAN model file(s)", default=os.path.join(models_path, "GFPGAN"))
|
| 80 |
+
parser.add_argument("--esrgan-models-path", type=normalized_filepath, help="Directory for ESRGAN model file(s)", default=os.path.join(models_path, "ESRGAN"))
|
| 81 |
+
|
| 82 |
+
# args added by. Forge
|
| 83 |
+
parser.add_argument("--forge-ref-a1111-home", type=Path, help="Look for models in an existing installation of Automatic1111 Webui", default=None)
|
| 84 |
+
|
| 85 |
+
# args added by. Neo
|
| 86 |
+
parser.add_argument("--forge-ref-comfy-home", type=Path, help="Look for models in an existing installation of ComfyUI", default=None)
|
| 87 |
+
parser.add_argument("--adv-samplers", action="store_true", help='show the "sampler parameters" advanced settings')
|
| 88 |
+
|
| 89 |
+
pkm = parser.add_mutually_exclusive_group()
|
| 90 |
+
pkm.add_argument("--uv", action="store_true", help="Use the uv package manager")
|
| 91 |
+
pkm.add_argument("--uv-symlink", action="store_true", help="Use the uv package manager with symlink")
|
| 92 |
+
|
| 93 |
+
# backward compatibility
|
| 94 |
+
parser.add_argument("--use-cpu", nargs="+", help="required by adetailer", default=[], type=str.lower)
|
modules/codeformer_model.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
from modules import (
|
| 7 |
+
devices,
|
| 8 |
+
errors,
|
| 9 |
+
face_restoration,
|
| 10 |
+
face_restoration_utils,
|
| 11 |
+
modelloader,
|
| 12 |
+
shared,
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
codeformer: face_restoration.FaceRestoration | None = None
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class FaceRestorerCodeFormer(face_restoration_utils.CommonFaceRestoration):
|
| 19 |
+
def name(self):
|
| 20 |
+
return "CodeFormer"
|
| 21 |
+
|
| 22 |
+
def load_net(self) -> torch.nn.Module:
|
| 23 |
+
os.makedirs(self.model_path, exist_ok=True)
|
| 24 |
+
for model_path in modelloader.load_models(
|
| 25 |
+
model_path=self.model_path,
|
| 26 |
+
model_url="https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/codeformer.pth",
|
| 27 |
+
command_path=self.model_path,
|
| 28 |
+
download_name="codeformer-v0.1.0.pth",
|
| 29 |
+
ext_filter=[".pth"],
|
| 30 |
+
):
|
| 31 |
+
return modelloader.load_spandrel_model(
|
| 32 |
+
model_path,
|
| 33 |
+
device=devices.device_codeformer,
|
| 34 |
+
expected_architecture="CodeFormer",
|
| 35 |
+
).model
|
| 36 |
+
raise ValueError("No CodeFormer Model Found")
|
| 37 |
+
|
| 38 |
+
def restore(self, np_image, w: float | None = None):
|
| 39 |
+
if w is None:
|
| 40 |
+
w = getattr(shared.opts, "code_former_weight", 0.5)
|
| 41 |
+
|
| 42 |
+
def restore_face(cropped_face_t):
|
| 43 |
+
assert self.net is not None
|
| 44 |
+
return self.net(cropped_face_t, w=w, adain=True)[0]
|
| 45 |
+
|
| 46 |
+
return self.restore_with_helper(np_image, restore_face)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def setup_model(dirname: str) -> None:
|
| 50 |
+
global codeformer
|
| 51 |
+
try:
|
| 52 |
+
codeformer = FaceRestorerCodeFormer(dirname)
|
| 53 |
+
shared.face_restorers.append(codeformer)
|
| 54 |
+
except Exception:
|
| 55 |
+
errors.report("Error setting up CodeFormer", exc_info=True)
|
modules/config_states.py
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Supports saving and restoring webui and extensions from a known working set of commits
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
import json
|
| 7 |
+
import tqdm
|
| 8 |
+
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
import git
|
| 11 |
+
|
| 12 |
+
from modules import shared, extensions, errors
|
| 13 |
+
from modules.paths_internal import script_path, config_states_dir
|
| 14 |
+
|
| 15 |
+
all_config_states = {}
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def list_config_states():
|
| 19 |
+
global all_config_states
|
| 20 |
+
|
| 21 |
+
all_config_states.clear()
|
| 22 |
+
os.makedirs(config_states_dir, exist_ok=True)
|
| 23 |
+
|
| 24 |
+
config_states = []
|
| 25 |
+
for filename in os.listdir(config_states_dir):
|
| 26 |
+
if filename.endswith(".json"):
|
| 27 |
+
path = os.path.join(config_states_dir, filename)
|
| 28 |
+
try:
|
| 29 |
+
with open(path, "r", encoding="utf-8") as f:
|
| 30 |
+
j = json.load(f)
|
| 31 |
+
assert "created_at" in j, '"created_at" does not exist'
|
| 32 |
+
j["filepath"] = path
|
| 33 |
+
config_states.append(j)
|
| 34 |
+
except Exception as e:
|
| 35 |
+
print(f'[ERROR]: Config states {path}, {e}')
|
| 36 |
+
|
| 37 |
+
config_states = sorted(config_states, key=lambda cs: cs["created_at"], reverse=True)
|
| 38 |
+
|
| 39 |
+
for cs in config_states:
|
| 40 |
+
timestamp = datetime.fromtimestamp(cs["created_at"]).strftime('%Y-%m-%d %H:%M:%S')
|
| 41 |
+
name = cs.get("name", "Config")
|
| 42 |
+
full_name = f"{name}: {timestamp}"
|
| 43 |
+
all_config_states[full_name] = cs
|
| 44 |
+
|
| 45 |
+
return all_config_states
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def get_webui_config():
|
| 49 |
+
webui_repo = None
|
| 50 |
+
|
| 51 |
+
try:
|
| 52 |
+
if os.path.exists(os.path.join(script_path, ".git")):
|
| 53 |
+
webui_repo = git.Repo(script_path)
|
| 54 |
+
except Exception:
|
| 55 |
+
errors.report(f"Error reading webui git info from {script_path}", exc_info=True)
|
| 56 |
+
|
| 57 |
+
webui_remote = None
|
| 58 |
+
webui_commit_hash = None
|
| 59 |
+
webui_commit_date = None
|
| 60 |
+
webui_branch = None
|
| 61 |
+
if webui_repo and not webui_repo.bare:
|
| 62 |
+
try:
|
| 63 |
+
webui_remote = next(webui_repo.remote().urls, None)
|
| 64 |
+
head = webui_repo.head.commit
|
| 65 |
+
webui_commit_date = webui_repo.head.commit.committed_date
|
| 66 |
+
webui_commit_hash = head.hexsha
|
| 67 |
+
webui_branch = webui_repo.active_branch.name
|
| 68 |
+
|
| 69 |
+
except Exception:
|
| 70 |
+
webui_remote = None
|
| 71 |
+
|
| 72 |
+
return {
|
| 73 |
+
"remote": webui_remote,
|
| 74 |
+
"commit_hash": webui_commit_hash,
|
| 75 |
+
"commit_date": webui_commit_date,
|
| 76 |
+
"branch": webui_branch,
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def get_extension_config():
|
| 81 |
+
ext_config = {}
|
| 82 |
+
|
| 83 |
+
for ext in extensions.extensions:
|
| 84 |
+
ext.read_info_from_repo()
|
| 85 |
+
|
| 86 |
+
entry = {
|
| 87 |
+
"name": ext.name,
|
| 88 |
+
"path": ext.path,
|
| 89 |
+
"enabled": ext.enabled,
|
| 90 |
+
"is_builtin": ext.is_builtin,
|
| 91 |
+
"remote": ext.remote,
|
| 92 |
+
"commit_hash": ext.commit_hash,
|
| 93 |
+
"commit_date": ext.commit_date,
|
| 94 |
+
"branch": ext.branch,
|
| 95 |
+
"have_info_from_repo": ext.have_info_from_repo
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
ext_config[ext.name] = entry
|
| 99 |
+
|
| 100 |
+
return ext_config
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def get_config():
|
| 104 |
+
creation_time = datetime.now().timestamp()
|
| 105 |
+
webui_config = get_webui_config()
|
| 106 |
+
ext_config = get_extension_config()
|
| 107 |
+
|
| 108 |
+
return {
|
| 109 |
+
"created_at": creation_time,
|
| 110 |
+
"webui": webui_config,
|
| 111 |
+
"extensions": ext_config
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def restore_webui_config(config):
|
| 116 |
+
print("* Restoring webui state...")
|
| 117 |
+
|
| 118 |
+
if "webui" not in config:
|
| 119 |
+
print("Error: No webui data saved to config")
|
| 120 |
+
return
|
| 121 |
+
|
| 122 |
+
webui_config = config["webui"]
|
| 123 |
+
|
| 124 |
+
if "commit_hash" not in webui_config:
|
| 125 |
+
print("Error: No commit saved to webui config")
|
| 126 |
+
return
|
| 127 |
+
|
| 128 |
+
webui_commit_hash = webui_config.get("commit_hash", None)
|
| 129 |
+
webui_repo = None
|
| 130 |
+
|
| 131 |
+
try:
|
| 132 |
+
if os.path.exists(os.path.join(script_path, ".git")):
|
| 133 |
+
webui_repo = git.Repo(script_path)
|
| 134 |
+
except Exception:
|
| 135 |
+
errors.report(f"Error reading webui git info from {script_path}", exc_info=True)
|
| 136 |
+
return
|
| 137 |
+
|
| 138 |
+
try:
|
| 139 |
+
webui_repo.git.fetch(all=True)
|
| 140 |
+
webui_repo.git.reset(webui_commit_hash, hard=True)
|
| 141 |
+
print(f"* Restored webui to commit {webui_commit_hash}.")
|
| 142 |
+
except Exception:
|
| 143 |
+
errors.report(f"Error restoring webui to commit{webui_commit_hash}")
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def restore_extension_config(config):
|
| 147 |
+
print("* Restoring extension state...")
|
| 148 |
+
|
| 149 |
+
if "extensions" not in config:
|
| 150 |
+
print("Error: No extension data saved to config")
|
| 151 |
+
return
|
| 152 |
+
|
| 153 |
+
ext_config = config["extensions"]
|
| 154 |
+
|
| 155 |
+
results = []
|
| 156 |
+
disabled = []
|
| 157 |
+
|
| 158 |
+
for ext in tqdm.tqdm(extensions.extensions):
|
| 159 |
+
if ext.is_builtin:
|
| 160 |
+
continue
|
| 161 |
+
|
| 162 |
+
ext.read_info_from_repo()
|
| 163 |
+
current_commit = ext.commit_hash
|
| 164 |
+
|
| 165 |
+
if ext.name not in ext_config:
|
| 166 |
+
ext.disabled = True
|
| 167 |
+
disabled.append(ext.name)
|
| 168 |
+
results.append((ext, current_commit[:8], False, "Saved extension state not found in config, marking as disabled"))
|
| 169 |
+
continue
|
| 170 |
+
|
| 171 |
+
entry = ext_config[ext.name]
|
| 172 |
+
|
| 173 |
+
if "commit_hash" in entry and entry["commit_hash"]:
|
| 174 |
+
try:
|
| 175 |
+
ext.fetch_and_reset_hard(entry["commit_hash"])
|
| 176 |
+
ext.read_info_from_repo()
|
| 177 |
+
if current_commit != entry["commit_hash"]:
|
| 178 |
+
results.append((ext, current_commit[:8], True, entry["commit_hash"][:8]))
|
| 179 |
+
except Exception as ex:
|
| 180 |
+
results.append((ext, current_commit[:8], False, ex))
|
| 181 |
+
else:
|
| 182 |
+
results.append((ext, current_commit[:8], False, "No commit hash found in config"))
|
| 183 |
+
|
| 184 |
+
if not entry.get("enabled", False):
|
| 185 |
+
ext.disabled = True
|
| 186 |
+
disabled.append(ext.name)
|
| 187 |
+
else:
|
| 188 |
+
ext.disabled = False
|
| 189 |
+
|
| 190 |
+
shared.opts.disabled_extensions = disabled
|
| 191 |
+
shared.opts.save(shared.config_filename)
|
| 192 |
+
|
| 193 |
+
print("* Finished restoring extensions. Results:")
|
| 194 |
+
for ext, prev_commit, success, result in results:
|
| 195 |
+
if success:
|
| 196 |
+
print(f" + {ext.name}: {prev_commit} -> {result}")
|
| 197 |
+
else:
|
| 198 |
+
print(f" ! {ext.name}: FAILURE ({result})")
|
modules/devices.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import contextlib
|
| 2 |
+
import torch
|
| 3 |
+
from backend import memory_management
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def has_xpu() -> bool:
|
| 7 |
+
return memory_management.xpu_available
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def has_mps() -> bool:
|
| 11 |
+
return memory_management.mps_mode()
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def cuda_no_autocast(device_id=None) -> bool:
|
| 15 |
+
return False
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def get_cuda_device_id():
|
| 19 |
+
return memory_management.get_torch_device().index
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def get_cuda_device_string():
|
| 23 |
+
return str(memory_management.get_torch_device())
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def get_optimal_device_name():
|
| 27 |
+
return memory_management.get_torch_device().type
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def get_optimal_device():
|
| 31 |
+
return memory_management.get_torch_device()
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def get_device_for(task):
|
| 35 |
+
return memory_management.get_torch_device()
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def torch_gc():
|
| 39 |
+
memory_management.soft_empty_cache()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def torch_npu_set_device():
|
| 43 |
+
return
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def enable_tf32():
|
| 47 |
+
return
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
cpu: torch.device = torch.device("cpu")
|
| 51 |
+
fp8: bool = False
|
| 52 |
+
device: torch.device = memory_management.get_torch_device()
|
| 53 |
+
device_gfpgan: torch.device = memory_management.get_torch_device() # will be managed by memory management system
|
| 54 |
+
device_esrgan: torch.device = memory_management.get_torch_device() # will be managed by memory management system
|
| 55 |
+
device_codeformer: torch.device = memory_management.get_torch_device() # will be managed by memory management system
|
| 56 |
+
dtype: torch.dtype = torch.float32 if memory_management.unet_dtype() is torch.float32 else torch.float16
|
| 57 |
+
dtype_vae: torch.dtype = memory_management.vae_dtype()
|
| 58 |
+
dtype_unet: torch.dtype = memory_management.unet_dtype()
|
| 59 |
+
dtype_inference: torch.dtype = memory_management.unet_dtype()
|
| 60 |
+
unet_needs_upcast = False
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def cond_cast_unet(input):
|
| 64 |
+
return input
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def cond_cast_float(input):
|
| 68 |
+
return input
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
nv_rng = None
|
| 72 |
+
patch_module_list = []
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def manual_cast_forward(target_dtype):
|
| 76 |
+
return
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
@contextlib.contextmanager
|
| 80 |
+
def manual_cast(target_dtype):
|
| 81 |
+
return
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def autocast(disable=False):
|
| 85 |
+
return contextlib.nullcontext()
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def without_autocast(disable=False):
|
| 89 |
+
return contextlib.nullcontext()
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class NansException(Exception):
|
| 93 |
+
pass
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def test_for_nans(x, where):
|
| 97 |
+
return
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def first_time_calculation():
|
| 101 |
+
return
|
modules/errors.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
import textwrap
|
| 3 |
+
import traceback
|
| 4 |
+
|
| 5 |
+
exception_records = []
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def format_traceback(tb):
|
| 9 |
+
return [[f"{x.filename}, line {x.lineno}, {x.name}", x.line] for x in traceback.extract_tb(tb)]
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def format_exception(e, tb):
|
| 13 |
+
return {"exception": str(e), "traceback": format_traceback(tb)}
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def get_exceptions():
|
| 17 |
+
try:
|
| 18 |
+
return list(reversed(exception_records))
|
| 19 |
+
except Exception as e:
|
| 20 |
+
return str(e)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def record_exception():
|
| 24 |
+
_, e, tb = sys.exc_info()
|
| 25 |
+
if e is None:
|
| 26 |
+
return
|
| 27 |
+
|
| 28 |
+
if exception_records and exception_records[-1] == e:
|
| 29 |
+
return
|
| 30 |
+
|
| 31 |
+
exception_records.append(format_exception(e, tb))
|
| 32 |
+
|
| 33 |
+
if len(exception_records) > 5:
|
| 34 |
+
exception_records.pop(0)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def report(message: str, *, exc_info: bool = False) -> None:
|
| 38 |
+
"""
|
| 39 |
+
Print an error message to stderr, with optional traceback.
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
record_exception()
|
| 43 |
+
|
| 44 |
+
for line in message.splitlines():
|
| 45 |
+
print("***", line, file=sys.stderr)
|
| 46 |
+
if exc_info:
|
| 47 |
+
print(textwrap.indent(traceback.format_exc(), " "), file=sys.stderr)
|
| 48 |
+
print("---", file=sys.stderr)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def print_error_explanation(message):
|
| 52 |
+
record_exception()
|
| 53 |
+
|
| 54 |
+
lines = message.strip().split("\n")
|
| 55 |
+
max_len = max([len(x) for x in lines])
|
| 56 |
+
|
| 57 |
+
print("=" * max_len, file=sys.stderr)
|
| 58 |
+
for line in lines:
|
| 59 |
+
print(line, file=sys.stderr)
|
| 60 |
+
print("=" * max_len, file=sys.stderr)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def display(e: Exception, task, *, full_traceback=False):
|
| 64 |
+
record_exception()
|
| 65 |
+
|
| 66 |
+
print(f"{task or 'error'}: {type(e).__name__}", file=sys.stderr)
|
| 67 |
+
te = traceback.TracebackException.from_exception(e)
|
| 68 |
+
if full_traceback:
|
| 69 |
+
# include frames leading up to the try-catch block
|
| 70 |
+
te.stack = traceback.StackSummary(traceback.extract_stack()[:-2] + te.stack)
|
| 71 |
+
print(*te.format(), sep="", file=sys.stderr)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
already_displayed = {}
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def display_once(e: Exception, task):
|
| 78 |
+
record_exception()
|
| 79 |
+
|
| 80 |
+
if task in already_displayed:
|
| 81 |
+
return
|
| 82 |
+
|
| 83 |
+
display(e, task)
|
| 84 |
+
|
| 85 |
+
already_displayed[task] = 1
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def run(code, task):
|
| 89 |
+
try:
|
| 90 |
+
code()
|
| 91 |
+
except Exception as e:
|
| 92 |
+
display(task, e)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def check_versions():
|
| 96 |
+
import gradio
|
| 97 |
+
import torch
|
| 98 |
+
from packaging import version
|
| 99 |
+
|
| 100 |
+
from modules import shared
|
| 101 |
+
|
| 102 |
+
expected_torch = "2.9.0"
|
| 103 |
+
expected_xformers = "0.0.33"
|
| 104 |
+
expected_gradio = "4.40.0"
|
| 105 |
+
|
| 106 |
+
_outdated = False
|
| 107 |
+
|
| 108 |
+
if version.parse(torch.__version__) < version.parse(expected_torch):
|
| 109 |
+
_outdated = True
|
| 110 |
+
print_error_explanation(
|
| 111 |
+
f"""
|
| 112 |
+
You are running torch {torch.__version__}, which is really outdated.
|
| 113 |
+
To install the latest version, run with commandline flag --reinstall-torch.
|
| 114 |
+
""".strip()
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
if shared.xformers_available:
|
| 118 |
+
import xformers
|
| 119 |
+
|
| 120 |
+
if version.parse(xformers.__version__) < version.parse(expected_xformers):
|
| 121 |
+
_outdated = True
|
| 122 |
+
print_error_explanation(
|
| 123 |
+
f"""
|
| 124 |
+
You are running xformers {xformers.__version__}, which is really outdated.
|
| 125 |
+
To install the latest version, run with commandline flag --reinstall-xformers.
|
| 126 |
+
""".strip()
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
if version.parse(gradio.__version__) < version.parse(expected_gradio):
|
| 130 |
+
_outdated = True
|
| 131 |
+
print_error_explanation(
|
| 132 |
+
f"""
|
| 133 |
+
You are running gradio {gradio.__version__}.
|
| 134 |
+
This program was built on gradio {expected_gradio}.
|
| 135 |
+
Using a different version of gradio is likely to break the program.
|
| 136 |
+
""".strip()
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
if _outdated:
|
| 140 |
+
print("\nUse --skip-version-check commandline argument to disable the version check(s).\n")
|
modules/esrgan_model.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
from functools import lru_cache
|
| 3 |
+
|
| 4 |
+
from PIL import Image
|
| 5 |
+
|
| 6 |
+
from modules import devices, errors, modelloader
|
| 7 |
+
from modules.shared import opts
|
| 8 |
+
from modules.upscaler import Upscaler, UpscalerData
|
| 9 |
+
from modules.upscaler_utils import upscale_with_model
|
| 10 |
+
from modules_forge.utils import prepare_free_memory
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
PREFER_HALF = opts.prefer_fp16_upscalers
|
| 14 |
+
if PREFER_HALF:
|
| 15 |
+
print("[Upscalers] Prefer Half-Precision:", PREFER_HALF)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class UpscalerESRGAN(Upscaler):
|
| 19 |
+
def __init__(self, dirname: str):
|
| 20 |
+
self.user_path = dirname
|
| 21 |
+
self.model_path = dirname
|
| 22 |
+
super().__init__(True)
|
| 23 |
+
|
| 24 |
+
self.name = "ESRGAN"
|
| 25 |
+
self.model_url = "https://github.com/cszn/KAIR/releases/download/v1.0/ESRGAN.pth"
|
| 26 |
+
self.model_name = "ESRGAN"
|
| 27 |
+
self.scalers = []
|
| 28 |
+
|
| 29 |
+
model_paths = self.find_models(ext_filter=[".pt", ".pth", ".safetensors"])
|
| 30 |
+
if len(model_paths) == 0:
|
| 31 |
+
scaler_data = UpscalerData(self.model_name, self.model_url, self, 4)
|
| 32 |
+
self.scalers.append(scaler_data)
|
| 33 |
+
|
| 34 |
+
for file in model_paths:
|
| 35 |
+
if file.startswith("http"):
|
| 36 |
+
name = self.model_name
|
| 37 |
+
else:
|
| 38 |
+
name = modelloader.friendly_name(file)
|
| 39 |
+
|
| 40 |
+
if match := re.search(r"(\d)[xX]|[xX](\d)", name):
|
| 41 |
+
scale = int(match.group(1) or match.group(2))
|
| 42 |
+
else:
|
| 43 |
+
scale = 4
|
| 44 |
+
|
| 45 |
+
scaler_data = UpscalerData(name, file, self, scale)
|
| 46 |
+
self.scalers.append(scaler_data)
|
| 47 |
+
|
| 48 |
+
def do_upscale(self, img: Image.Image, selected_model: str):
|
| 49 |
+
prepare_free_memory()
|
| 50 |
+
try:
|
| 51 |
+
model = self.load_model(selected_model)
|
| 52 |
+
except Exception:
|
| 53 |
+
errors.report(f"Unable to load {selected_model}", exc_info=True)
|
| 54 |
+
return img
|
| 55 |
+
return upscale_with_model(
|
| 56 |
+
model=model,
|
| 57 |
+
img=img,
|
| 58 |
+
tile_size=opts.ESRGAN_tile,
|
| 59 |
+
tile_overlap=opts.ESRGAN_tile_overlap,
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
@lru_cache(maxsize=4, typed=False)
|
| 63 |
+
def load_model(self, path: str):
|
| 64 |
+
if not path.startswith("http"):
|
| 65 |
+
filename = path
|
| 66 |
+
else:
|
| 67 |
+
filename = modelloader.load_file_from_url(
|
| 68 |
+
url=path,
|
| 69 |
+
model_dir=self.model_download_path,
|
| 70 |
+
file_name=path.rsplit("/", 1)[-1],
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
model = modelloader.load_spandrel_model(filename, device="cpu", prefer_half=PREFER_HALF)
|
| 74 |
+
model.to(devices.device_esrgan)
|
| 75 |
+
return model
|
modules/extensions.py
ADDED
|
@@ -0,0 +1,311 @@
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import configparser
|
| 4 |
+
import dataclasses
|
| 5 |
+
import os
|
| 6 |
+
import threading
|
| 7 |
+
import re
|
| 8 |
+
import json
|
| 9 |
+
|
| 10 |
+
from modules import shared, errors, cache, scripts
|
| 11 |
+
from modules.gitpython_hack import Repo
|
| 12 |
+
from modules.paths_internal import extensions_dir, extensions_builtin_dir, script_path # noqa: F401
|
| 13 |
+
from modules_forge.config import always_disabled_extensions
|
| 14 |
+
|
| 15 |
+
extensions: list[Extension] = []
|
| 16 |
+
extension_paths: dict[str, Extension] = {}
|
| 17 |
+
loaded_extensions: dict[str, Exception] = {}
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
os.makedirs(extensions_dir, exist_ok=True)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def active():
|
| 24 |
+
if shared.cmd_opts.disable_all_extensions or shared.opts.disable_all_extensions == "all":
|
| 25 |
+
return []
|
| 26 |
+
elif shared.cmd_opts.disable_extra_extensions or shared.opts.disable_all_extensions == "extra":
|
| 27 |
+
return [x for x in extensions if x.enabled and x.is_builtin]
|
| 28 |
+
else:
|
| 29 |
+
return [x for x in extensions if x.enabled]
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@dataclasses.dataclass
|
| 33 |
+
class CallbackOrderInfo:
|
| 34 |
+
name: str
|
| 35 |
+
before: list
|
| 36 |
+
after: list
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class ExtensionMetadata:
|
| 40 |
+
filename = "metadata.ini"
|
| 41 |
+
config: configparser.ConfigParser
|
| 42 |
+
canonical_name: str
|
| 43 |
+
requires: list
|
| 44 |
+
|
| 45 |
+
def __init__(self, path, canonical_name):
|
| 46 |
+
self.config = configparser.ConfigParser()
|
| 47 |
+
|
| 48 |
+
filepath = os.path.join(path, self.filename)
|
| 49 |
+
# `self.config.read()` will quietly swallow OSErrors (which FileNotFoundError is),
|
| 50 |
+
# so no need to check whether the file exists beforehand.
|
| 51 |
+
try:
|
| 52 |
+
self.config.read(filepath)
|
| 53 |
+
except Exception:
|
| 54 |
+
errors.report(f"Error reading {self.filename} for extension {canonical_name}.", exc_info=True)
|
| 55 |
+
|
| 56 |
+
self.canonical_name = self.config.get("Extension", "Name", fallback=canonical_name)
|
| 57 |
+
self.canonical_name = canonical_name.lower().strip()
|
| 58 |
+
|
| 59 |
+
self.requires = None
|
| 60 |
+
|
| 61 |
+
def get_script_requirements(self, field, section, extra_section=None):
|
| 62 |
+
"""reads a list of requirements from the config; field is the name of the field in the ini file,
|
| 63 |
+
like Requires or Before, and section is the name of the [section] in the ini file; additionally,
|
| 64 |
+
reads more requirements from [extra_section] if specified."""
|
| 65 |
+
|
| 66 |
+
x = self.config.get(section, field, fallback='')
|
| 67 |
+
|
| 68 |
+
if extra_section:
|
| 69 |
+
x = x + ', ' + self.config.get(extra_section, field, fallback='')
|
| 70 |
+
|
| 71 |
+
listed_requirements = self.parse_list(x.lower())
|
| 72 |
+
res = []
|
| 73 |
+
|
| 74 |
+
for requirement in listed_requirements:
|
| 75 |
+
loaded_requirements = (x for x in requirement.split("|") if x in loaded_extensions)
|
| 76 |
+
relevant_requirement = next(loaded_requirements, requirement)
|
| 77 |
+
res.append(relevant_requirement)
|
| 78 |
+
|
| 79 |
+
return res
|
| 80 |
+
|
| 81 |
+
def parse_list(self, text):
|
| 82 |
+
"""converts a line from config ("ext1 ext2, ext3 ") into a python list (["ext1", "ext2", "ext3"])"""
|
| 83 |
+
|
| 84 |
+
if not text:
|
| 85 |
+
return []
|
| 86 |
+
|
| 87 |
+
# both "," and " " are accepted as separator
|
| 88 |
+
return [x for x in re.split(r"[,\s]+", text.strip()) if x]
|
| 89 |
+
|
| 90 |
+
def list_callback_order_instructions(self):
|
| 91 |
+
for section in self.config.sections():
|
| 92 |
+
if not section.startswith("callbacks/"):
|
| 93 |
+
continue
|
| 94 |
+
|
| 95 |
+
callback_name = section[10:]
|
| 96 |
+
|
| 97 |
+
if not callback_name.startswith(self.canonical_name):
|
| 98 |
+
errors.report(f"Callback order section for extension {self.canonical_name} is referencing the wrong extension: {section}")
|
| 99 |
+
continue
|
| 100 |
+
|
| 101 |
+
before = self.parse_list(self.config.get(section, 'Before', fallback=''))
|
| 102 |
+
after = self.parse_list(self.config.get(section, 'After', fallback=''))
|
| 103 |
+
|
| 104 |
+
yield CallbackOrderInfo(callback_name, before, after)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
class Extension:
|
| 108 |
+
lock = threading.Lock()
|
| 109 |
+
cached_fields = ['remote', 'commit_date', 'branch', 'commit_hash', 'version']
|
| 110 |
+
metadata: ExtensionMetadata
|
| 111 |
+
|
| 112 |
+
def __init__(self, name, path, enabled=True, is_builtin=False, metadata=None):
|
| 113 |
+
self.name = name
|
| 114 |
+
self.path = path
|
| 115 |
+
self.enabled = enabled
|
| 116 |
+
self.status = ''
|
| 117 |
+
self.can_update = False
|
| 118 |
+
self.is_builtin = is_builtin
|
| 119 |
+
self.commit_hash = ''
|
| 120 |
+
self.commit_date = None
|
| 121 |
+
self.version = ''
|
| 122 |
+
self.branch = None
|
| 123 |
+
self.remote = None
|
| 124 |
+
self.have_info_from_repo = False
|
| 125 |
+
self.metadata = metadata if metadata else ExtensionMetadata(self.path, name.lower())
|
| 126 |
+
self.canonical_name = metadata.canonical_name
|
| 127 |
+
|
| 128 |
+
def to_dict(self):
|
| 129 |
+
return {x: getattr(self, x) for x in self.cached_fields}
|
| 130 |
+
|
| 131 |
+
def from_dict(self, d):
|
| 132 |
+
for field in self.cached_fields:
|
| 133 |
+
setattr(self, field, d[field])
|
| 134 |
+
|
| 135 |
+
def read_info_from_repo(self):
|
| 136 |
+
if self.is_builtin or self.have_info_from_repo:
|
| 137 |
+
return
|
| 138 |
+
|
| 139 |
+
def read_from_repo():
|
| 140 |
+
with self.lock:
|
| 141 |
+
if self.have_info_from_repo:
|
| 142 |
+
return
|
| 143 |
+
|
| 144 |
+
self.do_read_info_from_repo()
|
| 145 |
+
|
| 146 |
+
return self.to_dict()
|
| 147 |
+
|
| 148 |
+
try:
|
| 149 |
+
d = cache.cached_data_for_file('extensions-git', self.name, os.path.join(self.path, ".git"), read_from_repo)
|
| 150 |
+
self.from_dict(d)
|
| 151 |
+
except FileNotFoundError:
|
| 152 |
+
pass
|
| 153 |
+
self.status = 'unknown' if self.status == '' else self.status
|
| 154 |
+
|
| 155 |
+
def do_read_info_from_repo(self):
|
| 156 |
+
repo = None
|
| 157 |
+
try:
|
| 158 |
+
if os.path.exists(os.path.join(self.path, ".git")):
|
| 159 |
+
repo = Repo(self.path)
|
| 160 |
+
except Exception:
|
| 161 |
+
errors.report(f"Error reading github repository info from {self.path}", exc_info=True)
|
| 162 |
+
|
| 163 |
+
if repo is None or repo.bare:
|
| 164 |
+
self.remote = None
|
| 165 |
+
else:
|
| 166 |
+
try:
|
| 167 |
+
self.remote = next(repo.remote().urls, None)
|
| 168 |
+
commit = repo.head.commit
|
| 169 |
+
self.commit_date = commit.committed_date
|
| 170 |
+
if repo.active_branch:
|
| 171 |
+
self.branch = repo.active_branch.name
|
| 172 |
+
self.commit_hash = commit.hexsha
|
| 173 |
+
self.version = self.commit_hash[:8]
|
| 174 |
+
|
| 175 |
+
except Exception:
|
| 176 |
+
errors.report(f"Failed reading extension data from Git repository ({self.name})", exc_info=True)
|
| 177 |
+
self.remote = None
|
| 178 |
+
|
| 179 |
+
self.have_info_from_repo = True
|
| 180 |
+
|
| 181 |
+
def list_files(self, subdir, extension):
|
| 182 |
+
dirpath = os.path.join(self.path, subdir)
|
| 183 |
+
if not os.path.isdir(dirpath):
|
| 184 |
+
return []
|
| 185 |
+
|
| 186 |
+
res = []
|
| 187 |
+
for filename in sorted(os.listdir(dirpath)):
|
| 188 |
+
res.append(scripts.ScriptFile(self.path, filename, os.path.join(dirpath, filename)))
|
| 189 |
+
|
| 190 |
+
res = [x for x in res if os.path.splitext(x.path)[1].lower() == extension and os.path.isfile(x.path)]
|
| 191 |
+
|
| 192 |
+
return res
|
| 193 |
+
|
| 194 |
+
def check_updates(self):
|
| 195 |
+
repo = Repo(self.path)
|
| 196 |
+
branch_name = f'{repo.remote().name}/{self.branch}'
|
| 197 |
+
for fetch in repo.remote().fetch(dry_run=True):
|
| 198 |
+
if self.branch and fetch.name != branch_name:
|
| 199 |
+
continue
|
| 200 |
+
if fetch.flags != fetch.HEAD_UPTODATE:
|
| 201 |
+
self.can_update = True
|
| 202 |
+
self.status = "new commits"
|
| 203 |
+
return
|
| 204 |
+
|
| 205 |
+
try:
|
| 206 |
+
origin = repo.rev_parse(branch_name)
|
| 207 |
+
if repo.head.commit != origin:
|
| 208 |
+
self.can_update = True
|
| 209 |
+
self.status = "behind HEAD"
|
| 210 |
+
return
|
| 211 |
+
except Exception:
|
| 212 |
+
self.can_update = False
|
| 213 |
+
self.status = "unknown (remote error)"
|
| 214 |
+
return
|
| 215 |
+
|
| 216 |
+
self.can_update = False
|
| 217 |
+
self.status = "latest"
|
| 218 |
+
|
| 219 |
+
def fetch_and_reset_hard(self, commit=None):
|
| 220 |
+
repo = Repo(self.path)
|
| 221 |
+
if commit is None:
|
| 222 |
+
commit = f'{repo.remote().name}/{self.branch}'
|
| 223 |
+
# Fix: `error: Your local changes to the following files would be overwritten by merge`,
|
| 224 |
+
# because WSL2 Docker set 755 file permissions instead of 644, this results to the error.
|
| 225 |
+
repo.git.fetch(all=True)
|
| 226 |
+
repo.git.reset(commit, hard=True)
|
| 227 |
+
self.have_info_from_repo = False
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def list_extensions():
|
| 231 |
+
extensions.clear()
|
| 232 |
+
extension_paths.clear()
|
| 233 |
+
loaded_extensions.clear()
|
| 234 |
+
|
| 235 |
+
if shared.cmd_opts.disable_all_extensions:
|
| 236 |
+
print("*** \"--disable-all-extensions\" arg was used, will not load any extensions ***")
|
| 237 |
+
elif shared.opts.disable_all_extensions == "all":
|
| 238 |
+
print("*** \"Disable all extensions\" option was set, will not load any extensions ***")
|
| 239 |
+
elif shared.cmd_opts.disable_extra_extensions:
|
| 240 |
+
print("*** \"--disable-extra-extensions\" arg was used, will only load built-in extensions ***")
|
| 241 |
+
elif shared.opts.disable_all_extensions == "extra":
|
| 242 |
+
print("*** \"Disable all extensions\" option was set, will only load built-in extensions ***")
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
# scan through extensions directory and load metadata
|
| 246 |
+
for dirname in [extensions_builtin_dir, extensions_dir]:
|
| 247 |
+
if not os.path.isdir(dirname):
|
| 248 |
+
continue
|
| 249 |
+
|
| 250 |
+
for extension_dirname in sorted(os.listdir(dirname)):
|
| 251 |
+
path = os.path.join(dirname, extension_dirname)
|
| 252 |
+
if not os.path.isdir(path):
|
| 253 |
+
continue
|
| 254 |
+
|
| 255 |
+
canonical_name = extension_dirname
|
| 256 |
+
metadata = ExtensionMetadata(path, canonical_name)
|
| 257 |
+
|
| 258 |
+
# check for duplicated canonical names
|
| 259 |
+
already_loaded_extension = loaded_extensions.get(metadata.canonical_name)
|
| 260 |
+
if already_loaded_extension is not None:
|
| 261 |
+
errors.report(f'Duplicate canonical name "{canonical_name}" found in extensions "{extension_dirname}" and "{already_loaded_extension.name}". Former will be discarded.', exc_info=False)
|
| 262 |
+
continue
|
| 263 |
+
|
| 264 |
+
is_builtin = dirname == extensions_builtin_dir
|
| 265 |
+
|
| 266 |
+
disabled_extensions = shared.opts.disabled_extensions + always_disabled_extensions
|
| 267 |
+
|
| 268 |
+
extension = Extension(
|
| 269 |
+
name=extension_dirname,
|
| 270 |
+
path=path,
|
| 271 |
+
enabled=extension_dirname not in disabled_extensions,
|
| 272 |
+
is_builtin=is_builtin,
|
| 273 |
+
metadata=metadata
|
| 274 |
+
)
|
| 275 |
+
|
| 276 |
+
extensions.append(extension)
|
| 277 |
+
extension_paths[extension.path] = extension
|
| 278 |
+
loaded_extensions[canonical_name] = extension
|
| 279 |
+
|
| 280 |
+
for extension in extensions:
|
| 281 |
+
extension.metadata.requires = extension.metadata.get_script_requirements("Requires", "Extension")
|
| 282 |
+
|
| 283 |
+
# check for requirements
|
| 284 |
+
for extension in extensions:
|
| 285 |
+
if not extension.enabled:
|
| 286 |
+
continue
|
| 287 |
+
|
| 288 |
+
for req in extension.metadata.requires:
|
| 289 |
+
required_extension = loaded_extensions.get(req)
|
| 290 |
+
if required_extension is None:
|
| 291 |
+
errors.report(f'Extension "{extension.name}" requires "{req}" which is not installed.', exc_info=False)
|
| 292 |
+
continue
|
| 293 |
+
|
| 294 |
+
if not required_extension.enabled:
|
| 295 |
+
errors.report(f'Extension "{extension.name}" requires "{required_extension.name}" which is disabled.', exc_info=False)
|
| 296 |
+
continue
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def find_extension(filename):
|
| 300 |
+
parentdir = os.path.dirname(os.path.realpath(filename))
|
| 301 |
+
|
| 302 |
+
while parentdir != filename:
|
| 303 |
+
extension = extension_paths.get(parentdir)
|
| 304 |
+
if extension is not None:
|
| 305 |
+
return extension
|
| 306 |
+
|
| 307 |
+
filename = parentdir
|
| 308 |
+
parentdir = os.path.dirname(filename)
|
| 309 |
+
|
| 310 |
+
return None
|
| 311 |
+
|
modules/extra_networks.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
import re
|
| 4 |
+
import logging
|
| 5 |
+
from collections import defaultdict
|
| 6 |
+
|
| 7 |
+
from modules import errors
|
| 8 |
+
|
| 9 |
+
extra_network_registry = {}
|
| 10 |
+
extra_network_aliases = {}
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def initialize():
|
| 14 |
+
extra_network_registry.clear()
|
| 15 |
+
extra_network_aliases.clear()
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def register_extra_network(extra_network):
|
| 19 |
+
extra_network_registry[extra_network.name] = extra_network
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def register_extra_network_alias(extra_network, alias):
|
| 23 |
+
extra_network_aliases[alias] = extra_network
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class ExtraNetworkParams:
|
| 27 |
+
def __init__(self, items=None):
|
| 28 |
+
self.items = items or []
|
| 29 |
+
self.positional = []
|
| 30 |
+
self.named = {}
|
| 31 |
+
|
| 32 |
+
for item in self.items:
|
| 33 |
+
parts = item.split('=', 2) if isinstance(item, str) else [item]
|
| 34 |
+
if len(parts) == 2:
|
| 35 |
+
self.named[parts[0]] = parts[1]
|
| 36 |
+
else:
|
| 37 |
+
self.positional.append(item)
|
| 38 |
+
|
| 39 |
+
def __eq__(self, other):
|
| 40 |
+
return self.items == other.items
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class ExtraNetwork:
|
| 44 |
+
def __init__(self, name):
|
| 45 |
+
self.name = name
|
| 46 |
+
|
| 47 |
+
def activate(self, p, params_list):
|
| 48 |
+
"""
|
| 49 |
+
Called by processing on every run. Whatever the extra network is meant to do should be activated here.
|
| 50 |
+
Passes arguments related to this extra network in params_list.
|
| 51 |
+
User passes arguments by specifying this in his prompt:
|
| 52 |
+
|
| 53 |
+
<name:arg1:arg2:arg3>
|
| 54 |
+
|
| 55 |
+
Where name matches the name of this ExtraNetwork object, and arg1:arg2:arg3 are any natural number of text arguments
|
| 56 |
+
separated by colon.
|
| 57 |
+
|
| 58 |
+
Even if the user does not mention this ExtraNetwork in his prompt, the call will still be made, with empty params_list -
|
| 59 |
+
in this case, all effects of this extra networks should be disabled.
|
| 60 |
+
|
| 61 |
+
Can be called multiple times before deactivate() - each new call should override the previous call completely.
|
| 62 |
+
"""
|
| 63 |
+
raise NotImplementedError
|
| 64 |
+
|
| 65 |
+
def deactivate(self, p):
|
| 66 |
+
"""
|
| 67 |
+
Called at the end of processing for housekeeping. No need to do anything here.
|
| 68 |
+
"""
|
| 69 |
+
|
| 70 |
+
raise NotImplementedError
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def lookup_extra_networks(extra_network_data):
|
| 74 |
+
"""
|
| 75 |
+
returns a dict mapping ExtraNetwork objects to lists of arguments for those extra networks.
|
| 76 |
+
|
| 77 |
+
Example input:
|
| 78 |
+
{
|
| 79 |
+
'lora': [<modules.extra_networks.ExtraNetworkParams object at 0x0000020690D58310>],
|
| 80 |
+
'lyco': [<modules.extra_networks.ExtraNetworkParams object at 0x0000020690D58F70>],
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
Example output:
|
| 84 |
+
|
| 85 |
+
{
|
| 86 |
+
<extra_networks_lora.ExtraNetworkLora object at 0x0000020581BEECE0>: [<modules.extra_networks.ExtraNetworkParams object at 0x0000020690D58310>, <modules.extra_networks.ExtraNetworkParams object at 0x0000020690D58F70>],
|
| 87 |
+
}
|
| 88 |
+
"""
|
| 89 |
+
|
| 90 |
+
res = {}
|
| 91 |
+
|
| 92 |
+
for extra_network_name, extra_network_args in list(extra_network_data.items()):
|
| 93 |
+
extra_network = extra_network_registry.get(extra_network_name, None)
|
| 94 |
+
alias = extra_network_aliases.get(extra_network_name, None)
|
| 95 |
+
|
| 96 |
+
if alias is not None and extra_network is None:
|
| 97 |
+
extra_network = alias
|
| 98 |
+
|
| 99 |
+
if extra_network is None:
|
| 100 |
+
logging.info(f"Skipping unknown extra network: {extra_network_name}")
|
| 101 |
+
continue
|
| 102 |
+
|
| 103 |
+
res.setdefault(extra_network, []).extend(extra_network_args)
|
| 104 |
+
|
| 105 |
+
return res
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def activate(p, extra_network_data):
|
| 109 |
+
"""call activate for extra networks in extra_network_data in specified order, then call
|
| 110 |
+
activate for all remaining registered networks with an empty argument list"""
|
| 111 |
+
|
| 112 |
+
activated = []
|
| 113 |
+
|
| 114 |
+
for extra_network, extra_network_args in lookup_extra_networks(extra_network_data).items():
|
| 115 |
+
|
| 116 |
+
try:
|
| 117 |
+
extra_network.activate(p, extra_network_args)
|
| 118 |
+
activated.append(extra_network)
|
| 119 |
+
except Exception as e:
|
| 120 |
+
errors.display(e, f"activating extra network {extra_network.name} with arguments {extra_network_args}")
|
| 121 |
+
|
| 122 |
+
for extra_network_name, extra_network in extra_network_registry.items():
|
| 123 |
+
if extra_network in activated:
|
| 124 |
+
continue
|
| 125 |
+
|
| 126 |
+
try:
|
| 127 |
+
extra_network.activate(p, [])
|
| 128 |
+
except Exception as e:
|
| 129 |
+
errors.display(e, f"activating extra network {extra_network_name}")
|
| 130 |
+
|
| 131 |
+
if p.scripts is not None:
|
| 132 |
+
p.scripts.after_extra_networks_activate(p, batch_number=p.iteration, prompts=p.prompts, seeds=p.seeds, subseeds=p.subseeds, extra_network_data=extra_network_data)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def deactivate(p, extra_network_data):
|
| 136 |
+
"""call deactivate for extra networks in extra_network_data in specified order, then call
|
| 137 |
+
deactivate for all remaining registered networks"""
|
| 138 |
+
|
| 139 |
+
data = lookup_extra_networks(extra_network_data)
|
| 140 |
+
|
| 141 |
+
for extra_network in data:
|
| 142 |
+
try:
|
| 143 |
+
extra_network.deactivate(p)
|
| 144 |
+
except Exception as e:
|
| 145 |
+
errors.display(e, f"deactivating extra network {extra_network.name}")
|
| 146 |
+
|
| 147 |
+
for extra_network_name, extra_network in extra_network_registry.items():
|
| 148 |
+
if extra_network in data:
|
| 149 |
+
continue
|
| 150 |
+
|
| 151 |
+
try:
|
| 152 |
+
extra_network.deactivate(p)
|
| 153 |
+
except Exception as e:
|
| 154 |
+
errors.display(e, f"deactivating unmentioned extra network {extra_network_name}")
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
re_extra_net = re.compile(r"<(\w+):([^>]+)>")
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def parse_prompt(prompt):
|
| 161 |
+
res = defaultdict(list)
|
| 162 |
+
|
| 163 |
+
def found(m):
|
| 164 |
+
name = m.group(1)
|
| 165 |
+
args = m.group(2)
|
| 166 |
+
|
| 167 |
+
res[name].append(ExtraNetworkParams(items=args.split(":")))
|
| 168 |
+
|
| 169 |
+
return ""
|
| 170 |
+
|
| 171 |
+
prompt = re.sub(re_extra_net, found, prompt)
|
| 172 |
+
|
| 173 |
+
return prompt, res
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def parse_prompts(prompts):
|
| 177 |
+
res = []
|
| 178 |
+
extra_data = None
|
| 179 |
+
|
| 180 |
+
for prompt in prompts:
|
| 181 |
+
updated_prompt, parsed_extra_data = parse_prompt(prompt)
|
| 182 |
+
|
| 183 |
+
if extra_data is None:
|
| 184 |
+
extra_data = parsed_extra_data
|
| 185 |
+
|
| 186 |
+
res.append(updated_prompt)
|
| 187 |
+
|
| 188 |
+
return res, extra_data
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def get_user_metadata(filename, lister=None):
|
| 192 |
+
if filename is None:
|
| 193 |
+
return {}
|
| 194 |
+
|
| 195 |
+
basename, ext = os.path.splitext(filename)
|
| 196 |
+
metadata_filename = basename + '.json'
|
| 197 |
+
|
| 198 |
+
metadata = {}
|
| 199 |
+
try:
|
| 200 |
+
exists = lister.exists(metadata_filename) if lister else os.path.exists(metadata_filename)
|
| 201 |
+
if exists:
|
| 202 |
+
with open(metadata_filename, "r", encoding="utf8") as file:
|
| 203 |
+
metadata = json.load(file)
|
| 204 |
+
except Exception as e:
|
| 205 |
+
errors.display(e, f"reading extra network user metadata from {metadata_filename}")
|
| 206 |
+
|
| 207 |
+
return metadata
|
modules/extras.py
ADDED
|
@@ -0,0 +1,317 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
import re
|
| 4 |
+
|
| 5 |
+
import gradio as gr
|
| 6 |
+
import safetensors.torch
|
| 7 |
+
import torch
|
| 8 |
+
import tqdm
|
| 9 |
+
|
| 10 |
+
from backend.utils import load_torch_file
|
| 11 |
+
from modules import errors, images, sd_models, sd_vae, shared
|
| 12 |
+
from modules.ui_common import plaintext_to_html
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def run_pnginfo(image):
|
| 16 |
+
if image is None:
|
| 17 |
+
return "", "", ""
|
| 18 |
+
|
| 19 |
+
geninfo, items = images.read_info_from_image(image)
|
| 20 |
+
items = {**{"parameters": geninfo}, **items}
|
| 21 |
+
|
| 22 |
+
info = ""
|
| 23 |
+
for key, text in items.items():
|
| 24 |
+
info += (
|
| 25 |
+
f"""
|
| 26 |
+
<div>
|
| 27 |
+
<p><b>{plaintext_to_html(str(key))}</b></p>
|
| 28 |
+
<p>{plaintext_to_html(str(text))}</p>
|
| 29 |
+
</div>
|
| 30 |
+
""".strip()
|
| 31 |
+
+ "\n"
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
if len(info) == 0:
|
| 35 |
+
message = "Nothing found in the image."
|
| 36 |
+
info = f"<div><p>{message}<p></div>"
|
| 37 |
+
|
| 38 |
+
return "", geninfo, info
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
checkpoint_dict_skip_on_merge = ["cond_stage_model.transformer.text_model.embeddings.position_ids"]
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def to_half(tensor, enable):
|
| 45 |
+
if enable and tensor.dtype == torch.float:
|
| 46 |
+
return tensor.half()
|
| 47 |
+
|
| 48 |
+
return tensor
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def read_metadata(primary_model_name, secondary_model_name, tertiary_model_name):
|
| 52 |
+
metadata = {}
|
| 53 |
+
|
| 54 |
+
for checkpoint_name in [primary_model_name, secondary_model_name, tertiary_model_name]:
|
| 55 |
+
checkpoint_info = sd_models.checkpoints_list.get(checkpoint_name, None)
|
| 56 |
+
if checkpoint_info is None:
|
| 57 |
+
continue
|
| 58 |
+
|
| 59 |
+
metadata.update(checkpoint_info.metadata)
|
| 60 |
+
|
| 61 |
+
return json.dumps(metadata, indent=4, ensure_ascii=False)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def run_modelmerger(id_task, primary_model_name, secondary_model_name, tertiary_model_name, interp_method, multiplier, save_as_half, custom_name, checkpoint_format, config_source, bake_in_vae, discard_weights, save_metadata, add_merge_recipe, copy_metadata_fields, metadata_json):
|
| 65 |
+
shared.state.begin(job="model-merge")
|
| 66 |
+
|
| 67 |
+
def fail(message):
|
| 68 |
+
shared.state.textinfo = message
|
| 69 |
+
shared.state.end()
|
| 70 |
+
return [*[gr.skip() for _ in range(4)], message]
|
| 71 |
+
|
| 72 |
+
def weighted_sum(theta0, theta1, alpha):
|
| 73 |
+
return ((1 - alpha) * theta0) + (alpha * theta1)
|
| 74 |
+
|
| 75 |
+
def get_difference(theta1, theta2):
|
| 76 |
+
return theta1 - theta2
|
| 77 |
+
|
| 78 |
+
def add_difference(theta0, theta1_2_diff, alpha):
|
| 79 |
+
return theta0 + (alpha * theta1_2_diff)
|
| 80 |
+
|
| 81 |
+
def filename_weighted_sum():
|
| 82 |
+
a = primary_model_info.model_name
|
| 83 |
+
b = secondary_model_info.model_name
|
| 84 |
+
Ma = round(1 - multiplier, 2)
|
| 85 |
+
Mb = round(multiplier, 2)
|
| 86 |
+
|
| 87 |
+
return f"{Ma}({a}) + {Mb}({b})"
|
| 88 |
+
|
| 89 |
+
def filename_add_difference():
|
| 90 |
+
a = primary_model_info.model_name
|
| 91 |
+
b = secondary_model_info.model_name
|
| 92 |
+
c = tertiary_model_info.model_name
|
| 93 |
+
M = round(multiplier, 2)
|
| 94 |
+
|
| 95 |
+
return f"{a} + {M}({b} - {c})"
|
| 96 |
+
|
| 97 |
+
def filename_nothing():
|
| 98 |
+
return primary_model_info.model_name
|
| 99 |
+
|
| 100 |
+
theta_funcs = {
|
| 101 |
+
"Weighted sum": (filename_weighted_sum, None, weighted_sum),
|
| 102 |
+
"Add difference": (filename_add_difference, get_difference, add_difference),
|
| 103 |
+
"No interpolation": (filename_nothing, None, None),
|
| 104 |
+
}
|
| 105 |
+
filename_generator, theta_func1, theta_func2 = theta_funcs[interp_method]
|
| 106 |
+
shared.state.job_count = (1 if theta_func1 else 0) + (1 if theta_func2 else 0)
|
| 107 |
+
|
| 108 |
+
if not primary_model_name:
|
| 109 |
+
return fail("Failed: Merging requires a primary model.")
|
| 110 |
+
|
| 111 |
+
primary_model_info = sd_models.checkpoint_aliases[primary_model_name]
|
| 112 |
+
|
| 113 |
+
if theta_func2 and not secondary_model_name:
|
| 114 |
+
return fail("Failed: Merging requires a secondary model.")
|
| 115 |
+
|
| 116 |
+
secondary_model_info = sd_models.checkpoint_aliases[secondary_model_name] if theta_func2 else None
|
| 117 |
+
|
| 118 |
+
if theta_func1 and not tertiary_model_name:
|
| 119 |
+
return fail(f"Failed: Interpolation method ({interp_method}) requires a tertiary model.")
|
| 120 |
+
|
| 121 |
+
tertiary_model_info = sd_models.checkpoint_aliases[tertiary_model_name] if theta_func1 else None
|
| 122 |
+
|
| 123 |
+
result_is_inpainting_model = False
|
| 124 |
+
result_is_instruct_pix2pix_model = False
|
| 125 |
+
|
| 126 |
+
if theta_func2:
|
| 127 |
+
shared.state.textinfo = "Loading B"
|
| 128 |
+
print(f"Loading {secondary_model_info.filename}...")
|
| 129 |
+
theta_1 = load_torch_file(secondary_model_info.filename)
|
| 130 |
+
else:
|
| 131 |
+
theta_1 = None
|
| 132 |
+
|
| 133 |
+
if theta_func1:
|
| 134 |
+
shared.state.textinfo = "Loading C"
|
| 135 |
+
print(f"Loading {tertiary_model_info.filename}...")
|
| 136 |
+
theta_2 = load_torch_file(tertiary_model_info.filename)
|
| 137 |
+
|
| 138 |
+
shared.state.textinfo = "Merging B and C"
|
| 139 |
+
shared.state.sampling_steps = len(theta_1.keys())
|
| 140 |
+
for key in tqdm.tqdm(theta_1.keys()):
|
| 141 |
+
if key in checkpoint_dict_skip_on_merge:
|
| 142 |
+
continue
|
| 143 |
+
|
| 144 |
+
if "model" in key:
|
| 145 |
+
if key in theta_2:
|
| 146 |
+
t2 = theta_2.get(key, torch.zeros_like(theta_1[key]))
|
| 147 |
+
theta_1[key] = theta_func1(theta_1[key], t2)
|
| 148 |
+
else:
|
| 149 |
+
theta_1[key] = torch.zeros_like(theta_1[key])
|
| 150 |
+
|
| 151 |
+
shared.state.sampling_step += 1
|
| 152 |
+
del theta_2
|
| 153 |
+
|
| 154 |
+
shared.state.nextjob()
|
| 155 |
+
|
| 156 |
+
shared.state.textinfo = f"Loading {primary_model_info.filename}..."
|
| 157 |
+
print(f"Loading {primary_model_info.filename}...")
|
| 158 |
+
theta_0 = load_torch_file(primary_model_info.filename)
|
| 159 |
+
|
| 160 |
+
print("Merging...")
|
| 161 |
+
shared.state.textinfo = "Merging A and B"
|
| 162 |
+
shared.state.sampling_steps = len(theta_0.keys())
|
| 163 |
+
for key in tqdm.tqdm(theta_0.keys()):
|
| 164 |
+
if theta_1 and "model" in key and key in theta_1:
|
| 165 |
+
|
| 166 |
+
if key in checkpoint_dict_skip_on_merge:
|
| 167 |
+
continue
|
| 168 |
+
|
| 169 |
+
a = theta_0[key]
|
| 170 |
+
b = theta_1[key]
|
| 171 |
+
|
| 172 |
+
# this enables merging an inpainting model (A) with another one (B);
|
| 173 |
+
# where normal model would have 4 channels, for latenst space, inpainting model would
|
| 174 |
+
# have another 4 channels for unmasked picture's latent space, plus one channel for mask, for a total of 9
|
| 175 |
+
if a.shape != b.shape and a.shape[0:1] + a.shape[2:] == b.shape[0:1] + b.shape[2:]:
|
| 176 |
+
if a.shape[1] == 4 and b.shape[1] == 9:
|
| 177 |
+
raise RuntimeError("When merging inpainting model with a normal one, A must be the inpainting model.")
|
| 178 |
+
if a.shape[1] == 4 and b.shape[1] == 8:
|
| 179 |
+
raise RuntimeError("When merging instruct-pix2pix model with a normal one, A must be the instruct-pix2pix model.")
|
| 180 |
+
|
| 181 |
+
if a.shape[1] == 8 and b.shape[1] == 4: # If we have an Instruct-Pix2Pix model...
|
| 182 |
+
theta_0[key][:, 0:4, :, :] = theta_func2(a[:, 0:4, :, :], b, multiplier) # Merge only the vectors the models have in common. Otherwise we get an error due to dimension mismatch.
|
| 183 |
+
result_is_instruct_pix2pix_model = True
|
| 184 |
+
else:
|
| 185 |
+
assert a.shape[1] == 9 and b.shape[1] == 4, f"Bad dimensions for merged layer {key}: A={a.shape}, B={b.shape}"
|
| 186 |
+
theta_0[key][:, 0:4, :, :] = theta_func2(a[:, 0:4, :, :], b, multiplier)
|
| 187 |
+
result_is_inpainting_model = True
|
| 188 |
+
else:
|
| 189 |
+
theta_0[key] = theta_func2(a, b, multiplier)
|
| 190 |
+
|
| 191 |
+
theta_0[key] = to_half(theta_0[key], save_as_half)
|
| 192 |
+
|
| 193 |
+
shared.state.sampling_step += 1
|
| 194 |
+
|
| 195 |
+
del theta_1
|
| 196 |
+
|
| 197 |
+
bake_in_vae_filename = sd_vae.vae_dict.get(bake_in_vae, None)
|
| 198 |
+
if bake_in_vae_filename is not None:
|
| 199 |
+
print(f"Baking in VAE from {bake_in_vae_filename}")
|
| 200 |
+
shared.state.textinfo = "Baking in VAE"
|
| 201 |
+
vae_dict = load_torch_file(bake_in_vae_filename)
|
| 202 |
+
|
| 203 |
+
for key in vae_dict.keys():
|
| 204 |
+
theta_0_key = "first_stage_model." + key
|
| 205 |
+
if theta_0_key in theta_0:
|
| 206 |
+
theta_0[theta_0_key] = to_half(vae_dict[key], save_as_half)
|
| 207 |
+
|
| 208 |
+
del vae_dict
|
| 209 |
+
|
| 210 |
+
if save_as_half and not theta_func2:
|
| 211 |
+
for key in theta_0.keys():
|
| 212 |
+
theta_0[key] = to_half(theta_0[key], save_as_half)
|
| 213 |
+
|
| 214 |
+
if discard_weights:
|
| 215 |
+
regex = re.compile(discard_weights)
|
| 216 |
+
for key in list(theta_0):
|
| 217 |
+
if re.search(regex, key):
|
| 218 |
+
theta_0.pop(key, None)
|
| 219 |
+
|
| 220 |
+
filename = filename_generator() if custom_name == "" else custom_name
|
| 221 |
+
filename += ".inpainting" if result_is_inpainting_model else ""
|
| 222 |
+
filename += ".instruct-pix2pix" if result_is_instruct_pix2pix_model else ""
|
| 223 |
+
filename += "." + checkpoint_format
|
| 224 |
+
|
| 225 |
+
output_modelname = os.path.join(sd_models.model_path, filename)
|
| 226 |
+
|
| 227 |
+
shared.state.nextjob()
|
| 228 |
+
shared.state.textinfo = "Saving"
|
| 229 |
+
print(f"Saving to {output_modelname}...")
|
| 230 |
+
|
| 231 |
+
metadata = {}
|
| 232 |
+
|
| 233 |
+
if save_metadata and copy_metadata_fields:
|
| 234 |
+
if primary_model_info:
|
| 235 |
+
metadata.update(primary_model_info.metadata)
|
| 236 |
+
if secondary_model_info:
|
| 237 |
+
metadata.update(secondary_model_info.metadata)
|
| 238 |
+
if tertiary_model_info:
|
| 239 |
+
metadata.update(tertiary_model_info.metadata)
|
| 240 |
+
|
| 241 |
+
if save_metadata:
|
| 242 |
+
try:
|
| 243 |
+
metadata.update(json.loads(metadata_json))
|
| 244 |
+
except Exception as e:
|
| 245 |
+
errors.display(e, "readin metadata from json")
|
| 246 |
+
|
| 247 |
+
metadata["format"] = "pt"
|
| 248 |
+
|
| 249 |
+
if save_metadata and add_merge_recipe:
|
| 250 |
+
merge_recipe = {
|
| 251 |
+
"type": "webui", # indicate this model was merged with webui's built-in merger
|
| 252 |
+
"primary_model_hash": primary_model_info.sha256,
|
| 253 |
+
"secondary_model_hash": secondary_model_info.sha256 if secondary_model_info else None,
|
| 254 |
+
"tertiary_model_hash": tertiary_model_info.sha256 if tertiary_model_info else None,
|
| 255 |
+
"interp_method": interp_method,
|
| 256 |
+
"multiplier": multiplier,
|
| 257 |
+
"save_as_half": save_as_half,
|
| 258 |
+
"custom_name": custom_name,
|
| 259 |
+
"config_source": config_source,
|
| 260 |
+
"bake_in_vae": bake_in_vae,
|
| 261 |
+
"discard_weights": discard_weights,
|
| 262 |
+
"is_inpainting": result_is_inpainting_model,
|
| 263 |
+
"is_instruct_pix2pix": result_is_instruct_pix2pix_model,
|
| 264 |
+
}
|
| 265 |
+
|
| 266 |
+
sd_merge_models = {}
|
| 267 |
+
|
| 268 |
+
def add_model_metadata(checkpoint_info):
|
| 269 |
+
checkpoint_info.calculate_shorthash()
|
| 270 |
+
sd_merge_models[checkpoint_info.sha256] = {
|
| 271 |
+
"name": checkpoint_info.name,
|
| 272 |
+
"legacy_hash": checkpoint_info.hash,
|
| 273 |
+
"sd_merge_recipe": checkpoint_info.metadata.get("sd_merge_recipe", None),
|
| 274 |
+
}
|
| 275 |
+
|
| 276 |
+
sd_merge_models.update(checkpoint_info.metadata.get("sd_merge_models", {}))
|
| 277 |
+
|
| 278 |
+
add_model_metadata(primary_model_info)
|
| 279 |
+
if secondary_model_info:
|
| 280 |
+
add_model_metadata(secondary_model_info)
|
| 281 |
+
if tertiary_model_info:
|
| 282 |
+
add_model_metadata(tertiary_model_info)
|
| 283 |
+
|
| 284 |
+
metadata["sd_merge_recipe"] = json.dumps(merge_recipe)
|
| 285 |
+
metadata["sd_merge_models"] = json.dumps(sd_merge_models)
|
| 286 |
+
|
| 287 |
+
def sanitize_metadata(meta_dict: dict) -> dict | None:
|
| 288 |
+
if not meta_dict:
|
| 289 |
+
return None
|
| 290 |
+
sanitized = {}
|
| 291 |
+
for key, value in meta_dict.items():
|
| 292 |
+
if value is None:
|
| 293 |
+
sanitized[key] = ""
|
| 294 |
+
elif isinstance(value, str):
|
| 295 |
+
sanitized[key] = value
|
| 296 |
+
elif isinstance(value, (dict, list)):
|
| 297 |
+
sanitized[key] = json.dumps(value)
|
| 298 |
+
else:
|
| 299 |
+
sanitized[key] = str(value)
|
| 300 |
+
return sanitized
|
| 301 |
+
|
| 302 |
+
_, extension = os.path.splitext(output_modelname)
|
| 303 |
+
if extension.lower() == ".safetensors":
|
| 304 |
+
safetensors.torch.save_file(theta_0, output_modelname, metadata=sanitize_metadata(metadata))
|
| 305 |
+
else:
|
| 306 |
+
torch.save(theta_0, output_modelname)
|
| 307 |
+
|
| 308 |
+
sd_models.list_models()
|
| 309 |
+
created_model = next((ckpt for ckpt in sd_models.checkpoints_list.values() if ckpt.name == filename), None)
|
| 310 |
+
if created_model:
|
| 311 |
+
created_model.calculate_shorthash()
|
| 312 |
+
|
| 313 |
+
print(f"Checkpoint saved to {output_modelname}.")
|
| 314 |
+
shared.state.textinfo = "Checkpoint saved"
|
| 315 |
+
shared.state.end()
|
| 316 |
+
|
| 317 |
+
return [*[gr.update(choices=sd_models.checkpoint_tiles()) for _ in range(4)], "Checkpoint saved to " + output_modelname]
|
modules/face_restoration.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from modules import shared
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class FaceRestoration:
|
| 5 |
+
def name(self):
|
| 6 |
+
return "None"
|
| 7 |
+
|
| 8 |
+
def restore(self, np_image):
|
| 9 |
+
return np_image
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def restore_faces(np_image):
|
| 13 |
+
face_restorers = [x for x in shared.face_restorers if x.name() == shared.opts.face_restoration_model or shared.opts.face_restoration_model is None]
|
| 14 |
+
if len(face_restorers) == 0:
|
| 15 |
+
return np_image
|
| 16 |
+
|
| 17 |
+
face_restorer = face_restorers[0]
|
| 18 |
+
|
| 19 |
+
return face_restorer.restore(np_image)
|
modules/face_restoration_utils.py
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
from functools import cached_property
|
| 5 |
+
from typing import TYPE_CHECKING, Callable
|
| 6 |
+
|
| 7 |
+
import cv2
|
| 8 |
+
import numpy as np
|
| 9 |
+
import torch
|
| 10 |
+
|
| 11 |
+
from modules import devices, errors, face_restoration, shared
|
| 12 |
+
from modules_forge.utils import prepare_free_memory
|
| 13 |
+
|
| 14 |
+
if TYPE_CHECKING:
|
| 15 |
+
from facexlib.utils.face_restoration_helper import FaceRestoreHelper
|
| 16 |
+
|
| 17 |
+
logger = logging.getLogger(__name__)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def bgr_image_to_rgb_tensor(img: np.ndarray) -> torch.Tensor:
|
| 21 |
+
"""Convert a BGR NumPy image in [0..1] range to a PyTorch RGB float32 tensor."""
|
| 22 |
+
assert img.shape[2] == 3, "image must be RGB"
|
| 23 |
+
if img.dtype == "float64":
|
| 24 |
+
img = img.astype("float32")
|
| 25 |
+
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
|
| 26 |
+
return torch.from_numpy(img.transpose(2, 0, 1)).float()
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def rgb_tensor_to_bgr_image(tensor: torch.Tensor, *, min_max=(0.0, 1.0)) -> np.ndarray:
|
| 30 |
+
"""
|
| 31 |
+
Convert a PyTorch RGB tensor in range `min_max` to a BGR NumPy image in [0..1] range.
|
| 32 |
+
"""
|
| 33 |
+
tensor = tensor.squeeze(0).float().detach().cpu().clamp_(*min_max)
|
| 34 |
+
tensor = (tensor - min_max[0]) / (min_max[1] - min_max[0])
|
| 35 |
+
assert tensor.dim() == 3, "tensor must be RGB"
|
| 36 |
+
img_np = tensor.numpy().transpose(1, 2, 0)
|
| 37 |
+
if img_np.shape[2] == 1: # gray image, no RGB/BGR required
|
| 38 |
+
return np.squeeze(img_np, axis=2)
|
| 39 |
+
return cv2.cvtColor(img_np, cv2.COLOR_BGR2RGB)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def create_face_helper(device) -> FaceRestoreHelper:
|
| 43 |
+
from facexlib.detection import retinaface
|
| 44 |
+
from facexlib.utils.face_restoration_helper import FaceRestoreHelper
|
| 45 |
+
|
| 46 |
+
if hasattr(retinaface, "device"):
|
| 47 |
+
retinaface.device = device
|
| 48 |
+
return FaceRestoreHelper(
|
| 49 |
+
upscale_factor=1,
|
| 50 |
+
face_size=512,
|
| 51 |
+
crop_ratio=(1, 1),
|
| 52 |
+
det_model="retinaface_resnet50",
|
| 53 |
+
save_ext="png",
|
| 54 |
+
use_parse=True,
|
| 55 |
+
device=device,
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def restore_with_face_helper(
|
| 60 |
+
np_image: np.ndarray,
|
| 61 |
+
face_helper: FaceRestoreHelper,
|
| 62 |
+
restore_face: Callable[[torch.Tensor], torch.Tensor],
|
| 63 |
+
) -> np.ndarray:
|
| 64 |
+
"""
|
| 65 |
+
Find faces in the image using face_helper, restore them using restore_face, and paste them back into the image.
|
| 66 |
+
|
| 67 |
+
`restore_face` should take a cropped face image and return a restored face image.
|
| 68 |
+
"""
|
| 69 |
+
from torchvision.transforms.functional import normalize
|
| 70 |
+
|
| 71 |
+
np_image = np_image[:, :, ::-1]
|
| 72 |
+
original_resolution = np_image.shape[0:2]
|
| 73 |
+
|
| 74 |
+
try:
|
| 75 |
+
logger.debug("Detecting faces...")
|
| 76 |
+
face_helper.clean_all()
|
| 77 |
+
face_helper.read_image(np_image)
|
| 78 |
+
face_helper.get_face_landmarks_5(only_center_face=False, resize=640, eye_dist_threshold=5)
|
| 79 |
+
face_helper.align_warp_face()
|
| 80 |
+
logger.debug("Found %d faces, restoring", len(face_helper.cropped_faces))
|
| 81 |
+
for cropped_face in face_helper.cropped_faces:
|
| 82 |
+
cropped_face_t = bgr_image_to_rgb_tensor(cropped_face / 255.0)
|
| 83 |
+
normalize(cropped_face_t, (0.5, 0.5, 0.5), (0.5, 0.5, 0.5), inplace=True)
|
| 84 |
+
cropped_face_t = cropped_face_t.unsqueeze(0).to(devices.device_codeformer)
|
| 85 |
+
|
| 86 |
+
try:
|
| 87 |
+
with torch.no_grad():
|
| 88 |
+
cropped_face_t = restore_face(cropped_face_t)
|
| 89 |
+
devices.torch_gc()
|
| 90 |
+
except Exception:
|
| 91 |
+
errors.report("Failed face-restoration inference", exc_info=True)
|
| 92 |
+
|
| 93 |
+
restored_face = rgb_tensor_to_bgr_image(cropped_face_t, min_max=(-1, 1))
|
| 94 |
+
restored_face = (restored_face * 255.0).astype("uint8")
|
| 95 |
+
face_helper.add_restored_face(restored_face)
|
| 96 |
+
|
| 97 |
+
logger.debug("Merging restored faces into image")
|
| 98 |
+
face_helper.get_inverse_affine(None)
|
| 99 |
+
img = face_helper.paste_faces_to_input_image()
|
| 100 |
+
img = img[:, :, ::-1]
|
| 101 |
+
if original_resolution != img.shape[0:2]:
|
| 102 |
+
img = cv2.resize(
|
| 103 |
+
img,
|
| 104 |
+
(0, 0),
|
| 105 |
+
fx=original_resolution[1] / img.shape[1],
|
| 106 |
+
fy=original_resolution[0] / img.shape[0],
|
| 107 |
+
interpolation=cv2.INTER_LINEAR,
|
| 108 |
+
)
|
| 109 |
+
logger.debug("Face restoration complete")
|
| 110 |
+
finally:
|
| 111 |
+
face_helper.clean_all()
|
| 112 |
+
return img
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
class CommonFaceRestoration(face_restoration.FaceRestoration):
|
| 116 |
+
net: torch.nn.Module | None
|
| 117 |
+
model_url: str
|
| 118 |
+
model_download_name: str
|
| 119 |
+
|
| 120 |
+
def __init__(self, model_path: str):
|
| 121 |
+
super().__init__()
|
| 122 |
+
self.net = None
|
| 123 |
+
self.model_path = model_path
|
| 124 |
+
|
| 125 |
+
@cached_property
|
| 126 |
+
def face_helper(self) -> FaceRestoreHelper:
|
| 127 |
+
return create_face_helper(self.get_device())
|
| 128 |
+
|
| 129 |
+
def send_model_to(self, device):
|
| 130 |
+
if self.net:
|
| 131 |
+
logger.debug("Sending %s to %s", self.net, device)
|
| 132 |
+
self.net.to(device)
|
| 133 |
+
if self.face_helper:
|
| 134 |
+
logger.debug("Sending face helper to %s", device)
|
| 135 |
+
self.face_helper.face_det.to(device)
|
| 136 |
+
self.face_helper.face_parse.to(device)
|
| 137 |
+
|
| 138 |
+
def get_device(self):
|
| 139 |
+
return devices.get_optimal_device()
|
| 140 |
+
|
| 141 |
+
def load_net(self) -> torch.nn.Module:
|
| 142 |
+
raise NotImplementedError
|
| 143 |
+
|
| 144 |
+
def restore_with_helper(
|
| 145 |
+
self,
|
| 146 |
+
np_image: np.ndarray,
|
| 147 |
+
restore_face: Callable[[torch.Tensor], torch.Tensor],
|
| 148 |
+
) -> np.ndarray:
|
| 149 |
+
try:
|
| 150 |
+
if self.net is None:
|
| 151 |
+
self.net = self.load_net()
|
| 152 |
+
except Exception:
|
| 153 |
+
logger.warning("Unable to load face-restoration model", exc_info=True)
|
| 154 |
+
return np_image
|
| 155 |
+
|
| 156 |
+
try:
|
| 157 |
+
prepare_free_memory()
|
| 158 |
+
self.send_model_to(self.get_device())
|
| 159 |
+
return restore_with_face_helper(np_image, self.face_helper, restore_face)
|
| 160 |
+
finally:
|
| 161 |
+
if shared.opts.face_restoration_unload:
|
| 162 |
+
self.send_model_to(devices.cpu)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def patch_facexlib(dirname: str) -> None:
|
| 166 |
+
import facexlib.detection
|
| 167 |
+
import facexlib.parsing
|
| 168 |
+
|
| 169 |
+
det_facex_load_file_from_url = facexlib.detection.load_file_from_url
|
| 170 |
+
par_facex_load_file_from_url = facexlib.parsing.load_file_from_url
|
| 171 |
+
|
| 172 |
+
def update_kwargs(kwargs):
|
| 173 |
+
return dict(kwargs, save_dir=dirname, model_dir=None)
|
| 174 |
+
|
| 175 |
+
def facex_load_file_from_url(**kwargs):
|
| 176 |
+
return det_facex_load_file_from_url(**update_kwargs(kwargs))
|
| 177 |
+
|
| 178 |
+
def facex_load_file_from_url2(**kwargs):
|
| 179 |
+
return par_facex_load_file_from_url(**update_kwargs(kwargs))
|
| 180 |
+
|
| 181 |
+
facexlib.detection.load_file_from_url = facex_load_file_from_url
|
| 182 |
+
facexlib.parsing.load_file_from_url = facex_load_file_from_url2
|
modules/fifo_lock.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import threading
|
| 2 |
+
import collections
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
# reference: https://gist.github.com/vitaliyp/6d54dd76ca2c3cdfc1149d33007dc34a
|
| 6 |
+
class FIFOLock(object):
|
| 7 |
+
def __init__(self):
|
| 8 |
+
self._lock = threading.Lock()
|
| 9 |
+
self._inner_lock = threading.Lock()
|
| 10 |
+
self._pending_threads = collections.deque()
|
| 11 |
+
|
| 12 |
+
def acquire(self, blocking=True):
|
| 13 |
+
with self._inner_lock:
|
| 14 |
+
lock_acquired = self._lock.acquire(False)
|
| 15 |
+
if lock_acquired:
|
| 16 |
+
return True
|
| 17 |
+
elif not blocking:
|
| 18 |
+
return False
|
| 19 |
+
|
| 20 |
+
release_event = threading.Event()
|
| 21 |
+
self._pending_threads.append(release_event)
|
| 22 |
+
|
| 23 |
+
release_event.wait()
|
| 24 |
+
return self._lock.acquire()
|
| 25 |
+
|
| 26 |
+
def release(self):
|
| 27 |
+
with self._inner_lock:
|
| 28 |
+
if self._pending_threads:
|
| 29 |
+
release_event = self._pending_threads.popleft()
|
| 30 |
+
release_event.set()
|
| 31 |
+
|
| 32 |
+
self._lock.release()
|
| 33 |
+
|
| 34 |
+
__enter__ = acquire
|
| 35 |
+
|
| 36 |
+
def __exit__(self, t, v, tb):
|
| 37 |
+
self.release()
|
modules/gfpgan_model.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
from modules import (
|
| 7 |
+
devices,
|
| 8 |
+
errors,
|
| 9 |
+
face_restoration,
|
| 10 |
+
face_restoration_utils,
|
| 11 |
+
modelloader,
|
| 12 |
+
shared,
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
gfpgan_face_restorer: face_restoration.FaceRestoration | None = None
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class FaceRestorerGFPGAN(face_restoration_utils.CommonFaceRestoration):
|
| 19 |
+
def name(self):
|
| 20 |
+
return "GFPGAN"
|
| 21 |
+
|
| 22 |
+
def load_net(self) -> torch.nn.Module:
|
| 23 |
+
os.makedirs(self.model_path, exist_ok=True)
|
| 24 |
+
for model_path in modelloader.load_models(
|
| 25 |
+
model_path=self.model_path,
|
| 26 |
+
model_url="https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.4.pth",
|
| 27 |
+
command_path=self.model_path,
|
| 28 |
+
download_name="GFPGANv1.4.pth",
|
| 29 |
+
ext_filter=[".pth"],
|
| 30 |
+
):
|
| 31 |
+
return modelloader.load_spandrel_model(
|
| 32 |
+
model_path,
|
| 33 |
+
device=devices.device_gfpgan,
|
| 34 |
+
expected_architecture="GFPGAN",
|
| 35 |
+
).model
|
| 36 |
+
raise ValueError("No GFPGAN Model Found")
|
| 37 |
+
|
| 38 |
+
def restore(self, np_image):
|
| 39 |
+
def restore_face(cropped_face_t):
|
| 40 |
+
assert self.net is not None
|
| 41 |
+
return self.net(cropped_face_t, return_rgb=False)[0]
|
| 42 |
+
|
| 43 |
+
return self.restore_with_helper(np_image, restore_face)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def gfpgan_fix_faces(np_image):
|
| 47 |
+
if gfpgan_face_restorer:
|
| 48 |
+
return gfpgan_face_restorer.restore(np_image)
|
| 49 |
+
print("WARNING: GFPGAN face restorer was not set up")
|
| 50 |
+
return np_image
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def setup_model(dirname: str) -> None:
|
| 54 |
+
global gfpgan_face_restorer
|
| 55 |
+
|
| 56 |
+
try:
|
| 57 |
+
face_restoration_utils.patch_facexlib(dirname)
|
| 58 |
+
gfpgan_face_restorer = FaceRestorerGFPGAN(model_path=dirname)
|
| 59 |
+
shared.face_restorers.append(gfpgan_face_restorer)
|
| 60 |
+
except Exception:
|
| 61 |
+
errors.report("Error setting up GFPGAN", exc_info=True)
|
modules/gitpython_hack.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import io
|
| 4 |
+
import subprocess
|
| 5 |
+
|
| 6 |
+
import git
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class Git(git.Git):
|
| 10 |
+
"""
|
| 11 |
+
Git subclassed to never use persistent processes.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
def _get_persistent_cmd(self, attr_name, cmd_name, *args, **kwargs):
|
| 15 |
+
raise NotImplementedError(f"Refusing to use persistent process: {attr_name} ({cmd_name} {args} {kwargs})")
|
| 16 |
+
|
| 17 |
+
def get_object_header(self, ref: str | bytes) -> tuple[str, str, int]:
|
| 18 |
+
ret = subprocess.check_output(
|
| 19 |
+
[self.GIT_PYTHON_GIT_EXECUTABLE, "cat-file", "--batch-check"],
|
| 20 |
+
input=self._prepare_ref(ref),
|
| 21 |
+
cwd=self._working_dir,
|
| 22 |
+
timeout=2,
|
| 23 |
+
)
|
| 24 |
+
return self._parse_object_header(ret)
|
| 25 |
+
|
| 26 |
+
def stream_object_data(self, ref: str) -> tuple[str, str, int, Git.CatFileContentStream]:
|
| 27 |
+
# Not really streaming, per se; this buffers the entire object in memory.
|
| 28 |
+
# Shouldn't be a problem for our use case, since we're only using this for
|
| 29 |
+
# object headers (commit objects).
|
| 30 |
+
ret = subprocess.check_output(
|
| 31 |
+
[self.GIT_PYTHON_GIT_EXECUTABLE, "cat-file", "--batch"],
|
| 32 |
+
input=self._prepare_ref(ref),
|
| 33 |
+
cwd=self._working_dir,
|
| 34 |
+
timeout=30,
|
| 35 |
+
)
|
| 36 |
+
bio = io.BytesIO(ret)
|
| 37 |
+
hexsha, typename, size = self._parse_object_header(bio.readline())
|
| 38 |
+
return (hexsha, typename, size, self.CatFileContentStream(size, bio))
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class Repo(git.Repo):
|
| 42 |
+
GitCommandWrapperType = Git
|
modules/gradio_extensions.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import inspect
|
| 2 |
+
import warnings
|
| 3 |
+
from functools import wraps
|
| 4 |
+
|
| 5 |
+
import gradio as gr
|
| 6 |
+
import gradio.component_meta
|
| 7 |
+
|
| 8 |
+
from modules import patches, scripts, ui_tempdir
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class GradioDeprecationWarning(DeprecationWarning):
|
| 12 |
+
pass
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def add_classes_to_gradio_component(comp: gr.components.Component):
|
| 16 |
+
"""
|
| 17 |
+
this adds gradio-* to the component for css styling (ie gradio-button to gr.Button), as well as some others
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
comp.elem_classes = [f"gradio-{comp.get_block_name()}", *(getattr(comp, "elem_classes", None) or [])]
|
| 21 |
+
|
| 22 |
+
if getattr(comp, "multiselect", False):
|
| 23 |
+
comp.elem_classes.append("multiselect")
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def IOComponent_init(self, *args, **kwargs):
|
| 27 |
+
self.webui_tooltip = kwargs.pop("tooltip", None)
|
| 28 |
+
|
| 29 |
+
if scripts.scripts_current is not None:
|
| 30 |
+
scripts.scripts_current.before_component(self, **kwargs)
|
| 31 |
+
|
| 32 |
+
scripts.script_callbacks.before_component_callback(self, **kwargs)
|
| 33 |
+
|
| 34 |
+
res = original_IOComponent_init(self, *args, **kwargs)
|
| 35 |
+
|
| 36 |
+
add_classes_to_gradio_component(self)
|
| 37 |
+
|
| 38 |
+
scripts.script_callbacks.after_component_callback(self, **kwargs)
|
| 39 |
+
|
| 40 |
+
if scripts.scripts_current is not None:
|
| 41 |
+
scripts.scripts_current.after_component(self, **kwargs)
|
| 42 |
+
|
| 43 |
+
return res
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def Block_get_config(self):
|
| 47 |
+
config = original_Block_get_config(self)
|
| 48 |
+
|
| 49 |
+
webui_tooltip = getattr(self, "webui_tooltip", None)
|
| 50 |
+
if webui_tooltip:
|
| 51 |
+
config["webui_tooltip"] = webui_tooltip
|
| 52 |
+
|
| 53 |
+
config.pop("example_inputs", None)
|
| 54 |
+
|
| 55 |
+
return config
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def BlockContext_init(self, *args, **kwargs):
|
| 59 |
+
if scripts.scripts_current is not None:
|
| 60 |
+
scripts.scripts_current.before_component(self, **kwargs)
|
| 61 |
+
|
| 62 |
+
scripts.script_callbacks.before_component_callback(self, **kwargs)
|
| 63 |
+
|
| 64 |
+
res = original_BlockContext_init(self, *args, **kwargs)
|
| 65 |
+
|
| 66 |
+
add_classes_to_gradio_component(self)
|
| 67 |
+
|
| 68 |
+
scripts.script_callbacks.after_component_callback(self, **kwargs)
|
| 69 |
+
|
| 70 |
+
if scripts.scripts_current is not None:
|
| 71 |
+
scripts.scripts_current.after_component(self, **kwargs)
|
| 72 |
+
|
| 73 |
+
return res
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def Blocks_get_config_file(self, *args, **kwargs):
|
| 77 |
+
config = original_Blocks_get_config_file(self, *args, **kwargs)
|
| 78 |
+
|
| 79 |
+
for comp_config in config["components"]:
|
| 80 |
+
if "example_inputs" in comp_config:
|
| 81 |
+
comp_config["example_inputs"] = {"serialized": []}
|
| 82 |
+
|
| 83 |
+
return config
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
original_IOComponent_init = patches.patch(__name__, obj=gr.components.Component, field="__init__", replacement=IOComponent_init)
|
| 87 |
+
original_Block_get_config = patches.patch(__name__, obj=gr.blocks.Block, field="get_config", replacement=Block_get_config)
|
| 88 |
+
original_BlockContext_init = patches.patch(__name__, obj=gr.blocks.BlockContext, field="__init__", replacement=BlockContext_init)
|
| 89 |
+
original_Blocks_get_config_file = patches.patch(__name__, obj=gr.blocks.Blocks, field="get_config_file", replacement=Blocks_get_config_file)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
ui_tempdir.install_ui_tempdir_override()
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def gradio_component_meta_create_or_modify_pyi(component_class, class_name, events):
|
| 96 |
+
if hasattr(component_class, "webui_do_not_create_gradio_pyi_thank_you"):
|
| 97 |
+
return
|
| 98 |
+
|
| 99 |
+
gradio_component_meta_create_or_modify_pyi_original(component_class, class_name, events)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
# this prevents creation of .pyi files in webui dir
|
| 103 |
+
gradio_component_meta_create_or_modify_pyi_original = patches.patch(__file__, gradio.component_meta, "create_or_modify_pyi", gradio_component_meta_create_or_modify_pyi)
|
| 104 |
+
|
| 105 |
+
# this function is broken and does not seem to do anything useful
|
| 106 |
+
gradio.component_meta.updateable = lambda x: x
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class EventWrapper:
|
| 110 |
+
def __init__(self, replaced_event):
|
| 111 |
+
self.replaced_event = replaced_event
|
| 112 |
+
self.has_trigger = getattr(replaced_event, "has_trigger", None)
|
| 113 |
+
self.event_name = getattr(replaced_event, "event_name", None)
|
| 114 |
+
self.callback = getattr(replaced_event, "callback", None)
|
| 115 |
+
self.real_self = getattr(replaced_event, "__self__", None)
|
| 116 |
+
|
| 117 |
+
def __call__(self, *args, **kwargs):
|
| 118 |
+
if "_js" in kwargs:
|
| 119 |
+
kwargs["js"] = kwargs["_js"]
|
| 120 |
+
del kwargs["_js"]
|
| 121 |
+
return self.replaced_event(*args, **kwargs)
|
| 122 |
+
|
| 123 |
+
@property
|
| 124 |
+
def __self__(self):
|
| 125 |
+
return self.real_self
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def repair(grclass):
|
| 129 |
+
if not getattr(grclass, "EVENTS", None):
|
| 130 |
+
return
|
| 131 |
+
|
| 132 |
+
@wraps(grclass.__init__)
|
| 133 |
+
def __repaired_init__(self, *args, tooltip=None, source=None, original=grclass.__init__, **kwargs):
|
| 134 |
+
if source:
|
| 135 |
+
kwargs["sources"] = [source]
|
| 136 |
+
|
| 137 |
+
allowed_kwargs = inspect.signature(original).parameters
|
| 138 |
+
fixed_kwargs = {}
|
| 139 |
+
for k, v in kwargs.items():
|
| 140 |
+
if k in allowed_kwargs:
|
| 141 |
+
fixed_kwargs[k] = v
|
| 142 |
+
else:
|
| 143 |
+
warnings.warn(f"unexpected argument for {grclass.__name__}: {k}", GradioDeprecationWarning, stacklevel=2)
|
| 144 |
+
|
| 145 |
+
original(self, *args, **fixed_kwargs)
|
| 146 |
+
|
| 147 |
+
self.webui_tooltip = tooltip
|
| 148 |
+
|
| 149 |
+
for event in self.EVENTS:
|
| 150 |
+
replaced_event = getattr(self, str(event))
|
| 151 |
+
fun = EventWrapper(replaced_event)
|
| 152 |
+
setattr(self, str(event), fun)
|
| 153 |
+
|
| 154 |
+
grclass.__init__ = __repaired_init__
|
| 155 |
+
grclass.update = gr.update
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
for component in set(gr.components.__all__ + gr.layouts.__all__):
|
| 159 |
+
repair(getattr(gr, component, None))
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
class Dependency(gr.events.Dependency):
|
| 163 |
+
def __init__(self, *args, **kwargs):
|
| 164 |
+
super().__init__(*args, **kwargs)
|
| 165 |
+
|
| 166 |
+
def then(*xargs, _js=None, **xkwargs):
|
| 167 |
+
if _js:
|
| 168 |
+
xkwargs["js"] = _js
|
| 169 |
+
|
| 170 |
+
return original_then(*xargs, **xkwargs)
|
| 171 |
+
|
| 172 |
+
original_then = self.then
|
| 173 |
+
self.then = then
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
gr.events.Dependency = Dependency
|
| 177 |
+
|
| 178 |
+
gr.Box = gr.Group
|
modules/hashes.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import hashlib
|
| 2 |
+
import os.path
|
| 3 |
+
|
| 4 |
+
from modules import shared
|
| 5 |
+
import modules.cache
|
| 6 |
+
|
| 7 |
+
dump_cache = modules.cache.dump_cache
|
| 8 |
+
cache = modules.cache.cache
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def calculate_sha256_real(filename):
|
| 12 |
+
hash_sha256 = hashlib.sha256()
|
| 13 |
+
blksize = 1024 * 1024
|
| 14 |
+
|
| 15 |
+
with open(filename, "rb") as f:
|
| 16 |
+
for chunk in iter(lambda: f.read(blksize), b""):
|
| 17 |
+
hash_sha256.update(chunk)
|
| 18 |
+
|
| 19 |
+
return hash_sha256.hexdigest()
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def calculate_sha256(filename):
|
| 23 |
+
print("Calculating real hash: ", filename)
|
| 24 |
+
return calculate_sha256_real(filename)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def forge_fake_calculate_sha256(filename):
|
| 28 |
+
basename = os.path.basename(filename)
|
| 29 |
+
hash_sha256 = hashlib.sha256()
|
| 30 |
+
hash_sha256.update(basename.encode('utf-8'))
|
| 31 |
+
return hash_sha256.hexdigest()
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def sha256_from_cache(filename, title, use_addnet_hash=False):
|
| 35 |
+
hashes = cache("hashes-addnet") if use_addnet_hash else cache("hashes")
|
| 36 |
+
try:
|
| 37 |
+
ondisk_mtime = os.path.getmtime(filename)
|
| 38 |
+
except FileNotFoundError:
|
| 39 |
+
return None
|
| 40 |
+
|
| 41 |
+
if title not in hashes:
|
| 42 |
+
return None
|
| 43 |
+
|
| 44 |
+
cached_sha256 = hashes[title].get("sha256", None)
|
| 45 |
+
cached_mtime = hashes[title].get("mtime", 0)
|
| 46 |
+
|
| 47 |
+
if ondisk_mtime > cached_mtime or cached_sha256 is None:
|
| 48 |
+
return None
|
| 49 |
+
|
| 50 |
+
return cached_sha256
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def sha256(filename, title, use_addnet_hash=False):
|
| 54 |
+
hashes = cache("hashes-addnet") if use_addnet_hash else cache("hashes")
|
| 55 |
+
|
| 56 |
+
sha256_value = sha256_from_cache(filename, title, use_addnet_hash)
|
| 57 |
+
if sha256_value is not None:
|
| 58 |
+
return sha256_value
|
| 59 |
+
|
| 60 |
+
if shared.cmd_opts.no_hashing:
|
| 61 |
+
return None
|
| 62 |
+
|
| 63 |
+
print(f"Calculating sha256 for {filename}: ", end='', flush=True)
|
| 64 |
+
sha256_value = calculate_sha256_real(filename)
|
| 65 |
+
print(f"{sha256_value}")
|
| 66 |
+
|
| 67 |
+
hashes[title] = {
|
| 68 |
+
"mtime": os.path.getmtime(filename),
|
| 69 |
+
"sha256": sha256_value,
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
dump_cache()
|
| 73 |
+
|
| 74 |
+
return sha256_value
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def addnet_hash_safetensors(b):
|
| 78 |
+
"""kohya-ss hash for safetensors from https://github.com/kohya-ss/sd-scripts/blob/main/library/train_util.py"""
|
| 79 |
+
hash_sha256 = hashlib.sha256()
|
| 80 |
+
blksize = 1024 * 1024
|
| 81 |
+
|
| 82 |
+
b.seek(0)
|
| 83 |
+
header = b.read(8)
|
| 84 |
+
n = int.from_bytes(header, "little")
|
| 85 |
+
|
| 86 |
+
offset = n + 8
|
| 87 |
+
b.seek(offset)
|
| 88 |
+
for chunk in iter(lambda: b.read(blksize), b""):
|
| 89 |
+
hash_sha256.update(chunk)
|
| 90 |
+
|
| 91 |
+
return hash_sha256.hexdigest()
|
| 92 |
+
|
modules/images.py
ADDED
|
@@ -0,0 +1,972 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import datetime
|
| 4 |
+
import functools
|
| 5 |
+
import hashlib
|
| 6 |
+
import io
|
| 7 |
+
import json
|
| 8 |
+
import math
|
| 9 |
+
import os
|
| 10 |
+
import re
|
| 11 |
+
import string
|
| 12 |
+
import subprocess
|
| 13 |
+
from collections import namedtuple
|
| 14 |
+
|
| 15 |
+
import numpy as np
|
| 16 |
+
import piexif
|
| 17 |
+
import piexif.helper
|
| 18 |
+
import pillow_jxl # noqa
|
| 19 |
+
import pytz
|
| 20 |
+
from PIL import Image, ImageColor, ImageDraw, ImageFont, ImageOps, PngImagePlugin
|
| 21 |
+
from pillow_heif import register_heif_opener
|
| 22 |
+
|
| 23 |
+
from modules import errors, script_callbacks, sd_samplers, shared
|
| 24 |
+
from modules.paths_internal import roboto_ttf_file
|
| 25 |
+
from modules.shared import opts
|
| 26 |
+
|
| 27 |
+
register_heif_opener()
|
| 28 |
+
LANCZOS = Image.Resampling.LANCZOS
|
| 29 |
+
NEAREST = Image.Resampling.NEAREST
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def get_font(fontsize: int):
|
| 33 |
+
return ImageFont.truetype(roboto_ttf_file, fontsize)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def image_grid(imgs, batch_size=1, rows=None):
|
| 37 |
+
if rows is None:
|
| 38 |
+
if opts.n_rows > 0:
|
| 39 |
+
rows = opts.n_rows
|
| 40 |
+
elif opts.n_rows == 0:
|
| 41 |
+
rows = batch_size
|
| 42 |
+
elif opts.grid_prevent_empty_spots:
|
| 43 |
+
rows = math.floor(math.sqrt(len(imgs)))
|
| 44 |
+
while len(imgs) % rows != 0:
|
| 45 |
+
rows -= 1
|
| 46 |
+
else:
|
| 47 |
+
rows = math.sqrt(len(imgs))
|
| 48 |
+
rows = round(rows)
|
| 49 |
+
if rows > len(imgs):
|
| 50 |
+
rows = len(imgs)
|
| 51 |
+
|
| 52 |
+
cols = math.ceil(len(imgs) / rows)
|
| 53 |
+
|
| 54 |
+
params = script_callbacks.ImageGridLoopParams(imgs, cols, rows)
|
| 55 |
+
script_callbacks.image_grid_callback(params)
|
| 56 |
+
|
| 57 |
+
w, h = map(max, zip(*(img.size for img in imgs)))
|
| 58 |
+
grid_background_color = ImageColor.getcolor(opts.grid_background_color, 'RGBA')
|
| 59 |
+
grid = Image.new('RGBA', size=(params.cols * w, params.rows * h), color=grid_background_color)
|
| 60 |
+
|
| 61 |
+
for i, img in enumerate(params.imgs):
|
| 62 |
+
img_w, img_h = img.size
|
| 63 |
+
w_offset, h_offset = 0 if img_w == w else (w - img_w) // 2, 0 if img_h == h else (h - img_h) // 2
|
| 64 |
+
grid.paste(img, box=(i % params.cols * w + w_offset, i // params.cols * h + h_offset))
|
| 65 |
+
|
| 66 |
+
return grid
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class Grid(namedtuple("_Grid", ["tiles", "tile_w", "tile_h", "image_w", "image_h", "overlap"])):
|
| 70 |
+
@property
|
| 71 |
+
def tile_count(self) -> int:
|
| 72 |
+
"""
|
| 73 |
+
The total number of tiles in the grid.
|
| 74 |
+
"""
|
| 75 |
+
return sum(len(row[2]) for row in self.tiles)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def split_grid(image: Image.Image, tile_w: int = 512, tile_h: int = 512, overlap: int = 64) -> Grid:
|
| 79 |
+
w, h = image.size
|
| 80 |
+
|
| 81 |
+
non_overlap_width = tile_w - overlap
|
| 82 |
+
non_overlap_height = tile_h - overlap
|
| 83 |
+
|
| 84 |
+
cols = math.ceil((w - overlap) / non_overlap_width)
|
| 85 |
+
rows = math.ceil((h - overlap) / non_overlap_height)
|
| 86 |
+
|
| 87 |
+
dx = (w - tile_w) / (cols - 1) if cols > 1 else 0
|
| 88 |
+
dy = (h - tile_h) / (rows - 1) if rows > 1 else 0
|
| 89 |
+
|
| 90 |
+
grid = Grid([], tile_w, tile_h, w, h, overlap)
|
| 91 |
+
for row in range(rows):
|
| 92 |
+
row_images = []
|
| 93 |
+
|
| 94 |
+
y = int(row * dy)
|
| 95 |
+
|
| 96 |
+
if y + tile_h >= h:
|
| 97 |
+
y = h - tile_h
|
| 98 |
+
|
| 99 |
+
for col in range(cols):
|
| 100 |
+
x = int(col * dx)
|
| 101 |
+
|
| 102 |
+
if x + tile_w >= w:
|
| 103 |
+
x = w - tile_w
|
| 104 |
+
|
| 105 |
+
tile = image.crop((x, y, x + tile_w, y + tile_h))
|
| 106 |
+
|
| 107 |
+
row_images.append([x, tile_w, tile])
|
| 108 |
+
|
| 109 |
+
grid.tiles.append([y, tile_h, row_images])
|
| 110 |
+
|
| 111 |
+
return grid
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def combine_grid(grid):
|
| 115 |
+
def make_mask_image(r):
|
| 116 |
+
r = r * 255 / grid.overlap
|
| 117 |
+
r = r.astype(np.uint8)
|
| 118 |
+
return Image.fromarray(r, 'L')
|
| 119 |
+
|
| 120 |
+
mask_w = make_mask_image(np.arange(grid.overlap, dtype=np.float32).reshape((1, grid.overlap)).repeat(grid.tile_h, axis=0))
|
| 121 |
+
mask_h = make_mask_image(np.arange(grid.overlap, dtype=np.float32).reshape((grid.overlap, 1)).repeat(grid.image_w, axis=1))
|
| 122 |
+
|
| 123 |
+
combined_image = Image.new("RGB", (grid.image_w, grid.image_h))
|
| 124 |
+
for y, h, row in grid.tiles:
|
| 125 |
+
combined_row = Image.new("RGB", (grid.image_w, h))
|
| 126 |
+
for x, w, tile in row:
|
| 127 |
+
if x == 0:
|
| 128 |
+
combined_row.paste(tile, (0, 0))
|
| 129 |
+
continue
|
| 130 |
+
|
| 131 |
+
combined_row.paste(tile.crop((0, 0, grid.overlap, h)), (x, 0), mask=mask_w)
|
| 132 |
+
combined_row.paste(tile.crop((grid.overlap, 0, w, h)), (x + grid.overlap, 0))
|
| 133 |
+
|
| 134 |
+
if y == 0:
|
| 135 |
+
combined_image.paste(combined_row, (0, 0))
|
| 136 |
+
continue
|
| 137 |
+
|
| 138 |
+
combined_image.paste(combined_row.crop((0, 0, combined_row.width, grid.overlap)), (0, y), mask=mask_h)
|
| 139 |
+
combined_image.paste(combined_row.crop((0, grid.overlap, combined_row.width, h)), (0, y + grid.overlap))
|
| 140 |
+
|
| 141 |
+
return combined_image
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
class GridAnnotation:
|
| 145 |
+
def __init__(self, text='', is_active=True):
|
| 146 |
+
self.text = text
|
| 147 |
+
self.is_active = is_active
|
| 148 |
+
self.size = None
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def draw_grid_annotations(im, width, height, hor_texts, ver_texts, margin=0):
|
| 152 |
+
|
| 153 |
+
color_active = ImageColor.getcolor(opts.grid_text_active_color, 'RGB')
|
| 154 |
+
color_inactive = ImageColor.getcolor(opts.grid_text_inactive_color, 'RGB')
|
| 155 |
+
color_background = ImageColor.getcolor(opts.grid_background_color, 'RGB')
|
| 156 |
+
|
| 157 |
+
def wrap(drawing, text, font, line_length):
|
| 158 |
+
lines = ['']
|
| 159 |
+
for word in text.split():
|
| 160 |
+
line = f'{lines[-1]} {word}'.strip()
|
| 161 |
+
if drawing.textlength(line, font=font) <= line_length:
|
| 162 |
+
lines[-1] = line
|
| 163 |
+
else:
|
| 164 |
+
lines.append(word)
|
| 165 |
+
return lines
|
| 166 |
+
|
| 167 |
+
def draw_texts(drawing, draw_x, draw_y, lines, initial_fnt, initial_fontsize):
|
| 168 |
+
for line in lines:
|
| 169 |
+
fnt = initial_fnt
|
| 170 |
+
fontsize = initial_fontsize
|
| 171 |
+
while True:
|
| 172 |
+
bbox = drawing.multiline_textbbox((0, 0), line.text, font=fnt)
|
| 173 |
+
if (bbox[2] - bbox[0]) > line.allowed_width and fontsize > 0:
|
| 174 |
+
fontsize -= 1
|
| 175 |
+
fnt = get_font(fontsize)
|
| 176 |
+
else:
|
| 177 |
+
break
|
| 178 |
+
drawing.multiline_text((draw_x, draw_y + line.size[1] / 2), line.text, font=fnt, fill=color_active if line.is_active else color_inactive, anchor="mm", align="center")
|
| 179 |
+
|
| 180 |
+
if not line.is_active:
|
| 181 |
+
drawing.line((draw_x - line.size[0] // 2, draw_y + line.size[1] // 2, draw_x + line.size[0] // 2, draw_y + line.size[1] // 2), fill=color_inactive, width=4)
|
| 182 |
+
|
| 183 |
+
draw_y += line.size[1] + line_spacing
|
| 184 |
+
|
| 185 |
+
fontsize = (width + height) // 25
|
| 186 |
+
line_spacing = fontsize // 2
|
| 187 |
+
|
| 188 |
+
fnt = get_font(fontsize)
|
| 189 |
+
|
| 190 |
+
pad_left = 0 if sum([sum([len(line.text) for line in lines]) for lines in ver_texts]) == 0 else width * 3 // 4
|
| 191 |
+
|
| 192 |
+
cols = im.width // width
|
| 193 |
+
rows = im.height // height
|
| 194 |
+
|
| 195 |
+
assert cols == len(hor_texts), f'bad number of horizontal texts: {len(hor_texts)}; must be {cols}'
|
| 196 |
+
assert rows == len(ver_texts), f'bad number of vertical texts: {len(ver_texts)}; must be {rows}'
|
| 197 |
+
|
| 198 |
+
calc_img = Image.new("RGB", (1, 1), color_background)
|
| 199 |
+
calc_d = ImageDraw.Draw(calc_img)
|
| 200 |
+
|
| 201 |
+
for texts, allowed_width in zip(hor_texts + ver_texts, [width] * len(hor_texts) + [pad_left] * len(ver_texts)):
|
| 202 |
+
items = [] + texts
|
| 203 |
+
texts.clear()
|
| 204 |
+
|
| 205 |
+
for line in items:
|
| 206 |
+
wrapped = wrap(calc_d, line.text, fnt, allowed_width)
|
| 207 |
+
texts += [GridAnnotation(x, line.is_active) for x in wrapped]
|
| 208 |
+
|
| 209 |
+
for line in texts:
|
| 210 |
+
bbox = calc_d.multiline_textbbox((0, 0), line.text, font=fnt)
|
| 211 |
+
line.size = (bbox[2] - bbox[0], bbox[3] - bbox[1])
|
| 212 |
+
line.allowed_width = allowed_width
|
| 213 |
+
|
| 214 |
+
hor_text_heights = [sum([line.size[1] + line_spacing for line in lines]) - line_spacing for lines in hor_texts]
|
| 215 |
+
ver_text_heights = [sum([line.size[1] + line_spacing for line in lines]) - line_spacing * len(lines) for lines in ver_texts]
|
| 216 |
+
|
| 217 |
+
pad_top = 0 if sum(hor_text_heights) == 0 else max(hor_text_heights) + line_spacing * 2
|
| 218 |
+
|
| 219 |
+
result = Image.new("RGB", (im.width + pad_left + margin * (cols-1), im.height + pad_top + margin * (rows-1)), color_background)
|
| 220 |
+
|
| 221 |
+
for row in range(rows):
|
| 222 |
+
for col in range(cols):
|
| 223 |
+
cell = im.crop((width * col, height * row, width * (col+1), height * (row+1)))
|
| 224 |
+
result.paste(cell, (pad_left + (width + margin) * col, pad_top + (height + margin) * row))
|
| 225 |
+
|
| 226 |
+
d = ImageDraw.Draw(result)
|
| 227 |
+
|
| 228 |
+
for col in range(cols):
|
| 229 |
+
x = pad_left + (width + margin) * col + width / 2
|
| 230 |
+
y = pad_top / 2 - hor_text_heights[col] / 2
|
| 231 |
+
|
| 232 |
+
draw_texts(d, x, y, hor_texts[col], fnt, fontsize)
|
| 233 |
+
|
| 234 |
+
for row in range(rows):
|
| 235 |
+
x = pad_left / 2
|
| 236 |
+
y = pad_top + (height + margin) * row + height / 2 - ver_text_heights[row] / 2
|
| 237 |
+
|
| 238 |
+
draw_texts(d, x, y, ver_texts[row], fnt, fontsize)
|
| 239 |
+
|
| 240 |
+
return result
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def draw_prompt_matrix(im, width, height, all_prompts, margin=0):
|
| 244 |
+
prompts = all_prompts[1:]
|
| 245 |
+
boundary = math.ceil(len(prompts) / 2)
|
| 246 |
+
|
| 247 |
+
prompts_horiz = prompts[:boundary]
|
| 248 |
+
prompts_vert = prompts[boundary:]
|
| 249 |
+
|
| 250 |
+
hor_texts = [[GridAnnotation(x, is_active=pos & (1 << i) != 0) for i, x in enumerate(prompts_horiz)] for pos in range(1 << len(prompts_horiz))]
|
| 251 |
+
ver_texts = [[GridAnnotation(x, is_active=pos & (1 << i) != 0) for i, x in enumerate(prompts_vert)] for pos in range(1 << len(prompts_vert))]
|
| 252 |
+
|
| 253 |
+
return draw_grid_annotations(im, width, height, hor_texts, ver_texts, margin)
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def resize_image(resize_mode, im, width, height, upscaler_name=None, force_RGBA=False):
|
| 257 |
+
"""
|
| 258 |
+
Resizes an image with the specified resize_mode, width, and height.
|
| 259 |
+
|
| 260 |
+
Args:
|
| 261 |
+
resize_mode: The mode to use when resizing the image.
|
| 262 |
+
0: Resize the image to the specified width and height.
|
| 263 |
+
1: Resize the image to fill the specified width and height, maintaining the aspect ratio, and then center the image within the dimensions, cropping the excess.
|
| 264 |
+
2: Resize the image to fit within the specified width and height, maintaining the aspect ratio, and then center the image within the dimensions, filling empty with data from image.
|
| 265 |
+
im: The image to resize.
|
| 266 |
+
width: The width to resize the image to.
|
| 267 |
+
height: The height to resize the image to.
|
| 268 |
+
upscaler_name: The name of the upscaler to use. If not provided, defaults to opts.upscaler_for_img2img.
|
| 269 |
+
"""
|
| 270 |
+
|
| 271 |
+
if not force_RGBA and im.mode == 'RGBA':
|
| 272 |
+
im = im.convert('RGB')
|
| 273 |
+
|
| 274 |
+
upscaler_name = upscaler_name or opts.upscaler_for_img2img
|
| 275 |
+
|
| 276 |
+
def resize(im, w, h):
|
| 277 |
+
if upscaler_name is None or upscaler_name == "None" or im.mode == 'L' or force_RGBA:
|
| 278 |
+
return im.resize((w, h), resample=LANCZOS)
|
| 279 |
+
|
| 280 |
+
scale = max(w / im.width, h / im.height)
|
| 281 |
+
|
| 282 |
+
if scale > 1.0:
|
| 283 |
+
upscalers = [x for x in shared.sd_upscalers if x.name == upscaler_name]
|
| 284 |
+
if len(upscalers) == 0:
|
| 285 |
+
upscaler = shared.sd_upscalers[0]
|
| 286 |
+
print(f"could not find upscaler named {upscaler_name or '<empty string>'}, using {upscaler.name} as a fallback")
|
| 287 |
+
else:
|
| 288 |
+
upscaler = upscalers[0]
|
| 289 |
+
|
| 290 |
+
im = upscaler.scaler.upscale(im, scale, upscaler.data_path)
|
| 291 |
+
|
| 292 |
+
if im.width != w or im.height != h:
|
| 293 |
+
im = im.resize((w, h), resample=LANCZOS)
|
| 294 |
+
|
| 295 |
+
return im
|
| 296 |
+
|
| 297 |
+
if resize_mode == 0:
|
| 298 |
+
res = resize(im, width, height)
|
| 299 |
+
|
| 300 |
+
elif resize_mode == 1:
|
| 301 |
+
ratio = width / height
|
| 302 |
+
src_ratio = im.width / im.height
|
| 303 |
+
|
| 304 |
+
src_w = width if ratio > src_ratio else im.width * height // im.height
|
| 305 |
+
src_h = height if ratio <= src_ratio else im.height * width // im.width
|
| 306 |
+
|
| 307 |
+
resized = resize(im, src_w, src_h)
|
| 308 |
+
res = Image.new("RGB" if not force_RGBA else "RGBA", (width, height))
|
| 309 |
+
res.paste(resized, box=(width // 2 - src_w // 2, height // 2 - src_h // 2))
|
| 310 |
+
|
| 311 |
+
else:
|
| 312 |
+
ratio = width / height
|
| 313 |
+
src_ratio = im.width / im.height
|
| 314 |
+
|
| 315 |
+
src_w = width if ratio < src_ratio else im.width * height // im.height
|
| 316 |
+
src_h = height if ratio >= src_ratio else im.height * width // im.width
|
| 317 |
+
|
| 318 |
+
resized = resize(im, src_w, src_h)
|
| 319 |
+
res = Image.new("RGB" if not force_RGBA else "RGBA", (width, height))
|
| 320 |
+
res.paste(resized, box=(width // 2 - src_w // 2, height // 2 - src_h // 2))
|
| 321 |
+
|
| 322 |
+
if ratio < src_ratio:
|
| 323 |
+
fill_height = height // 2 - src_h // 2
|
| 324 |
+
if fill_height > 0:
|
| 325 |
+
res.paste(resized.resize((width, fill_height), box=(0, 0, width, 0)), box=(0, 0))
|
| 326 |
+
res.paste(resized.resize((width, fill_height), box=(0, resized.height, width, resized.height)), box=(0, fill_height + src_h))
|
| 327 |
+
elif ratio > src_ratio:
|
| 328 |
+
fill_width = width // 2 - src_w // 2
|
| 329 |
+
if fill_width > 0:
|
| 330 |
+
res.paste(resized.resize((fill_width, height), box=(0, 0, 0, height)), box=(0, 0))
|
| 331 |
+
res.paste(resized.resize((fill_width, height), box=(resized.width, 0, resized.width, height)), box=(fill_width + src_w, 0))
|
| 332 |
+
|
| 333 |
+
return res
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
if not shared.cmd_opts.unix_filenames_sanitization:
|
| 337 |
+
invalid_filename_chars = '#<>:"/\\|?*\n\r\t'
|
| 338 |
+
else:
|
| 339 |
+
invalid_filename_chars = '/'
|
| 340 |
+
invalid_filename_prefix = ' '
|
| 341 |
+
invalid_filename_postfix = ' .'
|
| 342 |
+
re_nonletters = re.compile(r'[\s' + string.punctuation + ']+')
|
| 343 |
+
re_pattern = re.compile(r"(.*?)(?:\[([^\[\]]+)\]|$)")
|
| 344 |
+
re_pattern_arg = re.compile(r"(.*)<([^>]*)>$")
|
| 345 |
+
max_filename_part_length = shared.cmd_opts.filenames_max_length
|
| 346 |
+
NOTHING_AND_SKIP_PREVIOUS_TEXT = object()
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
def sanitize_filename_part(text, replace_spaces=True):
|
| 350 |
+
if text is None:
|
| 351 |
+
return None
|
| 352 |
+
|
| 353 |
+
if replace_spaces:
|
| 354 |
+
text = text.replace(' ', '_')
|
| 355 |
+
|
| 356 |
+
text = text.translate({ord(x): '_' for x in invalid_filename_chars})
|
| 357 |
+
text = text.lstrip(invalid_filename_prefix)[:max_filename_part_length]
|
| 358 |
+
text = text.rstrip(invalid_filename_postfix)
|
| 359 |
+
return text
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
@functools.cache
|
| 363 |
+
def get_scheduler_str(sampler_name, scheduler_name):
|
| 364 |
+
"""Returns {Scheduler} if the scheduler is applicable to the sampler"""
|
| 365 |
+
if scheduler_name == 'Automatic':
|
| 366 |
+
config = sd_samplers.find_sampler_config(sampler_name)
|
| 367 |
+
scheduler_name = config.options.get('scheduler', 'Automatic')
|
| 368 |
+
return scheduler_name.capitalize()
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
@functools.cache
|
| 372 |
+
def get_sampler_scheduler_str(sampler_name, scheduler_name):
|
| 373 |
+
"""Returns the '{Sampler} {Scheduler}' if the scheduler is applicable to the sampler"""
|
| 374 |
+
return f'{sampler_name} {get_scheduler_str(sampler_name, scheduler_name)}'
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
def get_sampler_scheduler(p, sampler):
|
| 378 |
+
"""Returns '{Sampler} {Scheduler}' / '{Scheduler}' / 'NOTHING_AND_SKIP_PREVIOUS_TEXT'"""
|
| 379 |
+
if hasattr(p, 'scheduler') and hasattr(p, 'sampler_name'):
|
| 380 |
+
if sampler:
|
| 381 |
+
sampler_scheduler = get_sampler_scheduler_str(p.sampler_name, p.scheduler)
|
| 382 |
+
else:
|
| 383 |
+
sampler_scheduler = get_scheduler_str(p.sampler_name, p.scheduler)
|
| 384 |
+
return sanitize_filename_part(sampler_scheduler, replace_spaces=False)
|
| 385 |
+
return NOTHING_AND_SKIP_PREVIOUS_TEXT
|
| 386 |
+
|
| 387 |
+
|
| 388 |
+
class FilenameGenerator:
|
| 389 |
+
replacements = {
|
| 390 |
+
'basename': lambda self: self.basename or 'img',
|
| 391 |
+
'seed': lambda self: self.seed if self.seed is not None else '',
|
| 392 |
+
'seed_first': lambda self: self.seed if self.p.batch_size == 1 else self.p.all_seeds[0],
|
| 393 |
+
'seed_last': lambda self: NOTHING_AND_SKIP_PREVIOUS_TEXT if self.p.batch_size == 1 else self.p.all_seeds[-1],
|
| 394 |
+
'steps': lambda self: self.p and self.p.steps,
|
| 395 |
+
'cfg': lambda self: self.p and self.p.cfg_scale,
|
| 396 |
+
'width': lambda self: self.image.width,
|
| 397 |
+
'height': lambda self: self.image.height,
|
| 398 |
+
'styles': lambda self: self.p and sanitize_filename_part(", ".join([style for style in self.p.styles if not style == "None"]) or "None", replace_spaces=False),
|
| 399 |
+
'sampler': lambda self: self.p and sanitize_filename_part(self.p.sampler_name, replace_spaces=False),
|
| 400 |
+
'sampler_scheduler': lambda self: self.p and get_sampler_scheduler(self.p, True),
|
| 401 |
+
'scheduler': lambda self: self.p and get_sampler_scheduler(self.p, False),
|
| 402 |
+
'model_hash': lambda self: getattr(self.p, "sd_model_hash", shared.sd_model.sd_model_hash),
|
| 403 |
+
'model_name': lambda self: sanitize_filename_part(shared.sd_model.sd_checkpoint_info.name_for_extra, replace_spaces=False),
|
| 404 |
+
'date': lambda self: datetime.datetime.now().strftime('%Y-%m-%d'),
|
| 405 |
+
'datetime': lambda self, *args: self.datetime(*args), # accepts formats: [datetime], [datetime<Format>], [datetime<Format><Time Zone>]
|
| 406 |
+
'job_timestamp': lambda self: getattr(self.p, "job_timestamp", shared.state.job_timestamp),
|
| 407 |
+
'prompt_hash': lambda self, *args: self.string_hash(self.prompt, *args),
|
| 408 |
+
'negative_prompt_hash': lambda self, *args: self.string_hash(self.p.negative_prompt, *args),
|
| 409 |
+
'full_prompt_hash': lambda self, *args: self.string_hash(f"{self.p.prompt} {self.p.negative_prompt}", *args), # a space in between to create a unique string
|
| 410 |
+
'prompt': lambda self: sanitize_filename_part(self.prompt),
|
| 411 |
+
'prompt_no_styles': lambda self: self.prompt_no_style(),
|
| 412 |
+
'prompt_spaces': lambda self: sanitize_filename_part(self.prompt, replace_spaces=False),
|
| 413 |
+
'prompt_words': lambda self: self.prompt_words(),
|
| 414 |
+
'batch_number': lambda self: NOTHING_AND_SKIP_PREVIOUS_TEXT if self.p.batch_size == 1 or self.zip else self.p.batch_index + 1,
|
| 415 |
+
'batch_size': lambda self: self.p.batch_size,
|
| 416 |
+
'generation_number': lambda self: NOTHING_AND_SKIP_PREVIOUS_TEXT if (self.p.n_iter == 1 and self.p.batch_size == 1) or self.zip else self.p.iteration * self.p.batch_size + self.p.batch_index + 1,
|
| 417 |
+
'hasprompt': lambda self, *args: self.hasprompt(*args), # accepts formats:[hasprompt<prompt1|default><prompt2>..]
|
| 418 |
+
'clip_skip': lambda self: opts.data["CLIP_stop_at_last_layers"],
|
| 419 |
+
'denoising': lambda self: self.p.denoising_strength if self.p and self.p.denoising_strength else NOTHING_AND_SKIP_PREVIOUS_TEXT,
|
| 420 |
+
'user': lambda self: self.p.user,
|
| 421 |
+
'vae_filename': lambda self: self.get_vae_filename(),
|
| 422 |
+
'none': lambda self: '', # Overrides the default, so you can get just the sequence number
|
| 423 |
+
'image_hash': lambda self, *args: self.image_hash(*args) # accepts formats: [image_hash<length>] default full hash
|
| 424 |
+
}
|
| 425 |
+
default_time_format = '%Y%m%d%H%M%S'
|
| 426 |
+
|
| 427 |
+
def __init__(self, p, seed, prompt, image, zip=False, basename=""):
|
| 428 |
+
self.p = p
|
| 429 |
+
self.seed = seed
|
| 430 |
+
self.prompt = prompt
|
| 431 |
+
self.image = image
|
| 432 |
+
self.zip = zip
|
| 433 |
+
self.basename = basename
|
| 434 |
+
|
| 435 |
+
def get_vae_filename(self):
|
| 436 |
+
"""Get the name of the VAE file."""
|
| 437 |
+
|
| 438 |
+
import modules.sd_vae as sd_vae
|
| 439 |
+
|
| 440 |
+
if sd_vae.loaded_vae_file is None:
|
| 441 |
+
return "NoneType"
|
| 442 |
+
|
| 443 |
+
file_name = os.path.basename(sd_vae.loaded_vae_file)
|
| 444 |
+
split_file_name = file_name.split('.')
|
| 445 |
+
if len(split_file_name) > 1 and split_file_name[0] == '':
|
| 446 |
+
return split_file_name[1] # if the first character of the filename is "." then [1] is obtained.
|
| 447 |
+
else:
|
| 448 |
+
return split_file_name[0]
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
def hasprompt(self, *args):
|
| 452 |
+
lower = self.prompt.lower()
|
| 453 |
+
if self.p is None or self.prompt is None:
|
| 454 |
+
return None
|
| 455 |
+
outres = ""
|
| 456 |
+
for arg in args:
|
| 457 |
+
if arg != "":
|
| 458 |
+
division = arg.split("|")
|
| 459 |
+
expected = division[0].lower()
|
| 460 |
+
default = division[1] if len(division) > 1 else ""
|
| 461 |
+
if lower.find(expected) >= 0:
|
| 462 |
+
outres = f'{outres}{expected}'
|
| 463 |
+
else:
|
| 464 |
+
outres = outres if default == "" else f'{outres}{default}'
|
| 465 |
+
return sanitize_filename_part(outres)
|
| 466 |
+
|
| 467 |
+
def prompt_no_style(self):
|
| 468 |
+
if self.p is None or self.prompt is None:
|
| 469 |
+
return None
|
| 470 |
+
|
| 471 |
+
prompt_no_style = self.prompt
|
| 472 |
+
for style in shared.prompt_styles.get_style_prompts(self.p.styles):
|
| 473 |
+
if style:
|
| 474 |
+
for part in style.split("{prompt}"):
|
| 475 |
+
prompt_no_style = prompt_no_style.replace(part, "").replace(", ,", ",").strip().strip(',')
|
| 476 |
+
|
| 477 |
+
prompt_no_style = prompt_no_style.replace(style, "").strip().strip(',').strip()
|
| 478 |
+
|
| 479 |
+
return sanitize_filename_part(prompt_no_style, replace_spaces=False)
|
| 480 |
+
|
| 481 |
+
def prompt_words(self):
|
| 482 |
+
words = [x for x in re_nonletters.split(self.prompt or "") if x]
|
| 483 |
+
if len(words) == 0:
|
| 484 |
+
words = ["empty"]
|
| 485 |
+
return sanitize_filename_part(" ".join(words[0:opts.directories_max_prompt_words]), replace_spaces=False)
|
| 486 |
+
|
| 487 |
+
def datetime(self, *args):
|
| 488 |
+
time_datetime = datetime.datetime.now()
|
| 489 |
+
|
| 490 |
+
time_format = args[0] if (args and args[0] != "") else self.default_time_format
|
| 491 |
+
try:
|
| 492 |
+
time_zone = pytz.timezone(args[1]) if len(args) > 1 else None
|
| 493 |
+
except pytz.exceptions.UnknownTimeZoneError:
|
| 494 |
+
time_zone = None
|
| 495 |
+
|
| 496 |
+
time_zone_time = time_datetime.astimezone(time_zone)
|
| 497 |
+
try:
|
| 498 |
+
formatted_time = time_zone_time.strftime(time_format)
|
| 499 |
+
except (ValueError, TypeError):
|
| 500 |
+
formatted_time = time_zone_time.strftime(self.default_time_format)
|
| 501 |
+
|
| 502 |
+
return sanitize_filename_part(formatted_time, replace_spaces=False)
|
| 503 |
+
|
| 504 |
+
def image_hash(self, *args):
|
| 505 |
+
length = int(args[0]) if (args and args[0] != "") else None
|
| 506 |
+
return hashlib.sha256(self.image.tobytes()).hexdigest()[0:length]
|
| 507 |
+
|
| 508 |
+
def string_hash(self, text, *args):
|
| 509 |
+
length = int(args[0]) if (args and args[0] != "") else 8
|
| 510 |
+
return hashlib.sha256(text.encode()).hexdigest()[0:length]
|
| 511 |
+
|
| 512 |
+
def apply(self, x):
|
| 513 |
+
res = ''
|
| 514 |
+
|
| 515 |
+
for m in re_pattern.finditer(x):
|
| 516 |
+
text, pattern = m.groups()
|
| 517 |
+
|
| 518 |
+
if pattern is None:
|
| 519 |
+
res += text
|
| 520 |
+
continue
|
| 521 |
+
|
| 522 |
+
pattern_args = []
|
| 523 |
+
while True:
|
| 524 |
+
m = re_pattern_arg.match(pattern)
|
| 525 |
+
if m is None:
|
| 526 |
+
break
|
| 527 |
+
|
| 528 |
+
pattern, arg = m.groups()
|
| 529 |
+
pattern_args.insert(0, arg)
|
| 530 |
+
|
| 531 |
+
fun = self.replacements.get(pattern.lower())
|
| 532 |
+
if fun is not None:
|
| 533 |
+
try:
|
| 534 |
+
replacement = fun(self, *pattern_args)
|
| 535 |
+
except Exception:
|
| 536 |
+
replacement = None
|
| 537 |
+
errors.report(f"Error adding [{pattern}] to filename", exc_info=True)
|
| 538 |
+
|
| 539 |
+
if replacement == NOTHING_AND_SKIP_PREVIOUS_TEXT:
|
| 540 |
+
continue
|
| 541 |
+
elif replacement is not None:
|
| 542 |
+
res += text + str(replacement)
|
| 543 |
+
continue
|
| 544 |
+
|
| 545 |
+
res += f'{text}[{pattern}]'
|
| 546 |
+
|
| 547 |
+
return res
|
| 548 |
+
|
| 549 |
+
|
| 550 |
+
def get_next_sequence_number(path, basename):
|
| 551 |
+
"""
|
| 552 |
+
Determines and returns the next sequence number to use when saving an image in the specified directory.
|
| 553 |
+
|
| 554 |
+
The sequence starts at 0.
|
| 555 |
+
"""
|
| 556 |
+
result = -1
|
| 557 |
+
if basename != '':
|
| 558 |
+
basename = f"{basename}-"
|
| 559 |
+
|
| 560 |
+
prefix_length = len(basename)
|
| 561 |
+
for p in os.listdir(path):
|
| 562 |
+
if p.startswith(basename):
|
| 563 |
+
parts = os.path.splitext(p[prefix_length:])[0].split('-') # splits the filename (removing the basename first if one is defined, so the sequence number is always the first element)
|
| 564 |
+
try:
|
| 565 |
+
result = max(int(parts[0]), result)
|
| 566 |
+
except ValueError:
|
| 567 |
+
pass
|
| 568 |
+
|
| 569 |
+
return result + 1
|
| 570 |
+
|
| 571 |
+
|
| 572 |
+
def save_image_with_geninfo(image, geninfo, filename, extension=None, existing_pnginfo=None, pnginfo_section_name="parameters"):
|
| 573 |
+
"""
|
| 574 |
+
Saves image to filename, including geninfo as text information for generation info.
|
| 575 |
+
For PNG images, geninfo is added to existing pnginfo dictionary using the pnginfo_section_name argument as key.
|
| 576 |
+
For JPG images, there's no dictionary and geninfo just replaces the EXIF description.
|
| 577 |
+
"""
|
| 578 |
+
|
| 579 |
+
if extension is None:
|
| 580 |
+
extension = os.path.splitext(filename)[1]
|
| 581 |
+
|
| 582 |
+
image_format = Image.registered_extensions()[extension]
|
| 583 |
+
|
| 584 |
+
if extension.lower() == ".png":
|
| 585 |
+
existing_pnginfo = existing_pnginfo or {}
|
| 586 |
+
if opts.enable_pnginfo:
|
| 587 |
+
existing_pnginfo[pnginfo_section_name] = geninfo
|
| 588 |
+
pnginfo_data = PngImagePlugin.PngInfo()
|
| 589 |
+
for k, v in (existing_pnginfo or {}).items():
|
| 590 |
+
pnginfo_data.add_text(k, str(v))
|
| 591 |
+
else:
|
| 592 |
+
pnginfo_data = None
|
| 593 |
+
|
| 594 |
+
image.save(filename, format=image_format, quality=opts.jpeg_quality, pnginfo=pnginfo_data)
|
| 595 |
+
|
| 596 |
+
elif extension.lower() in (".jpg", ".jpeg", ".webp"):
|
| 597 |
+
if image.mode == "RGBA":
|
| 598 |
+
image = image.convert("RGB")
|
| 599 |
+
elif image.mode == "I;16":
|
| 600 |
+
image = image.point(lambda p: p * 0.0038910505836576).convert("RGB" if extension.lower() == ".webp" else "L")
|
| 601 |
+
|
| 602 |
+
image.save(filename, format=image_format, quality=opts.jpeg_quality, lossless=opts.webp_lossless)
|
| 603 |
+
|
| 604 |
+
if opts.enable_pnginfo and geninfo is not None:
|
| 605 |
+
exif_bytes = piexif.dump(
|
| 606 |
+
{
|
| 607 |
+
"Exif": {piexif.ExifIFD.UserComment: piexif.helper.UserComment.dump(geninfo or "", encoding="unicode")},
|
| 608 |
+
}
|
| 609 |
+
)
|
| 610 |
+
|
| 611 |
+
piexif.insert(exif_bytes, filename)
|
| 612 |
+
elif extension.lower() in (".avif", ".jxl"):
|
| 613 |
+
if opts.enable_pnginfo and geninfo is not None:
|
| 614 |
+
exif_bytes = piexif.dump(
|
| 615 |
+
{
|
| 616 |
+
"Exif": {piexif.ExifIFD.UserComment: piexif.helper.UserComment.dump(geninfo or "", encoding="unicode")},
|
| 617 |
+
}
|
| 618 |
+
)
|
| 619 |
+
else:
|
| 620 |
+
exif_bytes = None
|
| 621 |
+
|
| 622 |
+
image.save(filename, format=image_format, quality=opts.jpeg_quality, exif=exif_bytes)
|
| 623 |
+
elif extension.lower() == ".gif":
|
| 624 |
+
image.save(filename, format=image_format, comment=geninfo)
|
| 625 |
+
else:
|
| 626 |
+
image.save(filename, format=image_format, quality=opts.jpeg_quality)
|
| 627 |
+
|
| 628 |
+
|
| 629 |
+
def save_image(image, path, basename, seed=None, prompt=None, extension='png', info=None, short_filename=False, no_prompt=False, grid=False, pnginfo_section_name='parameters', p=None, existing_info=None, forced_filename=None, suffix="", save_to_dirs=None):
|
| 630 |
+
"""Save an image.
|
| 631 |
+
|
| 632 |
+
Args:
|
| 633 |
+
image (`PIL.Image`):
|
| 634 |
+
The image to be saved.
|
| 635 |
+
path (`str`):
|
| 636 |
+
The directory to save the image. Note, the option `save_to_dirs` will make the image to be saved into a sub directory.
|
| 637 |
+
basename (`str`):
|
| 638 |
+
The base filename which will be applied to `filename pattern`.
|
| 639 |
+
seed, prompt, short_filename,
|
| 640 |
+
extension (`str`):
|
| 641 |
+
Image file extension, default is `png`.
|
| 642 |
+
pngsectionname (`str`):
|
| 643 |
+
Specify the name of the section which `info` will be saved in.
|
| 644 |
+
info (`str` or `PngImagePlugin.iTXt`):
|
| 645 |
+
PNG info chunks.
|
| 646 |
+
existing_info (`dict`):
|
| 647 |
+
Additional PNG info. `existing_info == {pngsectionname: info, ...}`
|
| 648 |
+
no_prompt:
|
| 649 |
+
TODO I don't know its meaning.
|
| 650 |
+
p (`StableDiffusionProcessing` or `Processing`)
|
| 651 |
+
forced_filename (`str`):
|
| 652 |
+
If specified, `basename` and filename pattern will be ignored.
|
| 653 |
+
save_to_dirs (bool):
|
| 654 |
+
If true, the image will be saved into a subdirectory of `path`.
|
| 655 |
+
|
| 656 |
+
Returns: (fullfn, txt_fullfn)
|
| 657 |
+
fullfn (`str`):
|
| 658 |
+
The full path of the saved imaged.
|
| 659 |
+
txt_fullfn (`str` or None):
|
| 660 |
+
If a text file is saved for this image, this will be its full path. Otherwise None.
|
| 661 |
+
"""
|
| 662 |
+
namegen = FilenameGenerator(p, seed, prompt, image, basename=basename)
|
| 663 |
+
|
| 664 |
+
# WebP and JPG formats have maximum dimension limits of 16383 and 65535 respectively. switch to PNG which has a much higher limit
|
| 665 |
+
if (image.height > 65535 or image.width > 65535) and extension.lower() in ("jpg", "jpeg") or (image.height > 16383 or image.width > 16383) and extension.lower() == "webp":
|
| 666 |
+
print('Image dimensions too large; saving as PNG')
|
| 667 |
+
extension = "png"
|
| 668 |
+
|
| 669 |
+
if save_to_dirs is None:
|
| 670 |
+
save_to_dirs = (grid and opts.grid_save_to_dirs) or (not grid and opts.save_to_dirs and not no_prompt)
|
| 671 |
+
|
| 672 |
+
if save_to_dirs:
|
| 673 |
+
dirname = namegen.apply(opts.directories_filename_pattern or "[prompt_words]").lstrip(' ').rstrip('\\ /')
|
| 674 |
+
path = os.path.join(path, dirname)
|
| 675 |
+
|
| 676 |
+
os.makedirs(path, exist_ok=True)
|
| 677 |
+
|
| 678 |
+
if forced_filename is None:
|
| 679 |
+
if short_filename or seed is None:
|
| 680 |
+
file_decoration = ""
|
| 681 |
+
elif hasattr(p, 'override_settings'):
|
| 682 |
+
file_decoration = p.override_settings.get("samples_filename_pattern")
|
| 683 |
+
else:
|
| 684 |
+
file_decoration = None
|
| 685 |
+
|
| 686 |
+
if file_decoration is None:
|
| 687 |
+
file_decoration = opts.samples_filename_pattern or ("[seed]" if opts.save_to_dirs else "[seed]-[prompt_spaces]")
|
| 688 |
+
|
| 689 |
+
file_decoration = namegen.apply(file_decoration) + suffix
|
| 690 |
+
|
| 691 |
+
add_number = opts.save_images_add_number or file_decoration == ''
|
| 692 |
+
|
| 693 |
+
if file_decoration != "" and add_number:
|
| 694 |
+
file_decoration = f"-{file_decoration}"
|
| 695 |
+
|
| 696 |
+
if add_number:
|
| 697 |
+
basecount = get_next_sequence_number(path, basename)
|
| 698 |
+
fullfn = None
|
| 699 |
+
for i in range(500):
|
| 700 |
+
fn = f"{basecount + i:05}" if basename == '' else f"{basename}-{basecount + i:04}"
|
| 701 |
+
fullfn = os.path.join(path, f"{fn}{file_decoration}.{extension}")
|
| 702 |
+
if not os.path.exists(fullfn):
|
| 703 |
+
break
|
| 704 |
+
else:
|
| 705 |
+
fullfn = os.path.join(path, f"{file_decoration}.{extension}")
|
| 706 |
+
else:
|
| 707 |
+
fullfn = os.path.join(path, f"{forced_filename}.{extension}")
|
| 708 |
+
|
| 709 |
+
pnginfo = existing_info or {}
|
| 710 |
+
if info is not None:
|
| 711 |
+
pnginfo[pnginfo_section_name] = info
|
| 712 |
+
|
| 713 |
+
params = script_callbacks.ImageSaveParams(image, p, fullfn, pnginfo)
|
| 714 |
+
script_callbacks.before_image_saved_callback(params)
|
| 715 |
+
|
| 716 |
+
image = params.image
|
| 717 |
+
fullfn = params.filename
|
| 718 |
+
info = params.pnginfo.get(pnginfo_section_name, None)
|
| 719 |
+
|
| 720 |
+
def _atomically_save_image(image_to_save, filename_without_extension, extension):
|
| 721 |
+
"""
|
| 722 |
+
save image with .tmp extension to avoid race condition when another process detects new image in the directory
|
| 723 |
+
"""
|
| 724 |
+
temp_file_path = f"{filename_without_extension}.tmp"
|
| 725 |
+
|
| 726 |
+
save_image_with_geninfo(image_to_save, info, temp_file_path, extension, existing_pnginfo=params.pnginfo, pnginfo_section_name=pnginfo_section_name)
|
| 727 |
+
|
| 728 |
+
filename = filename_without_extension + extension
|
| 729 |
+
without_extension = filename_without_extension
|
| 730 |
+
if shared.opts.save_images_replace_action != "Replace":
|
| 731 |
+
n = 0
|
| 732 |
+
while os.path.exists(filename):
|
| 733 |
+
n += 1
|
| 734 |
+
without_extension = f"{filename_without_extension}-{n}"
|
| 735 |
+
filename = without_extension + extension
|
| 736 |
+
os.replace(temp_file_path, filename)
|
| 737 |
+
return without_extension
|
| 738 |
+
|
| 739 |
+
fullfn_without_extension, extension = os.path.splitext(params.filename)
|
| 740 |
+
if hasattr(os, 'statvfs'):
|
| 741 |
+
max_name_len = os.statvfs(path).f_namemax
|
| 742 |
+
fullfn_without_extension = fullfn_without_extension[:max_name_len - max(4, len(extension))]
|
| 743 |
+
params.filename = fullfn_without_extension + extension
|
| 744 |
+
fullfn = params.filename
|
| 745 |
+
|
| 746 |
+
fullfn_without_extension = _atomically_save_image(image, fullfn_without_extension, extension)
|
| 747 |
+
fullfn = fullfn_without_extension + extension
|
| 748 |
+
image.already_saved_as = fullfn
|
| 749 |
+
|
| 750 |
+
oversize = image.width > opts.target_side_length or image.height > opts.target_side_length
|
| 751 |
+
if opts.export_for_4chan and (oversize or os.stat(fullfn).st_size > opts.img_downscale_threshold * 1024 * 1024):
|
| 752 |
+
ratio = image.width / image.height
|
| 753 |
+
resize_to = None
|
| 754 |
+
if oversize and ratio > 1:
|
| 755 |
+
resize_to = round(opts.target_side_length), round(image.height * opts.target_side_length / image.width)
|
| 756 |
+
elif oversize:
|
| 757 |
+
resize_to = round(image.width * opts.target_side_length / image.height), round(opts.target_side_length)
|
| 758 |
+
|
| 759 |
+
if resize_to is not None:
|
| 760 |
+
try:
|
| 761 |
+
# Resizing image with LANCZOS could throw an exception if e.g. image mode is I;16
|
| 762 |
+
image = image.resize(resize_to, LANCZOS)
|
| 763 |
+
except Exception:
|
| 764 |
+
image = image.resize(resize_to)
|
| 765 |
+
try:
|
| 766 |
+
_ = _atomically_save_image(image, fullfn_without_extension, ".jpg")
|
| 767 |
+
except Exception as e:
|
| 768 |
+
errors.display(e, "saving image as downscaled JPG")
|
| 769 |
+
|
| 770 |
+
if opts.save_txt and info is not None:
|
| 771 |
+
txt_fullfn = f"{fullfn_without_extension}.txt"
|
| 772 |
+
with open(txt_fullfn, "w", encoding="utf8") as file:
|
| 773 |
+
file.write(f"{info}\n")
|
| 774 |
+
else:
|
| 775 |
+
txt_fullfn = None
|
| 776 |
+
|
| 777 |
+
script_callbacks.image_saved_callback(params)
|
| 778 |
+
|
| 779 |
+
return fullfn, txt_fullfn
|
| 780 |
+
|
| 781 |
+
|
| 782 |
+
IGNORED_INFO_KEYS = {
|
| 783 |
+
'jfif', 'jfif_version', 'jfif_unit', 'jfif_density', 'dpi', 'exif',
|
| 784 |
+
'loop', 'background', 'timestamp', 'duration', 'progressive', 'progression',
|
| 785 |
+
'icc_profile', 'chromaticity', 'photoshop',
|
| 786 |
+
}
|
| 787 |
+
|
| 788 |
+
|
| 789 |
+
def read_info_from_image(image: Image.Image) -> tuple[str | None, dict]:
|
| 790 |
+
"""Read generation info from an image, checking standard metadata first, then stealth info if needed."""
|
| 791 |
+
|
| 792 |
+
def read_standard():
|
| 793 |
+
items = (image.info or {}).copy()
|
| 794 |
+
|
| 795 |
+
geninfo = items.pop('parameters', None)
|
| 796 |
+
|
| 797 |
+
if "exif" in items:
|
| 798 |
+
exif_data = items["exif"]
|
| 799 |
+
try:
|
| 800 |
+
exif = piexif.load(exif_data)
|
| 801 |
+
except OSError:
|
| 802 |
+
# memory / exif was not valid so piexif tried to read from a file
|
| 803 |
+
exif = None
|
| 804 |
+
exif_comment = (exif or {}).get("Exif", {}).get(piexif.ExifIFD.UserComment, b'')
|
| 805 |
+
try:
|
| 806 |
+
exif_comment = piexif.helper.UserComment.load(exif_comment)
|
| 807 |
+
except ValueError:
|
| 808 |
+
exif_comment = exif_comment.decode('utf8', errors="ignore")
|
| 809 |
+
|
| 810 |
+
if exif_comment:
|
| 811 |
+
geninfo = exif_comment
|
| 812 |
+
elif "comment" in items: # for gif
|
| 813 |
+
if isinstance(items["comment"], bytes):
|
| 814 |
+
geninfo = items["comment"].decode('utf8', errors="ignore")
|
| 815 |
+
else:
|
| 816 |
+
geninfo = items["comment"]
|
| 817 |
+
|
| 818 |
+
for field in IGNORED_INFO_KEYS:
|
| 819 |
+
items.pop(field, None)
|
| 820 |
+
|
| 821 |
+
if items.get("Software", None) == "NovelAI":
|
| 822 |
+
try:
|
| 823 |
+
json_info = json.loads(items["Comment"])
|
| 824 |
+
sampler = sd_samplers.samplers_map.get(json_info["sampler"], "Euler a")
|
| 825 |
+
|
| 826 |
+
geninfo = f"""{items["Description"]}
|
| 827 |
+
Negative prompt: {json_info["uc"]}
|
| 828 |
+
Steps: {json_info["steps"]}, Sampler: {sampler}, CFG scale: {json_info["scale"]}, Seed: {json_info["seed"]}, Size: {image.width}x{image.height}, Clip skip: 2, ENSD: 31337"""
|
| 829 |
+
except Exception:
|
| 830 |
+
errors.report("Error parsing NovelAI image generation parameters", exc_info=True)
|
| 831 |
+
|
| 832 |
+
return geninfo, items
|
| 833 |
+
|
| 834 |
+
geninfo, items = read_standard()
|
| 835 |
+
|
| 836 |
+
return geninfo, items
|
| 837 |
+
|
| 838 |
+
|
| 839 |
+
def image_data(data):
|
| 840 |
+
import gradio as gr
|
| 841 |
+
|
| 842 |
+
try:
|
| 843 |
+
image = read(io.BytesIO(data))
|
| 844 |
+
textinfo, _ = read_info_from_image(image)
|
| 845 |
+
return textinfo, None
|
| 846 |
+
except Exception:
|
| 847 |
+
pass
|
| 848 |
+
|
| 849 |
+
try:
|
| 850 |
+
text = data.decode('utf8')
|
| 851 |
+
assert len(text) < 10000
|
| 852 |
+
return text, None
|
| 853 |
+
|
| 854 |
+
except Exception:
|
| 855 |
+
pass
|
| 856 |
+
|
| 857 |
+
return gr.skip(), None
|
| 858 |
+
|
| 859 |
+
|
| 860 |
+
def flatten(img, bgcolor):
|
| 861 |
+
"""replaces transparency with bgcolor (example: "#ffffff"), returning an RGB mode image with no transparency"""
|
| 862 |
+
|
| 863 |
+
if img.mode == "RGBA":
|
| 864 |
+
background = Image.new('RGBA', img.size, bgcolor)
|
| 865 |
+
background.paste(img, mask=img)
|
| 866 |
+
img = background
|
| 867 |
+
|
| 868 |
+
return img.convert('RGB')
|
| 869 |
+
|
| 870 |
+
|
| 871 |
+
def read(fp, **kwargs):
|
| 872 |
+
image = Image.open(fp, **kwargs)
|
| 873 |
+
image = fix_image(image)
|
| 874 |
+
|
| 875 |
+
return image
|
| 876 |
+
|
| 877 |
+
|
| 878 |
+
def fix_image(image: Image.Image):
|
| 879 |
+
if image is None:
|
| 880 |
+
return None
|
| 881 |
+
|
| 882 |
+
try:
|
| 883 |
+
image = ImageOps.exif_transpose(image)
|
| 884 |
+
image = fix_png_transparency(image)
|
| 885 |
+
except Exception:
|
| 886 |
+
pass
|
| 887 |
+
|
| 888 |
+
return image
|
| 889 |
+
|
| 890 |
+
|
| 891 |
+
def fix_png_transparency(image: Image.Image):
|
| 892 |
+
if image.mode not in ("RGB", "P") or not isinstance(image.info.get("transparency"), bytes):
|
| 893 |
+
return image
|
| 894 |
+
|
| 895 |
+
image = image.convert("RGBA")
|
| 896 |
+
return image
|
| 897 |
+
|
| 898 |
+
|
| 899 |
+
def save_video(p, frames: list[np.ndarray], fps: int = 16, basename: str = "") -> str:
|
| 900 |
+
height, width, channels = frames[0].shape
|
| 901 |
+
assert channels == 3, "Frames must be in (H, W, 3) RGB format"
|
| 902 |
+
|
| 903 |
+
namegen = FilenameGenerator(p, p.seeds[0], p.prompts[0], image=None, basename=basename)
|
| 904 |
+
file_decoration = opts.samples_filename_pattern or ("[seed]" if opts.save_to_dirs else "[seed]-[prompt_spaces]")
|
| 905 |
+
folder = opts.outdir_samples or opts.outdir_videos
|
| 906 |
+
extension = opts.video_container
|
| 907 |
+
|
| 908 |
+
os.makedirs(folder, exist_ok=True)
|
| 909 |
+
|
| 910 |
+
file_decoration = namegen.apply(file_decoration)
|
| 911 |
+
|
| 912 |
+
add_number = opts.save_images_add_number or file_decoration == ""
|
| 913 |
+
|
| 914 |
+
if file_decoration != "" and add_number:
|
| 915 |
+
file_decoration = f"-{file_decoration}"
|
| 916 |
+
|
| 917 |
+
if add_number:
|
| 918 |
+
basecount = get_next_sequence_number(folder, basename)
|
| 919 |
+
fullfn = None
|
| 920 |
+
for i in range(256):
|
| 921 |
+
fn = f"{basecount + i:05}" if basename == "" else f"{basename}-{basecount + i:04}"
|
| 922 |
+
fullfn = os.path.join(folder, f"{fn}{file_decoration}.{extension}")
|
| 923 |
+
if not os.path.exists(fullfn):
|
| 924 |
+
break
|
| 925 |
+
else:
|
| 926 |
+
fullfn = os.path.join(folder, f"{file_decoration}.{extension}")
|
| 927 |
+
|
| 928 |
+
crf = int(opts.video_crf)
|
| 929 |
+
preset = str(opts.video_preset)
|
| 930 |
+
profile = str(opts.video_profile)
|
| 931 |
+
|
| 932 |
+
cmd = [
|
| 933 |
+
"ffmpeg",
|
| 934 |
+
"-hide_banner",
|
| 935 |
+
"-loglevel",
|
| 936 |
+
"error",
|
| 937 |
+
"-hwaccel",
|
| 938 |
+
"auto",
|
| 939 |
+
"-y",
|
| 940 |
+
"-f",
|
| 941 |
+
"rawvideo",
|
| 942 |
+
"-vcodec",
|
| 943 |
+
"rawvideo",
|
| 944 |
+
"-pix_fmt",
|
| 945 |
+
"rgb24",
|
| 946 |
+
"-s",
|
| 947 |
+
f"{width}x{height}",
|
| 948 |
+
"-r",
|
| 949 |
+
str(fps),
|
| 950 |
+
"-i",
|
| 951 |
+
"-",
|
| 952 |
+
"-vcodec",
|
| 953 |
+
"h264",
|
| 954 |
+
"-crf",
|
| 955 |
+
str(crf),
|
| 956 |
+
"-preset",
|
| 957 |
+
str(preset),
|
| 958 |
+
"-pix_fmt",
|
| 959 |
+
"yuv420p",
|
| 960 |
+
"-profile:v",
|
| 961 |
+
profile,
|
| 962 |
+
"-an",
|
| 963 |
+
fullfn,
|
| 964 |
+
]
|
| 965 |
+
|
| 966 |
+
proc = subprocess.Popen(cmd, stdin=subprocess.PIPE)
|
| 967 |
+
for frame in frames:
|
| 968 |
+
proc.stdin.write(frame.tobytes())
|
| 969 |
+
proc.stdin.close()
|
| 970 |
+
proc.wait()
|
| 971 |
+
|
| 972 |
+
return fullfn
|
modules/img2img.py
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from contextlib import closing
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
import gradio as gr
|
| 6 |
+
from PIL import Image, ImageFilter, ImageOps, UnidentifiedImageError
|
| 7 |
+
|
| 8 |
+
import modules.processing as processing
|
| 9 |
+
import modules.scripts
|
| 10 |
+
import modules.shared as shared
|
| 11 |
+
from modules import images
|
| 12 |
+
from modules.infotext_utils import (
|
| 13 |
+
create_override_settings_dict,
|
| 14 |
+
parse_generation_parameters,
|
| 15 |
+
)
|
| 16 |
+
from modules.processing import (
|
| 17 |
+
Processed,
|
| 18 |
+
StableDiffusionProcessingImg2Img,
|
| 19 |
+
process_images,
|
| 20 |
+
)
|
| 21 |
+
from modules.sd_models import get_closet_checkpoint_match
|
| 22 |
+
from modules.shared import opts, state
|
| 23 |
+
from modules.ui import plaintext_to_html
|
| 24 |
+
from modules_forge import main_thread
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def process_batch(p, input, output_dir, inpaint_mask_dir, args, to_scale=False, scale_by=1.0, use_png_info=False, png_info_props=None, png_info_dir=None):
|
| 28 |
+
output_dir = output_dir.strip()
|
| 29 |
+
processing.fix_seed(p)
|
| 30 |
+
|
| 31 |
+
if isinstance(input, str):
|
| 32 |
+
batch_images = list(shared.walk_files(input, allowed_extensions=(".png", ".jpg", ".jpeg", ".webp", ".tif", ".tiff", ".avif")))
|
| 33 |
+
else:
|
| 34 |
+
batch_images = [os.path.abspath(x.name) for x in input]
|
| 35 |
+
|
| 36 |
+
is_inpaint_batch = False
|
| 37 |
+
if inpaint_mask_dir:
|
| 38 |
+
inpaint_masks = shared.listfiles(inpaint_mask_dir)
|
| 39 |
+
is_inpaint_batch = bool(inpaint_masks)
|
| 40 |
+
|
| 41 |
+
if is_inpaint_batch:
|
| 42 |
+
print(f"\nInpaint batch is enabled. {len(inpaint_masks)} masks found.")
|
| 43 |
+
|
| 44 |
+
print(f"Will process {len(batch_images)} images, creating {p.n_iter * p.batch_size} new images for each.")
|
| 45 |
+
|
| 46 |
+
state.job_count = len(batch_images) * p.n_iter
|
| 47 |
+
|
| 48 |
+
# extract "default" params to use in case getting png info fails
|
| 49 |
+
prompt = p.prompt
|
| 50 |
+
negative_prompt = p.negative_prompt
|
| 51 |
+
seed = p.seed
|
| 52 |
+
cfg_scale = p.cfg_scale
|
| 53 |
+
sampler_name = p.sampler_name
|
| 54 |
+
steps = p.steps
|
| 55 |
+
override_settings = p.override_settings
|
| 56 |
+
sd_model_checkpoint_override = get_closet_checkpoint_match(override_settings.get("sd_model_checkpoint", None))
|
| 57 |
+
batch_results = None
|
| 58 |
+
discard_further_results = False
|
| 59 |
+
for i, image in enumerate(batch_images):
|
| 60 |
+
state.job = f"{i+1} out of {len(batch_images)}"
|
| 61 |
+
if state.skipped:
|
| 62 |
+
state.skipped = False
|
| 63 |
+
|
| 64 |
+
if state.interrupted or state.stopping_generation:
|
| 65 |
+
break
|
| 66 |
+
|
| 67 |
+
try:
|
| 68 |
+
img = images.read(image)
|
| 69 |
+
except UnidentifiedImageError as e:
|
| 70 |
+
print(e)
|
| 71 |
+
continue
|
| 72 |
+
# Use the EXIF orientation of photos taken by smartphones.
|
| 73 |
+
img = ImageOps.exif_transpose(img)
|
| 74 |
+
|
| 75 |
+
if to_scale:
|
| 76 |
+
p.width = int(img.width * scale_by)
|
| 77 |
+
p.height = int(img.height * scale_by)
|
| 78 |
+
|
| 79 |
+
p.init_images = [img] * p.batch_size
|
| 80 |
+
|
| 81 |
+
image_path = Path(image)
|
| 82 |
+
if is_inpaint_batch:
|
| 83 |
+
# try to find corresponding mask for an image using simple filename matching
|
| 84 |
+
if len(inpaint_masks) == 1:
|
| 85 |
+
mask_image_path = inpaint_masks[0]
|
| 86 |
+
else:
|
| 87 |
+
# try to find corresponding mask for an image using simple filename matching
|
| 88 |
+
mask_image_dir = Path(inpaint_mask_dir)
|
| 89 |
+
masks_found = list(mask_image_dir.glob(f"{image_path.stem}.*"))
|
| 90 |
+
|
| 91 |
+
if len(masks_found) == 0:
|
| 92 |
+
print(f"Warning: mask is not found for {image_path} in {mask_image_dir}. Skipping it.")
|
| 93 |
+
continue
|
| 94 |
+
|
| 95 |
+
# it should contain only 1 matching mask
|
| 96 |
+
# otherwise user has many masks with the same name but different extensions
|
| 97 |
+
mask_image_path = masks_found[0]
|
| 98 |
+
|
| 99 |
+
mask_image = images.read(mask_image_path)
|
| 100 |
+
p.image_mask = mask_image
|
| 101 |
+
|
| 102 |
+
if use_png_info:
|
| 103 |
+
try:
|
| 104 |
+
info_img = img
|
| 105 |
+
if png_info_dir:
|
| 106 |
+
info_img_path = os.path.join(png_info_dir, os.path.basename(image))
|
| 107 |
+
info_img = images.read(info_img_path)
|
| 108 |
+
geninfo, _ = images.read_info_from_image(info_img)
|
| 109 |
+
parsed_parameters = parse_generation_parameters(geninfo)
|
| 110 |
+
parsed_parameters = {k: v for k, v in parsed_parameters.items() if k in (png_info_props or {})}
|
| 111 |
+
except Exception:
|
| 112 |
+
parsed_parameters = {}
|
| 113 |
+
|
| 114 |
+
if "Filename" in png_info_props:
|
| 115 |
+
filename = image_path.stem
|
| 116 |
+
parsed_parameters["Filename"] = filename.replace("(", "\\(").replace(")", "\\)")
|
| 117 |
+
|
| 118 |
+
p.prompt = "".join(
|
| 119 |
+
[
|
| 120 |
+
prompt,
|
| 121 |
+
(" " + parsed_parameters["Prompt"] if "Prompt" in parsed_parameters else ""),
|
| 122 |
+
(" " + parsed_parameters["Filename"] if "Filename" in parsed_parameters else ""),
|
| 123 |
+
]
|
| 124 |
+
)
|
| 125 |
+
p.negative_prompt = negative_prompt + (" " + parsed_parameters["Negative prompt"] if "Negative prompt" in parsed_parameters else "")
|
| 126 |
+
p.seed = int(parsed_parameters.get("Seed", seed))
|
| 127 |
+
p.cfg_scale = float(parsed_parameters.get("CFG scale", cfg_scale))
|
| 128 |
+
p.sampler_name = parsed_parameters.get("Sampler", sampler_name)
|
| 129 |
+
p.steps = int(parsed_parameters.get("Steps", steps))
|
| 130 |
+
|
| 131 |
+
model_info = get_closet_checkpoint_match(parsed_parameters.get("Model hash", None))
|
| 132 |
+
if model_info is not None:
|
| 133 |
+
p.override_settings["sd_model_checkpoint"] = model_info.name
|
| 134 |
+
elif sd_model_checkpoint_override:
|
| 135 |
+
p.override_settings["sd_model_checkpoint"] = sd_model_checkpoint_override
|
| 136 |
+
else:
|
| 137 |
+
p.override_settings.pop("sd_model_checkpoint", None)
|
| 138 |
+
|
| 139 |
+
if output_dir:
|
| 140 |
+
p.outpath_samples = output_dir
|
| 141 |
+
p.override_settings["save_to_dirs"] = False
|
| 142 |
+
|
| 143 |
+
if opts.img2img_batch_use_original_name:
|
| 144 |
+
filename_pattern = f"{image_path.stem}-[generation_number]" if p.n_iter > 1 or p.batch_size > 1 else f"{image_path.stem}"
|
| 145 |
+
p.override_settings["samples_filename_pattern"] = filename_pattern
|
| 146 |
+
|
| 147 |
+
proc = modules.scripts.scripts_img2img.run(p, *args)
|
| 148 |
+
|
| 149 |
+
if proc is None:
|
| 150 |
+
proc = process_images(p)
|
| 151 |
+
|
| 152 |
+
if not discard_further_results and proc:
|
| 153 |
+
if batch_results:
|
| 154 |
+
batch_results.images.extend(proc.images)
|
| 155 |
+
batch_results.infotexts.extend(proc.infotexts)
|
| 156 |
+
else:
|
| 157 |
+
batch_results = proc
|
| 158 |
+
|
| 159 |
+
if 0 <= shared.opts.img2img_batch_show_results_limit < len(batch_results.images):
|
| 160 |
+
discard_further_results = True
|
| 161 |
+
batch_results.images = batch_results.images[: int(shared.opts.img2img_batch_show_results_limit)]
|
| 162 |
+
batch_results.infotexts = batch_results.infotexts[: int(shared.opts.img2img_batch_show_results_limit)]
|
| 163 |
+
|
| 164 |
+
return batch_results
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def img2img_function(id_task: str, request: gr.Request, mode: int, prompt: str, negative_prompt: str, prompt_styles, init_img, sketch, sketch_fg, init_img_with_mask, init_img_with_mask_fg, inpaint_color_sketch, inpaint_color_sketch_fg, init_img_inpaint, init_mask_inpaint, mask_blur: int, mask_alpha: float, inpainting_fill: int, n_iter: int, batch_size: int, cfg_scale: float, distilled_cfg_scale: float, image_cfg_scale: float, denoising_strength: float, selected_scale_tab: int, height: int, width: int, scale_by: float, resize_mode: int, inpaint_full_res: bool, inpaint_full_res_padding: int, inpainting_mask_invert: int, img2img_batch_input_dir: str, img2img_batch_output_dir: str, img2img_batch_inpaint_mask_dir: str, override_settings_texts, img2img_batch_use_png_info: bool, img2img_batch_png_info_props: list, img2img_batch_png_info_dir: str, img2img_batch_source_type: str, img2img_batch_upload: list, *args):
|
| 168 |
+
|
| 169 |
+
override_settings = create_override_settings_dict(override_settings_texts)
|
| 170 |
+
|
| 171 |
+
is_batch = mode == 5
|
| 172 |
+
|
| 173 |
+
height, width = int(height), int(width)
|
| 174 |
+
|
| 175 |
+
image = None
|
| 176 |
+
mask = None
|
| 177 |
+
|
| 178 |
+
if mode == 0: # img2img
|
| 179 |
+
image = init_img
|
| 180 |
+
mask = None
|
| 181 |
+
elif mode == 1: # img2img sketch
|
| 182 |
+
mask = None
|
| 183 |
+
image = Image.alpha_composite(sketch, sketch_fg)
|
| 184 |
+
elif mode == 2: # inpaint
|
| 185 |
+
image = init_img_with_mask
|
| 186 |
+
mask = init_img_with_mask_fg.getchannel("A").convert("L")
|
| 187 |
+
mask = Image.merge("RGBA", (mask, mask, mask, Image.new("L", mask.size, 255)))
|
| 188 |
+
elif mode == 3: # inpaint sketch
|
| 189 |
+
image = Image.alpha_composite(inpaint_color_sketch, inpaint_color_sketch_fg)
|
| 190 |
+
mask = inpaint_color_sketch_fg.getchannel("A").convert("L")
|
| 191 |
+
short_side = min(mask.size)
|
| 192 |
+
dilation_size = int(0.015 * short_side) * 2 + 1
|
| 193 |
+
mask = mask.filter(ImageFilter.MaxFilter(dilation_size))
|
| 194 |
+
mask = Image.merge("RGBA", (mask, mask, mask, Image.new("L", mask.size, 255)))
|
| 195 |
+
elif mode == 4: # inpaint upload mask
|
| 196 |
+
image = init_img_inpaint
|
| 197 |
+
mask = init_mask_inpaint
|
| 198 |
+
|
| 199 |
+
if mask and isinstance(mask, Image.Image):
|
| 200 |
+
mask = mask.point(lambda v: 255 if v > 128 else 0)
|
| 201 |
+
|
| 202 |
+
image = images.fix_image(image)
|
| 203 |
+
mask = images.fix_image(mask)
|
| 204 |
+
|
| 205 |
+
if selected_scale_tab == 1 and not is_batch:
|
| 206 |
+
assert image, "Can't scale by because no image is selected"
|
| 207 |
+
|
| 208 |
+
width = int(image.width * scale_by)
|
| 209 |
+
width -= width % 8
|
| 210 |
+
height = int(image.height * scale_by)
|
| 211 |
+
height -= height % 8
|
| 212 |
+
|
| 213 |
+
assert 0.0 <= denoising_strength <= 1.0, "can only work with strength in [0.0, 1.0]"
|
| 214 |
+
|
| 215 |
+
p = StableDiffusionProcessingImg2Img(
|
| 216 |
+
outpath_samples=opts.outdir_samples or opts.outdir_img2img_samples,
|
| 217 |
+
outpath_grids=opts.outdir_grids or opts.outdir_img2img_grids,
|
| 218 |
+
prompt=prompt,
|
| 219 |
+
negative_prompt=negative_prompt,
|
| 220 |
+
styles=prompt_styles,
|
| 221 |
+
batch_size=batch_size,
|
| 222 |
+
n_iter=n_iter,
|
| 223 |
+
cfg_scale=cfg_scale,
|
| 224 |
+
width=width,
|
| 225 |
+
height=height,
|
| 226 |
+
init_images=[image],
|
| 227 |
+
mask=mask,
|
| 228 |
+
mask_blur=mask_blur,
|
| 229 |
+
inpainting_fill=inpainting_fill,
|
| 230 |
+
resize_mode=resize_mode,
|
| 231 |
+
denoising_strength=denoising_strength,
|
| 232 |
+
image_cfg_scale=image_cfg_scale,
|
| 233 |
+
inpaint_full_res=inpaint_full_res,
|
| 234 |
+
inpaint_full_res_padding=inpaint_full_res_padding,
|
| 235 |
+
inpainting_mask_invert=inpainting_mask_invert,
|
| 236 |
+
override_settings=override_settings,
|
| 237 |
+
distilled_cfg_scale=distilled_cfg_scale,
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
p.scripts = modules.scripts.scripts_img2img
|
| 241 |
+
p.script_args = args
|
| 242 |
+
|
| 243 |
+
p.user = request.username
|
| 244 |
+
|
| 245 |
+
if shared.opts.enable_console_prompts:
|
| 246 |
+
print(f"\nimg2img: {prompt}", file=shared.progress_print_out)
|
| 247 |
+
|
| 248 |
+
with closing(p):
|
| 249 |
+
if is_batch:
|
| 250 |
+
if img2img_batch_source_type == "upload":
|
| 251 |
+
assert isinstance(img2img_batch_upload, list) and img2img_batch_upload
|
| 252 |
+
output_dir = ""
|
| 253 |
+
inpaint_mask_dir = ""
|
| 254 |
+
png_info_dir = img2img_batch_png_info_dir if not shared.cmd_opts.hide_ui_dir_config else ""
|
| 255 |
+
processed = process_batch(p, img2img_batch_upload, output_dir, inpaint_mask_dir, args, to_scale=selected_scale_tab == 1, scale_by=scale_by, use_png_info=img2img_batch_use_png_info, png_info_props=img2img_batch_png_info_props, png_info_dir=png_info_dir)
|
| 256 |
+
else: # "from dir"
|
| 257 |
+
assert not shared.cmd_opts.hide_ui_dir_config, "Launched with --hide-ui-dir-config, batch img2img disabled"
|
| 258 |
+
processed = process_batch(p, img2img_batch_input_dir, img2img_batch_output_dir, img2img_batch_inpaint_mask_dir, args, to_scale=selected_scale_tab == 1, scale_by=scale_by, use_png_info=img2img_batch_use_png_info, png_info_props=img2img_batch_png_info_props, png_info_dir=img2img_batch_png_info_dir)
|
| 259 |
+
|
| 260 |
+
if processed is None:
|
| 261 |
+
processed = Processed(p, [], p.seed, "")
|
| 262 |
+
else:
|
| 263 |
+
processed = modules.scripts.scripts_img2img.run(p, *args)
|
| 264 |
+
if processed is None:
|
| 265 |
+
processed = process_images(p)
|
| 266 |
+
|
| 267 |
+
shared.total_tqdm.clear()
|
| 268 |
+
|
| 269 |
+
generation_info_js = processed.js()
|
| 270 |
+
if opts.samples_log_stdout:
|
| 271 |
+
print(generation_info_js)
|
| 272 |
+
|
| 273 |
+
if opts.do_not_show_images:
|
| 274 |
+
processed.images = []
|
| 275 |
+
|
| 276 |
+
if processed.video_path is None:
|
| 277 |
+
gallery_arg = gr.update(value=processed.images + processed.extra_images, visible=True)
|
| 278 |
+
video_arg = gr.update(value=None, visible=False)
|
| 279 |
+
else:
|
| 280 |
+
gallery_arg = gr.update(value=None, visible=False)
|
| 281 |
+
video_arg = gr.update(value=processed.video_path, visible=True)
|
| 282 |
+
|
| 283 |
+
return gallery_arg, video_arg, generation_info_js, plaintext_to_html(processed.info), plaintext_to_html(processed.comments, classname="comments")
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def img2img(id_task: str, request: gr.Request, mode: int, prompt: str, negative_prompt: str, prompt_styles, init_img, sketch, sketch_fg, init_img_with_mask, init_img_with_mask_fg, inpaint_color_sketch, inpaint_color_sketch_fg, init_img_inpaint, init_mask_inpaint, mask_blur: int, mask_alpha: float, inpainting_fill: int, n_iter: int, batch_size: int, cfg_scale: float, distilled_cfg_scale: float, image_cfg_scale: float, denoising_strength: float, selected_scale_tab: int, height: int, width: int, scale_by: float, resize_mode: int, inpaint_full_res: bool, inpaint_full_res_padding: int, inpainting_mask_invert: int, img2img_batch_input_dir: str, img2img_batch_output_dir: str, img2img_batch_inpaint_mask_dir: str, override_settings_texts, img2img_batch_use_png_info: bool, img2img_batch_png_info_props: list, img2img_batch_png_info_dir: str, img2img_batch_source_type: str, img2img_batch_upload: list, *args):
|
| 287 |
+
return main_thread.run_and_wait_result(img2img_function, id_task, request, mode, prompt, negative_prompt, prompt_styles, init_img, sketch, sketch_fg, init_img_with_mask, init_img_with_mask_fg, inpaint_color_sketch, inpaint_color_sketch_fg, init_img_inpaint, init_mask_inpaint, mask_blur, mask_alpha, inpainting_fill, n_iter, batch_size, cfg_scale, distilled_cfg_scale, image_cfg_scale, denoising_strength, selected_scale_tab, height, width, scale_by, resize_mode, inpaint_full_res, inpaint_full_res_padding, inpainting_mask_invert, img2img_batch_input_dir, img2img_batch_output_dir, img2img_batch_inpaint_mask_dir, override_settings_texts, img2img_batch_use_png_info, img2img_batch_png_info_props, img2img_batch_png_info_dir, img2img_batch_source_type, img2img_batch_upload, *args)
|
modules/infotext_utils.py
ADDED
|
@@ -0,0 +1,626 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import base64
|
| 4 |
+
import io
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
import re
|
| 8 |
+
import sys
|
| 9 |
+
|
| 10 |
+
import gradio as gr
|
| 11 |
+
from PIL import Image
|
| 12 |
+
|
| 13 |
+
from modules import errors, images, infotext_versions, processing, prompt_parser, script_callbacks, shared, ui_tempdir
|
| 14 |
+
from modules.paths import data_path
|
| 15 |
+
from modules_forge import main_entry
|
| 16 |
+
|
| 17 |
+
sys.modules["modules.generation_parameters_copypaste"] = sys.modules[__name__] # alias for old name
|
| 18 |
+
|
| 19 |
+
re_param_code = r'\s*(\w[\w \-/]+):\s*("(?:\\.|[^\\"])+"|[^,]*)(?:,|$)'
|
| 20 |
+
re_param = re.compile(re_param_code)
|
| 21 |
+
re_imagesize = re.compile(r"^(\d+)x(\d+)$")
|
| 22 |
+
type_of_gr_update = type(gr.skip())
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class ParamBinding:
|
| 26 |
+
def __init__(self, paste_button, tabname, source_text_component=None, source_image_component=None, source_tabname=None, override_settings_component=None, paste_field_names=None):
|
| 27 |
+
self.paste_button = paste_button
|
| 28 |
+
self.tabname = tabname
|
| 29 |
+
self.source_text_component = source_text_component
|
| 30 |
+
self.source_image_component = source_image_component
|
| 31 |
+
self.source_tabname = source_tabname
|
| 32 |
+
self.override_settings_component = override_settings_component
|
| 33 |
+
self.paste_field_names = paste_field_names or []
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class PasteField(tuple):
|
| 37 |
+
def __new__(cls, component, target, *, api=None):
|
| 38 |
+
return super().__new__(cls, (component, target))
|
| 39 |
+
|
| 40 |
+
def __init__(self, component, target, *, api=None):
|
| 41 |
+
super().__init__()
|
| 42 |
+
|
| 43 |
+
self.api = api
|
| 44 |
+
self.component = component
|
| 45 |
+
self.label = target if isinstance(target, str) else None
|
| 46 |
+
self.function = target if callable(target) else None
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
paste_fields: dict[str, dict] = {}
|
| 50 |
+
registered_param_bindings: list[ParamBinding] = []
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def reset():
|
| 54 |
+
paste_fields.clear()
|
| 55 |
+
registered_param_bindings.clear()
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def quote(text):
|
| 59 |
+
if "," not in str(text) and "\n" not in str(text) and ":" not in str(text):
|
| 60 |
+
return text
|
| 61 |
+
|
| 62 |
+
return json.dumps(text, ensure_ascii=False)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def unquote(text):
|
| 66 |
+
if len(text) == 0 or text[0] != '"' or text[-1] != '"':
|
| 67 |
+
return text
|
| 68 |
+
|
| 69 |
+
try:
|
| 70 |
+
return json.loads(text)
|
| 71 |
+
except Exception:
|
| 72 |
+
return text
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def image_from_url_text(filedata):
|
| 76 |
+
if filedata is None:
|
| 77 |
+
return None
|
| 78 |
+
|
| 79 |
+
if isinstance(filedata, list):
|
| 80 |
+
if len(filedata) == 0:
|
| 81 |
+
return None
|
| 82 |
+
|
| 83 |
+
filedata = filedata[0]
|
| 84 |
+
|
| 85 |
+
if isinstance(filedata, dict) and filedata.get("is_file", False):
|
| 86 |
+
filedata = filedata
|
| 87 |
+
|
| 88 |
+
filename = None
|
| 89 |
+
if type(filedata) == dict and filedata.get("is_file", False):
|
| 90 |
+
filename = filedata["name"]
|
| 91 |
+
|
| 92 |
+
elif isinstance(filedata, tuple) and len(filedata) == 2: # gradio 4.16 sends images from gallery as a list of tuples
|
| 93 |
+
return filedata[0]
|
| 94 |
+
|
| 95 |
+
if filename:
|
| 96 |
+
is_in_right_dir = ui_tempdir.check_tmp_file(shared.demo, filename)
|
| 97 |
+
assert is_in_right_dir, "trying to open image file outside of allowed directories"
|
| 98 |
+
|
| 99 |
+
filename = filename.rsplit("?", 1)[0]
|
| 100 |
+
return images.read(filename)
|
| 101 |
+
|
| 102 |
+
if isinstance(filedata, str):
|
| 103 |
+
if filedata.startswith("data:image/png;base64,"):
|
| 104 |
+
filedata = filedata[len("data:image/png;base64,") :]
|
| 105 |
+
|
| 106 |
+
filedata = base64.decodebytes(filedata.encode("utf-8"))
|
| 107 |
+
image = images.read(io.BytesIO(filedata))
|
| 108 |
+
return image
|
| 109 |
+
|
| 110 |
+
return None
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def add_paste_fields(tabname, init_img, fields, override_settings_component=None):
|
| 114 |
+
|
| 115 |
+
if fields:
|
| 116 |
+
for i in range(len(fields)):
|
| 117 |
+
if not isinstance(fields[i], PasteField):
|
| 118 |
+
fields[i] = PasteField(*fields[i])
|
| 119 |
+
|
| 120 |
+
paste_fields[tabname] = {"init_img": init_img, "fields": fields, "override_settings_component": override_settings_component}
|
| 121 |
+
|
| 122 |
+
# backwards compatibility for existing extensions
|
| 123 |
+
import modules.ui
|
| 124 |
+
|
| 125 |
+
if tabname == "txt2img":
|
| 126 |
+
modules.ui.txt2img_paste_fields = fields
|
| 127 |
+
elif tabname == "img2img":
|
| 128 |
+
modules.ui.img2img_paste_fields = fields
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def create_buttons(tabs_list):
|
| 132 |
+
buttons = {}
|
| 133 |
+
for tab in tabs_list:
|
| 134 |
+
buttons[tab] = gr.Button(f"Send to {tab}", elem_id=f"{tab}_tab")
|
| 135 |
+
return buttons
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def bind_buttons(buttons, send_image, send_generate_info):
|
| 139 |
+
"""old function for backwards compatibility; do not use this, use register_paste_params_button"""
|
| 140 |
+
for tabname, button in buttons.items():
|
| 141 |
+
source_text_component = send_generate_info if isinstance(send_generate_info, gr.components.Component) else None
|
| 142 |
+
source_tabname = send_generate_info if isinstance(send_generate_info, str) else None
|
| 143 |
+
|
| 144 |
+
register_paste_params_button(ParamBinding(paste_button=button, tabname=tabname, source_text_component=source_text_component, source_image_component=send_image, source_tabname=source_tabname))
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def register_paste_params_button(binding: ParamBinding):
|
| 148 |
+
registered_param_bindings.append(binding)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def connect_paste_params_buttons():
|
| 152 |
+
for binding in registered_param_bindings:
|
| 153 |
+
destination_image_component = paste_fields[binding.tabname]["init_img"]
|
| 154 |
+
fields = paste_fields[binding.tabname]["fields"]
|
| 155 |
+
override_settings_component = binding.override_settings_component or paste_fields[binding.tabname]["override_settings_component"]
|
| 156 |
+
|
| 157 |
+
destination_width_component = next(iter([field for field, name in fields if name == "Size-1"] if fields else []), None)
|
| 158 |
+
destination_height_component = next(iter([field for field, name in fields if name == "Size-2"] if fields else []), None)
|
| 159 |
+
|
| 160 |
+
if binding.source_image_component and destination_image_component:
|
| 161 |
+
need_send_dementions = destination_width_component and binding.tabname != "inpaint"
|
| 162 |
+
if isinstance(binding.source_image_component, gr.Gallery):
|
| 163 |
+
func = send_image_and_dimensions if need_send_dementions else image_from_url_text
|
| 164 |
+
jsfunc = "extract_image_from_gallery"
|
| 165 |
+
else:
|
| 166 |
+
func = send_image_and_dimensions if need_send_dementions else lambda x: x
|
| 167 |
+
jsfunc = None
|
| 168 |
+
|
| 169 |
+
binding.paste_button.click(
|
| 170 |
+
fn=func,
|
| 171 |
+
_js=jsfunc,
|
| 172 |
+
inputs=[binding.source_image_component],
|
| 173 |
+
outputs=[destination_image_component, destination_width_component, destination_height_component] if need_send_dementions else [destination_image_component],
|
| 174 |
+
show_progress=False,
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
if binding.source_text_component is not None and fields is not None:
|
| 178 |
+
connect_paste(binding.paste_button, fields, binding.source_text_component, override_settings_component, binding.tabname)
|
| 179 |
+
|
| 180 |
+
if binding.source_tabname is not None and fields is not None:
|
| 181 |
+
paste_field_names = [
|
| 182 |
+
*["Prompt", "Negative prompt", "Steps", "Face restoration"],
|
| 183 |
+
*(["Seed"] if shared.opts.send_seed else []),
|
| 184 |
+
*(["CFG scale"] if shared.opts.send_cfg else []),
|
| 185 |
+
*binding.paste_field_names,
|
| 186 |
+
]
|
| 187 |
+
|
| 188 |
+
binding.paste_button.click(
|
| 189 |
+
fn=lambda *x: x,
|
| 190 |
+
inputs=[field for field, name in paste_fields[binding.source_tabname]["fields"] if name in paste_field_names],
|
| 191 |
+
outputs=[field for field, name in fields if name in paste_field_names],
|
| 192 |
+
show_progress=False,
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
binding.paste_button.click(
|
| 196 |
+
fn=None,
|
| 197 |
+
_js=f"switch_to_{binding.tabname}",
|
| 198 |
+
inputs=None,
|
| 199 |
+
outputs=None,
|
| 200 |
+
show_progress=False,
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def send_image_and_dimensions(x):
|
| 205 |
+
if isinstance(x, Image.Image):
|
| 206 |
+
img = x
|
| 207 |
+
if img.mode == "RGBA":
|
| 208 |
+
img = img.convert("RGB")
|
| 209 |
+
elif isinstance(x, list) and isinstance(x[0], tuple):
|
| 210 |
+
img = x[0][0]
|
| 211 |
+
else:
|
| 212 |
+
img = image_from_url_text(x)
|
| 213 |
+
if img is not None and img.mode == "RGBA":
|
| 214 |
+
img = img.convert("RGB")
|
| 215 |
+
|
| 216 |
+
if shared.opts.send_size and isinstance(img, Image.Image):
|
| 217 |
+
w = img.width
|
| 218 |
+
h = img.height
|
| 219 |
+
else:
|
| 220 |
+
w = gr.skip()
|
| 221 |
+
h = gr.skip()
|
| 222 |
+
|
| 223 |
+
return img, w, h
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def restore_old_hires_fix_params(res):
|
| 227 |
+
"""
|
| 228 |
+
for infotexts that specify old First pass size parameter,
|
| 229 |
+
convert it into width, height, and hr scale
|
| 230 |
+
"""
|
| 231 |
+
|
| 232 |
+
firstpass_width = res.get("First pass size-1", None)
|
| 233 |
+
firstpass_height = res.get("First pass size-2", None)
|
| 234 |
+
|
| 235 |
+
if shared.opts.use_old_hires_fix_width_height:
|
| 236 |
+
hires_width = int(res.get("Hires resize-1", 0))
|
| 237 |
+
hires_height = int(res.get("Hires resize-2", 0))
|
| 238 |
+
|
| 239 |
+
if hires_width and hires_height:
|
| 240 |
+
res["Size-1"] = hires_width
|
| 241 |
+
res["Size-2"] = hires_height
|
| 242 |
+
return
|
| 243 |
+
|
| 244 |
+
if firstpass_width is None or firstpass_height is None:
|
| 245 |
+
return
|
| 246 |
+
|
| 247 |
+
firstpass_width, firstpass_height = int(firstpass_width), int(firstpass_height)
|
| 248 |
+
width = int(res.get("Size-1", 512))
|
| 249 |
+
height = int(res.get("Size-2", 512))
|
| 250 |
+
|
| 251 |
+
if firstpass_width == 0 or firstpass_height == 0:
|
| 252 |
+
firstpass_width, firstpass_height = processing.old_hires_fix_first_pass_dimensions(width, height)
|
| 253 |
+
|
| 254 |
+
res["Size-1"] = firstpass_width
|
| 255 |
+
res["Size-2"] = firstpass_height
|
| 256 |
+
res["Hires resize-1"] = width
|
| 257 |
+
res["Hires resize-2"] = height
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def parse_generation_parameters(x: str, skip_fields: list[str] | None = None):
|
| 261 |
+
"""parses generation parameters string, the one you see in text field under the picture in UI:
|
| 262 |
+
```
|
| 263 |
+
girl with an artist's beret, determined, blue eyes, desert scene, computer monitors, heavy makeup, by Alphonse Mucha and Charlie Bowater, ((eyeshadow)), (coquettish), detailed, intricate
|
| 264 |
+
Negative prompt: ugly, fat, obese, chubby, (((deformed))), [blurry], bad anatomy, disfigured, poorly drawn face, mutation, mutated, (extra_limb), (ugly), (poorly drawn hands), messy drawing
|
| 265 |
+
Steps: 20, Sampler: Euler a, CFG scale: 7, Seed: 965400086, Size: 512x512, Model hash: 45dee52b
|
| 266 |
+
```
|
| 267 |
+
|
| 268 |
+
returns a dict with field values
|
| 269 |
+
"""
|
| 270 |
+
if skip_fields is None:
|
| 271 |
+
skip_fields = shared.opts.infotext_skip_pasting
|
| 272 |
+
|
| 273 |
+
res = {}
|
| 274 |
+
|
| 275 |
+
prompt = ""
|
| 276 |
+
negative_prompt = ""
|
| 277 |
+
|
| 278 |
+
done_with_prompt = False
|
| 279 |
+
|
| 280 |
+
*lines, lastline = x.strip().split("\n")
|
| 281 |
+
if len(re_param.findall(lastline)) < 3:
|
| 282 |
+
lines.append(lastline)
|
| 283 |
+
lastline = ""
|
| 284 |
+
|
| 285 |
+
for line in lines:
|
| 286 |
+
line = line.strip()
|
| 287 |
+
if line.startswith("Negative prompt:"):
|
| 288 |
+
done_with_prompt = True
|
| 289 |
+
line = line[16:].strip()
|
| 290 |
+
if done_with_prompt:
|
| 291 |
+
negative_prompt += ("" if negative_prompt == "" else "\n") + line
|
| 292 |
+
else:
|
| 293 |
+
prompt += ("" if prompt == "" else "\n") + line
|
| 294 |
+
|
| 295 |
+
if "Civitai" in lastline and "FLUX" in lastline:
|
| 296 |
+
lastline = lastline.replace("Sampler: Undefined,", "Sampler: Euler, Schedule type: Simple,")
|
| 297 |
+
lastline = lastline.replace("CFG scale: ", "CFG scale: 1, Distilled CFG Scale: ")
|
| 298 |
+
|
| 299 |
+
for k, v in re_param.findall(lastline):
|
| 300 |
+
if k == "Noise Schedule":
|
| 301 |
+
continue
|
| 302 |
+
try:
|
| 303 |
+
if v[0] == '"' and v[-1] == '"':
|
| 304 |
+
v = unquote(v)
|
| 305 |
+
|
| 306 |
+
m = re_imagesize.match(v)
|
| 307 |
+
if m is not None:
|
| 308 |
+
res[f"{k}-1"] = m.group(1)
|
| 309 |
+
res[f"{k}-2"] = m.group(2)
|
| 310 |
+
else:
|
| 311 |
+
res[k] = v
|
| 312 |
+
except Exception:
|
| 313 |
+
print(f'Error parsing "{k}: {v}"')
|
| 314 |
+
|
| 315 |
+
# Extract styles from prompt
|
| 316 |
+
if shared.opts.infotext_styles != "Ignore":
|
| 317 |
+
found_styles, prompt_no_styles, negative_prompt_no_styles = shared.prompt_styles.extract_styles_from_prompt(prompt, negative_prompt)
|
| 318 |
+
|
| 319 |
+
same_hr_styles = True
|
| 320 |
+
if ("Hires prompt" in res or "Hires negative prompt" in res) and (infotext_ver > infotext_versions.v180_hr_styles if (infotext_ver := infotext_versions.parse_version(res.get("Version"))) else True):
|
| 321 |
+
hr_prompt, hr_negative_prompt = res.get("Hires prompt", prompt), res.get("Hires negative prompt", negative_prompt)
|
| 322 |
+
hr_found_styles, hr_prompt_no_styles, hr_negative_prompt_no_styles = shared.prompt_styles.extract_styles_from_prompt(hr_prompt, hr_negative_prompt)
|
| 323 |
+
if same_hr_styles := found_styles == hr_found_styles:
|
| 324 |
+
res["Hires prompt"] = "" if hr_prompt_no_styles == prompt_no_styles else hr_prompt_no_styles
|
| 325 |
+
res["Hires negative prompt"] = "" if hr_negative_prompt_no_styles == negative_prompt_no_styles else hr_negative_prompt_no_styles
|
| 326 |
+
|
| 327 |
+
if same_hr_styles:
|
| 328 |
+
prompt, negative_prompt = prompt_no_styles, negative_prompt_no_styles
|
| 329 |
+
if (shared.opts.infotext_styles == "Apply if any" and found_styles) or shared.opts.infotext_styles == "Apply":
|
| 330 |
+
res["Styles array"] = found_styles
|
| 331 |
+
|
| 332 |
+
res["Prompt"] = prompt
|
| 333 |
+
res["Negative prompt"] = negative_prompt
|
| 334 |
+
|
| 335 |
+
res.pop("Clip skip", None)
|
| 336 |
+
|
| 337 |
+
if "Hires resize-1" not in res:
|
| 338 |
+
res["Hires resize-1"] = 0
|
| 339 |
+
res["Hires resize-2"] = 0
|
| 340 |
+
|
| 341 |
+
if "Hires sampler" not in res:
|
| 342 |
+
res["Hires sampler"] = "Use same sampler"
|
| 343 |
+
|
| 344 |
+
if "Hires schedule type" not in res:
|
| 345 |
+
res["Hires schedule type"] = "Use same scheduler"
|
| 346 |
+
|
| 347 |
+
if "Hires checkpoint" not in res:
|
| 348 |
+
res["Hires checkpoint"] = "Use same checkpoint"
|
| 349 |
+
|
| 350 |
+
if "Hires prompt" not in res:
|
| 351 |
+
res["Hires prompt"] = ""
|
| 352 |
+
|
| 353 |
+
if "Hires negative prompt" not in res:
|
| 354 |
+
res["Hires negative prompt"] = ""
|
| 355 |
+
|
| 356 |
+
if "Mask mode" not in res:
|
| 357 |
+
res["Mask mode"] = "Inpaint masked"
|
| 358 |
+
|
| 359 |
+
if "Masked content" not in res:
|
| 360 |
+
res["Masked content"] = "original"
|
| 361 |
+
|
| 362 |
+
if "Inpaint area" not in res:
|
| 363 |
+
res["Inpaint area"] = "Whole picture"
|
| 364 |
+
|
| 365 |
+
if "Masked area padding" not in res:
|
| 366 |
+
res["Masked area padding"] = 32
|
| 367 |
+
|
| 368 |
+
restore_old_hires_fix_params(res)
|
| 369 |
+
|
| 370 |
+
# Missing RNG means the default was set, which is GPU RNG
|
| 371 |
+
if "RNG" not in res:
|
| 372 |
+
res["RNG"] = "GPU"
|
| 373 |
+
|
| 374 |
+
if "Schedule type" not in res:
|
| 375 |
+
res["Schedule type"] = "Automatic"
|
| 376 |
+
|
| 377 |
+
if "Schedule max sigma" not in res:
|
| 378 |
+
res["Schedule max sigma"] = 0
|
| 379 |
+
|
| 380 |
+
if "Schedule min sigma" not in res:
|
| 381 |
+
res["Schedule min sigma"] = 0
|
| 382 |
+
|
| 383 |
+
if "Schedule rho" not in res:
|
| 384 |
+
res["Schedule rho"] = 0
|
| 385 |
+
|
| 386 |
+
if "VAE Encoder" not in res:
|
| 387 |
+
res["VAE Encoder"] = "Full"
|
| 388 |
+
|
| 389 |
+
if "VAE Decoder" not in res:
|
| 390 |
+
res["VAE Decoder"] = "Full"
|
| 391 |
+
|
| 392 |
+
prompt_attention = prompt_parser.parse_prompt_attention(prompt)
|
| 393 |
+
prompt_attention += prompt_parser.parse_prompt_attention(negative_prompt)
|
| 394 |
+
prompt_uses_emphasis = len(prompt_attention) != len([p for p in prompt_attention if p[1] == 1.0 or p[0] == "BREAK"])
|
| 395 |
+
if "Emphasis" not in res and prompt_uses_emphasis:
|
| 396 |
+
res["Emphasis"] = "Original"
|
| 397 |
+
|
| 398 |
+
if "Refiner switch by sampling steps" not in res:
|
| 399 |
+
res["Refiner switch by sampling steps"] = False
|
| 400 |
+
|
| 401 |
+
if "Shift" in res:
|
| 402 |
+
res["Distilled CFG Scale"] = res.pop("Shift")
|
| 403 |
+
|
| 404 |
+
infotext_versions.backcompat(res)
|
| 405 |
+
|
| 406 |
+
for key in skip_fields:
|
| 407 |
+
res.pop(key, None)
|
| 408 |
+
|
| 409 |
+
# checkpoint override is not supported
|
| 410 |
+
res.pop("Model", None)
|
| 411 |
+
|
| 412 |
+
# VAE / TE
|
| 413 |
+
modules = []
|
| 414 |
+
hr_modules = []
|
| 415 |
+
vae = res.pop("VAE", None)
|
| 416 |
+
if vae:
|
| 417 |
+
modules = [vae]
|
| 418 |
+
else:
|
| 419 |
+
for key in res:
|
| 420 |
+
if key.startswith("Module "):
|
| 421 |
+
added = False
|
| 422 |
+
for knownmodule in main_entry.module_list.keys():
|
| 423 |
+
filename, _ = os.path.splitext(knownmodule)
|
| 424 |
+
if res[key] == filename:
|
| 425 |
+
added = True
|
| 426 |
+
modules.append(knownmodule)
|
| 427 |
+
break
|
| 428 |
+
if not added:
|
| 429 |
+
modules.append(res[key]) # so it shows in the override section (consistent with checkpoint and old vae)
|
| 430 |
+
elif key.startswith("Hires Module "):
|
| 431 |
+
for knownmodule in main_entry.module_list.keys():
|
| 432 |
+
filename, _ = os.path.splitext(knownmodule)
|
| 433 |
+
if res[key] == filename:
|
| 434 |
+
hr_modules.append(knownmodule)
|
| 435 |
+
break
|
| 436 |
+
|
| 437 |
+
if modules != []:
|
| 438 |
+
current_modules = shared.opts.forge_additional_modules
|
| 439 |
+
basename_modules = []
|
| 440 |
+
for m in current_modules:
|
| 441 |
+
basename_modules.append(os.path.basename(m))
|
| 442 |
+
|
| 443 |
+
if sorted(modules) != sorted(basename_modules):
|
| 444 |
+
res["VAE/TE"] = modules
|
| 445 |
+
|
| 446 |
+
# if 'Use same choices' was the selection for Hires VAE / Text Encoder, it will be the only Hires Module
|
| 447 |
+
# if the selection was empty, it will be the only Hires Module, saved as 'Built-in'
|
| 448 |
+
if "Hires Module 1" in res:
|
| 449 |
+
if res["Hires Module 1"] == "Use same choices":
|
| 450 |
+
hr_modules = ["Use same choices"]
|
| 451 |
+
elif res["Hires Module 1"] == "Built-in":
|
| 452 |
+
hr_modules = []
|
| 453 |
+
|
| 454 |
+
res["Hires VAE/TE"] = hr_modules
|
| 455 |
+
else:
|
| 456 |
+
# no Hires Module infotext, use default
|
| 457 |
+
res["Hires VAE/TE"] = ["Use same choices"]
|
| 458 |
+
|
| 459 |
+
return res
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
infotext_to_setting_name_mapping = [
|
| 463 |
+
("VAE/TE", "forge_additional_modules"),
|
| 464 |
+
]
|
| 465 |
+
"""Mapping of infotext labels to setting names. Only left for backwards compatibility - use OptionInfo(..., infotext='...') instead.
|
| 466 |
+
Example content:
|
| 467 |
+
|
| 468 |
+
infotext_to_setting_name_mapping = [
|
| 469 |
+
('Conditional mask weight', 'inpainting_mask_weight'),
|
| 470 |
+
('Model hash', 'sd_model_checkpoint'),
|
| 471 |
+
('ENSD', 'eta_noise_seed_delta'),
|
| 472 |
+
('Schedule type', 'k_sched_type'),
|
| 473 |
+
]
|
| 474 |
+
"""
|
| 475 |
+
from ast import literal_eval
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
def create_override_settings_dict(text_pairs):
|
| 479 |
+
"""creates processing's override_settings parameters from gradio's multiselect
|
| 480 |
+
|
| 481 |
+
Example input:
|
| 482 |
+
['Clip skip: 2', 'Model hash: e6e99610c4', 'ENSD: 31337']
|
| 483 |
+
|
| 484 |
+
Example output:
|
| 485 |
+
{'CLIP_stop_at_last_layers': 2, 'sd_model_checkpoint': 'e6e99610c4', 'eta_noise_seed_delta': 31337}
|
| 486 |
+
"""
|
| 487 |
+
|
| 488 |
+
res = {}
|
| 489 |
+
|
| 490 |
+
if not text_pairs:
|
| 491 |
+
return res
|
| 492 |
+
|
| 493 |
+
params = {}
|
| 494 |
+
for pair in text_pairs:
|
| 495 |
+
k, v = pair.split(":", maxsplit=1)
|
| 496 |
+
|
| 497 |
+
params[k] = v.strip()
|
| 498 |
+
|
| 499 |
+
mapping = [(info.infotext, k) for k, info in shared.opts.data_labels.items() if info.infotext]
|
| 500 |
+
for param_name, setting_name in mapping + infotext_to_setting_name_mapping:
|
| 501 |
+
value = params.get(param_name, None)
|
| 502 |
+
|
| 503 |
+
if value is None:
|
| 504 |
+
continue
|
| 505 |
+
|
| 506 |
+
if setting_name == "forge_additional_modules":
|
| 507 |
+
res[setting_name] = literal_eval(value)
|
| 508 |
+
continue
|
| 509 |
+
|
| 510 |
+
res[setting_name] = shared.opts.cast_value(setting_name, value)
|
| 511 |
+
|
| 512 |
+
return res
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
def get_override_settings(params, *, skip_fields=None):
|
| 516 |
+
"""Returns a list of settings overrides from the infotext parameters dictionary.
|
| 517 |
+
|
| 518 |
+
This function checks the `params` dictionary for any keys that correspond to settings in `shared.opts` and returns
|
| 519 |
+
a list of tuples containing the parameter name, setting name, and new value cast to correct type.
|
| 520 |
+
|
| 521 |
+
It checks for conditions before adding an override:
|
| 522 |
+
- ignores settings that match the current value
|
| 523 |
+
- ignores parameter keys present in skip_fields argument.
|
| 524 |
+
|
| 525 |
+
Example input:
|
| 526 |
+
{"Clip skip": "2"}
|
| 527 |
+
|
| 528 |
+
Example output:
|
| 529 |
+
[("Clip skip", "CLIP_stop_at_last_layers", 2)]
|
| 530 |
+
"""
|
| 531 |
+
|
| 532 |
+
res = []
|
| 533 |
+
|
| 534 |
+
mapping = [(info.infotext, k) for k, info in shared.opts.data_labels.items() if info.infotext]
|
| 535 |
+
for param_name, setting_name in mapping + infotext_to_setting_name_mapping:
|
| 536 |
+
if param_name in (skip_fields or {}):
|
| 537 |
+
continue
|
| 538 |
+
|
| 539 |
+
v = params.get(param_name, None)
|
| 540 |
+
if v is None:
|
| 541 |
+
continue
|
| 542 |
+
|
| 543 |
+
if setting_name in ["sd_model_checkpoint", "forge_additional_modules"]:
|
| 544 |
+
continue
|
| 545 |
+
|
| 546 |
+
v = shared.opts.cast_value(setting_name, v)
|
| 547 |
+
current_value = getattr(shared.opts, setting_name, None)
|
| 548 |
+
|
| 549 |
+
if v == current_value:
|
| 550 |
+
continue
|
| 551 |
+
|
| 552 |
+
res.append((param_name, setting_name, v))
|
| 553 |
+
|
| 554 |
+
return res
|
| 555 |
+
|
| 556 |
+
|
| 557 |
+
def connect_paste(button, paste_fields, input_comp, override_settings_component, tabname):
|
| 558 |
+
def paste_func(prompt):
|
| 559 |
+
if not prompt and not shared.cmd_opts.hide_ui_dir_config and not shared.cmd_opts.no_prompt_history:
|
| 560 |
+
filename = os.path.join(data_path, "params.txt")
|
| 561 |
+
try:
|
| 562 |
+
with open(filename, "r", encoding="utf8") as file:
|
| 563 |
+
prompt = file.read()
|
| 564 |
+
except OSError:
|
| 565 |
+
pass
|
| 566 |
+
|
| 567 |
+
params = parse_generation_parameters(prompt)
|
| 568 |
+
script_callbacks.infotext_pasted_callback(prompt, params)
|
| 569 |
+
res = []
|
| 570 |
+
|
| 571 |
+
for output, key in paste_fields:
|
| 572 |
+
if callable(key):
|
| 573 |
+
try:
|
| 574 |
+
v = key(params)
|
| 575 |
+
except Exception:
|
| 576 |
+
errors.report(f"Error executing {key}", exc_info=True)
|
| 577 |
+
v = None
|
| 578 |
+
else:
|
| 579 |
+
v = params.get(key, None)
|
| 580 |
+
|
| 581 |
+
if v is None:
|
| 582 |
+
res.append(gr.skip())
|
| 583 |
+
elif isinstance(v, type_of_gr_update):
|
| 584 |
+
res.append(v)
|
| 585 |
+
else:
|
| 586 |
+
try:
|
| 587 |
+
valtype = type(output.value)
|
| 588 |
+
|
| 589 |
+
if valtype == bool and v == "False":
|
| 590 |
+
val = False
|
| 591 |
+
elif valtype == int:
|
| 592 |
+
val = float(v)
|
| 593 |
+
else:
|
| 594 |
+
val = valtype(v)
|
| 595 |
+
|
| 596 |
+
res.append(gr.update(value=val))
|
| 597 |
+
except Exception:
|
| 598 |
+
res.append(gr.skip())
|
| 599 |
+
|
| 600 |
+
return res
|
| 601 |
+
|
| 602 |
+
if override_settings_component is not None:
|
| 603 |
+
already_handled_fields = {key: 1 for _, key in paste_fields}
|
| 604 |
+
|
| 605 |
+
def paste_settings(params):
|
| 606 |
+
vals = get_override_settings(params, skip_fields=already_handled_fields)
|
| 607 |
+
|
| 608 |
+
vals_pairs = [f"{infotext_text}: {value}" for infotext_text, setting_name, value in vals]
|
| 609 |
+
|
| 610 |
+
return gr.update(value=vals_pairs, choices=vals_pairs, visible=bool(vals_pairs))
|
| 611 |
+
|
| 612 |
+
paste_fields = paste_fields + [(override_settings_component, paste_settings)]
|
| 613 |
+
|
| 614 |
+
button.click(
|
| 615 |
+
fn=paste_func,
|
| 616 |
+
inputs=[input_comp],
|
| 617 |
+
outputs=[x[0] for x in paste_fields],
|
| 618 |
+
show_progress=False,
|
| 619 |
+
)
|
| 620 |
+
button.click(
|
| 621 |
+
fn=None,
|
| 622 |
+
_js=f"recalculate_prompts_{tabname}",
|
| 623 |
+
inputs=[],
|
| 624 |
+
outputs=[],
|
| 625 |
+
show_progress=False,
|
| 626 |
+
)
|
modules/infotext_versions.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from modules import shared
|
| 2 |
+
from packaging import version
|
| 3 |
+
import re
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
v160 = version.parse("1.6.0")
|
| 7 |
+
v170_tsnr = version.parse("v1.7.0-225")
|
| 8 |
+
v180 = version.parse("1.8.0")
|
| 9 |
+
v180_hr_styles = version.parse("1.8.0-139")
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def parse_version(text):
|
| 13 |
+
if text is None:
|
| 14 |
+
return None
|
| 15 |
+
|
| 16 |
+
m = re.match(r'([^-]+-[^-]+)-.*', text)
|
| 17 |
+
if m:
|
| 18 |
+
text = m.group(1)
|
| 19 |
+
|
| 20 |
+
try:
|
| 21 |
+
return version.parse(text)
|
| 22 |
+
except Exception:
|
| 23 |
+
return None
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def backcompat(d):
|
| 27 |
+
"""Checks infotext Version field, and enables backwards compatibility options according to it."""
|
| 28 |
+
|
| 29 |
+
if not shared.opts.auto_backcompat:
|
| 30 |
+
return
|
| 31 |
+
|
| 32 |
+
ver = parse_version(d.get("Version"))
|
| 33 |
+
if ver is None:
|
| 34 |
+
return
|
| 35 |
+
|
| 36 |
+
if ver < v160 and '[' in d.get('Prompt', ''):
|
| 37 |
+
d["Old prompt editing timelines"] = True
|
| 38 |
+
|
| 39 |
+
if ver < v160 and d.get('Sampler', '') in ('DDIM', 'PLMS'):
|
| 40 |
+
d["Pad conds v0"] = True
|
| 41 |
+
|
| 42 |
+
if ver < v170_tsnr:
|
| 43 |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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import importlib
|
| 2 |
+
import logging
|
| 3 |
+
import os
|
| 4 |
+
import sys
|
| 5 |
+
import warnings
|
| 6 |
+
|
| 7 |
+
from modules.timer import startup_timer
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def shush():
|
| 11 |
+
logging.getLogger("torch.distributed.nn").setLevel(logging.ERROR)
|
| 12 |
+
logging.getLogger("transformers.dynamic_module_utils").setLevel(logging.ERROR)
|
| 13 |
+
logging.getLogger("xformers").addFilter(lambda record: "triton" not in record.getMessage().lower())
|
| 14 |
+
warnings.filterwarnings(action="ignore", category=DeprecationWarning, module="pytorch_lightning")
|
| 15 |
+
warnings.filterwarnings(action="ignore", category=UserWarning, module="torchvision.transforms.functional_tensor")
|
| 16 |
+
warnings.filterwarnings(action="ignore", category=UserWarning, module="torchvision")
|
| 17 |
+
startup_timer.record("filter logging")
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def shush_nunchaku():
|
| 21 |
+
_original = logging.basicConfig
|
| 22 |
+
logging.basicConfig = lambda *args, **kwargs: None
|
| 23 |
+
|
| 24 |
+
try:
|
| 25 |
+
import nunchaku
|
| 26 |
+
except ImportError:
|
| 27 |
+
pass
|
| 28 |
+
|
| 29 |
+
logging.basicConfig = _original
|
| 30 |
+
startup_timer.record("bypass basicConfig")
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def imports():
|
| 34 |
+
os.environ.setdefault("GRADIO_ANALYTICS_ENABLED", "False")
|
| 35 |
+
|
| 36 |
+
import gradio # noqa: F401
|
| 37 |
+
|
| 38 |
+
startup_timer.record("import gradio")
|
| 39 |
+
|
| 40 |
+
from modules import errors, paths, timer # noqa: F401
|
| 41 |
+
|
| 42 |
+
startup_timer.record("setup paths")
|
| 43 |
+
|
| 44 |
+
from modules import shared_init
|
| 45 |
+
|
| 46 |
+
shared_init.initialize()
|
| 47 |
+
startup_timer.record("shared init")
|
| 48 |
+
|
| 49 |
+
from modules import gradio_extensions, processing, ui # noqa: F401
|
| 50 |
+
|
| 51 |
+
startup_timer.record("misc. imports")
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def check_versions():
|
| 55 |
+
from modules.shared_cmd_options import cmd_opts
|
| 56 |
+
|
| 57 |
+
if cmd_opts.skip_version_check:
|
| 58 |
+
return
|
| 59 |
+
|
| 60 |
+
from modules import errors
|
| 61 |
+
|
| 62 |
+
errors.check_versions()
|
| 63 |
+
|
| 64 |
+
startup_timer.record("version check")
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def initialize():
|
| 68 |
+
from modules import initialize_util
|
| 69 |
+
|
| 70 |
+
initialize_util.fix_torch_version()
|
| 71 |
+
initialize_util.fix_asyncio_event_loop_policy()
|
| 72 |
+
initialize_util.validate_tls_options()
|
| 73 |
+
initialize_util.configure_sigint_handler()
|
| 74 |
+
initialize_util.configure_opts_onchange()
|
| 75 |
+
|
| 76 |
+
from modules import sd_models
|
| 77 |
+
|
| 78 |
+
sd_models.setup_model()
|
| 79 |
+
|
| 80 |
+
from modules import codeformer_model
|
| 81 |
+
from modules.shared_cmd_options import cmd_opts
|
| 82 |
+
|
| 83 |
+
codeformer_model.setup_model(cmd_opts.codeformer_models_path)
|
| 84 |
+
startup_timer.record("setup codeformer")
|
| 85 |
+
|
| 86 |
+
from modules import gfpgan_model
|
| 87 |
+
|
| 88 |
+
gfpgan_model.setup_model(cmd_opts.gfpgan_models_path)
|
| 89 |
+
startup_timer.record("setup gfpgan")
|
| 90 |
+
|
| 91 |
+
initialize_rest(reload_script_modules=False)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def initialize_rest(*, reload_script_modules=False):
|
| 95 |
+
"""
|
| 96 |
+
Called both from initialize() and when reloading the webui.
|
| 97 |
+
"""
|
| 98 |
+
from modules import sd_samplers
|
| 99 |
+
from modules.shared_cmd_options import cmd_opts
|
| 100 |
+
|
| 101 |
+
sd_samplers.set_samplers()
|
| 102 |
+
startup_timer.record("set samplers")
|
| 103 |
+
|
| 104 |
+
from modules import extensions
|
| 105 |
+
|
| 106 |
+
extensions.list_extensions()
|
| 107 |
+
startup_timer.record("list extensions")
|
| 108 |
+
|
| 109 |
+
from modules import initialize_util
|
| 110 |
+
|
| 111 |
+
initialize_util.restore_config_state_file()
|
| 112 |
+
startup_timer.record("restore config state file")
|
| 113 |
+
|
| 114 |
+
from modules import scripts, shared, upscaler
|
| 115 |
+
|
| 116 |
+
if cmd_opts.ui_debug_mode:
|
| 117 |
+
shared.sd_upscalers = upscaler.UpscalerLanczos().scalers
|
| 118 |
+
scripts.load_scripts()
|
| 119 |
+
return
|
| 120 |
+
|
| 121 |
+
from modules import sd_models
|
| 122 |
+
|
| 123 |
+
sd_models.list_models()
|
| 124 |
+
startup_timer.record("list SD models")
|
| 125 |
+
|
| 126 |
+
from modules import localization
|
| 127 |
+
|
| 128 |
+
localization.list_localizations(cmd_opts.localizations_dir)
|
| 129 |
+
startup_timer.record("list localizations")
|
| 130 |
+
|
| 131 |
+
with startup_timer.subcategory("load scripts"):
|
| 132 |
+
scripts.load_scripts()
|
| 133 |
+
|
| 134 |
+
if reload_script_modules and shared.opts.enable_reloading_ui_scripts:
|
| 135 |
+
for module in [module for name, module in sys.modules.items() if name.startswith("modules.ui")]:
|
| 136 |
+
importlib.reload(module)
|
| 137 |
+
startup_timer.record("reload script modules")
|
| 138 |
+
|
| 139 |
+
from modules import modelloader
|
| 140 |
+
|
| 141 |
+
modelloader.load_upscalers()
|
| 142 |
+
startup_timer.record("load upscalers")
|
| 143 |
+
|
| 144 |
+
from modules import sd_vae
|
| 145 |
+
|
| 146 |
+
sd_vae.refresh_vae_list()
|
| 147 |
+
startup_timer.record("refresh VAE")
|
| 148 |
+
|
| 149 |
+
from modules import sd_unet
|
| 150 |
+
|
| 151 |
+
sd_unet.list_unets()
|
| 152 |
+
startup_timer.record("scripts list_unets")
|
| 153 |
+
|
| 154 |
+
from modules import ui_extra_networks
|
| 155 |
+
|
| 156 |
+
ui_extra_networks.initialize()
|
| 157 |
+
ui_extra_networks.register_default_pages()
|
| 158 |
+
|
| 159 |
+
from modules import extra_networks
|
| 160 |
+
|
| 161 |
+
extra_networks.initialize()
|
| 162 |
+
startup_timer.record("initialize extra networks")
|
modules/initialize_util.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
import re
|
| 4 |
+
import signal
|
| 5 |
+
import sys
|
| 6 |
+
|
| 7 |
+
import starlette
|
| 8 |
+
|
| 9 |
+
from modules.timer import startup_timer
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def gradio_server_name():
|
| 13 |
+
from modules.shared_cmd_options import cmd_opts
|
| 14 |
+
|
| 15 |
+
if cmd_opts.server_name:
|
| 16 |
+
return cmd_opts.server_name
|
| 17 |
+
else:
|
| 18 |
+
return "0.0.0.0" if cmd_opts.listen else None
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def fix_torch_version():
|
| 22 |
+
import torch
|
| 23 |
+
|
| 24 |
+
# truncate version number of nightly/local build of PyTorch
|
| 25 |
+
if ".dev" in torch.__version__ or "+git" in torch.__version__:
|
| 26 |
+
torch.__long_version__ = torch.__version__
|
| 27 |
+
torch.__version__ = re.search(r"[\d.]+[\d]", torch.__version__).group(0)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def fix_asyncio_event_loop_policy():
|
| 31 |
+
"""
|
| 32 |
+
The default `asyncio` event loop policy only automatically creates
|
| 33 |
+
event loops in the main threads. Other threads must create event
|
| 34 |
+
loops explicitly or `asyncio.get_event_loop` and `.IOLoop.current`
|
| 35 |
+
will fail. Installing this policy allows event loops to be created
|
| 36 |
+
automatically on any thread, matching the behavior of Tornado prior to 5.0
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
import asyncio
|
| 40 |
+
|
| 41 |
+
if sys.platform == "win32" and hasattr(asyncio, "WindowsSelectorEventLoopPolicy"):
|
| 42 |
+
# "Any thread" and "selector" should be orthogonal, but there's not a clean
|
| 43 |
+
# interface for composing policies so pick the right base.
|
| 44 |
+
_BasePolicy = asyncio.WindowsSelectorEventLoopPolicy # type: ignore
|
| 45 |
+
else:
|
| 46 |
+
_BasePolicy = asyncio.DefaultEventLoopPolicy
|
| 47 |
+
|
| 48 |
+
class AnyThreadEventLoopPolicy(_BasePolicy): # type: ignore
|
| 49 |
+
"""Event loop policy that allows loop creation on any thread.
|
| 50 |
+
Usage::
|
| 51 |
+
|
| 52 |
+
asyncio.set_event_loop_policy(AnyThreadEventLoopPolicy())
|
| 53 |
+
"""
|
| 54 |
+
|
| 55 |
+
def get_event_loop(self) -> asyncio.AbstractEventLoop:
|
| 56 |
+
try:
|
| 57 |
+
return super().get_event_loop()
|
| 58 |
+
except (RuntimeError, AssertionError):
|
| 59 |
+
# This was an AssertionError in python 3.4.2 (which ships with debian jessie)
|
| 60 |
+
# and changed to a RuntimeError in 3.4.3.
|
| 61 |
+
# "There is no current event loop in thread %r"
|
| 62 |
+
loop = self.new_event_loop()
|
| 63 |
+
self.set_event_loop(loop)
|
| 64 |
+
return loop
|
| 65 |
+
|
| 66 |
+
asyncio.set_event_loop_policy(AnyThreadEventLoopPolicy())
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def restore_config_state_file():
|
| 70 |
+
from modules import config_states, shared
|
| 71 |
+
|
| 72 |
+
config_state_file = shared.opts.restore_config_state_file
|
| 73 |
+
if config_state_file == "":
|
| 74 |
+
return
|
| 75 |
+
|
| 76 |
+
shared.opts.restore_config_state_file = ""
|
| 77 |
+
shared.opts.save(shared.config_filename)
|
| 78 |
+
|
| 79 |
+
if os.path.isfile(config_state_file):
|
| 80 |
+
print(f"*** About to restore extension state from file: {config_state_file}")
|
| 81 |
+
with open(config_state_file, "r", encoding="utf-8") as f:
|
| 82 |
+
config_state = json.load(f)
|
| 83 |
+
config_states.restore_extension_config(config_state)
|
| 84 |
+
startup_timer.record("restore extension config")
|
| 85 |
+
elif config_state_file:
|
| 86 |
+
print(f"!!! Config state backup not found: {config_state_file}")
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def validate_tls_options():
|
| 90 |
+
from modules.shared_cmd_options import cmd_opts
|
| 91 |
+
|
| 92 |
+
if not (cmd_opts.tls_keyfile and cmd_opts.tls_certfile):
|
| 93 |
+
return
|
| 94 |
+
|
| 95 |
+
try:
|
| 96 |
+
if not os.path.exists(cmd_opts.tls_keyfile):
|
| 97 |
+
print("Invalid path to TLS keyfile given")
|
| 98 |
+
if not os.path.exists(cmd_opts.tls_certfile):
|
| 99 |
+
print(f"Invalid path to TLS certfile: '{cmd_opts.tls_certfile}'")
|
| 100 |
+
except TypeError:
|
| 101 |
+
cmd_opts.tls_keyfile = cmd_opts.tls_certfile = None
|
| 102 |
+
print("TLS setup invalid, running webui without TLS")
|
| 103 |
+
else:
|
| 104 |
+
print("Running with TLS")
|
| 105 |
+
startup_timer.record("TLS")
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def get_gradio_auth_creds():
|
| 109 |
+
"""
|
| 110 |
+
Convert the gradio_auth and gradio_auth_path commandline arguments into
|
| 111 |
+
an iterable of (username, password) tuples.
|
| 112 |
+
"""
|
| 113 |
+
from modules.shared_cmd_options import cmd_opts
|
| 114 |
+
|
| 115 |
+
def process_credential_line(s):
|
| 116 |
+
s = s.strip()
|
| 117 |
+
if not s:
|
| 118 |
+
return None
|
| 119 |
+
return tuple(s.split(":", 1))
|
| 120 |
+
|
| 121 |
+
if cmd_opts.gradio_auth:
|
| 122 |
+
for cred in cmd_opts.gradio_auth.split(","):
|
| 123 |
+
cred = process_credential_line(cred)
|
| 124 |
+
if cred:
|
| 125 |
+
yield cred
|
| 126 |
+
|
| 127 |
+
if cmd_opts.gradio_auth_path:
|
| 128 |
+
with open(cmd_opts.gradio_auth_path, "r", encoding="utf8") as file:
|
| 129 |
+
for line in file.readlines():
|
| 130 |
+
for cred in line.strip().split(","):
|
| 131 |
+
cred = process_credential_line(cred)
|
| 132 |
+
if cred:
|
| 133 |
+
yield cred
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def dumpstacks():
|
| 137 |
+
import threading
|
| 138 |
+
import traceback
|
| 139 |
+
|
| 140 |
+
id2name = {th.ident: th.name for th in threading.enumerate()}
|
| 141 |
+
code = []
|
| 142 |
+
for threadId, stack in sys._current_frames().items():
|
| 143 |
+
code.append(f"\n# Thread: {id2name.get(threadId, '')}({threadId})")
|
| 144 |
+
for filename, lineno, name, line in traceback.extract_stack(stack):
|
| 145 |
+
code.append(f"""File: "{filename}", line {lineno}, in {name}""")
|
| 146 |
+
if line:
|
| 147 |
+
code.append(" " + line.strip())
|
| 148 |
+
|
| 149 |
+
print("\n".join(code))
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def configure_sigint_handler():
|
| 153 |
+
# make the program just exit at Ctrl + C without waiting for anything
|
| 154 |
+
|
| 155 |
+
from modules import shared
|
| 156 |
+
|
| 157 |
+
def sigint_handler(sig, frame):
|
| 158 |
+
print(f"Interrupted with signal {sig} in {frame}")
|
| 159 |
+
|
| 160 |
+
if shared.opts.dump_stacks_on_signal:
|
| 161 |
+
dumpstacks()
|
| 162 |
+
|
| 163 |
+
os._exit(0)
|
| 164 |
+
|
| 165 |
+
if not os.environ.get("COVERAGE_RUN"):
|
| 166 |
+
# Don't install the immediate-quit handler when running under coverage,
|
| 167 |
+
# as then the coverage report won't be generated.
|
| 168 |
+
signal.signal(signal.SIGINT, sigint_handler)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def configure_opts_onchange():
|
| 172 |
+
from modules import shared, ui_tempdir
|
| 173 |
+
|
| 174 |
+
shared.opts.onchange("temp_dir", ui_tempdir.on_tmpdir_changed)
|
| 175 |
+
shared.opts.onchange("gradio_theme", shared.reload_gradio_theme)
|
| 176 |
+
startup_timer.record("opts onchange")
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def setup_middleware(app):
|
| 180 |
+
from starlette.middleware.gzip import GZipMiddleware
|
| 181 |
+
|
| 182 |
+
app.user_middleware.insert(0, starlette.middleware.Middleware(GZipMiddleware, minimum_size=1000))
|
| 183 |
+
configure_cors_middleware(app)
|
| 184 |
+
app.build_middleware_stack() # rebuild middleware stack on-the-fly
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def configure_cors_middleware(app):
|
| 188 |
+
from starlette.middleware.cors import CORSMiddleware
|
| 189 |
+
|
| 190 |
+
from modules.shared_cmd_options import cmd_opts
|
| 191 |
+
|
| 192 |
+
cors_options = {
|
| 193 |
+
"allow_methods": ["*"],
|
| 194 |
+
"allow_headers": ["*"],
|
| 195 |
+
"allow_credentials": True,
|
| 196 |
+
}
|
| 197 |
+
if cmd_opts.cors_allow_origins:
|
| 198 |
+
cors_options["allow_origins"] = cmd_opts.cors_allow_origins.split(",")
|
| 199 |
+
if cmd_opts.cors_allow_origins_regex:
|
| 200 |
+
cors_options["allow_origin_regex"] = cmd_opts.cors_allow_origins_regex
|
| 201 |
+
|
| 202 |
+
app.user_middleware.insert(0, starlette.middleware.Middleware(CORSMiddleware, **cors_options))
|
modules/launch_utils.py
ADDED
|
@@ -0,0 +1,529 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
+
import json
|
| 8 |
+
import logging
|
| 9 |
+
import os
|
| 10 |
+
import re
|
| 11 |
+
import shlex
|
| 12 |
+
import subprocess
|
| 13 |
+
import sys
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
from typing import NamedTuple
|
| 16 |
+
|
| 17 |
+
from modules import cmd_args, errors, logging_config
|
| 18 |
+
from modules.paths_internal import extensions_builtin_dir, extensions_dir, script_path
|
| 19 |
+
from modules.timer import startup_timer
|
| 20 |
+
from modules_forge import forge_version
|
| 21 |
+
from modules_forge.config import always_disabled_extensions
|
| 22 |
+
|
| 23 |
+
args, _ = cmd_args.parser.parse_known_args()
|
| 24 |
+
logging_config.setup_logging(args.loglevel)
|
| 25 |
+
|
| 26 |
+
python = sys.executable
|
| 27 |
+
git = os.environ.get("GIT", "git")
|
| 28 |
+
index_url = os.environ.get("INDEX_URL", "")
|
| 29 |
+
dir_repos = "repositories"
|
| 30 |
+
|
| 31 |
+
default_command_live = os.environ.get("WEBUI_LAUNCH_LIVE_OUTPUT") == "1"
|
| 32 |
+
|
| 33 |
+
os.environ.setdefault("GRADIO_ANALYTICS_ENABLED", "False")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def check_python_version():
|
| 37 |
+
major = sys.version_info.major
|
| 38 |
+
minor = sys.version_info.minor
|
| 39 |
+
micro = sys.version_info.micro
|
| 40 |
+
|
| 41 |
+
if not (major == 3 and minor == 11):
|
| 42 |
+
import modules.errors
|
| 43 |
+
|
| 44 |
+
modules.errors.print_error_explanation(
|
| 45 |
+
f"""
|
| 46 |
+
This program is tested with 3.11.9 Python, but you have {major}.{minor}.{micro}.
|
| 47 |
+
If you encounter any error regarding unsuccessful package/library installation,
|
| 48 |
+
please downgrade (or upgrade) to the latest version of 3.11 Python,
|
| 49 |
+
and delete the current Python "venv" folder in WebUI's directory.
|
| 50 |
+
|
| 51 |
+
Use --skip-python-version-check to suppress this warning
|
| 52 |
+
"""
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def git_tag():
|
| 57 |
+
return forge_version.version
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def run(command, desc=None, errdesc=None, custom_env=None, live: bool = default_command_live) -> str:
|
| 61 |
+
if desc is not None:
|
| 62 |
+
print(desc)
|
| 63 |
+
|
| 64 |
+
run_kwargs = {
|
| 65 |
+
"args": command,
|
| 66 |
+
"shell": True,
|
| 67 |
+
"env": os.environ if custom_env is None else custom_env,
|
| 68 |
+
"encoding": "utf8",
|
| 69 |
+
"errors": "ignore",
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
if not live:
|
| 73 |
+
run_kwargs["stdout"] = run_kwargs["stderr"] = subprocess.PIPE
|
| 74 |
+
|
| 75 |
+
result = subprocess.run(**run_kwargs)
|
| 76 |
+
|
| 77 |
+
if result.returncode != 0:
|
| 78 |
+
error_bits = [
|
| 79 |
+
f"{errdesc or 'Error running command'}.",
|
| 80 |
+
f"Command: {command}",
|
| 81 |
+
f"Error code: {result.returncode}",
|
| 82 |
+
]
|
| 83 |
+
if result.stdout:
|
| 84 |
+
error_bits.append(f"stdout: {result.stdout}")
|
| 85 |
+
if result.stderr:
|
| 86 |
+
error_bits.append(f"stderr: {result.stderr}")
|
| 87 |
+
raise RuntimeError("\n".join(error_bits))
|
| 88 |
+
|
| 89 |
+
return result.stdout or ""
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _torch_version() -> tuple[str, str]:
|
| 93 |
+
"""Given `2.10.0.dev20251111+cu130` ; Return `("2.10.0", "cu130")`"""
|
| 94 |
+
import importlib.metadata
|
| 95 |
+
|
| 96 |
+
ver = importlib.metadata.version("torch")
|
| 97 |
+
m = re.search(r"(\d+\.\d+\.\d+)(?:[^+]+)?\+(.+)", ver)
|
| 98 |
+
|
| 99 |
+
if m is None:
|
| 100 |
+
print("\n\nFailed to parse PyTorch version...")
|
| 101 |
+
ver = os.environ.get("PYTORCH_VERSION", "2.9.1+cu128")
|
| 102 |
+
print("Assuming: ", ver)
|
| 103 |
+
print('(you can change this with `export PYTORCH_VERSION="..."`)\n\n')
|
| 104 |
+
m = re.search(r"(\d+\.\d+\.\d+)(?:[^+]+)?\+(.+)", ver)
|
| 105 |
+
|
| 106 |
+
return m.group(1), m.group(2)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def is_installed(package):
|
| 110 |
+
try:
|
| 111 |
+
dist = importlib.metadata.distribution(package)
|
| 112 |
+
except importlib.metadata.PackageNotFoundError:
|
| 113 |
+
try:
|
| 114 |
+
spec = importlib.util.find_spec(package)
|
| 115 |
+
except ModuleNotFoundError:
|
| 116 |
+
return False
|
| 117 |
+
|
| 118 |
+
return spec is not None
|
| 119 |
+
|
| 120 |
+
return dist is not None
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def repo_dir(name):
|
| 124 |
+
return os.path.join(script_path, dir_repos, name)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def run_pip(command, desc=None, live=default_command_live):
|
| 128 |
+
if args.skip_install:
|
| 129 |
+
return
|
| 130 |
+
|
| 131 |
+
index_url_line = f" --index-url {index_url}" if index_url != "" else ""
|
| 132 |
+
return run(f'"{python}" -m pip {command} --prefer-binary{index_url_line}', desc=f"Installing {desc}", errdesc=f"Couldn't install {desc}", live=live)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def check_run_python(code: str, *, return_error: bool = False) -> bool | tuple[bool, str]:
|
| 136 |
+
result = subprocess.run([python, "-c", code], capture_output=True, shell=False)
|
| 137 |
+
if return_error:
|
| 138 |
+
return result.returncode == 0, result.stderr
|
| 139 |
+
else:
|
| 140 |
+
return result.returncode == 0
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def git_fix_workspace(*args, **kwargs):
|
| 144 |
+
raise NotImplementedError()
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def run_git(*args, **kwargs):
|
| 148 |
+
raise NotImplementedError()
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def git_clone(*args, **kwargs):
|
| 152 |
+
raise NotImplementedError()
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def git_pull_recursive(dir):
|
| 156 |
+
for subdir, _, _ in os.walk(dir):
|
| 157 |
+
if os.path.exists(os.path.join(subdir, ".git")):
|
| 158 |
+
try:
|
| 159 |
+
output = subprocess.check_output([git, "-C", subdir, "pull", "--autostash"])
|
| 160 |
+
print(f"Pulled changes for repository in '{subdir}':\n{output.decode('utf-8').strip()}\n")
|
| 161 |
+
except subprocess.CalledProcessError as e:
|
| 162 |
+
print(f"Couldn't perform 'git pull' on repository in '{subdir}':\n{e.output.decode('utf-8').strip()}\n")
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def run_extension_installer(extension_dir):
|
| 166 |
+
path_installer = os.path.join(extension_dir, "install.py")
|
| 167 |
+
if not os.path.isfile(path_installer):
|
| 168 |
+
return
|
| 169 |
+
|
| 170 |
+
try:
|
| 171 |
+
env = os.environ.copy()
|
| 172 |
+
env["PYTHONPATH"] = f"{script_path}{os.pathsep}{env.get('PYTHONPATH', '')}"
|
| 173 |
+
|
| 174 |
+
stdout = run(f'"{python}" "{path_installer}"', errdesc=f"Error running install.py for extension {extension_dir}", custom_env=env).strip()
|
| 175 |
+
if stdout:
|
| 176 |
+
print(stdout)
|
| 177 |
+
except Exception as e:
|
| 178 |
+
errors.report(str(e))
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def list_extensions(settings_file):
|
| 182 |
+
settings = {}
|
| 183 |
+
|
| 184 |
+
try:
|
| 185 |
+
with open(settings_file, "r", encoding="utf8") as file:
|
| 186 |
+
settings = json.load(file)
|
| 187 |
+
except FileNotFoundError:
|
| 188 |
+
pass
|
| 189 |
+
except Exception:
|
| 190 |
+
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)
|
| 191 |
+
os.replace(settings_file, os.path.join(script_path, "tmp", "config.json"))
|
| 192 |
+
|
| 193 |
+
disabled_extensions = set(settings.get("disabled_extensions", []) + always_disabled_extensions)
|
| 194 |
+
disable_all_extensions = settings.get("disable_all_extensions", "none")
|
| 195 |
+
|
| 196 |
+
if disable_all_extensions != "none" or args.disable_extra_extensions or args.disable_all_extensions or not os.path.isdir(extensions_dir):
|
| 197 |
+
return []
|
| 198 |
+
|
| 199 |
+
return [x for x in os.listdir(extensions_dir) if x not in disabled_extensions]
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def list_extensions_builtin(settings_file):
|
| 203 |
+
settings = {}
|
| 204 |
+
|
| 205 |
+
try:
|
| 206 |
+
with open(settings_file, "r", encoding="utf8") as file:
|
| 207 |
+
settings = json.load(file)
|
| 208 |
+
except FileNotFoundError:
|
| 209 |
+
pass
|
| 210 |
+
except Exception:
|
| 211 |
+
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)
|
| 212 |
+
os.replace(settings_file, os.path.join(script_path, "tmp", "config.json"))
|
| 213 |
+
|
| 214 |
+
disabled_extensions = set(settings.get("disabled_extensions", []))
|
| 215 |
+
disable_all_extensions = settings.get("disable_all_extensions", "none")
|
| 216 |
+
|
| 217 |
+
if disable_all_extensions != "none" or args.disable_extra_extensions or args.disable_all_extensions or not os.path.isdir(extensions_builtin_dir):
|
| 218 |
+
return []
|
| 219 |
+
|
| 220 |
+
return [x for x in os.listdir(extensions_builtin_dir) if x not in disabled_extensions]
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def run_extensions_installers(settings_file):
|
| 224 |
+
if not os.path.isdir(extensions_dir):
|
| 225 |
+
return
|
| 226 |
+
|
| 227 |
+
with startup_timer.subcategory("run extensions installers"):
|
| 228 |
+
for dirname_extension in list_extensions(settings_file):
|
| 229 |
+
logging.debug(f"Installing {dirname_extension}")
|
| 230 |
+
|
| 231 |
+
path = os.path.join(extensions_dir, dirname_extension)
|
| 232 |
+
|
| 233 |
+
if os.path.isdir(path):
|
| 234 |
+
run_extension_installer(path)
|
| 235 |
+
startup_timer.record(dirname_extension)
|
| 236 |
+
|
| 237 |
+
if not os.path.isdir(extensions_builtin_dir):
|
| 238 |
+
return
|
| 239 |
+
|
| 240 |
+
with startup_timer.subcategory("run extensions_builtin installers"):
|
| 241 |
+
for dirname_extension in list_extensions_builtin(settings_file):
|
| 242 |
+
logging.debug(f"Installing {dirname_extension}")
|
| 243 |
+
|
| 244 |
+
path = os.path.join(extensions_builtin_dir, dirname_extension)
|
| 245 |
+
|
| 246 |
+
if os.path.isdir(path):
|
| 247 |
+
run_extension_installer(path)
|
| 248 |
+
startup_timer.record(dirname_extension)
|
| 249 |
+
|
| 250 |
+
return
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
re_requirement = re.compile(r"\s*(\S+)\s*==\s*(\S+)\s*")
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def requirements_met(requirements_file):
|
| 257 |
+
"""
|
| 258 |
+
Does a simple parse of a requirements.txt file to determine if all rerqirements in it
|
| 259 |
+
are already installed. Returns True if so, False if not installed or parsing fails.
|
| 260 |
+
"""
|
| 261 |
+
|
| 262 |
+
import importlib.metadata
|
| 263 |
+
|
| 264 |
+
import packaging.version
|
| 265 |
+
|
| 266 |
+
with open(requirements_file, "r", encoding="utf8") as file:
|
| 267 |
+
for line in file:
|
| 268 |
+
if line.strip() == "":
|
| 269 |
+
continue
|
| 270 |
+
|
| 271 |
+
if (m := re.match(re_requirement, line)) is None:
|
| 272 |
+
continue
|
| 273 |
+
|
| 274 |
+
package = m.group(1)
|
| 275 |
+
version_required = m.group(2)
|
| 276 |
+
|
| 277 |
+
try:
|
| 278 |
+
version_installed = importlib.metadata.version(package)
|
| 279 |
+
except Exception:
|
| 280 |
+
return False
|
| 281 |
+
|
| 282 |
+
if packaging.version.parse(version_installed) < packaging.version.parse(version_required):
|
| 283 |
+
return False
|
| 284 |
+
|
| 285 |
+
return True
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def prepare_environment():
|
| 289 |
+
torch_index_url = os.environ.get("TORCH_INDEX_URL", "https://download.pytorch.org/whl/cu130")
|
| 290 |
+
torch_command = os.environ.get("TORCH_COMMAND", f"pip install torch==2.9.1+cu130 torchvision==0.24.1+cu130 --extra-index-url {torch_index_url}")
|
| 291 |
+
xformers_package = os.environ.get("XFORMERS_PACKAGE", f"xformers==0.0.33.post2 --extra-index-url {torch_index_url}")
|
| 292 |
+
bnb_package = os.environ.get("BNB_PACKAGE", "bitsandbytes==0.48.2")
|
| 293 |
+
|
| 294 |
+
clip_package = os.environ.get("CLIP_PACKAGE", "https://github.com/openai/CLIP/archive/d50d76daa670286dd6cacf3bcd80b5e4823fc8e1.zip")
|
| 295 |
+
packaging_package = os.environ.get("PACKAGING_PACKAGE", "packaging==25.0")
|
| 296 |
+
gradio_package = os.environ.get("GRADIO_PACKAGE", "gradio==4.40.0 gradio_imageslider==0.0.20 gradio_rangeslider==0.0.8")
|
| 297 |
+
requirements_file = os.environ.get("REQS_FILE", "requirements.txt")
|
| 298 |
+
|
| 299 |
+
try:
|
| 300 |
+
# the existence of this file is a signal to webui.sh/bat that webui needs to be restarted when it stops execution
|
| 301 |
+
os.remove(os.path.join(script_path, "tmp", "restart"))
|
| 302 |
+
os.environ.setdefault("SD_WEBUI_RESTARTING", "1")
|
| 303 |
+
except OSError:
|
| 304 |
+
pass
|
| 305 |
+
|
| 306 |
+
if not args.skip_python_version_check:
|
| 307 |
+
check_python_version()
|
| 308 |
+
|
| 309 |
+
startup_timer.record("checks")
|
| 310 |
+
|
| 311 |
+
tag = git_tag()
|
| 312 |
+
|
| 313 |
+
print(f"Python {sys.version}")
|
| 314 |
+
print(f"Version: {tag}")
|
| 315 |
+
|
| 316 |
+
if args.reinstall_torch or not is_installed("torch") or not is_installed("torchvision"):
|
| 317 |
+
run(f'"{python}" -m {torch_command}', "Installing torch and torchvision", "Couldn't install torch", live=True)
|
| 318 |
+
startup_timer.record("install torch")
|
| 319 |
+
|
| 320 |
+
if not args.skip_torch_cuda_test:
|
| 321 |
+
success, err = check_run_python("import torch; assert torch.cuda.is_available()", return_error=True)
|
| 322 |
+
if not success:
|
| 323 |
+
if "older driver" in str(err).lower():
|
| 324 |
+
raise SystemError("Please update your GPU driver to support cu130 ; or manually install older PyTorch")
|
| 325 |
+
raise RuntimeError("PyTorch is not able to access CUDA")
|
| 326 |
+
startup_timer.record("torch GPU test")
|
| 327 |
+
|
| 328 |
+
if not is_installed("packaging"):
|
| 329 |
+
run_pip(f"install {packaging_package}", "packaging")
|
| 330 |
+
|
| 331 |
+
ver_PY = f"cp{sys.version_info.major}{sys.version_info.minor}"
|
| 332 |
+
ver_SAGE = "2.2.0"
|
| 333 |
+
ver_FLASH = "2.8.3"
|
| 334 |
+
ver_TRITON = "3.5.1"
|
| 335 |
+
ver_NUNCHAKU = "1.1.0"
|
| 336 |
+
ver_TORCH, ver_CUDA = _torch_version()
|
| 337 |
+
v_TORCH = ver_TORCH.rsplit(".", 1)[0]
|
| 338 |
+
|
| 339 |
+
if os.name == "nt":
|
| 340 |
+
ver_TRITON += ".post22"
|
| 341 |
+
|
| 342 |
+
sage_package = os.environ.get("SAGE_PACKAGE", f"https://github.com/woct0rdho/SageAttention/releases/download/v{ver_SAGE}-windows.post4/sageattention-{ver_SAGE}+{ver_CUDA}torch2.9.0andhigher.post4-cp39-abi3-win_amd64.whl")
|
| 343 |
+
flash_package = os.environ.get("FLASH_PACKAGE", f"https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.4.19/flash_attn-{ver_FLASH}+{ver_CUDA}torch{v_TORCH}-{ver_PY}-{ver_PY}-win_amd64.whl")
|
| 344 |
+
triton_package = os.environ.get("TRITION_PACKAGE", f"triton-windows=={ver_TRITON}")
|
| 345 |
+
nunchaku_package = os.environ.get("NUNCHAKU_PACKAGE", f"https://github.com/nunchaku-tech/nunchaku/releases/download/v{ver_NUNCHAKU}/nunchaku-{ver_NUNCHAKU}+torch{v_TORCH}-{ver_PY}-{ver_PY}-win_amd64.whl")
|
| 346 |
+
|
| 347 |
+
else:
|
| 348 |
+
sage_package = os.environ.get("SAGE_PACKAGE", f"sageattention=={ver_SAGE}")
|
| 349 |
+
flash_package = os.environ.get("FLASH_PACKAGE", f"https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.5.4/flash_attn-{ver_FLASH}+{ver_CUDA}torch{v_TORCH}-{ver_PY}-{ver_PY}-linux_x86_64.whl")
|
| 350 |
+
triton_package = os.environ.get("TRITION_PACKAGE", f"triton=={ver_TRITON}")
|
| 351 |
+
nunchaku_package = os.environ.get("NUNCHAKU_PACKAGE", f"https://github.com/nunchaku-tech/nunchaku/releases/download/v{ver_NUNCHAKU}/nunchaku-{ver_NUNCHAKU}+torch{v_TORCH}-{ver_PY}-{ver_PY}-linux_x86_64.whl")
|
| 352 |
+
|
| 353 |
+
def _verify_nunchaku() -> bool:
|
| 354 |
+
if not is_installed("nunchaku"):
|
| 355 |
+
return False
|
| 356 |
+
|
| 357 |
+
import importlib.metadata
|
| 358 |
+
|
| 359 |
+
import packaging.version
|
| 360 |
+
|
| 361 |
+
ver_installed: str = importlib.metadata.version("nunchaku")
|
| 362 |
+
current: tuple[int] = packaging.version.parse(ver_installed)
|
| 363 |
+
target: tuple[int] = packaging.version.parse(ver_NUNCHAKU)
|
| 364 |
+
|
| 365 |
+
return current >= target
|
| 366 |
+
|
| 367 |
+
if not is_installed("clip"):
|
| 368 |
+
run_pip(f"install {clip_package}", "clip")
|
| 369 |
+
startup_timer.record("install clip")
|
| 370 |
+
|
| 371 |
+
if args.xformers and (not is_installed("xformers") or args.reinstall_xformers):
|
| 372 |
+
run_pip(f"install -U -I --no-deps {xformers_package}", "xformers")
|
| 373 |
+
startup_timer.record("install xformers")
|
| 374 |
+
|
| 375 |
+
if args.sage:
|
| 376 |
+
if not is_installed("triton"):
|
| 377 |
+
try:
|
| 378 |
+
run_pip(f"install -U -I --no-deps {triton_package}", "triton")
|
| 379 |
+
except RuntimeError:
|
| 380 |
+
print("Failed to install triton; Please manually install it")
|
| 381 |
+
else:
|
| 382 |
+
startup_timer.record("install triton")
|
| 383 |
+
if not is_installed("sageattention"):
|
| 384 |
+
try:
|
| 385 |
+
run_pip(f"install -U -I --no-deps {sage_package}", "sageattention")
|
| 386 |
+
except RuntimeError:
|
| 387 |
+
print("Failed to install sageattention; Please manually install it")
|
| 388 |
+
else:
|
| 389 |
+
startup_timer.record("install sageattention")
|
| 390 |
+
|
| 391 |
+
if args.flash and not is_installed("flash_attn"):
|
| 392 |
+
try:
|
| 393 |
+
run_pip(f"install {flash_package}", "flash_attn")
|
| 394 |
+
except RuntimeError:
|
| 395 |
+
print("Failed to install flash_attn; Please manually install it")
|
| 396 |
+
else:
|
| 397 |
+
startup_timer.record("install flash_attn")
|
| 398 |
+
|
| 399 |
+
if args.nunchaku and not _verify_nunchaku():
|
| 400 |
+
try:
|
| 401 |
+
run_pip(f"install {nunchaku_package}", "nunchaku")
|
| 402 |
+
except RuntimeError:
|
| 403 |
+
print("Failed to install nunchaku; Please manually install it")
|
| 404 |
+
else:
|
| 405 |
+
startup_timer.record("install nunchaku")
|
| 406 |
+
|
| 407 |
+
if args.bnb and not is_installed("bitsandbytes"):
|
| 408 |
+
try:
|
| 409 |
+
run_pip(f"install {bnb_package}", "bitsandbytes")
|
| 410 |
+
except RuntimeError:
|
| 411 |
+
print("Failed to install bitsandbytes; Please manually install it")
|
| 412 |
+
else:
|
| 413 |
+
startup_timer.record("install bitsandbytes")
|
| 414 |
+
|
| 415 |
+
if not is_installed("ngrok") and args.ngrok:
|
| 416 |
+
run_pip("install ngrok", "ngrok")
|
| 417 |
+
startup_timer.record("install ngrok")
|
| 418 |
+
|
| 419 |
+
if not is_installed("gradio"):
|
| 420 |
+
run_pip(f"install {gradio_package}", "gradio")
|
| 421 |
+
|
| 422 |
+
if not os.path.isfile(requirements_file):
|
| 423 |
+
requirements_file = os.path.join(script_path, requirements_file)
|
| 424 |
+
|
| 425 |
+
if not requirements_met(requirements_file):
|
| 426 |
+
run_pip(f'install -r "{requirements_file}"', "requirements")
|
| 427 |
+
startup_timer.record("install requirements")
|
| 428 |
+
|
| 429 |
+
if args.onnxruntime_gpu and not is_installed("onnxruntime-gpu"):
|
| 430 |
+
# https://onnxruntime.ai/docs/install/#nightly-for-cuda-13x
|
| 431 |
+
onnxruntime_package = os.environ.get("ONNX_PACKAGE", "onnxruntime-gpu --pre --index-url https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/ort-cuda-13-nightly/pypi/simple/")
|
| 432 |
+
run_pip(f"install {onnxruntime_package}", "onnxruntime-gpu")
|
| 433 |
+
startup_timer.record("install onnxruntime-gpu")
|
| 434 |
+
|
| 435 |
+
if not args.skip_install:
|
| 436 |
+
run_extensions_installers(settings_file=args.ui_settings_file)
|
| 437 |
+
|
| 438 |
+
if args.update_all_extensions:
|
| 439 |
+
git_pull_recursive(extensions_dir)
|
| 440 |
+
startup_timer.record("update extensions")
|
| 441 |
+
|
| 442 |
+
if not requirements_met(requirements_file):
|
| 443 |
+
run_pip(f'install -r "{requirements_file}"', "requirements")
|
| 444 |
+
startup_timer.record("enforce requirements")
|
| 445 |
+
|
| 446 |
+
if "--exit" in sys.argv:
|
| 447 |
+
print("Exiting because of --exit argument")
|
| 448 |
+
exit(0)
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
class ModelRef(NamedTuple):
|
| 452 |
+
arg_name: str
|
| 453 |
+
relative_path: str
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
def configure_a1111_reference(a1111_home: Path):
|
| 457 |
+
"""Append model paths based on an existing A1111 installation"""
|
| 458 |
+
|
| 459 |
+
refs = (
|
| 460 |
+
ModelRef(arg_name="--embeddings-dir", relative_path="embeddings"),
|
| 461 |
+
ModelRef(arg_name="--esrgan-models-path", relative_path="ESRGAN"),
|
| 462 |
+
ModelRef(arg_name="--lora-dirs", relative_path="Lora"),
|
| 463 |
+
ModelRef(arg_name="--ckpt-dirs", relative_path="Stable-diffusion"),
|
| 464 |
+
ModelRef(arg_name="--text-encoder-dirs", relative_path="text_encoder"),
|
| 465 |
+
ModelRef(arg_name="--vae-dirs", relative_path="VAE"),
|
| 466 |
+
ModelRef(arg_name="--controlnet-dir", relative_path="ControlNet"),
|
| 467 |
+
ModelRef(arg_name="--controlnet-preprocessor-models-dir", relative_path="ControlNetPreprocessor"),
|
| 468 |
+
)
|
| 469 |
+
|
| 470 |
+
for ref in refs:
|
| 471 |
+
target_path = a1111_home / ref.relative_path
|
| 472 |
+
if not target_path.exists():
|
| 473 |
+
target_path = a1111_home / "models" / ref.relative_path
|
| 474 |
+
if not target_path.exists():
|
| 475 |
+
continue
|
| 476 |
+
|
| 477 |
+
sys.argv.extend([ref.arg_name, str(target_path.absolute())])
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
def configure_comfy_reference(comfy_home: Path):
|
| 481 |
+
"""Append model paths based on an existing Comfy installation"""
|
| 482 |
+
|
| 483 |
+
refs = (
|
| 484 |
+
ModelRef(arg_name="--ckpt-dirs", relative_path="checkpoints"),
|
| 485 |
+
ModelRef(arg_name="--ckpt-dirs", relative_path="diffusion_models"),
|
| 486 |
+
ModelRef(arg_name="--ckpt-dirs", relative_path="unet"),
|
| 487 |
+
ModelRef(arg_name="--text-encoder-dirs", relative_path="clip"),
|
| 488 |
+
ModelRef(arg_name="--text-encoder-dirs", relative_path="text_encoders"),
|
| 489 |
+
ModelRef(arg_name="--lora-dirs", relative_path="loras"),
|
| 490 |
+
ModelRef(arg_name="--vae-dirs", relative_path="vae"),
|
| 491 |
+
)
|
| 492 |
+
|
| 493 |
+
for ref in refs:
|
| 494 |
+
target_path = comfy_home / ref.relative_path
|
| 495 |
+
if not target_path.exists():
|
| 496 |
+
target_path = comfy_home / "models" / ref.relative_path
|
| 497 |
+
if not target_path.exists():
|
| 498 |
+
continue
|
| 499 |
+
|
| 500 |
+
sys.argv.extend([ref.arg_name, str(target_path.absolute())])
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
def start():
|
| 504 |
+
print(f"Launching {'API server' if '--nowebui' in sys.argv else 'Web UI'} with arguments: {shlex.join(sys.argv[1:])}")
|
| 505 |
+
import webui
|
| 506 |
+
|
| 507 |
+
if "--nowebui" in sys.argv:
|
| 508 |
+
webui.api_only()
|
| 509 |
+
else:
|
| 510 |
+
webui.webui()
|
| 511 |
+
|
| 512 |
+
from modules_forge import main_thread
|
| 513 |
+
|
| 514 |
+
main_thread.loop()
|
| 515 |
+
return
|
| 516 |
+
|
| 517 |
+
|
| 518 |
+
def dump_sysinfo():
|
| 519 |
+
import datetime
|
| 520 |
+
|
| 521 |
+
from modules import sysinfo
|
| 522 |
+
|
| 523 |
+
text = sysinfo.get()
|
| 524 |
+
filename = f"sysinfo-{datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%d-%H-%M')}.json"
|
| 525 |
+
|
| 526 |
+
with open(filename, "w", encoding="utf8") as file:
|
| 527 |
+
file.write(text)
|
| 528 |
+
|
| 529 |
+
return filename
|
modules/localization.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
from modules import errors, scripts
|
| 5 |
+
|
| 6 |
+
localizations = {}
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def list_localizations(dirname):
|
| 10 |
+
localizations.clear()
|
| 11 |
+
|
| 12 |
+
for file in os.listdir(dirname):
|
| 13 |
+
fn, ext = os.path.splitext(file)
|
| 14 |
+
if ext.lower() != ".json":
|
| 15 |
+
continue
|
| 16 |
+
|
| 17 |
+
localizations[fn] = [os.path.join(dirname, file)]
|
| 18 |
+
|
| 19 |
+
for file in scripts.list_scripts("localizations", ".json"):
|
| 20 |
+
fn, ext = os.path.splitext(file.filename)
|
| 21 |
+
if fn not in localizations:
|
| 22 |
+
localizations[fn] = []
|
| 23 |
+
localizations[fn].append(file.path)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def localization_js(current_localization_name: str) -> str:
|
| 27 |
+
fns = localizations.get(current_localization_name, None)
|
| 28 |
+
data = {}
|
| 29 |
+
if fns is not None:
|
| 30 |
+
for fn in fns:
|
| 31 |
+
try:
|
| 32 |
+
with open(fn, "r", encoding="utf8") as file:
|
| 33 |
+
data.update(json.load(file))
|
| 34 |
+
except Exception:
|
| 35 |
+
errors.report(f"Error loading localization from {fn}", exc_info=True)
|
| 36 |
+
|
| 37 |
+
return f"window.localization = {json.dumps(data)}"
|
modules/logging_config.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
try:
|
| 5 |
+
from tqdm import tqdm
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class TqdmLoggingHandler(logging.Handler):
|
| 9 |
+
def __init__(self, fallback_handler: logging.Handler):
|
| 10 |
+
super().__init__()
|
| 11 |
+
self.fallback_handler = fallback_handler
|
| 12 |
+
|
| 13 |
+
def emit(self, record):
|
| 14 |
+
try:
|
| 15 |
+
# If there are active tqdm progress bars,
|
| 16 |
+
# attempt to not interfere with them.
|
| 17 |
+
if tqdm._instances:
|
| 18 |
+
tqdm.write(self.format(record))
|
| 19 |
+
else:
|
| 20 |
+
self.fallback_handler.emit(record)
|
| 21 |
+
except Exception:
|
| 22 |
+
self.fallback_handler.emit(record)
|
| 23 |
+
|
| 24 |
+
except ImportError:
|
| 25 |
+
TqdmLoggingHandler = None
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def setup_logging(loglevel):
|
| 29 |
+
if loglevel is None:
|
| 30 |
+
loglevel = os.environ.get("SD_WEBUI_LOG_LEVEL")
|
| 31 |
+
|
| 32 |
+
if not loglevel:
|
| 33 |
+
return
|
| 34 |
+
|
| 35 |
+
if logging.root.handlers:
|
| 36 |
+
# Already configured, do not interfere
|
| 37 |
+
return
|
| 38 |
+
|
| 39 |
+
formatter = logging.Formatter(
|
| 40 |
+
'%(asctime)s %(levelname)s [%(name)s] %(message)s',
|
| 41 |
+
'%Y-%m-%d %H:%M:%S',
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
if os.environ.get("SD_WEBUI_RICH_LOG"):
|
| 45 |
+
from rich.logging import RichHandler
|
| 46 |
+
handler = RichHandler()
|
| 47 |
+
else:
|
| 48 |
+
handler = logging.StreamHandler()
|
| 49 |
+
handler.setFormatter(formatter)
|
| 50 |
+
|
| 51 |
+
if TqdmLoggingHandler:
|
| 52 |
+
handler = TqdmLoggingHandler(handler)
|
| 53 |
+
|
| 54 |
+
handler.setFormatter(formatter)
|
| 55 |
+
|
| 56 |
+
log_level = getattr(logging, loglevel.upper(), None) or logging.INFO
|
| 57 |
+
logging.root.setLevel(log_level)
|
| 58 |
+
logging.root.addHandler(handler)
|
modules/masking.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from PIL import Image, ImageFilter, ImageOps
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def get_crop_region_v2(mask, pad=0):
|
| 5 |
+
"""
|
| 6 |
+
Finds a rectangular region that contains all masked ares in a mask.
|
| 7 |
+
Returns None if mask is completely black mask (all 0)
|
| 8 |
+
|
| 9 |
+
Parameters:
|
| 10 |
+
mask: PIL.Image.Image L mode or numpy 1d array
|
| 11 |
+
pad: int number of pixels that the region will be extended on all sides
|
| 12 |
+
Returns: (x1, y1, x2, y2) | None
|
| 13 |
+
|
| 14 |
+
Introduced post 1.9.0
|
| 15 |
+
"""
|
| 16 |
+
mask = mask if isinstance(mask, Image.Image) else Image.fromarray(mask)
|
| 17 |
+
if box := mask.getbbox():
|
| 18 |
+
x1, y1, x2, y2 = box
|
| 19 |
+
return (max(x1 - pad, 0), max(y1 - pad, 0), min(x2 + pad, mask.size[0]), min(y2 + pad, mask.size[1])) if pad else box
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def get_crop_region(mask, pad=0):
|
| 23 |
+
"""
|
| 24 |
+
Same function as get_crop_region_v2 but handles completely black mask (all 0) differently
|
| 25 |
+
when mask all black still return coordinates but the coordinates may be invalid ie x2>x1 or y2>y1
|
| 26 |
+
Notes: it is possible for the coordinates to be "valid" again if pad size is sufficiently large
|
| 27 |
+
(mask_size.x-pad, mask_size.y-pad, pad, pad)
|
| 28 |
+
|
| 29 |
+
Extension developer should use get_crop_region_v2 instead unless for compatibility considerations.
|
| 30 |
+
"""
|
| 31 |
+
mask = mask if isinstance(mask, Image.Image) else Image.fromarray(mask)
|
| 32 |
+
if box := get_crop_region_v2(mask, pad):
|
| 33 |
+
return box
|
| 34 |
+
x1, y1 = mask.size
|
| 35 |
+
x2 = y2 = 0
|
| 36 |
+
return max(x1 - pad, 0), max(y1 - pad, 0), min(x2 + pad, mask.size[0]), min(y2 + pad, mask.size[1])
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def expand_crop_region(crop_region, processing_width, processing_height, image_width, image_height):
|
| 40 |
+
"""expands crop region get_crop_region() to match the ratio of the image the region will processed in; returns expanded region
|
| 41 |
+
for example, if user drew mask in a 128x32 region, and the dimensions for processing are 512x512, the region will be expanded to 128x128."""
|
| 42 |
+
|
| 43 |
+
x1, y1, x2, y2 = crop_region
|
| 44 |
+
|
| 45 |
+
ratio_crop_region = (x2 - x1) / (y2 - y1)
|
| 46 |
+
ratio_processing = processing_width / processing_height
|
| 47 |
+
|
| 48 |
+
if ratio_crop_region > ratio_processing:
|
| 49 |
+
desired_height = (x2 - x1) / ratio_processing
|
| 50 |
+
desired_height_diff = int(desired_height - (y2-y1))
|
| 51 |
+
y1 -= desired_height_diff//2
|
| 52 |
+
y2 += desired_height_diff - desired_height_diff//2
|
| 53 |
+
if y2 >= image_height:
|
| 54 |
+
diff = y2 - image_height
|
| 55 |
+
y2 -= diff
|
| 56 |
+
y1 -= diff
|
| 57 |
+
if y1 < 0:
|
| 58 |
+
y2 -= y1
|
| 59 |
+
y1 -= y1
|
| 60 |
+
if y2 >= image_height:
|
| 61 |
+
y2 = image_height
|
| 62 |
+
else:
|
| 63 |
+
desired_width = (y2 - y1) * ratio_processing
|
| 64 |
+
desired_width_diff = int(desired_width - (x2-x1))
|
| 65 |
+
x1 -= desired_width_diff//2
|
| 66 |
+
x2 += desired_width_diff - desired_width_diff//2
|
| 67 |
+
if x2 >= image_width:
|
| 68 |
+
diff = x2 - image_width
|
| 69 |
+
x2 -= diff
|
| 70 |
+
x1 -= diff
|
| 71 |
+
if x1 < 0:
|
| 72 |
+
x2 -= x1
|
| 73 |
+
x1 -= x1
|
| 74 |
+
if x2 >= image_width:
|
| 75 |
+
x2 = image_width
|
| 76 |
+
|
| 77 |
+
return x1, y1, x2, y2
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def fill(image, mask):
|
| 81 |
+
"""fills masked regions with colors from image using blur. Not extremely effective."""
|
| 82 |
+
|
| 83 |
+
image_mod = Image.new('RGBA', (image.width, image.height))
|
| 84 |
+
|
| 85 |
+
image_masked = Image.new('RGBa', (image.width, image.height))
|
| 86 |
+
image_masked.paste(image.convert("RGBA").convert("RGBa"), mask=ImageOps.invert(mask.convert('L')))
|
| 87 |
+
|
| 88 |
+
image_masked = image_masked.convert('RGBa')
|
| 89 |
+
|
| 90 |
+
for radius, repeats in [(256, 1), (64, 1), (16, 2), (4, 4), (2, 2), (0, 1)]:
|
| 91 |
+
blurred = image_masked.filter(ImageFilter.GaussianBlur(radius)).convert('RGBA')
|
| 92 |
+
for _ in range(repeats):
|
| 93 |
+
image_mod.alpha_composite(blurred)
|
| 94 |
+
|
| 95 |
+
return image_mod.convert("RGB")
|
| 96 |
+
|
modules/memmon.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import threading
|
| 2 |
+
import time
|
| 3 |
+
from collections import defaultdict
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class MemUsageMonitor(threading.Thread):
|
| 9 |
+
run_flag = None
|
| 10 |
+
device = None
|
| 11 |
+
disabled = False
|
| 12 |
+
opts = None
|
| 13 |
+
data = None
|
| 14 |
+
|
| 15 |
+
def __init__(self, name, device, opts):
|
| 16 |
+
threading.Thread.__init__(self)
|
| 17 |
+
self.name = name
|
| 18 |
+
self.device = device
|
| 19 |
+
self.opts = opts
|
| 20 |
+
|
| 21 |
+
self.daemon = True
|
| 22 |
+
self.run_flag = threading.Event()
|
| 23 |
+
self.data = defaultdict(int)
|
| 24 |
+
|
| 25 |
+
try:
|
| 26 |
+
self.cuda_mem_get_info()
|
| 27 |
+
torch.cuda.memory_stats(self.device)
|
| 28 |
+
except Exception as e: # AMD or whatever
|
| 29 |
+
print(f"Warning: caught exception '{e}', memory monitor disabled")
|
| 30 |
+
self.disabled = True
|
| 31 |
+
|
| 32 |
+
def cuda_mem_get_info(self):
|
| 33 |
+
index = self.device.index if self.device.index is not None else torch.cuda.current_device()
|
| 34 |
+
return torch.cuda.mem_get_info(index)
|
| 35 |
+
|
| 36 |
+
def run(self):
|
| 37 |
+
if self.disabled:
|
| 38 |
+
return
|
| 39 |
+
|
| 40 |
+
while True:
|
| 41 |
+
self.run_flag.wait()
|
| 42 |
+
|
| 43 |
+
torch.cuda.reset_peak_memory_stats()
|
| 44 |
+
self.data.clear()
|
| 45 |
+
|
| 46 |
+
if self.opts.memmon_poll_rate <= 0:
|
| 47 |
+
self.run_flag.clear()
|
| 48 |
+
continue
|
| 49 |
+
|
| 50 |
+
self.data["min_free"] = self.cuda_mem_get_info()[0]
|
| 51 |
+
|
| 52 |
+
while self.run_flag.is_set():
|
| 53 |
+
free, total = self.cuda_mem_get_info()
|
| 54 |
+
self.data["min_free"] = min(self.data["min_free"], free)
|
| 55 |
+
|
| 56 |
+
time.sleep(1 / self.opts.memmon_poll_rate)
|
| 57 |
+
|
| 58 |
+
def dump_debug(self):
|
| 59 |
+
print(self, "recorded data:")
|
| 60 |
+
for k, v in self.read().items():
|
| 61 |
+
print(k, -(v // -(1024**2)))
|
| 62 |
+
|
| 63 |
+
print(self, "raw torch memory stats:")
|
| 64 |
+
tm = torch.cuda.memory_stats(self.device)
|
| 65 |
+
for k, v in tm.items():
|
| 66 |
+
if "bytes" not in k:
|
| 67 |
+
continue
|
| 68 |
+
print("\t" if "peak" in k else "", k, -(v // -(1024**2)))
|
| 69 |
+
|
| 70 |
+
print(torch.cuda.memory_summary())
|
| 71 |
+
|
| 72 |
+
def monitor(self):
|
| 73 |
+
self.run_flag.set()
|
| 74 |
+
|
| 75 |
+
def read(self):
|
| 76 |
+
if not self.disabled:
|
| 77 |
+
free, total = self.cuda_mem_get_info()
|
| 78 |
+
self.data["free"] = free
|
| 79 |
+
self.data["total"] = total
|
| 80 |
+
|
| 81 |
+
torch_stats = torch.cuda.memory_stats(self.device)
|
| 82 |
+
self.data["active"] = torch_stats["active.all.current"]
|
| 83 |
+
self.data["active_peak"] = torch_stats["active_bytes.all.peak"]
|
| 84 |
+
self.data["reserved"] = torch_stats["reserved_bytes.all.current"]
|
| 85 |
+
self.data["reserved_peak"] = torch_stats["reserved_bytes.all.peak"]
|
| 86 |
+
self.data["system_peak"] = total - self.data["min_free"]
|
| 87 |
+
|
| 88 |
+
return self.data
|
| 89 |
+
|
| 90 |
+
def stop(self):
|
| 91 |
+
self.run_flag.clear()
|
| 92 |
+
return self.read()
|
modules/modelloader.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
import os
|
| 5 |
+
from urllib.parse import urlparse
|
| 6 |
+
|
| 7 |
+
import spandrel
|
| 8 |
+
import spandrel_extra_arches
|
| 9 |
+
import torch
|
| 10 |
+
|
| 11 |
+
from modules import shared
|
| 12 |
+
from modules.upscaler import Upscaler, UpscalerLanczos, UpscalerNearest, UpscalerNone # noqa
|
| 13 |
+
from modules.util import load_file_from_url # noqa
|
| 14 |
+
|
| 15 |
+
spandrel_extra_arches.install()
|
| 16 |
+
|
| 17 |
+
logger = logging.getLogger(__name__)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def load_models(model_path: str, model_url: str = None, command_path: str = None, ext_filter=None, download_name=None, ext_blacklist=None, hash_prefix=None) -> list:
|
| 21 |
+
"""
|
| 22 |
+
A one-and done loader to try finding the desired models in specified directories.
|
| 23 |
+
|
| 24 |
+
@param download_name: Specify to download from model_url immediately.
|
| 25 |
+
@param model_url: If no other models are found, this will be downloaded on upscale.
|
| 26 |
+
@param model_path: The location to store/find models in.
|
| 27 |
+
@param command_path: A command-line argument to search for models in first.
|
| 28 |
+
@param ext_filter: An optional list of filename extensions to filter by
|
| 29 |
+
@param hash_prefix: the expected sha256 of the model_url
|
| 30 |
+
@return: A list of paths containing the desired model(s)
|
| 31 |
+
"""
|
| 32 |
+
output = []
|
| 33 |
+
|
| 34 |
+
try:
|
| 35 |
+
places = []
|
| 36 |
+
|
| 37 |
+
if command_path is not None and command_path != model_path:
|
| 38 |
+
pretrained_path = os.path.join(command_path, "experiments/pretrained_models")
|
| 39 |
+
if os.path.exists(pretrained_path):
|
| 40 |
+
print(f"Appending path: {pretrained_path}")
|
| 41 |
+
places.append(pretrained_path)
|
| 42 |
+
elif os.path.exists(command_path):
|
| 43 |
+
places.append(command_path)
|
| 44 |
+
|
| 45 |
+
places.append(model_path)
|
| 46 |
+
|
| 47 |
+
for place in places:
|
| 48 |
+
for full_path in shared.walk_files(place, allowed_extensions=ext_filter):
|
| 49 |
+
if os.path.islink(full_path) and not os.path.exists(full_path):
|
| 50 |
+
print(f"Skipping broken symlink: {full_path}")
|
| 51 |
+
continue
|
| 52 |
+
if ext_blacklist is not None and any(full_path.endswith(x) for x in ext_blacklist):
|
| 53 |
+
continue
|
| 54 |
+
if full_path not in output:
|
| 55 |
+
output.append(full_path)
|
| 56 |
+
|
| 57 |
+
if model_url is not None and len(output) == 0:
|
| 58 |
+
if download_name is not None:
|
| 59 |
+
output.append(load_file_from_url(model_url, model_dir=places[0], file_name=download_name, hash_prefix=hash_prefix))
|
| 60 |
+
else:
|
| 61 |
+
output.append(model_url)
|
| 62 |
+
|
| 63 |
+
except Exception:
|
| 64 |
+
pass
|
| 65 |
+
|
| 66 |
+
return output
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def friendly_name(file: str):
|
| 70 |
+
if file.startswith("http"):
|
| 71 |
+
file = urlparse(file).path
|
| 72 |
+
|
| 73 |
+
file = os.path.basename(file)
|
| 74 |
+
model_name, _ = os.path.splitext(file)
|
| 75 |
+
return model_name
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def load_upscalers():
|
| 79 |
+
from modules.esrgan_model import UpscalerESRGAN
|
| 80 |
+
|
| 81 |
+
del shared.sd_upscalers
|
| 82 |
+
|
| 83 |
+
commandline_model_path = shared.cmd_opts.esrgan_models_path
|
| 84 |
+
upscaler = UpscalerESRGAN(commandline_model_path)
|
| 85 |
+
upscaler.user_path = commandline_model_path
|
| 86 |
+
upscaler.model_download_path = commandline_model_path or upscaler.model_path
|
| 87 |
+
|
| 88 |
+
shared.sd_upscalers = [
|
| 89 |
+
*UpscalerNone().scalers,
|
| 90 |
+
*UpscalerLanczos().scalers,
|
| 91 |
+
*UpscalerNearest().scalers,
|
| 92 |
+
*sorted(upscaler.scalers, key=lambda s: s.name.lower()),
|
| 93 |
+
]
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def load_spandrel_model(
|
| 97 |
+
path: str | os.PathLike,
|
| 98 |
+
*,
|
| 99 |
+
device: str | torch.device | None,
|
| 100 |
+
prefer_half: bool = False,
|
| 101 |
+
dtype: str | torch.dtype | None = None,
|
| 102 |
+
expected_architecture: str | None = None,
|
| 103 |
+
) -> spandrel.ModelDescriptor:
|
| 104 |
+
model_descriptor = spandrel.ModelLoader(device=device).load_from_file(str(path))
|
| 105 |
+
arch = model_descriptor.architecture
|
| 106 |
+
logger.info(f'Loaded {arch.name} Model: "{os.path.basename(path)}"')
|
| 107 |
+
|
| 108 |
+
half = False
|
| 109 |
+
if prefer_half:
|
| 110 |
+
if model_descriptor.supports_half:
|
| 111 |
+
model_descriptor.model.half()
|
| 112 |
+
half = True
|
| 113 |
+
elif model_descriptor.supports_bfloat16:
|
| 114 |
+
model_descriptor.model.bfloat16()
|
| 115 |
+
half = True
|
| 116 |
+
else:
|
| 117 |
+
logger.warning(f"Model {path} does not support half precision...")
|
| 118 |
+
|
| 119 |
+
if dtype:
|
| 120 |
+
model_descriptor.model.to(dtype=dtype)
|
| 121 |
+
|
| 122 |
+
logger.debug("Loaded %s from %s (device=%s, half=%s, dtype=%s)", arch, path, device, half, dtype)
|
| 123 |
+
|
| 124 |
+
model_descriptor.model.eval()
|
| 125 |
+
return model_descriptor
|
modules/ngrok.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ngrok
|
| 2 |
+
|
| 3 |
+
# Connect to ngrok for ingress
|
| 4 |
+
def connect(token, port, options):
|
| 5 |
+
account = None
|
| 6 |
+
if token is None:
|
| 7 |
+
token = 'None'
|
| 8 |
+
else:
|
| 9 |
+
if ':' in token:
|
| 10 |
+
# token = authtoken:username:password
|
| 11 |
+
token, username, password = token.split(':', 2)
|
| 12 |
+
account = f"{username}:{password}"
|
| 13 |
+
|
| 14 |
+
# For all options see: https://github.com/ngrok/ngrok-py/blob/main/examples/ngrok-connect-full.py
|
| 15 |
+
if not options.get('authtoken_from_env'):
|
| 16 |
+
options['authtoken'] = token
|
| 17 |
+
if account:
|
| 18 |
+
options['basic_auth'] = account
|
| 19 |
+
if not options.get('session_metadata'):
|
| 20 |
+
options['session_metadata'] = 'stable-diffusion-webui'
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
try:
|
| 24 |
+
public_url = ngrok.connect(f"127.0.0.1:{port}", **options).url()
|
| 25 |
+
except Exception as e:
|
| 26 |
+
print(f'Invalid ngrok authtoken? ngrok connection aborted due to: {e}\n'
|
| 27 |
+
f'Your token: {token}, get the right one on https://dashboard.ngrok.com/get-started/your-authtoken')
|
| 28 |
+
else:
|
| 29 |
+
print(f'ngrok connected to localhost:{port}! URL: {public_url}\n'
|
| 30 |
+
'You can use this link after the launch is complete.')
|
modules/options.py
ADDED
|
@@ -0,0 +1,343 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import sys
|
| 4 |
+
from dataclasses import dataclass
|
| 5 |
+
|
| 6 |
+
import gradio as gr
|
| 7 |
+
|
| 8 |
+
from modules import errors
|
| 9 |
+
from modules.shared_cmd_options import cmd_opts
|
| 10 |
+
from modules.paths_internal import script_path
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class OptionInfo:
|
| 14 |
+
def __init__(self, default=None, label="", component=None, component_args=None, onchange=None, section=None, refresh=None, comment_before='', comment_after='', infotext=None, restrict_api=False, category_id=None):
|
| 15 |
+
self.default = default
|
| 16 |
+
self.label = label
|
| 17 |
+
self.component = component
|
| 18 |
+
self.component_args = component_args
|
| 19 |
+
self.onchange = onchange
|
| 20 |
+
self.section = section
|
| 21 |
+
self.category_id = category_id
|
| 22 |
+
self.refresh = refresh
|
| 23 |
+
self.do_not_save = False
|
| 24 |
+
|
| 25 |
+
self.comment_before = comment_before
|
| 26 |
+
"""HTML text that will be added after label in UI"""
|
| 27 |
+
|
| 28 |
+
self.comment_after = comment_after
|
| 29 |
+
"""HTML text that will be added before label in UI"""
|
| 30 |
+
|
| 31 |
+
self.infotext = infotext
|
| 32 |
+
|
| 33 |
+
self.restrict_api = restrict_api
|
| 34 |
+
"""If True, the setting will not be accessible via API"""
|
| 35 |
+
|
| 36 |
+
def link(self, label, url):
|
| 37 |
+
self.comment_before += f"[<a href='{url}' target='_blank'>{label}</a>]"
|
| 38 |
+
return self
|
| 39 |
+
|
| 40 |
+
def js(self, label, js_func):
|
| 41 |
+
self.comment_before += f"[<a onclick='{js_func}(); return false'>{label}</a>]"
|
| 42 |
+
return self
|
| 43 |
+
|
| 44 |
+
def info(self, info):
|
| 45 |
+
self.comment_after += f"<span class='info'>({info})</span>"
|
| 46 |
+
return self
|
| 47 |
+
|
| 48 |
+
def html(self, html):
|
| 49 |
+
self.comment_after += html
|
| 50 |
+
return self
|
| 51 |
+
|
| 52 |
+
def needs_restart(self):
|
| 53 |
+
self.comment_after += " <span class='info'>(requires restart)</span>"
|
| 54 |
+
return self
|
| 55 |
+
|
| 56 |
+
def needs_reload_ui(self):
|
| 57 |
+
self.comment_after += " <span class='info'>(requires Reload UI)</span>"
|
| 58 |
+
return self
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class OptionHTML(OptionInfo):
|
| 62 |
+
def __init__(self, text):
|
| 63 |
+
super().__init__(str(text).strip(), label='', component=lambda **kwargs: gr.HTML(elem_classes="settings-info", **kwargs))
|
| 64 |
+
|
| 65 |
+
self.do_not_save = True
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class OptionDiv(OptionInfo):
|
| 69 |
+
def __init__(self):
|
| 70 |
+
super().__init__("", label="", component=lambda **kwargs: gr.HTML(elem_classes="settings-div", **kwargs))
|
| 71 |
+
|
| 72 |
+
self.do_not_save = True
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def options_section(section_identifier, options_dict):
|
| 76 |
+
for v in options_dict.values():
|
| 77 |
+
if len(section_identifier) == 2:
|
| 78 |
+
v.section = section_identifier
|
| 79 |
+
elif len(section_identifier) == 3:
|
| 80 |
+
v.section = section_identifier[0:2]
|
| 81 |
+
v.category_id = section_identifier[2]
|
| 82 |
+
|
| 83 |
+
return options_dict
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
options_builtin_fields = {"data_labels", "data", "restricted_opts", "typemap"}
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class Options:
|
| 90 |
+
typemap = {int: float}
|
| 91 |
+
|
| 92 |
+
def __init__(self, data_labels: dict[str, OptionInfo], restricted_opts):
|
| 93 |
+
self.data_labels = data_labels
|
| 94 |
+
self.data = {k: v.default for k, v in self.data_labels.items() if not v.do_not_save}
|
| 95 |
+
self.restricted_opts = restricted_opts
|
| 96 |
+
|
| 97 |
+
def __setattr__(self, key, value):
|
| 98 |
+
if key in options_builtin_fields:
|
| 99 |
+
return super(Options, self).__setattr__(key, value)
|
| 100 |
+
|
| 101 |
+
if self.data is not None:
|
| 102 |
+
if key in self.data or key in self.data_labels:
|
| 103 |
+
|
| 104 |
+
# Check that settings aren't globally frozen
|
| 105 |
+
assert not cmd_opts.freeze_settings, "changing settings is disabled"
|
| 106 |
+
|
| 107 |
+
# Get the info related to the setting being changed
|
| 108 |
+
info = self.data_labels.get(key, None)
|
| 109 |
+
if info.do_not_save:
|
| 110 |
+
return
|
| 111 |
+
|
| 112 |
+
# Restrict component arguments
|
| 113 |
+
comp_args = info.component_args if info else None
|
| 114 |
+
if isinstance(comp_args, dict) and comp_args.get('visible', True) is False:
|
| 115 |
+
raise RuntimeError(f"not possible to set '{key}' because it is restricted")
|
| 116 |
+
|
| 117 |
+
# Check that this section isn't frozen
|
| 118 |
+
if cmd_opts.freeze_settings_in_sections is not None:
|
| 119 |
+
frozen_sections = list(map(str.strip, cmd_opts.freeze_settings_in_sections.split(','))) # Trim whitespace from section names
|
| 120 |
+
section_key = info.section[0]
|
| 121 |
+
section_name = info.section[1]
|
| 122 |
+
assert section_key not in frozen_sections, f"not possible to set '{key}' because settings in section '{section_name}' ({section_key}) are frozen with --freeze-settings-in-sections"
|
| 123 |
+
|
| 124 |
+
# Check that this section of the settings isn't frozen
|
| 125 |
+
if cmd_opts.freeze_specific_settings is not None:
|
| 126 |
+
frozen_keys = list(map(str.strip, cmd_opts.freeze_specific_settings.split(','))) # Trim whitespace from setting keys
|
| 127 |
+
assert key not in frozen_keys, f"not possible to set '{key}' because this setting is frozen with --freeze-specific-settings"
|
| 128 |
+
|
| 129 |
+
# Check shorthand option which disables editing options in "saving-paths"
|
| 130 |
+
if cmd_opts.hide_ui_dir_config and key in self.restricted_opts:
|
| 131 |
+
raise RuntimeError(f"not possible to set '{key}' because it is restricted with --hide_ui_dir_config")
|
| 132 |
+
|
| 133 |
+
self.data[key] = value
|
| 134 |
+
return
|
| 135 |
+
|
| 136 |
+
return super(Options, self).__setattr__(key, value)
|
| 137 |
+
|
| 138 |
+
def __getattr__(self, item):
|
| 139 |
+
if item in options_builtin_fields:
|
| 140 |
+
return super(Options, self).__getattribute__(item)
|
| 141 |
+
|
| 142 |
+
if self.data is not None:
|
| 143 |
+
if item in self.data:
|
| 144 |
+
return self.data[item]
|
| 145 |
+
|
| 146 |
+
if item in self.data_labels:
|
| 147 |
+
return self.data_labels[item].default
|
| 148 |
+
|
| 149 |
+
return super(Options, self).__getattribute__(item)
|
| 150 |
+
|
| 151 |
+
def set(self, key, value, is_api=False, run_callbacks=True):
|
| 152 |
+
"""sets an option and calls its onchange callback, returning True if the option changed and False otherwise"""
|
| 153 |
+
|
| 154 |
+
oldval = self.data.get(key, None)
|
| 155 |
+
if oldval == value:
|
| 156 |
+
return False
|
| 157 |
+
|
| 158 |
+
option = self.data_labels[key]
|
| 159 |
+
if option.do_not_save:
|
| 160 |
+
return False
|
| 161 |
+
|
| 162 |
+
if is_api and option.restrict_api:
|
| 163 |
+
return False
|
| 164 |
+
|
| 165 |
+
try:
|
| 166 |
+
setattr(self, key, value)
|
| 167 |
+
except RuntimeError:
|
| 168 |
+
return False
|
| 169 |
+
|
| 170 |
+
if run_callbacks and option.onchange is not None:
|
| 171 |
+
try:
|
| 172 |
+
option.onchange()
|
| 173 |
+
except Exception as e:
|
| 174 |
+
errors.display(e, f"changing setting {key} to {value}")
|
| 175 |
+
setattr(self, key, oldval)
|
| 176 |
+
return False
|
| 177 |
+
|
| 178 |
+
return True
|
| 179 |
+
|
| 180 |
+
def get_default(self, key):
|
| 181 |
+
"""returns the default value for the key"""
|
| 182 |
+
|
| 183 |
+
data_label = self.data_labels.get(key)
|
| 184 |
+
if data_label is None:
|
| 185 |
+
return None
|
| 186 |
+
|
| 187 |
+
return data_label.default
|
| 188 |
+
|
| 189 |
+
def save(self, filename):
|
| 190 |
+
assert not cmd_opts.freeze_settings, "saving settings is disabled"
|
| 191 |
+
|
| 192 |
+
with open(filename, "w", encoding="utf8") as file:
|
| 193 |
+
json.dump(self.data, file, indent=4, ensure_ascii=False)
|
| 194 |
+
|
| 195 |
+
def same_type(self, x, y):
|
| 196 |
+
if x is None or y is None:
|
| 197 |
+
return True
|
| 198 |
+
|
| 199 |
+
type_x = self.typemap.get(type(x), type(x))
|
| 200 |
+
type_y = self.typemap.get(type(y), type(y))
|
| 201 |
+
|
| 202 |
+
return type_x == type_y
|
| 203 |
+
|
| 204 |
+
def load(self, filename):
|
| 205 |
+
try:
|
| 206 |
+
with open(filename, "r", encoding="utf8") as file:
|
| 207 |
+
self.data = json.load(file)
|
| 208 |
+
except FileNotFoundError:
|
| 209 |
+
self.data = {}
|
| 210 |
+
except Exception:
|
| 211 |
+
errors.report(f'\nCould not load settings\nThe config file "{filename}" is likely corrupted\nIt has been moved to the "tmp/config.json"\nReverting config to default\n\n''', exc_info=True)
|
| 212 |
+
os.replace(filename, os.path.join(script_path, "tmp", "config.json"))
|
| 213 |
+
self.data = {}
|
| 214 |
+
# 1.6.0 VAE defaults
|
| 215 |
+
if self.data.get('sd_vae_as_default') is not None and self.data.get('sd_vae_overrides_per_model_preferences') is None:
|
| 216 |
+
self.data['sd_vae_overrides_per_model_preferences'] = not self.data.get('sd_vae_as_default')
|
| 217 |
+
|
| 218 |
+
# 1.1.1 quicksettings list migration
|
| 219 |
+
if self.data.get('quicksettings') is not None and self.data.get('quicksettings_list') is None:
|
| 220 |
+
self.data['quicksettings_list'] = [i.strip() for i in self.data.get('quicksettings').split(',')]
|
| 221 |
+
|
| 222 |
+
# 1.4.0 ui_reorder
|
| 223 |
+
if isinstance(self.data.get('ui_reorder'), str) and self.data.get('ui_reorder') and "ui_reorder_list" not in self.data:
|
| 224 |
+
self.data['ui_reorder_list'] = [i.strip() for i in self.data.get('ui_reorder').split(',')]
|
| 225 |
+
|
| 226 |
+
bad_settings = 0
|
| 227 |
+
for k, v in self.data.items():
|
| 228 |
+
info = self.data_labels.get(k, None)
|
| 229 |
+
if info is not None and not self.same_type(info.default, v):
|
| 230 |
+
print(f"Warning: bad setting value: {k}: {v} ({type(v).__name__}; expected {type(info.default).__name__})", file=sys.stderr)
|
| 231 |
+
bad_settings += 1
|
| 232 |
+
|
| 233 |
+
if bad_settings > 0:
|
| 234 |
+
print(f"The program is likely to not work with bad settings.\nSettings file: {filename}\nEither fix the file, or delete it and restart.", file=sys.stderr)
|
| 235 |
+
|
| 236 |
+
def onchange(self, key, func, call=True):
|
| 237 |
+
item = self.data_labels.get(key)
|
| 238 |
+
item.onchange = func
|
| 239 |
+
|
| 240 |
+
if call:
|
| 241 |
+
func()
|
| 242 |
+
|
| 243 |
+
def dumpjson(self):
|
| 244 |
+
d = {k: self.data.get(k, v.default) for k, v in self.data_labels.items()}
|
| 245 |
+
d["_comments_before"] = {k: v.comment_before for k, v in self.data_labels.items() if v.comment_before is not None}
|
| 246 |
+
d["_comments_after"] = {k: v.comment_after for k, v in self.data_labels.items() if v.comment_after is not None}
|
| 247 |
+
|
| 248 |
+
item_categories = {}
|
| 249 |
+
for item in self.data_labels.values():
|
| 250 |
+
if item.section[0] is None:
|
| 251 |
+
continue
|
| 252 |
+
|
| 253 |
+
category = categories.mapping.get(item.category_id)
|
| 254 |
+
category = "Extensions" if category is None else category.label
|
| 255 |
+
if category not in item_categories:
|
| 256 |
+
item_categories[category] = item.section[1]
|
| 257 |
+
|
| 258 |
+
# _categories is a list of pairs: [section, category]. Each section (a setting page) will get a special heading above it with the category as text.
|
| 259 |
+
d["_categories"] = [[v, k] for k, v in item_categories.items()] + [["Defaults", "Other"]]
|
| 260 |
+
|
| 261 |
+
return json.dumps(d)
|
| 262 |
+
|
| 263 |
+
def add_option(self, key, info):
|
| 264 |
+
self.data_labels[key] = info
|
| 265 |
+
if key not in self.data and not info.do_not_save:
|
| 266 |
+
self.data[key] = info.default
|
| 267 |
+
|
| 268 |
+
def reorder(self):
|
| 269 |
+
"""Reorder settings so that:
|
| 270 |
+
- all items related to section always go together
|
| 271 |
+
- all sections belonging to a category go together
|
| 272 |
+
- sections inside a category are ordered alphabetically
|
| 273 |
+
- categories are ordered by creation order
|
| 274 |
+
|
| 275 |
+
Category is a superset of sections: for category "postprocessing" there could be multiple sections: "face restoration", "upscaling".
|
| 276 |
+
|
| 277 |
+
This function also changes items' category_id so that all items belonging to a section have the same category_id.
|
| 278 |
+
"""
|
| 279 |
+
|
| 280 |
+
category_ids = {}
|
| 281 |
+
section_categories = {}
|
| 282 |
+
|
| 283 |
+
settings_items = self.data_labels.items()
|
| 284 |
+
for _, item in settings_items:
|
| 285 |
+
if item.section not in section_categories:
|
| 286 |
+
section_categories[item.section] = item.category_id
|
| 287 |
+
|
| 288 |
+
for _, item in settings_items:
|
| 289 |
+
item.category_id = section_categories.get(item.section)
|
| 290 |
+
|
| 291 |
+
for category_id in categories.mapping:
|
| 292 |
+
if category_id not in category_ids:
|
| 293 |
+
category_ids[category_id] = len(category_ids)
|
| 294 |
+
|
| 295 |
+
def sort_key(x):
|
| 296 |
+
item: OptionInfo = x[1]
|
| 297 |
+
category_order = category_ids.get(item.category_id, len(category_ids))
|
| 298 |
+
section_order = item.section[1]
|
| 299 |
+
|
| 300 |
+
return category_order, section_order
|
| 301 |
+
|
| 302 |
+
self.data_labels = dict(sorted(settings_items, key=sort_key))
|
| 303 |
+
|
| 304 |
+
def cast_value(self, key, value):
|
| 305 |
+
"""casts an arbitrary to the same type as this setting's value with key
|
| 306 |
+
Example: cast_value("eta_noise_seed_delta", "12") -> returns 12 (an int rather than str)
|
| 307 |
+
"""
|
| 308 |
+
|
| 309 |
+
if value is None:
|
| 310 |
+
return None
|
| 311 |
+
|
| 312 |
+
default_value = self.data_labels[key].default
|
| 313 |
+
if default_value is None:
|
| 314 |
+
default_value = getattr(self, key, None)
|
| 315 |
+
if default_value is None:
|
| 316 |
+
return None
|
| 317 |
+
|
| 318 |
+
expected_type = type(default_value)
|
| 319 |
+
if expected_type == bool and value == "False":
|
| 320 |
+
value = False
|
| 321 |
+
else:
|
| 322 |
+
value = expected_type(value)
|
| 323 |
+
|
| 324 |
+
return value
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
@dataclass
|
| 328 |
+
class OptionsCategory:
|
| 329 |
+
id: str
|
| 330 |
+
label: str
|
| 331 |
+
|
| 332 |
+
class OptionsCategories:
|
| 333 |
+
def __init__(self):
|
| 334 |
+
self.mapping = {}
|
| 335 |
+
|
| 336 |
+
def register_category(self, category_id, label):
|
| 337 |
+
if category_id in self.mapping:
|
| 338 |
+
return category_id
|
| 339 |
+
|
| 340 |
+
self.mapping[category_id] = OptionsCategory(category_id, label)
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
categories = OptionsCategories()
|
modules/patches.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import defaultdict
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def patch(key, obj, field, replacement):
|
| 5 |
+
"""Replaces a function in a module or a class.
|
| 6 |
+
|
| 7 |
+
Also stores the original function in this module, possible to be retrieved via original(key, obj, field).
|
| 8 |
+
If the function is already replaced by this caller (key), an exception is raised -- use undo() before that.
|
| 9 |
+
|
| 10 |
+
Arguments:
|
| 11 |
+
key: identifying information for who is doing the replacement. You can use __name__.
|
| 12 |
+
obj: the module or the class
|
| 13 |
+
field: name of the function as a string
|
| 14 |
+
replacement: the new function
|
| 15 |
+
|
| 16 |
+
Returns:
|
| 17 |
+
the original function
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
patch_key = (obj, field)
|
| 21 |
+
if patch_key in originals[key]:
|
| 22 |
+
raise RuntimeError(f"patch for {field} is already applied")
|
| 23 |
+
|
| 24 |
+
original_func = getattr(obj, field)
|
| 25 |
+
originals[key][patch_key] = original_func
|
| 26 |
+
|
| 27 |
+
setattr(obj, field, replacement)
|
| 28 |
+
|
| 29 |
+
return original_func
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def undo(key, obj, field):
|
| 33 |
+
"""Undoes the peplacement by the patch().
|
| 34 |
+
|
| 35 |
+
If the function is not replaced, raises an exception.
|
| 36 |
+
|
| 37 |
+
Arguments:
|
| 38 |
+
key: identifying information for who is doing the replacement. You can use __name__.
|
| 39 |
+
obj: the module or the class
|
| 40 |
+
field: name of the function as a string
|
| 41 |
+
|
| 42 |
+
Returns:
|
| 43 |
+
Always None
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
patch_key = (obj, field)
|
| 47 |
+
|
| 48 |
+
if patch_key not in originals[key]:
|
| 49 |
+
raise RuntimeError(f"there is no patch for {field} to undo")
|
| 50 |
+
|
| 51 |
+
original_func = originals[key].pop(patch_key)
|
| 52 |
+
setattr(obj, field, original_func)
|
| 53 |
+
|
| 54 |
+
return None
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def original(key, obj, field):
|
| 58 |
+
"""Returns the original function for the patch created by the patch() function"""
|
| 59 |
+
patch_key = (obj, field)
|
| 60 |
+
|
| 61 |
+
return originals[key].get(patch_key, None)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
originals = defaultdict(dict)
|
modules/paths.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
from modules.paths_internal import models_path, script_path, data_path, extensions_dir, extensions_builtin_dir, cwd # noqa: F401
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
sys.path.insert(0, script_path)
|
| 7 |
+
|
| 8 |
+
sd_path = os.path.dirname(__file__)
|
modules/paths_internal.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
this module defines internal paths used by program and is safe to import before dependencies are installed in launch.py
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
import shlex
|
| 7 |
+
import sys
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
normalized_filepath = lambda filepath: str(Path(filepath).absolute())
|
| 11 |
+
|
| 12 |
+
commandline_args = os.environ.get("COMMANDLINE_ARGS", "")
|
| 13 |
+
sys.argv += shlex.split(commandline_args)
|
| 14 |
+
|
| 15 |
+
cwd = os.getcwd()
|
| 16 |
+
modules_path = os.path.dirname(os.path.realpath(__file__))
|
| 17 |
+
script_path = os.path.dirname(modules_path)
|
| 18 |
+
|
| 19 |
+
from backend.args import parser
|
| 20 |
+
|
| 21 |
+
parser.add_argument("--data-dir", type=str, default=os.path.dirname(modules_path), help="base path where all user data is stored")
|
| 22 |
+
parser.add_argument("--model-ref", type=str, default=None, help="base path for all models")
|
| 23 |
+
cmd_opts_pre, _ = parser.parse_known_args()
|
| 24 |
+
|
| 25 |
+
data_path = cmd_opts_pre.data_dir
|
| 26 |
+
|
| 27 |
+
models_path = cmd_opts_pre.model_ref or os.path.join(data_path, "models")
|
| 28 |
+
extensions_dir = os.path.join(data_path, "extensions")
|
| 29 |
+
extensions_builtin_dir = os.path.join(script_path, "extensions-builtin")
|
| 30 |
+
config_states_dir = os.path.join(script_path, "config_states")
|
| 31 |
+
default_output_dir = os.path.join(data_path, "output")
|
| 32 |
+
|
| 33 |
+
roboto_ttf_file = os.path.join(modules_path, "Roboto-Regular.ttf")
|
modules/postprocessing.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
from PIL import Image
|
| 4 |
+
|
| 5 |
+
from modules import shared, images, devices, scripts, scripts_postprocessing, ui_common, infotext_utils
|
| 6 |
+
from modules.shared import opts
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def run_postprocessing(extras_mode, image, image_folder, input_dir, output_dir, show_extras_results, *args, save_output: bool = True):
|
| 10 |
+
devices.torch_gc()
|
| 11 |
+
|
| 12 |
+
shared.state.begin(job="extras")
|
| 13 |
+
|
| 14 |
+
outputs = []
|
| 15 |
+
|
| 16 |
+
if isinstance(image, dict):
|
| 17 |
+
image = image["composite"]
|
| 18 |
+
|
| 19 |
+
def get_images(extras_mode, image, image_folder, input_dir):
|
| 20 |
+
if extras_mode == 1:
|
| 21 |
+
for img in image_folder:
|
| 22 |
+
if isinstance(img, Image.Image):
|
| 23 |
+
image = images.fix_image(img)
|
| 24 |
+
fn = ''
|
| 25 |
+
else:
|
| 26 |
+
image = images.read(os.path.abspath(img.name))
|
| 27 |
+
fn = os.path.splitext(img.name)[0]
|
| 28 |
+
yield image, fn
|
| 29 |
+
elif extras_mode == 2:
|
| 30 |
+
assert not shared.cmd_opts.hide_ui_dir_config, '--hide-ui-dir-config option must be disabled'
|
| 31 |
+
assert input_dir, 'input directory not selected'
|
| 32 |
+
|
| 33 |
+
image_list = shared.listfiles(input_dir)
|
| 34 |
+
for filename in image_list:
|
| 35 |
+
yield filename, filename
|
| 36 |
+
else:
|
| 37 |
+
assert image, 'image not selected'
|
| 38 |
+
yield image, None
|
| 39 |
+
|
| 40 |
+
if extras_mode == 2 and output_dir != '':
|
| 41 |
+
outpath = output_dir
|
| 42 |
+
else:
|
| 43 |
+
outpath = opts.outdir_samples or opts.outdir_extras_samples
|
| 44 |
+
|
| 45 |
+
infotext = ''
|
| 46 |
+
|
| 47 |
+
data_to_process = list(get_images(extras_mode, image, image_folder, input_dir))
|
| 48 |
+
shared.state.job_count = len(data_to_process)
|
| 49 |
+
|
| 50 |
+
for image_placeholder, name in data_to_process:
|
| 51 |
+
image_data: Image.Image
|
| 52 |
+
|
| 53 |
+
shared.state.nextjob()
|
| 54 |
+
shared.state.textinfo = name
|
| 55 |
+
shared.state.skipped = False
|
| 56 |
+
|
| 57 |
+
if shared.state.interrupted or shared.state.stopping_generation:
|
| 58 |
+
break
|
| 59 |
+
|
| 60 |
+
if isinstance(image_placeholder, str):
|
| 61 |
+
try:
|
| 62 |
+
image_data = images.read(image_placeholder)
|
| 63 |
+
except Exception:
|
| 64 |
+
continue
|
| 65 |
+
else:
|
| 66 |
+
image_data = image_placeholder
|
| 67 |
+
|
| 68 |
+
image_data = image_data if image_data.mode in ("RGBA", "RGB") else image_data.convert("RGB")
|
| 69 |
+
|
| 70 |
+
parameters, existing_pnginfo = images.read_info_from_image(image_data)
|
| 71 |
+
if parameters:
|
| 72 |
+
existing_pnginfo["parameters"] = parameters
|
| 73 |
+
|
| 74 |
+
initial_pp = scripts_postprocessing.PostprocessedImage(image_data)
|
| 75 |
+
|
| 76 |
+
scripts.scripts_postproc.run(initial_pp, args)
|
| 77 |
+
|
| 78 |
+
if shared.state.skipped:
|
| 79 |
+
continue
|
| 80 |
+
|
| 81 |
+
used_suffixes = {}
|
| 82 |
+
for pp in [initial_pp, *initial_pp.extra_images]:
|
| 83 |
+
suffix = pp.get_suffix(used_suffixes)
|
| 84 |
+
|
| 85 |
+
if opts.use_original_name_batch and name is not None:
|
| 86 |
+
basename = os.path.splitext(os.path.basename(name))[0]
|
| 87 |
+
forced_filename = basename + suffix
|
| 88 |
+
else:
|
| 89 |
+
basename = ''
|
| 90 |
+
forced_filename = None
|
| 91 |
+
|
| 92 |
+
infotext = ", ".join([k if k == v else f'{k}: {infotext_utils.quote(v)}' for k, v in pp.info.items() if v is not None])
|
| 93 |
+
|
| 94 |
+
if opts.enable_pnginfo:
|
| 95 |
+
pp.image.info = existing_pnginfo
|
| 96 |
+
|
| 97 |
+
shared.state.assign_current_image(pp.image)
|
| 98 |
+
|
| 99 |
+
if save_output:
|
| 100 |
+
fullfn, _ = images.save_image(pp.image, path=outpath, basename=basename, extension=opts.samples_format, info=infotext, short_filename=True, no_prompt=True, grid=False, pnginfo_section_name="postprocessing", existing_info=existing_pnginfo, forced_filename=forced_filename, suffix=suffix)
|
| 101 |
+
|
| 102 |
+
if extras_mode != 2 or show_extras_results:
|
| 103 |
+
outputs.append(pp.image)
|
| 104 |
+
|
| 105 |
+
devices.torch_gc()
|
| 106 |
+
shared.state.end()
|
| 107 |
+
return outputs, ui_common.plaintext_to_html(infotext), ''
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def run_postprocessing_webui(id_task, *args, **kwargs):
|
| 111 |
+
return run_postprocessing(*args, **kwargs)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def run_extras(extras_mode, resize_mode, image, image_folder, input_dir, output_dir, show_extras_results, gfpgan_visibility, codeformer_visibility, codeformer_weight, upscaling_resize, upscaling_resize_w, upscaling_resize_h, upscaling_crop, extras_upscaler_1, extras_upscaler_2, extras_upscaler_2_visibility, upscale_first: bool, save_output: bool = True, max_side_length: int = 0):
|
| 115 |
+
"""old handler for API"""
|
| 116 |
+
|
| 117 |
+
args = scripts.scripts_postproc.create_args_for_run({
|
| 118 |
+
"Upscale": {
|
| 119 |
+
"upscale_enabled": True,
|
| 120 |
+
"upscale_mode": resize_mode,
|
| 121 |
+
"upscale_by": upscaling_resize,
|
| 122 |
+
"max_side_length": max_side_length,
|
| 123 |
+
"upscale_to_width": upscaling_resize_w,
|
| 124 |
+
"upscale_to_height": upscaling_resize_h,
|
| 125 |
+
"upscale_crop": upscaling_crop,
|
| 126 |
+
"upscaler_1_name": extras_upscaler_1,
|
| 127 |
+
"upscaler_2_name": extras_upscaler_2,
|
| 128 |
+
"upscaler_2_visibility": extras_upscaler_2_visibility,
|
| 129 |
+
},
|
| 130 |
+
"GFPGAN": {
|
| 131 |
+
"enable": True,
|
| 132 |
+
"gfpgan_visibility": gfpgan_visibility,
|
| 133 |
+
},
|
| 134 |
+
"CodeFormer": {
|
| 135 |
+
"enable": True,
|
| 136 |
+
"codeformer_visibility": codeformer_visibility,
|
| 137 |
+
"codeformer_weight": codeformer_weight,
|
| 138 |
+
},
|
| 139 |
+
})
|
| 140 |
+
|
| 141 |
+
return run_postprocessing(extras_mode, image, image_folder, input_dir, output_dir, show_extras_results, *args, save_output=save_output)
|
modules/processing.py
ADDED
|
@@ -0,0 +1,1900 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
import math
|
| 7 |
+
import os
|
| 8 |
+
import random
|
| 9 |
+
import sys
|
| 10 |
+
from dataclasses import dataclass, field
|
| 11 |
+
from typing import Any
|
| 12 |
+
|
| 13 |
+
import cv2
|
| 14 |
+
import numpy as np
|
| 15 |
+
import torch
|
| 16 |
+
from einops import repeat
|
| 17 |
+
from PIL import Image, ImageOps
|
| 18 |
+
from skimage.exposure import match_histograms
|
| 19 |
+
|
| 20 |
+
import modules.face_restoration
|
| 21 |
+
import modules.paths as paths
|
| 22 |
+
import modules.sd_models as sd_models
|
| 23 |
+
import modules.sd_vae as sd_vae
|
| 24 |
+
import modules.shared as shared
|
| 25 |
+
from backend import memory_management
|
| 26 |
+
from backend.modules.k_prediction import rescale_zero_terminal_snr_sigmas
|
| 27 |
+
from backend.utils import hash_tensor
|
| 28 |
+
from modules import devices, errors, extra_networks, images, infotext_utils, masking, profiling, prompt_parser, rng, scripts, sd_samplers, sd_samplers_common, sd_unet, sd_vae_approx
|
| 29 |
+
from modules.rng import get_noise_source_type, slerp # noqa: F401
|
| 30 |
+
from modules.sd_models import apply_token_merging, forge_model_reload
|
| 31 |
+
from modules.sd_samplers_common import approximation_indexes, decode_first_stage, images_tensor_to_samples
|
| 32 |
+
from modules.shared import cmd_opts, opts, state
|
| 33 |
+
from modules.sysinfo import set_config
|
| 34 |
+
from modules_forge import main_entry
|
| 35 |
+
from modules_forge.utils import apply_circular_forge
|
| 36 |
+
|
| 37 |
+
# some of those options should not be changed at all because they would break the model, so I removed them from options.
|
| 38 |
+
opt_C = 4
|
| 39 |
+
opt_f = 8
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def setup_color_correction(image: Image.Image) -> np.ndarray:
|
| 43 |
+
correction_target = cv2.cvtColor(np.asarray(image.copy(), dtype=np.uint8), cv2.COLOR_RGB2LAB)
|
| 44 |
+
return correction_target
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def apply_color_correction(correction_target: np.ndarray, original_image: Image.Image):
|
| 48 |
+
image = cv2.cvtColor(
|
| 49 |
+
match_histograms(
|
| 50 |
+
cv2.cvtColor(np.asarray(original_image, dtype=np.uint8), cv2.COLOR_RGB2LAB),
|
| 51 |
+
correction_target,
|
| 52 |
+
channel_axis=2,
|
| 53 |
+
),
|
| 54 |
+
cv2.COLOR_Lab2RGB,
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
return Image.fromarray(image.astype("uint8")).convert("RGB")
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def uncrop(image, dest_size, paste_loc):
|
| 61 |
+
x, y, w, h = paste_loc
|
| 62 |
+
base_image = Image.new("RGBA", dest_size)
|
| 63 |
+
image = images.resize_image(1, image, w, h)
|
| 64 |
+
base_image.paste(image, (x, y))
|
| 65 |
+
image = base_image
|
| 66 |
+
|
| 67 |
+
return image
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def apply_overlay(image, paste_loc, overlay):
|
| 71 |
+
if overlay is None:
|
| 72 |
+
return image, image.copy()
|
| 73 |
+
|
| 74 |
+
if paste_loc is not None:
|
| 75 |
+
image = uncrop(image, (overlay.width, overlay.height), paste_loc)
|
| 76 |
+
|
| 77 |
+
original_denoised_image = image.copy()
|
| 78 |
+
|
| 79 |
+
image = image.convert("RGBA")
|
| 80 |
+
image.alpha_composite(overlay)
|
| 81 |
+
image = image.convert("RGB")
|
| 82 |
+
|
| 83 |
+
return image, original_denoised_image
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def create_binary_mask(image, round=True):
|
| 87 |
+
if image.mode == "RGBA" and image.getextrema()[-1] != (255, 255):
|
| 88 |
+
if round:
|
| 89 |
+
image = image.split()[-1].convert("L").point(lambda x: 255 if x > 128 else 0)
|
| 90 |
+
else:
|
| 91 |
+
image = image.split()[-1].convert("L")
|
| 92 |
+
else:
|
| 93 |
+
image = image.convert("L")
|
| 94 |
+
return image
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def txt2img_image_conditioning(sd_model, x, width, height):
|
| 98 |
+
if sd_model.is_inpaint: # Inpainting models
|
| 99 |
+
|
| 100 |
+
# The "masked-image" in this case will just be all 0.5 since the entire image is masked.
|
| 101 |
+
image_conditioning = torch.ones(x.shape[0], 3, height, width, device=x.device) * 0.5
|
| 102 |
+
image_conditioning = images_tensor_to_samples(image_conditioning, approximation_indexes.get(opts.sd_vae_encode_method))
|
| 103 |
+
|
| 104 |
+
# Add the fake full 1s mask to the first dimension.
|
| 105 |
+
image_conditioning = torch.nn.functional.pad(image_conditioning, (0, 0, 0, 0, 1, 0), value=1.0)
|
| 106 |
+
image_conditioning = image_conditioning.to(x.dtype)
|
| 107 |
+
|
| 108 |
+
return image_conditioning
|
| 109 |
+
else:
|
| 110 |
+
# Dummy zero conditioning if we're not using inpainting or unclip models.
|
| 111 |
+
# Still takes up a bit of memory, but no encoder call.
|
| 112 |
+
# Pretty sure we can just make this a 1x1 image since its not going to be used besides its batch size.
|
| 113 |
+
return x.new_zeros(x.shape[0], 5, 1, 1, dtype=x.dtype, device=x.device)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
@dataclass(repr=False)
|
| 117 |
+
class StableDiffusionProcessing:
|
| 118 |
+
sd_model: object = None
|
| 119 |
+
outpath_samples: str = None
|
| 120 |
+
outpath_grids: str = None
|
| 121 |
+
prompt: str = ""
|
| 122 |
+
prompt_for_display: str = None
|
| 123 |
+
negative_prompt: str = ""
|
| 124 |
+
styles: list[str] = None
|
| 125 |
+
seed: int = -1
|
| 126 |
+
subseed: int = -1
|
| 127 |
+
subseed_strength: float = 0
|
| 128 |
+
seed_resize_from_h: int = -1
|
| 129 |
+
seed_resize_from_w: int = -1
|
| 130 |
+
seed_enable_extras: bool = True
|
| 131 |
+
sampler_name: str = None
|
| 132 |
+
scheduler: str = None
|
| 133 |
+
batch_size: int = 1
|
| 134 |
+
n_iter: int = 1
|
| 135 |
+
steps: int = 50
|
| 136 |
+
cfg_scale: float = 7.0
|
| 137 |
+
distilled_cfg_scale: float = 3.5
|
| 138 |
+
width: int = 512
|
| 139 |
+
height: int = 512
|
| 140 |
+
restore_faces: bool = None
|
| 141 |
+
tiling: bool = None
|
| 142 |
+
do_not_save_samples: bool = False
|
| 143 |
+
do_not_save_grid: bool = False
|
| 144 |
+
extra_generation_params: dict[str, Any] = None
|
| 145 |
+
overlay_images: list = None
|
| 146 |
+
eta: float = None
|
| 147 |
+
do_not_reload_embeddings: bool = False
|
| 148 |
+
denoising_strength: float = None
|
| 149 |
+
ddim_discretize: str = None
|
| 150 |
+
s_min_uncond: float = None
|
| 151 |
+
s_churn: float = None
|
| 152 |
+
s_tmax: float = None
|
| 153 |
+
s_tmin: float = None
|
| 154 |
+
s_noise: float = None
|
| 155 |
+
override_settings: dict[str, Any] = None
|
| 156 |
+
override_settings_restore_afterwards: bool = True
|
| 157 |
+
sampler_index: int = None
|
| 158 |
+
refiner_checkpoint: str = None
|
| 159 |
+
refiner_switch_at: float = None
|
| 160 |
+
token_merging_ratio = 0
|
| 161 |
+
token_merging_ratio_hr = 0
|
| 162 |
+
disable_extra_networks: bool = False
|
| 163 |
+
firstpass_image: Image = None
|
| 164 |
+
|
| 165 |
+
scripts_value: scripts.ScriptRunner = field(default=None, init=False)
|
| 166 |
+
script_args_value: list = field(default=None, init=False)
|
| 167 |
+
scripts_setup_complete: bool = field(default=False, init=False)
|
| 168 |
+
|
| 169 |
+
cached_uc = [None, None, None]
|
| 170 |
+
cached_c = [None, None, None]
|
| 171 |
+
|
| 172 |
+
comments: dict = None
|
| 173 |
+
sampler: sd_samplers_common.Sampler | None = field(default=None, init=False)
|
| 174 |
+
is_using_inpainting_conditioning: bool = field(default=False, init=False)
|
| 175 |
+
paste_to: tuple | None = field(default=None, init=False)
|
| 176 |
+
|
| 177 |
+
is_hr_pass: bool = field(default=False, init=False)
|
| 178 |
+
|
| 179 |
+
c: tuple = field(default=None, init=False)
|
| 180 |
+
uc: tuple = field(default=None, init=False)
|
| 181 |
+
|
| 182 |
+
rng: rng.ImageRNG | None = field(default=None, init=False)
|
| 183 |
+
step_multiplier: int = field(default=1, init=False)
|
| 184 |
+
color_corrections: list = field(default=None, init=False)
|
| 185 |
+
|
| 186 |
+
all_prompts: list = field(default=None, init=False)
|
| 187 |
+
all_negative_prompts: list = field(default=None, init=False)
|
| 188 |
+
all_seeds: list = field(default=None, init=False)
|
| 189 |
+
all_subseeds: list = field(default=None, init=False)
|
| 190 |
+
iteration: int = field(default=0, init=False)
|
| 191 |
+
main_prompt: str = field(default=None, init=False)
|
| 192 |
+
main_negative_prompt: str = field(default=None, init=False)
|
| 193 |
+
|
| 194 |
+
prompts: list = field(default=None, init=False)
|
| 195 |
+
negative_prompts: list = field(default=None, init=False)
|
| 196 |
+
seeds: list = field(default=None, init=False)
|
| 197 |
+
subseeds: list = field(default=None, init=False)
|
| 198 |
+
extra_network_data: dict = field(default=None, init=False)
|
| 199 |
+
|
| 200 |
+
user: str = field(default=None, init=False)
|
| 201 |
+
|
| 202 |
+
sd_model_name: str = field(default=None, init=False)
|
| 203 |
+
sd_model_hash: str = field(default=None, init=False)
|
| 204 |
+
sd_vae_name: str = field(default=None, init=False)
|
| 205 |
+
sd_vae_hash: str = field(default=None, init=False)
|
| 206 |
+
|
| 207 |
+
is_api: bool = field(default=False, init=False)
|
| 208 |
+
|
| 209 |
+
latents_after_sampling = []
|
| 210 |
+
pixels_after_sampling = []
|
| 211 |
+
|
| 212 |
+
def clear_prompt_cache(self):
|
| 213 |
+
self.cached_c = [None, None, None]
|
| 214 |
+
self.cached_uc = [None, None, None]
|
| 215 |
+
StableDiffusionProcessing.cached_c = [None, None, None]
|
| 216 |
+
StableDiffusionProcessing.cached_uc = [None, None, None]
|
| 217 |
+
|
| 218 |
+
def __post_init__(self):
|
| 219 |
+
if self.sampler_index is not None:
|
| 220 |
+
print("sampler_index argument for StableDiffusionProcessing does not do anything; use sampler_name", file=sys.stderr)
|
| 221 |
+
|
| 222 |
+
self.comments = {}
|
| 223 |
+
|
| 224 |
+
if self.styles is None:
|
| 225 |
+
self.styles = []
|
| 226 |
+
|
| 227 |
+
self.sampler_noise_scheduler_override = None
|
| 228 |
+
|
| 229 |
+
self.extra_generation_params = self.extra_generation_params or {}
|
| 230 |
+
self.override_settings = self.override_settings or {}
|
| 231 |
+
self.script_args = self.script_args or {}
|
| 232 |
+
|
| 233 |
+
self.refiner_checkpoint_info = None
|
| 234 |
+
|
| 235 |
+
if not self.seed_enable_extras:
|
| 236 |
+
self.subseed = -1
|
| 237 |
+
self.subseed_strength = 0
|
| 238 |
+
self.seed_resize_from_h = 0
|
| 239 |
+
self.seed_resize_from_w = 0
|
| 240 |
+
|
| 241 |
+
self.cached_uc = StableDiffusionProcessing.cached_uc
|
| 242 |
+
self.cached_c = StableDiffusionProcessing.cached_c
|
| 243 |
+
|
| 244 |
+
self.extra_result_images = []
|
| 245 |
+
self.latents_after_sampling = []
|
| 246 |
+
self.pixels_after_sampling = []
|
| 247 |
+
self.modified_noise = None
|
| 248 |
+
|
| 249 |
+
def fill_fields_from_opts(self):
|
| 250 |
+
self.s_min_uncond = self.s_min_uncond if self.s_min_uncond is not None else opts.s_min_uncond
|
| 251 |
+
self.s_churn = self.s_churn if self.s_churn is not None else opts.s_churn
|
| 252 |
+
self.s_tmin = self.s_tmin if self.s_tmin is not None else opts.s_tmin
|
| 253 |
+
self.s_tmax = (self.s_tmax if self.s_tmax is not None else opts.s_tmax) or float("inf")
|
| 254 |
+
self.s_noise = self.s_noise if self.s_noise is not None else opts.s_noise
|
| 255 |
+
|
| 256 |
+
@property
|
| 257 |
+
def sd_model(self):
|
| 258 |
+
return shared.sd_model
|
| 259 |
+
|
| 260 |
+
@sd_model.setter
|
| 261 |
+
def sd_model(self, value):
|
| 262 |
+
pass
|
| 263 |
+
|
| 264 |
+
@property
|
| 265 |
+
def scripts(self):
|
| 266 |
+
return self.scripts_value
|
| 267 |
+
|
| 268 |
+
@scripts.setter
|
| 269 |
+
def scripts(self, value):
|
| 270 |
+
self.scripts_value = value
|
| 271 |
+
|
| 272 |
+
if self.scripts_value and self.script_args_value and not self.scripts_setup_complete:
|
| 273 |
+
self.setup_scripts()
|
| 274 |
+
|
| 275 |
+
@property
|
| 276 |
+
def script_args(self):
|
| 277 |
+
return self.script_args_value
|
| 278 |
+
|
| 279 |
+
@script_args.setter
|
| 280 |
+
def script_args(self, value):
|
| 281 |
+
self.script_args_value = value
|
| 282 |
+
|
| 283 |
+
if self.scripts_value and self.script_args_value and not self.scripts_setup_complete:
|
| 284 |
+
self.setup_scripts()
|
| 285 |
+
|
| 286 |
+
def setup_scripts(self):
|
| 287 |
+
self.scripts_setup_complete = True
|
| 288 |
+
|
| 289 |
+
self.scripts.setup_scrips(self, is_ui=not self.is_api)
|
| 290 |
+
|
| 291 |
+
def comment(self, text):
|
| 292 |
+
self.comments[text] = 1
|
| 293 |
+
|
| 294 |
+
def txt2img_image_conditioning(self, x, width=None, height=None):
|
| 295 |
+
self.is_using_inpainting_conditioning = self.sd_model.is_inpaint
|
| 296 |
+
|
| 297 |
+
return txt2img_image_conditioning(self.sd_model, x, width or self.width, height or self.height)
|
| 298 |
+
|
| 299 |
+
def depth2img_image_conditioning(self, source_image):
|
| 300 |
+
raise NotImplementedError("NotImplementedError: depth2img_image_conditioning")
|
| 301 |
+
|
| 302 |
+
def edit_image_conditioning(self, source_image):
|
| 303 |
+
conditioning_image = shared.sd_model.encode_first_stage(source_image).mode()
|
| 304 |
+
|
| 305 |
+
return conditioning_image
|
| 306 |
+
|
| 307 |
+
def unclip_image_conditioning(self, source_image):
|
| 308 |
+
c_adm = self.sd_model.embedder(source_image)
|
| 309 |
+
if self.sd_model.noise_augmentor is not None:
|
| 310 |
+
noise_level = 0 # TODO: Allow other noise levels?
|
| 311 |
+
c_adm, noise_level_emb = self.sd_model.noise_augmentor(c_adm, noise_level=repeat(torch.tensor([noise_level]).to(c_adm.device), "1 -> b", b=c_adm.shape[0]))
|
| 312 |
+
c_adm = torch.cat((c_adm, noise_level_emb), 1)
|
| 313 |
+
return c_adm
|
| 314 |
+
|
| 315 |
+
def inpainting_image_conditioning(self, source_image, latent_image, image_mask=None, round_image_mask=True):
|
| 316 |
+
self.is_using_inpainting_conditioning = True
|
| 317 |
+
|
| 318 |
+
# Handle the different mask inputs
|
| 319 |
+
if image_mask is not None:
|
| 320 |
+
if torch.is_tensor(image_mask):
|
| 321 |
+
conditioning_mask = image_mask
|
| 322 |
+
else:
|
| 323 |
+
conditioning_mask = np.array(image_mask.convert("L"))
|
| 324 |
+
conditioning_mask = conditioning_mask.astype(np.float32) / 255.0
|
| 325 |
+
conditioning_mask = torch.from_numpy(conditioning_mask[None, None])
|
| 326 |
+
|
| 327 |
+
if round_image_mask:
|
| 328 |
+
# Caller is requesting a discretized mask as input, so we round to either 1.0 or 0.0
|
| 329 |
+
conditioning_mask = torch.round(conditioning_mask)
|
| 330 |
+
|
| 331 |
+
else:
|
| 332 |
+
conditioning_mask = source_image.new_ones(1, 1, *source_image.shape[-2:])
|
| 333 |
+
|
| 334 |
+
# Create another latent image, this time with a masked version of the original input.
|
| 335 |
+
# Smoothly interpolate between the masked and unmasked latent conditioning image using a parameter.
|
| 336 |
+
conditioning_mask = conditioning_mask.to(device=source_image.device, dtype=source_image.dtype)
|
| 337 |
+
conditioning_image = torch.lerp(source_image, source_image * (1.0 - conditioning_mask), getattr(self, "inpainting_mask_weight", shared.opts.inpainting_mask_weight))
|
| 338 |
+
|
| 339 |
+
# Encode the new masked image using first stage of network.
|
| 340 |
+
conditioning_image = self.sd_model.get_first_stage_encoding(self.sd_model.encode_first_stage(conditioning_image))
|
| 341 |
+
|
| 342 |
+
# Create the concatenated conditioning tensor to be fed to `c_concat`
|
| 343 |
+
conditioning_mask = torch.nn.functional.interpolate(conditioning_mask, size=latent_image.shape[-2:])
|
| 344 |
+
conditioning_mask = conditioning_mask.expand(conditioning_image.shape[0], -1, -1, -1)
|
| 345 |
+
image_conditioning = torch.cat([conditioning_mask, conditioning_image], dim=1)
|
| 346 |
+
# image_conditioning = image_conditioning.to(shared.device).type(self.sd_model.dtype)
|
| 347 |
+
|
| 348 |
+
return image_conditioning
|
| 349 |
+
|
| 350 |
+
def img2img_image_conditioning(self, source_image, latent_image, image_mask=None, round_image_mask=True):
|
| 351 |
+
source_image = devices.cond_cast_float(source_image)
|
| 352 |
+
|
| 353 |
+
# if self.sd_model.cond_stage_key == "edit":
|
| 354 |
+
# return self.edit_image_conditioning(source_image)
|
| 355 |
+
|
| 356 |
+
if self.sd_model.is_inpaint:
|
| 357 |
+
return self.inpainting_image_conditioning(source_image, latent_image, image_mask=image_mask, round_image_mask=round_image_mask)
|
| 358 |
+
|
| 359 |
+
# if self.sampler.conditioning_key == "crossattn-adm":
|
| 360 |
+
# return self.unclip_image_conditioning(source_image)
|
| 361 |
+
#
|
| 362 |
+
# if self.sampler.model_wrap.inner_model.is_sdxl_inpaint:
|
| 363 |
+
# return self.inpainting_image_conditioning(source_image, latent_image, image_mask=image_mask)
|
| 364 |
+
|
| 365 |
+
# Dummy zero conditioning if we're not using inpainting or depth model.
|
| 366 |
+
return latent_image.new_zeros(latent_image.shape[0], 5, 1, 1)
|
| 367 |
+
|
| 368 |
+
def init(self, all_prompts, all_seeds, all_subseeds):
|
| 369 |
+
pass
|
| 370 |
+
|
| 371 |
+
def sample(self, conditioning, unconditional_conditioning, seeds, subseeds, subseed_strength, prompts):
|
| 372 |
+
raise NotImplementedError()
|
| 373 |
+
|
| 374 |
+
def close(self):
|
| 375 |
+
self.sampler = None
|
| 376 |
+
self.c = None
|
| 377 |
+
self.uc = None
|
| 378 |
+
if not opts.persistent_cond_cache:
|
| 379 |
+
StableDiffusionProcessing.cached_c = [None, None]
|
| 380 |
+
StableDiffusionProcessing.cached_uc = [None, None]
|
| 381 |
+
|
| 382 |
+
def get_token_merging_ratio(self, for_hr=False):
|
| 383 |
+
if for_hr:
|
| 384 |
+
return self.token_merging_ratio_hr or opts.token_merging_ratio_hr or self.token_merging_ratio or opts.token_merging_ratio
|
| 385 |
+
|
| 386 |
+
return self.token_merging_ratio or opts.token_merging_ratio
|
| 387 |
+
|
| 388 |
+
def setup_prompts(self):
|
| 389 |
+
if isinstance(self.prompt, list):
|
| 390 |
+
self.all_prompts = self.prompt
|
| 391 |
+
elif isinstance(self.negative_prompt, list):
|
| 392 |
+
self.all_prompts = [self.prompt] * len(self.negative_prompt)
|
| 393 |
+
else:
|
| 394 |
+
self.all_prompts = self.batch_size * self.n_iter * [self.prompt]
|
| 395 |
+
|
| 396 |
+
if isinstance(self.negative_prompt, list):
|
| 397 |
+
self.all_negative_prompts = self.negative_prompt
|
| 398 |
+
else:
|
| 399 |
+
self.all_negative_prompts = [self.negative_prompt] * len(self.all_prompts)
|
| 400 |
+
|
| 401 |
+
if len(self.all_prompts) != len(self.all_negative_prompts):
|
| 402 |
+
raise RuntimeError(f"Received a different number of prompts ({len(self.all_prompts)}) and negative prompts ({len(self.all_negative_prompts)})")
|
| 403 |
+
|
| 404 |
+
self.all_prompts = [shared.prompt_styles.apply_styles_to_prompt(x, self.styles) for x in self.all_prompts]
|
| 405 |
+
self.all_negative_prompts = [shared.prompt_styles.apply_negative_styles_to_prompt(x, self.styles) for x in self.all_negative_prompts]
|
| 406 |
+
|
| 407 |
+
self.main_prompt = self.all_prompts[0]
|
| 408 |
+
self.main_negative_prompt = self.all_negative_prompts[0]
|
| 409 |
+
|
| 410 |
+
def cached_params(self, required_prompts, steps, extra_network_data, hires_steps, use_old_scheduling):
|
| 411 |
+
"""Returns parameters that invalidate the cond cache if changed"""
|
| 412 |
+
|
| 413 |
+
return (
|
| 414 |
+
required_prompts,
|
| 415 |
+
self.distilled_cfg_scale,
|
| 416 |
+
self.hr_distilled_cfg,
|
| 417 |
+
steps,
|
| 418 |
+
hires_steps,
|
| 419 |
+
use_old_scheduling,
|
| 420 |
+
opts.CLIP_stop_at_last_layers,
|
| 421 |
+
str(sd_models.model_data.forge_loading_parameters),
|
| 422 |
+
extra_network_data,
|
| 423 |
+
opts.sdxl_crop_left,
|
| 424 |
+
opts.sdxl_crop_top,
|
| 425 |
+
self.width,
|
| 426 |
+
self.height,
|
| 427 |
+
opts.emphasis,
|
| 428 |
+
hash_tensor(self.init_latent) if isinstance(self, StableDiffusionProcessingImg2Img) else None,
|
| 429 |
+
)
|
| 430 |
+
|
| 431 |
+
def get_conds_with_caching(self, function, required_prompts, steps, caches, extra_network_data, hires_steps=None):
|
| 432 |
+
"""
|
| 433 |
+
Returns the result of calling function(shared.sd_model, required_prompts, steps)
|
| 434 |
+
using a cache to store the result if the same arguments have been used before.
|
| 435 |
+
|
| 436 |
+
cache is an array containing two elements. The first element is a tuple
|
| 437 |
+
representing the previously used arguments, or None if no arguments
|
| 438 |
+
have been used before. The second element is where the previously
|
| 439 |
+
computed result is stored.
|
| 440 |
+
|
| 441 |
+
caches is a list with items described above.
|
| 442 |
+
"""
|
| 443 |
+
|
| 444 |
+
if shared.opts.use_old_scheduling:
|
| 445 |
+
old_schedules = prompt_parser.get_learned_conditioning_prompt_schedules(required_prompts, steps, hires_steps, False)
|
| 446 |
+
new_schedules = prompt_parser.get_learned_conditioning_prompt_schedules(required_prompts, steps, hires_steps, True)
|
| 447 |
+
if old_schedules != new_schedules:
|
| 448 |
+
self.extra_generation_params["Old prompt editing timelines"] = True
|
| 449 |
+
|
| 450 |
+
cached_params = self.cached_params(required_prompts, steps, extra_network_data, hires_steps, shared.opts.use_old_scheduling)
|
| 451 |
+
|
| 452 |
+
for cache in caches:
|
| 453 |
+
if cache[0] is not None and cached_params == cache[0]:
|
| 454 |
+
if len(cache) > 2:
|
| 455 |
+
shared.sd_model.extra_generation_params.update(cache[2])
|
| 456 |
+
return cache[1]
|
| 457 |
+
|
| 458 |
+
cache = caches[0]
|
| 459 |
+
|
| 460 |
+
with devices.autocast():
|
| 461 |
+
shared.sd_model.set_clip_skip(int(opts.CLIP_stop_at_last_layers))
|
| 462 |
+
|
| 463 |
+
cache[1] = function(shared.sd_model, required_prompts, steps, hires_steps, shared.opts.use_old_scheduling)
|
| 464 |
+
|
| 465 |
+
import backend.text_processing.classic_engine
|
| 466 |
+
|
| 467 |
+
last_extra_generation_params = backend.text_processing.classic_engine.last_extra_generation_params.copy()
|
| 468 |
+
|
| 469 |
+
shared.sd_model.extra_generation_params.update(last_extra_generation_params)
|
| 470 |
+
|
| 471 |
+
if len(cache) > 2:
|
| 472 |
+
cache[2] = last_extra_generation_params
|
| 473 |
+
|
| 474 |
+
backend.text_processing.classic_engine.last_extra_generation_params = {}
|
| 475 |
+
|
| 476 |
+
cache[0] = cached_params
|
| 477 |
+
return cache[1]
|
| 478 |
+
|
| 479 |
+
def setup_conds(self):
|
| 480 |
+
prompts = prompt_parser.SdConditioning(self.prompts, width=self.width, height=self.height, distilled_cfg_scale=self.distilled_cfg_scale)
|
| 481 |
+
negative_prompts = prompt_parser.SdConditioning(self.negative_prompts, width=self.width, height=self.height, is_negative_prompt=True, distilled_cfg_scale=self.distilled_cfg_scale)
|
| 482 |
+
|
| 483 |
+
sampler_config = sd_samplers.find_sampler_config(self.sampler_name)
|
| 484 |
+
total_steps = sampler_config.total_steps(self.steps) if sampler_config else self.steps
|
| 485 |
+
self.step_multiplier = total_steps // self.steps
|
| 486 |
+
self.firstpass_steps = total_steps
|
| 487 |
+
|
| 488 |
+
if self.cfg_scale == 1:
|
| 489 |
+
self.uc = None
|
| 490 |
+
print("Skipping unconditional conditioning when CFG = 1. Negative Prompts are ignored.")
|
| 491 |
+
else:
|
| 492 |
+
self.uc = self.get_conds_with_caching(prompt_parser.get_learned_conditioning, negative_prompts, total_steps, [self.cached_uc], self.extra_network_data)
|
| 493 |
+
|
| 494 |
+
self.c = self.get_conds_with_caching(prompt_parser.get_multicond_learned_conditioning, prompts, total_steps, [self.cached_c], self.extra_network_data)
|
| 495 |
+
|
| 496 |
+
def get_conds(self):
|
| 497 |
+
return self.c, self.uc
|
| 498 |
+
|
| 499 |
+
def parse_extra_network_prompts(self):
|
| 500 |
+
self.prompts, self.extra_network_data = extra_networks.parse_prompts(self.prompts)
|
| 501 |
+
|
| 502 |
+
def save_samples(self, *, is_video: bool = False) -> bool:
|
| 503 |
+
"""Returns whether generated images need to be written to disk"""
|
| 504 |
+
return opts.samples_save and (not self.do_not_save_samples) and (opts.save_incomplete_images or not state.interrupted and not state.skipped) and not (is_video and not opts.video_save_frames)
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
class Processed:
|
| 508 |
+
def __init__(self, p: StableDiffusionProcessing, images_list, seed=-1, info="", subseed=None, all_prompts=None, all_negative_prompts=None, all_seeds=None, all_subseeds=None, index_of_first_image=0, infotexts=None, comments="", extra_images_list=[]):
|
| 509 |
+
self.images = images_list
|
| 510 |
+
self.extra_images = extra_images_list
|
| 511 |
+
self.prompt = p.prompt
|
| 512 |
+
self.negative_prompt = p.negative_prompt
|
| 513 |
+
self.seed = seed
|
| 514 |
+
self.subseed = subseed
|
| 515 |
+
self.subseed_strength = p.subseed_strength
|
| 516 |
+
self.info = info
|
| 517 |
+
self.comments = "".join(f"{comment}\n" for comment in p.comments)
|
| 518 |
+
self.width = p.width
|
| 519 |
+
self.height = p.height
|
| 520 |
+
self.sampler_name = p.sampler_name
|
| 521 |
+
self.cfg_scale = p.cfg_scale
|
| 522 |
+
self.image_cfg_scale = getattr(p, "image_cfg_scale", None)
|
| 523 |
+
self.steps = p.steps
|
| 524 |
+
self.batch_size = p.batch_size
|
| 525 |
+
self.restore_faces = p.restore_faces
|
| 526 |
+
self.face_restoration_model = opts.face_restoration_model if p.restore_faces else None
|
| 527 |
+
self.sd_model_name = p.sd_model_name
|
| 528 |
+
self.sd_model_hash = p.sd_model_hash
|
| 529 |
+
self.sd_vae_name = p.sd_vae_name
|
| 530 |
+
self.sd_vae_hash = p.sd_vae_hash
|
| 531 |
+
self.seed_resize_from_w = p.seed_resize_from_w
|
| 532 |
+
self.seed_resize_from_h = p.seed_resize_from_h
|
| 533 |
+
self.denoising_strength = getattr(p, "denoising_strength", None)
|
| 534 |
+
self.extra_generation_params = p.extra_generation_params
|
| 535 |
+
self.index_of_first_image = index_of_first_image
|
| 536 |
+
self.styles = p.styles
|
| 537 |
+
self.job_timestamp = state.job_timestamp
|
| 538 |
+
self.clip_skip = int(opts.CLIP_stop_at_last_layers)
|
| 539 |
+
self.token_merging_ratio = p.token_merging_ratio
|
| 540 |
+
self.token_merging_ratio_hr = p.token_merging_ratio_hr
|
| 541 |
+
|
| 542 |
+
self.eta = p.eta
|
| 543 |
+
self.ddim_discretize = p.ddim_discretize
|
| 544 |
+
self.s_churn = p.s_churn
|
| 545 |
+
self.s_tmin = p.s_tmin
|
| 546 |
+
self.s_tmax = p.s_tmax
|
| 547 |
+
self.s_noise = p.s_noise
|
| 548 |
+
self.s_min_uncond = p.s_min_uncond
|
| 549 |
+
self.sampler_noise_scheduler_override = p.sampler_noise_scheduler_override
|
| 550 |
+
self.prompt = self.prompt if not isinstance(self.prompt, list) else self.prompt[0]
|
| 551 |
+
self.negative_prompt = self.negative_prompt if not isinstance(self.negative_prompt, list) else self.negative_prompt[0]
|
| 552 |
+
self.seed = int(self.seed if not isinstance(self.seed, list) else self.seed[0]) if self.seed is not None else -1
|
| 553 |
+
self.subseed = int(self.subseed if not isinstance(self.subseed, list) else self.subseed[0]) if self.subseed is not None else -1
|
| 554 |
+
self.is_using_inpainting_conditioning = p.is_using_inpainting_conditioning
|
| 555 |
+
|
| 556 |
+
self.all_prompts = all_prompts or p.all_prompts or [self.prompt]
|
| 557 |
+
self.all_negative_prompts = all_negative_prompts or p.all_negative_prompts or [self.negative_prompt]
|
| 558 |
+
self.all_seeds = all_seeds or p.all_seeds or [self.seed]
|
| 559 |
+
self.all_subseeds = all_subseeds or p.all_subseeds or [self.subseed]
|
| 560 |
+
self.infotexts = infotexts or [info] * len(images_list)
|
| 561 |
+
self.version = program_version()
|
| 562 |
+
|
| 563 |
+
self.video_path = None
|
| 564 |
+
|
| 565 |
+
def js(self):
|
| 566 |
+
obj = {
|
| 567 |
+
"prompt": self.all_prompts[0],
|
| 568 |
+
"all_prompts": self.all_prompts,
|
| 569 |
+
"negative_prompt": self.all_negative_prompts[0],
|
| 570 |
+
"all_negative_prompts": self.all_negative_prompts,
|
| 571 |
+
"seed": self.seed,
|
| 572 |
+
"all_seeds": self.all_seeds,
|
| 573 |
+
"subseed": self.subseed,
|
| 574 |
+
"all_subseeds": self.all_subseeds,
|
| 575 |
+
"subseed_strength": self.subseed_strength,
|
| 576 |
+
"width": self.width,
|
| 577 |
+
"height": self.height,
|
| 578 |
+
"sampler_name": self.sampler_name,
|
| 579 |
+
"cfg_scale": self.cfg_scale,
|
| 580 |
+
"steps": self.steps,
|
| 581 |
+
"batch_size": self.batch_size,
|
| 582 |
+
"restore_faces": self.restore_faces,
|
| 583 |
+
"face_restoration_model": self.face_restoration_model,
|
| 584 |
+
"sd_model_name": self.sd_model_name,
|
| 585 |
+
"sd_model_hash": self.sd_model_hash,
|
| 586 |
+
"sd_vae_name": self.sd_vae_name,
|
| 587 |
+
"sd_vae_hash": self.sd_vae_hash,
|
| 588 |
+
"seed_resize_from_w": self.seed_resize_from_w,
|
| 589 |
+
"seed_resize_from_h": self.seed_resize_from_h,
|
| 590 |
+
"denoising_strength": self.denoising_strength,
|
| 591 |
+
"extra_generation_params": self.extra_generation_params,
|
| 592 |
+
"index_of_first_image": self.index_of_first_image,
|
| 593 |
+
"infotexts": self.infotexts,
|
| 594 |
+
"styles": self.styles,
|
| 595 |
+
"job_timestamp": self.job_timestamp,
|
| 596 |
+
"clip_skip": self.clip_skip,
|
| 597 |
+
"is_using_inpainting_conditioning": self.is_using_inpainting_conditioning,
|
| 598 |
+
"version": self.version,
|
| 599 |
+
}
|
| 600 |
+
|
| 601 |
+
return json.dumps(obj, default=lambda o: None)
|
| 602 |
+
|
| 603 |
+
def infotext(self, p: StableDiffusionProcessing, index):
|
| 604 |
+
return create_infotext(p, self.all_prompts, self.all_seeds, self.all_subseeds, comments=[], position_in_batch=index % self.batch_size, iteration=index // self.batch_size)
|
| 605 |
+
|
| 606 |
+
def get_token_merging_ratio(self, for_hr=False):
|
| 607 |
+
return self.token_merging_ratio_hr if for_hr else self.token_merging_ratio
|
| 608 |
+
|
| 609 |
+
|
| 610 |
+
def create_random_tensors(shape, seeds, subseeds=None, subseed_strength=0.0, seed_resize_from_h=0, seed_resize_from_w=0, p=None):
|
| 611 |
+
g = rng.ImageRNG(shape, seeds, subseeds=subseeds, subseed_strength=subseed_strength, seed_resize_from_h=seed_resize_from_h, seed_resize_from_w=seed_resize_from_w)
|
| 612 |
+
return g.next()
|
| 613 |
+
|
| 614 |
+
|
| 615 |
+
class DecodedSamples(list):
|
| 616 |
+
already_decoded = True
|
| 617 |
+
|
| 618 |
+
|
| 619 |
+
def decode_latent_batch(model, batch, target_device=None, check_for_nans=False):
|
| 620 |
+
samples = DecodedSamples()
|
| 621 |
+
samples_pytorch = decode_first_stage(model, batch).to(target_device)
|
| 622 |
+
|
| 623 |
+
for x in samples_pytorch:
|
| 624 |
+
samples.append(x)
|
| 625 |
+
|
| 626 |
+
return samples
|
| 627 |
+
|
| 628 |
+
|
| 629 |
+
def get_fixed_seed(seed):
|
| 630 |
+
if seed == "" or seed is None:
|
| 631 |
+
seed = -1
|
| 632 |
+
elif isinstance(seed, str):
|
| 633 |
+
try:
|
| 634 |
+
seed = int(seed)
|
| 635 |
+
except Exception:
|
| 636 |
+
seed = -1
|
| 637 |
+
|
| 638 |
+
if seed == -1:
|
| 639 |
+
return int(random.randrange(4294967294))
|
| 640 |
+
|
| 641 |
+
return seed
|
| 642 |
+
|
| 643 |
+
|
| 644 |
+
def fix_seed(p):
|
| 645 |
+
p.seed = get_fixed_seed(p.seed)
|
| 646 |
+
p.subseed = get_fixed_seed(p.subseed)
|
| 647 |
+
|
| 648 |
+
|
| 649 |
+
def program_version():
|
| 650 |
+
import launch
|
| 651 |
+
|
| 652 |
+
res = launch.git_tag()
|
| 653 |
+
if res == "<none>":
|
| 654 |
+
res = None
|
| 655 |
+
|
| 656 |
+
return res
|
| 657 |
+
|
| 658 |
+
|
| 659 |
+
def create_infotext(p, all_prompts, all_seeds, all_subseeds, comments=None, iteration=0, position_in_batch=0, use_main_prompt=False, index=None, all_negative_prompts=None):
|
| 660 |
+
"""
|
| 661 |
+
this function is used to generate the infotext that is stored in the generated images, it's contains the parameters that are required to generate the imagee
|
| 662 |
+
Args:
|
| 663 |
+
p: StableDiffusionProcessing
|
| 664 |
+
all_prompts: list[str]
|
| 665 |
+
all_seeds: list[int]
|
| 666 |
+
all_subseeds: list[int]
|
| 667 |
+
comments: list[str]
|
| 668 |
+
iteration: int
|
| 669 |
+
position_in_batch: int
|
| 670 |
+
use_main_prompt: bool
|
| 671 |
+
index: int
|
| 672 |
+
all_negative_prompts: list[str]
|
| 673 |
+
|
| 674 |
+
Returns: str
|
| 675 |
+
|
| 676 |
+
Extra generation params
|
| 677 |
+
p.extra_generation_params dictionary allows for additional parameters to be added to the infotext
|
| 678 |
+
this can be use by the base webui or extensions.
|
| 679 |
+
To add a new entry, add a new key value pair, the dictionary key will be used as the key of the parameter in the infotext
|
| 680 |
+
the value generation_params can be defined as:
|
| 681 |
+
- str | None
|
| 682 |
+
- List[str|None]
|
| 683 |
+
- callable func(**kwargs) -> str | None
|
| 684 |
+
|
| 685 |
+
When defined as a string, it will be used as without extra processing; this is this most common use case.
|
| 686 |
+
|
| 687 |
+
Defining as a list allows for parameter that changes across images in the job, for example, the 'Seed' parameter.
|
| 688 |
+
The list should have the same length as the total number of images in the entire job.
|
| 689 |
+
|
| 690 |
+
Defining as a callable function allows parameter cannot be generated earlier or when extra logic is required.
|
| 691 |
+
For example 'Hires prompt', due to reasons the hr_prompt might be changed by process in the pipeline or extensions
|
| 692 |
+
and may vary across different images, defining as a static string or list would not work.
|
| 693 |
+
|
| 694 |
+
The function takes locals() as **kwargs, as such will have access to variables like 'p' and 'index'.
|
| 695 |
+
the base signature of the function should be:
|
| 696 |
+
func(**kwargs) -> str | None
|
| 697 |
+
optionally it can have additional arguments that will be used in the function:
|
| 698 |
+
func(p, index, **kwargs) -> str | None
|
| 699 |
+
note: for better future compatibility even though this function will have access to all variables in the locals(),
|
| 700 |
+
it is recommended to only use the arguments present in the function signature of create_infotext.
|
| 701 |
+
For actual implementation examples, see StableDiffusionProcessingTxt2Img.init > get_hr_prompt.
|
| 702 |
+
"""
|
| 703 |
+
|
| 704 |
+
if use_main_prompt:
|
| 705 |
+
index = 0
|
| 706 |
+
elif index is None:
|
| 707 |
+
index = position_in_batch + iteration * p.batch_size
|
| 708 |
+
|
| 709 |
+
if all_negative_prompts is None:
|
| 710 |
+
all_negative_prompts = p.all_negative_prompts
|
| 711 |
+
|
| 712 |
+
clip_skip = int(getattr(p, "clip_skip", opts.CLIP_stop_at_last_layers))
|
| 713 |
+
enable_hr = getattr(p, "enable_hr", False)
|
| 714 |
+
token_merging_ratio = p.get_token_merging_ratio()
|
| 715 |
+
token_merging_ratio_hr = p.get_token_merging_ratio(for_hr=True)
|
| 716 |
+
|
| 717 |
+
prompt_text = p.main_prompt if use_main_prompt else all_prompts[index]
|
| 718 |
+
negative_prompt = p.main_negative_prompt if use_main_prompt else all_negative_prompts[index]
|
| 719 |
+
|
| 720 |
+
uses_ensd = opts.eta_noise_seed_delta != 0
|
| 721 |
+
if uses_ensd:
|
| 722 |
+
uses_ensd = sd_samplers_common.is_sampler_using_eta_noise_seed_delta(p)
|
| 723 |
+
|
| 724 |
+
generation_params = {
|
| 725 |
+
"Steps": p.steps,
|
| 726 |
+
"Sampler": p.sampler_name,
|
| 727 |
+
"Schedule type": p.scheduler,
|
| 728 |
+
"CFG scale": p.cfg_scale,
|
| 729 |
+
}
|
| 730 |
+
|
| 731 |
+
if p.sd_model.use_distilled_cfg_scale:
|
| 732 |
+
generation_params["Distilled CFG Scale"] = p.distilled_cfg_scale
|
| 733 |
+
if p.sd_model.use_shift:
|
| 734 |
+
generation_params["Shift"] = p.distilled_cfg_scale
|
| 735 |
+
|
| 736 |
+
noise_source_type = get_noise_source_type()
|
| 737 |
+
|
| 738 |
+
generation_params.update(
|
| 739 |
+
{
|
| 740 |
+
"Image CFG scale": getattr(p, "image_cfg_scale", None),
|
| 741 |
+
"Seed": p.all_seeds[0] if use_main_prompt else all_seeds[index],
|
| 742 |
+
"Face restoration": opts.face_restoration_model if p.restore_faces else None,
|
| 743 |
+
"Size": f"{p.width}x{p.height}",
|
| 744 |
+
"Model hash": p.sd_model_hash if opts.add_model_hash_to_info else None,
|
| 745 |
+
"Model": p.sd_model_name if opts.add_model_name_to_info else None,
|
| 746 |
+
# "VAE hash": p.sd_vae_hash if opts.add_vae_hash_to_info else None,
|
| 747 |
+
# "VAE": p.sd_vae_name if opts.add_vae_name_to_info else None,
|
| 748 |
+
"Variation seed": (None if p.subseed_strength == 0 else (p.all_subseeds[0] if use_main_prompt else all_subseeds[index])),
|
| 749 |
+
"Variation seed strength": (None if p.subseed_strength == 0 else p.subseed_strength),
|
| 750 |
+
"Seed resize from": (None if p.seed_resize_from_w <= 0 or p.seed_resize_from_h <= 0 else f"{p.seed_resize_from_w}x{p.seed_resize_from_h}"),
|
| 751 |
+
"Denoising strength": p.extra_generation_params.get("Denoising strength"),
|
| 752 |
+
"Conditional mask weight": getattr(p, "inpainting_mask_weight", shared.opts.inpainting_mask_weight) if p.is_using_inpainting_conditioning else None,
|
| 753 |
+
"Clip skip": None if clip_skip <= 1 else clip_skip,
|
| 754 |
+
"ENSD": opts.eta_noise_seed_delta if uses_ensd else None,
|
| 755 |
+
"eps_scaling_factor": opts.scaling_factor if opts.scaling_factor > 1.0 else None,
|
| 756 |
+
"Token merging ratio": None if token_merging_ratio == 0 else token_merging_ratio,
|
| 757 |
+
"Token merging ratio hr": None if not enable_hr or token_merging_ratio_hr == 0 else token_merging_ratio_hr,
|
| 758 |
+
"Init image hash": getattr(p, "init_img_hash", None),
|
| 759 |
+
"RNG": noise_source_type if noise_source_type != "GPU" else None,
|
| 760 |
+
"Tiling": "True" if p.tiling else None,
|
| 761 |
+
**p.extra_generation_params,
|
| 762 |
+
"Version": program_version() if opts.add_version_to_infotext else None,
|
| 763 |
+
"User": p.user if opts.add_user_name_to_info else None,
|
| 764 |
+
}
|
| 765 |
+
)
|
| 766 |
+
|
| 767 |
+
if shared.opts.forge_unet_storage_dtype != "Automatic":
|
| 768 |
+
generation_params["Diffusion in Low Bits"] = shared.opts.forge_unet_storage_dtype
|
| 769 |
+
|
| 770 |
+
if isinstance(shared.opts.forge_additional_modules, list) and len(shared.opts.forge_additional_modules) > 0:
|
| 771 |
+
for i, m in enumerate(shared.opts.forge_additional_modules):
|
| 772 |
+
generation_params[f"Module {i+1}"] = os.path.splitext(os.path.basename(m))[0]
|
| 773 |
+
|
| 774 |
+
for key, value in generation_params.items():
|
| 775 |
+
try:
|
| 776 |
+
if isinstance(value, list):
|
| 777 |
+
generation_params[key] = value[index]
|
| 778 |
+
elif callable(value):
|
| 779 |
+
generation_params[key] = value(**locals())
|
| 780 |
+
except Exception:
|
| 781 |
+
errors.report(f'Error creating infotext for key "{key}"', exc_info=True)
|
| 782 |
+
generation_params[key] = None
|
| 783 |
+
|
| 784 |
+
generation_params_text = ", ".join([k if k == v else f"{k}: {infotext_utils.quote(v)}" for k, v in generation_params.items() if v is not None])
|
| 785 |
+
|
| 786 |
+
negative_prompt_text = f"\nNegative prompt: {negative_prompt}" if negative_prompt else ""
|
| 787 |
+
|
| 788 |
+
return f"{prompt_text}{negative_prompt_text}\n{generation_params_text}".strip()
|
| 789 |
+
|
| 790 |
+
|
| 791 |
+
need_global_unload = False
|
| 792 |
+
|
| 793 |
+
|
| 794 |
+
def manage_model_and_prompt_cache(p: StableDiffusionProcessing):
|
| 795 |
+
global need_global_unload
|
| 796 |
+
|
| 797 |
+
p.sd_model, just_reloaded = forge_model_reload()
|
| 798 |
+
|
| 799 |
+
if need_global_unload and not just_reloaded:
|
| 800 |
+
memory_management.unload_all_models()
|
| 801 |
+
|
| 802 |
+
# if need_global_unload:
|
| 803 |
+
# p.clear_prompt_cache()
|
| 804 |
+
|
| 805 |
+
need_global_unload = False
|
| 806 |
+
|
| 807 |
+
|
| 808 |
+
def process_images(p: StableDiffusionProcessing) -> Processed:
|
| 809 |
+
"""applies settings overrides (if any) before processing images, then restores settings as applicable."""
|
| 810 |
+
if p.scripts is not None:
|
| 811 |
+
p.scripts.before_process(p)
|
| 812 |
+
|
| 813 |
+
stored_opts = {k: opts.data[k] if k in opts.data else opts.get_default(k) for k in p.override_settings.keys() if k in opts.data}
|
| 814 |
+
|
| 815 |
+
try:
|
| 816 |
+
# if no checkpoint override or the override checkpoint can't be found, remove override entry and load opts checkpoint
|
| 817 |
+
# and if after running refiner, the refiner model is not unloaded - webui swaps back to main model here, if model over is present it will be reloaded afterwards
|
| 818 |
+
if sd_models.checkpoint_aliases.get(p.override_settings.get("sd_model_checkpoint")) is None:
|
| 819 |
+
p.override_settings.pop("sd_model_checkpoint", None)
|
| 820 |
+
|
| 821 |
+
# apply any options overrides
|
| 822 |
+
set_config(p.override_settings, is_api=True, run_callbacks=False, save_config=False)
|
| 823 |
+
|
| 824 |
+
# load/reload model and manage prompt cache as needed
|
| 825 |
+
if getattr(p, "txt2img_upscale", False):
|
| 826 |
+
# avoid model load from hiresfix quickbutton, as it could be redundant
|
| 827 |
+
pass
|
| 828 |
+
else:
|
| 829 |
+
manage_model_and_prompt_cache(p)
|
| 830 |
+
|
| 831 |
+
# backwards compatibility, fix sampler and scheduler if invalid
|
| 832 |
+
sd_samplers.fix_p_invalid_sampler_and_scheduler(p)
|
| 833 |
+
|
| 834 |
+
with profiling.Profiler():
|
| 835 |
+
res = process_images_inner(p)
|
| 836 |
+
|
| 837 |
+
finally:
|
| 838 |
+
# restore original options
|
| 839 |
+
if p.override_settings_restore_afterwards:
|
| 840 |
+
set_config(stored_opts, save_config=False)
|
| 841 |
+
|
| 842 |
+
return res
|
| 843 |
+
|
| 844 |
+
|
| 845 |
+
def process_images_inner(p: StableDiffusionProcessing) -> Processed:
|
| 846 |
+
"""this is the main loop that both txt2img and img2img use; it calls func_init once inside all the scopes and func_sample once per batch"""
|
| 847 |
+
|
| 848 |
+
_is_video = False
|
| 849 |
+
video_path = None
|
| 850 |
+
if shared.sd_model.is_wan:
|
| 851 |
+
_times = ((getattr(p, "batch_size", 1) - 1) // 4) + 1 # https://github.com/comfyanonymous/ComfyUI/blob/v0.3.64/comfy_extras/nodes_wan.py#L41
|
| 852 |
+
p.batch_size = (_times - 1) * 4 + 1
|
| 853 |
+
_is_video: bool = _times > 1
|
| 854 |
+
if _is_video:
|
| 855 |
+
p.do_not_save_grid = True
|
| 856 |
+
|
| 857 |
+
if isinstance(p.prompt, list):
|
| 858 |
+
assert len(p.prompt) > 0
|
| 859 |
+
else:
|
| 860 |
+
assert p.prompt is not None
|
| 861 |
+
|
| 862 |
+
devices.torch_gc()
|
| 863 |
+
|
| 864 |
+
seed = get_fixed_seed(p.seed)
|
| 865 |
+
subseed = get_fixed_seed(p.subseed)
|
| 866 |
+
|
| 867 |
+
if p.restore_faces is None:
|
| 868 |
+
p.restore_faces = opts.face_restoration
|
| 869 |
+
|
| 870 |
+
if p.tiling is None:
|
| 871 |
+
p.tiling = opts.tiling
|
| 872 |
+
|
| 873 |
+
if p.refiner_checkpoint not in (None, "", "None", "none"):
|
| 874 |
+
p.refiner_checkpoint_info = sd_models.get_closet_checkpoint_match(p.refiner_checkpoint)
|
| 875 |
+
if p.refiner_checkpoint_info is None:
|
| 876 |
+
raise Exception(f"Could not find checkpoint with name {p.refiner_checkpoint}")
|
| 877 |
+
|
| 878 |
+
if hasattr(shared.sd_model, "fix_dimensions"):
|
| 879 |
+
p.width, p.height = shared.sd_model.fix_dimensions(p.width, p.height)
|
| 880 |
+
|
| 881 |
+
p.sd_model_name = shared.sd_model.sd_checkpoint_info.name_for_extra
|
| 882 |
+
p.sd_model_hash = shared.sd_model.sd_model_hash
|
| 883 |
+
p.sd_vae_name = sd_vae.get_loaded_vae_name()
|
| 884 |
+
p.sd_vae_hash = sd_vae.get_loaded_vae_hash()
|
| 885 |
+
|
| 886 |
+
apply_circular_forge(p.sd_model, p.tiling)
|
| 887 |
+
p.sd_model.comments = []
|
| 888 |
+
p.sd_model.extra_generation_params = {}
|
| 889 |
+
|
| 890 |
+
p.fill_fields_from_opts()
|
| 891 |
+
p.setup_prompts()
|
| 892 |
+
|
| 893 |
+
if isinstance(seed, list):
|
| 894 |
+
p.all_seeds = seed
|
| 895 |
+
else:
|
| 896 |
+
p.all_seeds = [int(seed) + (x if p.subseed_strength == 0 else 0) for x in range(len(p.all_prompts))]
|
| 897 |
+
|
| 898 |
+
if isinstance(subseed, list):
|
| 899 |
+
p.all_subseeds = subseed
|
| 900 |
+
else:
|
| 901 |
+
p.all_subseeds = [int(subseed) + x for x in range(len(p.all_prompts))]
|
| 902 |
+
|
| 903 |
+
if os.path.exists(cmd_opts.embeddings_dir) and not p.do_not_reload_embeddings:
|
| 904 |
+
# todo: reload ti
|
| 905 |
+
# model_hijack.embedding_db.load_textual_inversion_embeddings()
|
| 906 |
+
pass
|
| 907 |
+
|
| 908 |
+
if p.scripts is not None:
|
| 909 |
+
p.scripts.process(p)
|
| 910 |
+
|
| 911 |
+
infotexts = []
|
| 912 |
+
output_images = []
|
| 913 |
+
with torch.inference_mode():
|
| 914 |
+
with devices.autocast():
|
| 915 |
+
p.init(p.all_prompts, p.all_seeds, p.all_subseeds)
|
| 916 |
+
|
| 917 |
+
# for OSX, loading the model during sampling changes the generated picture, so it is loaded here
|
| 918 |
+
if shared.opts.live_previews_enable and opts.show_progress_type == "Approx NN":
|
| 919 |
+
sd_vae_approx.model()
|
| 920 |
+
|
| 921 |
+
sd_unet.apply_unet()
|
| 922 |
+
|
| 923 |
+
if state.job_count == -1:
|
| 924 |
+
state.job_count = p.n_iter
|
| 925 |
+
|
| 926 |
+
for n in range(p.n_iter):
|
| 927 |
+
p.iteration = n
|
| 928 |
+
|
| 929 |
+
if state.skipped:
|
| 930 |
+
state.skipped = False
|
| 931 |
+
|
| 932 |
+
if state.interrupted or state.stopping_generation:
|
| 933 |
+
break
|
| 934 |
+
|
| 935 |
+
if not getattr(p, "txt2img_upscale", False) or p.hr_checkpoint_name is None:
|
| 936 |
+
# hiresfix quickbutton may not need reload of firstpass model
|
| 937 |
+
sd_models.forge_model_reload() # model can be changed for example by refiner, hiresfix
|
| 938 |
+
|
| 939 |
+
p.sd_model.forge_objects = p.sd_model.forge_objects_original.shallow_copy()
|
| 940 |
+
p.prompts = p.all_prompts[n * p.batch_size : (n + 1) * p.batch_size]
|
| 941 |
+
p.negative_prompts = p.all_negative_prompts[n * p.batch_size : (n + 1) * p.batch_size]
|
| 942 |
+
p.seeds = p.all_seeds[n * p.batch_size : (n + 1) * p.batch_size]
|
| 943 |
+
p.subseeds = p.all_subseeds[n * p.batch_size : (n + 1) * p.batch_size]
|
| 944 |
+
|
| 945 |
+
latent_channels = shared.sd_model.forge_objects.vae.latent_channels
|
| 946 |
+
_shape = (latent_channels, _times, p.height // opt_f, p.width // opt_f) if shared.sd_model.is_wan else (latent_channels, p.height // opt_f, p.width // opt_f)
|
| 947 |
+
p.rng = rng.ImageRNG(_shape, p.seeds, subseeds=p.subseeds, subseed_strength=p.subseed_strength, seed_resize_from_h=p.seed_resize_from_h, seed_resize_from_w=p.seed_resize_from_w)
|
| 948 |
+
|
| 949 |
+
if p.scripts is not None:
|
| 950 |
+
p.scripts.before_process_batch(p, batch_number=n, prompts=p.prompts, seeds=p.seeds, subseeds=p.subseeds)
|
| 951 |
+
|
| 952 |
+
if len(p.prompts) == 0:
|
| 953 |
+
break
|
| 954 |
+
|
| 955 |
+
p.parse_extra_network_prompts()
|
| 956 |
+
|
| 957 |
+
if not p.disable_extra_networks:
|
| 958 |
+
extra_networks.activate(p, p.extra_network_data)
|
| 959 |
+
|
| 960 |
+
p.sd_model.forge_objects = p.sd_model.forge_objects_after_applying_lora.shallow_copy()
|
| 961 |
+
|
| 962 |
+
if p.scripts is not None:
|
| 963 |
+
p.scripts.process_batch(p, batch_number=n, prompts=p.prompts, seeds=p.seeds, subseeds=p.subseeds)
|
| 964 |
+
|
| 965 |
+
p.setup_conds()
|
| 966 |
+
|
| 967 |
+
p.extra_generation_params.update(p.sd_model.extra_generation_params)
|
| 968 |
+
|
| 969 |
+
# params.txt should be saved after scripts.process_batch, since the
|
| 970 |
+
# infotext could be modified by that callback
|
| 971 |
+
# Example: a wildcard processed by process_batch sets an extra model
|
| 972 |
+
# strength, which is saved as "Model Strength: 1.0" in the infotext
|
| 973 |
+
if n == 0 and not cmd_opts.no_prompt_history:
|
| 974 |
+
with open(os.path.join(paths.data_path, "params.txt"), "w", encoding="utf8") as file:
|
| 975 |
+
processed = Processed(p, [])
|
| 976 |
+
file.write(processed.infotext(p, 0))
|
| 977 |
+
|
| 978 |
+
for comment in p.sd_model.comments:
|
| 979 |
+
p.comment(comment)
|
| 980 |
+
|
| 981 |
+
if p.n_iter > 1:
|
| 982 |
+
shared.state.job = f"Batch {n+1} out of {p.n_iter}"
|
| 983 |
+
|
| 984 |
+
sigmas_backup = None
|
| 985 |
+
if (opts.sd_noise_schedule == "Zero Terminal SNR" or getattr(p.sd_model.model_config, "ztsnr", False)) and p is not None:
|
| 986 |
+
p.extra_generation_params["Noise Schedule"] = "Zero Terminal SNR"
|
| 987 |
+
sigmas_backup = p.sd_model.forge_objects.unet.model.predictor.sigmas
|
| 988 |
+
p.sd_model.forge_objects.unet.model.predictor.set_sigmas(rescale_zero_terminal_snr_sigmas(p.sd_model.forge_objects.unet.model.predictor.sigmas))
|
| 989 |
+
|
| 990 |
+
samples_ddim = p.sample(conditioning=p.c, unconditional_conditioning=p.uc, seeds=p.seeds, subseeds=p.subseeds, subseed_strength=p.subseed_strength, prompts=p.prompts)
|
| 991 |
+
|
| 992 |
+
for x_sample in samples_ddim:
|
| 993 |
+
p.latents_after_sampling.append(x_sample)
|
| 994 |
+
|
| 995 |
+
if sigmas_backup is not None:
|
| 996 |
+
p.sd_model.forge_objects.unet.model.predictor.set_sigmas(sigmas_backup)
|
| 997 |
+
|
| 998 |
+
if p.scripts is not None:
|
| 999 |
+
ps = scripts.PostSampleArgs(samples_ddim)
|
| 1000 |
+
p.scripts.post_sample(p, ps)
|
| 1001 |
+
samples_ddim = ps.samples
|
| 1002 |
+
|
| 1003 |
+
if getattr(samples_ddim, "already_decoded", False):
|
| 1004 |
+
x_samples_ddim = samples_ddim
|
| 1005 |
+
else:
|
| 1006 |
+
devices.test_for_nans(samples_ddim, "unet")
|
| 1007 |
+
|
| 1008 |
+
if opts.sd_vae_decode_method != "Full":
|
| 1009 |
+
p.extra_generation_params["VAE Decoder"] = opts.sd_vae_decode_method
|
| 1010 |
+
x_samples_ddim = decode_latent_batch(p.sd_model, samples_ddim, target_device=devices.cpu, check_for_nans=True)
|
| 1011 |
+
|
| 1012 |
+
x_samples_ddim = torch.stack(x_samples_ddim).float()
|
| 1013 |
+
x_samples_ddim = torch.clamp((x_samples_ddim + 1.0) / 2.0, min=0.0, max=1.0)
|
| 1014 |
+
|
| 1015 |
+
if len(x_samples_ddim.shape) == 5:
|
| 1016 |
+
x_samples_ddim = x_samples_ddim.reshape(-1, *x_samples_ddim.shape[-3:])
|
| 1017 |
+
|
| 1018 |
+
del samples_ddim
|
| 1019 |
+
|
| 1020 |
+
devices.torch_gc()
|
| 1021 |
+
|
| 1022 |
+
state.nextjob()
|
| 1023 |
+
|
| 1024 |
+
if p.scripts is not None:
|
| 1025 |
+
p.scripts.postprocess_batch(p, x_samples_ddim, batch_number=n)
|
| 1026 |
+
|
| 1027 |
+
p.prompts = p.all_prompts[n * p.batch_size : (n + 1) * p.batch_size]
|
| 1028 |
+
p.negative_prompts = p.all_negative_prompts[n * p.batch_size : (n + 1) * p.batch_size]
|
| 1029 |
+
|
| 1030 |
+
batch_params = scripts.PostprocessBatchListArgs(list(x_samples_ddim))
|
| 1031 |
+
p.scripts.postprocess_batch_list(p, batch_params, batch_number=n)
|
| 1032 |
+
x_samples_ddim = batch_params.images
|
| 1033 |
+
|
| 1034 |
+
def infotext(index=0, use_main_prompt=False):
|
| 1035 |
+
if opts.save_prompt_comments and hasattr(p, "_all_prompts_c") and hasattr(p, "_all_negative_prompts_c"):
|
| 1036 |
+
_prompts = p._all_prompts_c[n * p.batch_size : (n + 1) * p.batch_size]
|
| 1037 |
+
_negative_prompts = p._all_negative_prompts_c[n * p.batch_size : (n + 1) * p.batch_size]
|
| 1038 |
+
return create_infotext(p, _prompts, p.seeds, p.subseeds, use_main_prompt=False, index=index, all_negative_prompts=_negative_prompts)
|
| 1039 |
+
|
| 1040 |
+
return create_infotext(p, p.prompts, p.seeds, p.subseeds, use_main_prompt=use_main_prompt, index=index, all_negative_prompts=p.negative_prompts)
|
| 1041 |
+
|
| 1042 |
+
save_samples = p.save_samples(is_video=_is_video)
|
| 1043 |
+
if _is_video:
|
| 1044 |
+
frames = []
|
| 1045 |
+
|
| 1046 |
+
for i, x_sample in enumerate(x_samples_ddim):
|
| 1047 |
+
p.batch_index = i
|
| 1048 |
+
x_sample = 255.0 * np.moveaxis(x_sample.cpu().numpy(), 0, 2)
|
| 1049 |
+
x_sample = x_sample.astype(np.uint8)
|
| 1050 |
+
if _is_video:
|
| 1051 |
+
frames.append(x_sample)
|
| 1052 |
+
|
| 1053 |
+
if p.restore_faces:
|
| 1054 |
+
if save_samples and opts.save_images_before_face_restoration:
|
| 1055 |
+
images.save_image(Image.fromarray(x_sample), p.outpath_samples, "", p.seeds[i], p.prompts[i], opts.samples_format, info=infotext(i), p=p, suffix="-before-face-restoration")
|
| 1056 |
+
|
| 1057 |
+
devices.torch_gc()
|
| 1058 |
+
|
| 1059 |
+
x_sample = modules.face_restoration.restore_faces(x_sample)
|
| 1060 |
+
devices.torch_gc()
|
| 1061 |
+
|
| 1062 |
+
image = Image.fromarray(x_sample)
|
| 1063 |
+
|
| 1064 |
+
if p.scripts is not None:
|
| 1065 |
+
pp = scripts.PostprocessImageArgs(image, i + p.iteration * p.batch_size)
|
| 1066 |
+
p.scripts.postprocess_image(p, pp)
|
| 1067 |
+
image = pp.image
|
| 1068 |
+
|
| 1069 |
+
mask_for_overlay = getattr(p, "mask_for_overlay", None)
|
| 1070 |
+
|
| 1071 |
+
if not shared.opts.overlay_inpaint:
|
| 1072 |
+
overlay_image = None
|
| 1073 |
+
elif getattr(p, "overlay_images", None) is not None and i < len(p.overlay_images):
|
| 1074 |
+
overlay_image = p.overlay_images[i]
|
| 1075 |
+
else:
|
| 1076 |
+
overlay_image = None
|
| 1077 |
+
|
| 1078 |
+
if p.scripts is not None:
|
| 1079 |
+
ppmo = scripts.PostProcessMaskOverlayArgs(i, mask_for_overlay, overlay_image)
|
| 1080 |
+
p.scripts.postprocess_maskoverlay(p, ppmo)
|
| 1081 |
+
mask_for_overlay, overlay_image = ppmo.mask_for_overlay, ppmo.overlay_image
|
| 1082 |
+
|
| 1083 |
+
if p.color_corrections is not None and i < len(p.color_corrections):
|
| 1084 |
+
if save_samples and opts.save_images_before_color_correction:
|
| 1085 |
+
image_without_cc, _ = apply_overlay(image, p.paste_to, overlay_image)
|
| 1086 |
+
images.save_image(image_without_cc, p.outpath_samples, "", p.seeds[i], p.prompts[i], opts.samples_format, info=infotext(i), p=p, suffix="-before-color-correction")
|
| 1087 |
+
image = apply_color_correction(p.color_corrections[i], image)
|
| 1088 |
+
|
| 1089 |
+
# If the intention is to show the output from the model
|
| 1090 |
+
# that is being composited over the original image,
|
| 1091 |
+
# we need to keep the original image around
|
| 1092 |
+
# and use it in the composite step.
|
| 1093 |
+
image, original_denoised_image = apply_overlay(image, p.paste_to, overlay_image)
|
| 1094 |
+
|
| 1095 |
+
p.pixels_after_sampling.append(image)
|
| 1096 |
+
|
| 1097 |
+
if p.scripts is not None:
|
| 1098 |
+
pp = scripts.PostprocessImageArgs(image, i + p.iteration * p.batch_size)
|
| 1099 |
+
p.scripts.postprocess_image_after_composite(p, pp)
|
| 1100 |
+
image = pp.image
|
| 1101 |
+
|
| 1102 |
+
if save_samples:
|
| 1103 |
+
images.save_image(image, p.outpath_samples, "", p.seeds[i], p.prompts[i], opts.samples_format, info=infotext(i), p=p)
|
| 1104 |
+
|
| 1105 |
+
text = infotext(i)
|
| 1106 |
+
infotexts.append(text)
|
| 1107 |
+
if opts.enable_pnginfo:
|
| 1108 |
+
image.info["parameters"] = text
|
| 1109 |
+
output_images.append(image)
|
| 1110 |
+
|
| 1111 |
+
if mask_for_overlay is not None:
|
| 1112 |
+
if opts.return_mask or opts.save_mask:
|
| 1113 |
+
image_mask = mask_for_overlay.convert("RGB")
|
| 1114 |
+
if save_samples and opts.save_mask:
|
| 1115 |
+
images.save_image(image_mask, p.outpath_samples, "", p.seeds[i], p.prompts[i], opts.samples_format, info=infotext(i), p=p, suffix="-mask")
|
| 1116 |
+
if opts.return_mask:
|
| 1117 |
+
output_images.append(image_mask)
|
| 1118 |
+
|
| 1119 |
+
if opts.return_mask_composite or opts.save_mask_composite:
|
| 1120 |
+
image_mask_composite = Image.composite(original_denoised_image.convert("RGBA").convert("RGBa"), Image.new("RGBa", image.size), images.resize_image(2, mask_for_overlay, image.width, image.height).convert("L")).convert("RGBA")
|
| 1121 |
+
if save_samples and opts.save_mask_composite:
|
| 1122 |
+
images.save_image(image_mask_composite, p.outpath_samples, "", p.seeds[i], p.prompts[i], opts.samples_format, info=infotext(i), p=p, suffix="-mask-composite")
|
| 1123 |
+
if opts.return_mask_composite:
|
| 1124 |
+
output_images.append(image_mask_composite)
|
| 1125 |
+
|
| 1126 |
+
if _is_video:
|
| 1127 |
+
video_path = images.save_video(p, frames)
|
| 1128 |
+
del frames
|
| 1129 |
+
|
| 1130 |
+
del x_samples_ddim
|
| 1131 |
+
|
| 1132 |
+
devices.torch_gc()
|
| 1133 |
+
|
| 1134 |
+
if not infotexts:
|
| 1135 |
+
infotexts.append(Processed(p, []).infotext(p, 0))
|
| 1136 |
+
|
| 1137 |
+
p.color_corrections = None
|
| 1138 |
+
|
| 1139 |
+
index_of_first_image = 0
|
| 1140 |
+
unwanted_grid_because_of_img_count = len(output_images) < 2 and opts.grid_only_if_multiple
|
| 1141 |
+
if (opts.return_grid or opts.grid_save) and not p.do_not_save_grid and not unwanted_grid_because_of_img_count:
|
| 1142 |
+
grid = images.image_grid(output_images, p.batch_size)
|
| 1143 |
+
|
| 1144 |
+
if opts.return_grid:
|
| 1145 |
+
text = infotext(use_main_prompt=True)
|
| 1146 |
+
infotexts.insert(0, text)
|
| 1147 |
+
if opts.enable_pnginfo:
|
| 1148 |
+
grid.info["parameters"] = text
|
| 1149 |
+
output_images.insert(0, grid)
|
| 1150 |
+
index_of_first_image = 1
|
| 1151 |
+
if opts.grid_save:
|
| 1152 |
+
images.save_image(grid, p.outpath_grids, "grid", p.all_seeds[0], p.all_prompts[0], opts.grid_format, info=infotext(use_main_prompt=True), short_filename=not opts.grid_extended_filename, p=p, grid=True)
|
| 1153 |
+
|
| 1154 |
+
if not p.disable_extra_networks and p.extra_network_data:
|
| 1155 |
+
extra_networks.deactivate(p, p.extra_network_data)
|
| 1156 |
+
|
| 1157 |
+
devices.torch_gc()
|
| 1158 |
+
|
| 1159 |
+
res = Processed(
|
| 1160 |
+
p,
|
| 1161 |
+
images_list=output_images,
|
| 1162 |
+
seed=p.all_seeds[0],
|
| 1163 |
+
info=infotexts[0],
|
| 1164 |
+
subseed=p.all_subseeds[0],
|
| 1165 |
+
index_of_first_image=index_of_first_image,
|
| 1166 |
+
infotexts=infotexts,
|
| 1167 |
+
extra_images_list=p.extra_result_images,
|
| 1168 |
+
)
|
| 1169 |
+
|
| 1170 |
+
res.video_path = video_path
|
| 1171 |
+
|
| 1172 |
+
if p.scripts is not None:
|
| 1173 |
+
p.scripts.postprocess(p, res)
|
| 1174 |
+
|
| 1175 |
+
return res
|
| 1176 |
+
|
| 1177 |
+
|
| 1178 |
+
def process_extra_images(processed: Processed):
|
| 1179 |
+
"""used by API processing functions to ensure extra images are PIL image objects"""
|
| 1180 |
+
extra_images = []
|
| 1181 |
+
for img in processed.extra_images:
|
| 1182 |
+
if isinstance(img, np.ndarray):
|
| 1183 |
+
img = Image.fromarray(img)
|
| 1184 |
+
if not Image.isImageType(img):
|
| 1185 |
+
continue
|
| 1186 |
+
extra_images.append(img)
|
| 1187 |
+
processed.extra_images = extra_images
|
| 1188 |
+
|
| 1189 |
+
|
| 1190 |
+
def old_hires_fix_first_pass_dimensions(width, height):
|
| 1191 |
+
"""old algorithm for auto-calculating first pass size"""
|
| 1192 |
+
|
| 1193 |
+
desired_pixel_count = 512 * 512
|
| 1194 |
+
actual_pixel_count = width * height
|
| 1195 |
+
scale = math.sqrt(desired_pixel_count / actual_pixel_count)
|
| 1196 |
+
width = math.ceil(scale * width / 64) * 64
|
| 1197 |
+
height = math.ceil(scale * height / 64) * 64
|
| 1198 |
+
|
| 1199 |
+
return width, height
|
| 1200 |
+
|
| 1201 |
+
|
| 1202 |
+
@dataclass(repr=False)
|
| 1203 |
+
class StableDiffusionProcessingTxt2Img(StableDiffusionProcessing):
|
| 1204 |
+
enable_hr: bool = False
|
| 1205 |
+
denoising_strength: float = 0.75
|
| 1206 |
+
firstphase_width: int = 0
|
| 1207 |
+
firstphase_height: int = 0
|
| 1208 |
+
hr_scale: float = 2.0
|
| 1209 |
+
hr_upscaler: str = None
|
| 1210 |
+
hr_second_pass_steps: int = 0
|
| 1211 |
+
hr_resize_x: int = 0
|
| 1212 |
+
hr_resize_y: int = 0
|
| 1213 |
+
hr_checkpoint_name: str = None
|
| 1214 |
+
hr_additional_modules: list = field(default=None)
|
| 1215 |
+
hr_sampler_name: str = None
|
| 1216 |
+
hr_scheduler: str = None
|
| 1217 |
+
hr_prompt: str = ""
|
| 1218 |
+
hr_negative_prompt: str = ""
|
| 1219 |
+
hr_cfg: float = 1.0
|
| 1220 |
+
hr_distilled_cfg: float = 3.5
|
| 1221 |
+
force_task_id: str = None
|
| 1222 |
+
|
| 1223 |
+
cached_hr_uc = [None, None, None]
|
| 1224 |
+
cached_hr_c = [None, None, None]
|
| 1225 |
+
|
| 1226 |
+
hr_checkpoint_info: dict = field(default=None, init=False)
|
| 1227 |
+
hr_upscale_to_x: int = field(default=0, init=False)
|
| 1228 |
+
hr_upscale_to_y: int = field(default=0, init=False)
|
| 1229 |
+
truncate_x: int = field(default=0, init=False)
|
| 1230 |
+
truncate_y: int = field(default=0, init=False)
|
| 1231 |
+
applied_old_hires_behavior_to: tuple = field(default=None, init=False)
|
| 1232 |
+
latent_scale_mode: dict = field(default=None, init=False)
|
| 1233 |
+
hr_c: tuple | None = field(default=None, init=False)
|
| 1234 |
+
hr_uc: tuple | None = field(default=None, init=False)
|
| 1235 |
+
all_hr_prompts: list = field(default=None, init=False)
|
| 1236 |
+
all_hr_negative_prompts: list = field(default=None, init=False)
|
| 1237 |
+
hr_prompts: list = field(default=None, init=False)
|
| 1238 |
+
hr_negative_prompts: list = field(default=None, init=False)
|
| 1239 |
+
hr_extra_network_data: list = field(default=None, init=False)
|
| 1240 |
+
|
| 1241 |
+
def __post_init__(self):
|
| 1242 |
+
super().__post_init__()
|
| 1243 |
+
|
| 1244 |
+
if self.firstphase_width != 0 or self.firstphase_height != 0:
|
| 1245 |
+
self.hr_upscale_to_x = self.width
|
| 1246 |
+
self.hr_upscale_to_y = self.height
|
| 1247 |
+
self.width = self.firstphase_width
|
| 1248 |
+
self.height = self.firstphase_height
|
| 1249 |
+
|
| 1250 |
+
self.cached_hr_uc = StableDiffusionProcessingTxt2Img.cached_hr_uc
|
| 1251 |
+
self.cached_hr_c = StableDiffusionProcessingTxt2Img.cached_hr_c
|
| 1252 |
+
|
| 1253 |
+
def calculate_target_resolution(self):
|
| 1254 |
+
if opts.use_old_hires_fix_width_height and self.applied_old_hires_behavior_to != (self.width, self.height):
|
| 1255 |
+
self.hr_resize_x = self.width
|
| 1256 |
+
self.hr_resize_y = self.height
|
| 1257 |
+
self.hr_upscale_to_x = self.width
|
| 1258 |
+
self.hr_upscale_to_y = self.height
|
| 1259 |
+
|
| 1260 |
+
self.width, self.height = old_hires_fix_first_pass_dimensions(self.width, self.height)
|
| 1261 |
+
self.applied_old_hires_behavior_to = (self.width, self.height)
|
| 1262 |
+
|
| 1263 |
+
if self.hr_resize_x == 0 and self.hr_resize_y == 0:
|
| 1264 |
+
self.extra_generation_params["Hires upscale"] = self.hr_scale
|
| 1265 |
+
self.hr_upscale_to_x = int(self.width * self.hr_scale)
|
| 1266 |
+
self.hr_upscale_to_y = int(self.height * self.hr_scale)
|
| 1267 |
+
else:
|
| 1268 |
+
self.extra_generation_params["Hires resize"] = f"{self.hr_resize_x}x{self.hr_resize_y}"
|
| 1269 |
+
|
| 1270 |
+
if self.hr_resize_y == 0:
|
| 1271 |
+
self.hr_upscale_to_x = self.hr_resize_x
|
| 1272 |
+
self.hr_upscale_to_y = self.hr_resize_x * self.height // self.width
|
| 1273 |
+
elif self.hr_resize_x == 0:
|
| 1274 |
+
self.hr_upscale_to_x = self.hr_resize_y * self.width // self.height
|
| 1275 |
+
self.hr_upscale_to_y = self.hr_resize_y
|
| 1276 |
+
else:
|
| 1277 |
+
target_w = self.hr_resize_x
|
| 1278 |
+
target_h = self.hr_resize_y
|
| 1279 |
+
src_ratio = self.width / self.height
|
| 1280 |
+
dst_ratio = self.hr_resize_x / self.hr_resize_y
|
| 1281 |
+
|
| 1282 |
+
if src_ratio < dst_ratio:
|
| 1283 |
+
self.hr_upscale_to_x = self.hr_resize_x
|
| 1284 |
+
self.hr_upscale_to_y = self.hr_resize_x * self.height // self.width
|
| 1285 |
+
else:
|
| 1286 |
+
self.hr_upscale_to_x = self.hr_resize_y * self.width // self.height
|
| 1287 |
+
self.hr_upscale_to_y = self.hr_resize_y
|
| 1288 |
+
|
| 1289 |
+
self.truncate_x = (self.hr_upscale_to_x - target_w) // opt_f
|
| 1290 |
+
self.truncate_y = (self.hr_upscale_to_y - target_h) // opt_f
|
| 1291 |
+
|
| 1292 |
+
def init(self, all_prompts, all_seeds, all_subseeds):
|
| 1293 |
+
if self.enable_hr:
|
| 1294 |
+
self.extra_generation_params["Denoising strength"] = self.denoising_strength
|
| 1295 |
+
|
| 1296 |
+
if self.hr_checkpoint_name and self.hr_checkpoint_name != "Use same checkpoint":
|
| 1297 |
+
self.hr_checkpoint_info = sd_models.get_closet_checkpoint_match(self.hr_checkpoint_name)
|
| 1298 |
+
|
| 1299 |
+
if self.hr_checkpoint_info is None:
|
| 1300 |
+
raise Exception(f"Could not find checkpoint with name {self.hr_checkpoint_name}")
|
| 1301 |
+
|
| 1302 |
+
self.extra_generation_params["Hires checkpoint"] = self.hr_checkpoint_info.short_title
|
| 1303 |
+
|
| 1304 |
+
if isinstance(self.hr_additional_modules, list):
|
| 1305 |
+
if self.hr_additional_modules == []:
|
| 1306 |
+
self.extra_generation_params["Hires Module 1"] = "Built-in"
|
| 1307 |
+
elif "Use same choices" in self.hr_additional_modules:
|
| 1308 |
+
self.extra_generation_params["Hires Module 1"] = "Use same choices"
|
| 1309 |
+
else:
|
| 1310 |
+
for i, m in enumerate(self.hr_additional_modules):
|
| 1311 |
+
self.extra_generation_params[f"Hires Module {i+1}"] = os.path.splitext(os.path.basename(m))[0]
|
| 1312 |
+
|
| 1313 |
+
if self.hr_sampler_name is not None and self.hr_sampler_name != self.sampler_name:
|
| 1314 |
+
self.extra_generation_params["Hires sampler"] = self.hr_sampler_name
|
| 1315 |
+
|
| 1316 |
+
def get_hr_prompt(p, index, prompt_text, **kwargs):
|
| 1317 |
+
hr_prompt = p.all_hr_prompts[index]
|
| 1318 |
+
return hr_prompt if hr_prompt != prompt_text else None
|
| 1319 |
+
|
| 1320 |
+
def get_hr_negative_prompt(p, index, negative_prompt, **kwargs):
|
| 1321 |
+
hr_negative_prompt = p.all_hr_negative_prompts[index]
|
| 1322 |
+
return hr_negative_prompt if hr_negative_prompt != negative_prompt else None
|
| 1323 |
+
|
| 1324 |
+
self.extra_generation_params["Hires prompt"] = get_hr_prompt
|
| 1325 |
+
self.extra_generation_params["Hires negative prompt"] = get_hr_negative_prompt
|
| 1326 |
+
|
| 1327 |
+
self.extra_generation_params["Hires CFG Scale"] = self.hr_cfg
|
| 1328 |
+
self.extra_generation_params["Hires Distilled CFG Scale"] = None # set after potential hires model load
|
| 1329 |
+
|
| 1330 |
+
self.extra_generation_params["Hires schedule type"] = None # to be set in sd_samplers_kdiffusion.py
|
| 1331 |
+
|
| 1332 |
+
if self.hr_scheduler is None:
|
| 1333 |
+
self.hr_scheduler = self.scheduler
|
| 1334 |
+
|
| 1335 |
+
self.latent_scale_mode = shared.latent_upscale_modes.get(self.hr_upscaler, None) if self.hr_upscaler is not None else shared.latent_upscale_modes.get(shared.latent_upscale_default_mode, "nearest")
|
| 1336 |
+
if self.enable_hr and self.latent_scale_mode is None:
|
| 1337 |
+
if not any(x.name == self.hr_upscaler for x in shared.sd_upscalers):
|
| 1338 |
+
raise Exception(f"could not find upscaler named {self.hr_upscaler}")
|
| 1339 |
+
|
| 1340 |
+
self.calculate_target_resolution()
|
| 1341 |
+
|
| 1342 |
+
if not state.processing_has_refined_job_count:
|
| 1343 |
+
if state.job_count == -1:
|
| 1344 |
+
state.job_count = self.n_iter
|
| 1345 |
+
if getattr(self, "txt2img_upscale", False):
|
| 1346 |
+
total_steps = (self.hr_second_pass_steps or self.steps) * state.job_count
|
| 1347 |
+
else:
|
| 1348 |
+
total_steps = (self.steps + (self.hr_second_pass_steps or self.steps)) * state.job_count
|
| 1349 |
+
shared.total_tqdm.updateTotal(total_steps)
|
| 1350 |
+
state.job_count = state.job_count * 2
|
| 1351 |
+
state.processing_has_refined_job_count = True
|
| 1352 |
+
|
| 1353 |
+
if self.hr_second_pass_steps:
|
| 1354 |
+
self.extra_generation_params["Hires steps"] = self.hr_second_pass_steps
|
| 1355 |
+
|
| 1356 |
+
if self.hr_upscaler is not None:
|
| 1357 |
+
self.extra_generation_params["Hires upscaler"] = self.hr_upscaler
|
| 1358 |
+
|
| 1359 |
+
def sample(self, conditioning, unconditional_conditioning, seeds, subseeds, subseed_strength, prompts):
|
| 1360 |
+
self.sampler = sd_samplers.create_sampler(self.sampler_name, self.sd_model)
|
| 1361 |
+
|
| 1362 |
+
if self.firstpass_image is not None and self.enable_hr:
|
| 1363 |
+
# here we don't need to generate image, we just take self.firstpass_image and prepare it for hires fix
|
| 1364 |
+
|
| 1365 |
+
if self.latent_scale_mode is None:
|
| 1366 |
+
image = np.array(self.firstpass_image).astype(np.float32) / 255.0 * 2.0 - 1.0
|
| 1367 |
+
image = np.moveaxis(image, 2, 0)
|
| 1368 |
+
|
| 1369 |
+
samples = None
|
| 1370 |
+
decoded_samples = torch.asarray(np.expand_dims(image, 0))
|
| 1371 |
+
|
| 1372 |
+
else:
|
| 1373 |
+
image = np.array(self.firstpass_image).astype(np.float32) / 255.0
|
| 1374 |
+
image = np.moveaxis(image, 2, 0)
|
| 1375 |
+
image = torch.from_numpy(np.expand_dims(image, axis=0))
|
| 1376 |
+
image = image.to(shared.device, dtype=torch.float32)
|
| 1377 |
+
|
| 1378 |
+
if opts.sd_vae_encode_method != "Full":
|
| 1379 |
+
self.extra_generation_params["VAE Encoder"] = opts.sd_vae_encode_method
|
| 1380 |
+
|
| 1381 |
+
samples = images_tensor_to_samples(image, approximation_indexes.get(opts.sd_vae_encode_method), self.sd_model)
|
| 1382 |
+
decoded_samples = None
|
| 1383 |
+
devices.torch_gc()
|
| 1384 |
+
|
| 1385 |
+
else:
|
| 1386 |
+
# here we generate an image normally
|
| 1387 |
+
|
| 1388 |
+
x = self.rng.next()
|
| 1389 |
+
if shared.sd_model.is_wan: # enforce batch_size of 1
|
| 1390 |
+
x = x[0].unsqueeze(0)
|
| 1391 |
+
|
| 1392 |
+
self.sd_model.forge_objects = self.sd_model.forge_objects_after_applying_lora.shallow_copy()
|
| 1393 |
+
apply_token_merging(self.sd_model, self.get_token_merging_ratio())
|
| 1394 |
+
|
| 1395 |
+
if self.scripts is not None:
|
| 1396 |
+
self.scripts.process_before_every_sampling(self, x=x, noise=x, c=conditioning, uc=unconditional_conditioning)
|
| 1397 |
+
|
| 1398 |
+
if self.modified_noise is not None:
|
| 1399 |
+
x = self.modified_noise
|
| 1400 |
+
self.modified_noise = None
|
| 1401 |
+
|
| 1402 |
+
samples = self.sampler.sample(self, x, conditioning, unconditional_conditioning, image_conditioning=self.txt2img_image_conditioning(x))
|
| 1403 |
+
del x
|
| 1404 |
+
|
| 1405 |
+
if not self.enable_hr:
|
| 1406 |
+
return samples
|
| 1407 |
+
|
| 1408 |
+
devices.torch_gc()
|
| 1409 |
+
|
| 1410 |
+
if self.latent_scale_mode is None:
|
| 1411 |
+
decoded_samples = torch.stack(decode_latent_batch(self.sd_model, samples, target_device=devices.cpu, check_for_nans=True)).to(dtype=torch.float32)
|
| 1412 |
+
else:
|
| 1413 |
+
decoded_samples = None
|
| 1414 |
+
|
| 1415 |
+
fp_checkpoint = getattr(shared.opts, "sd_model_checkpoint")
|
| 1416 |
+
fp_additional_modules = getattr(shared.opts, "forge_additional_modules")
|
| 1417 |
+
|
| 1418 |
+
reload = False
|
| 1419 |
+
if hasattr(self, "hr_additional_modules") and "Use same choices" not in self.hr_additional_modules:
|
| 1420 |
+
modules_changed = main_entry.modules_change(self.hr_additional_modules, preset=None, save=False, refresh=False)
|
| 1421 |
+
if modules_changed:
|
| 1422 |
+
reload = True
|
| 1423 |
+
|
| 1424 |
+
if self.hr_checkpoint_name and self.hr_checkpoint_name != "Use same checkpoint":
|
| 1425 |
+
checkpoint_changed = main_entry.checkpoint_change(self.hr_checkpoint_name, preset=None, save=False, refresh=False)
|
| 1426 |
+
if checkpoint_changed:
|
| 1427 |
+
reload = True
|
| 1428 |
+
|
| 1429 |
+
if reload:
|
| 1430 |
+
try:
|
| 1431 |
+
main_entry.refresh_model_loading_parameters()
|
| 1432 |
+
sd_models.forge_model_reload()
|
| 1433 |
+
finally:
|
| 1434 |
+
main_entry.modules_change(fp_additional_modules, preset=None, save=False, refresh=False)
|
| 1435 |
+
main_entry.checkpoint_change(fp_checkpoint, preset=None, save=False, refresh=False)
|
| 1436 |
+
main_entry.refresh_model_loading_parameters()
|
| 1437 |
+
|
| 1438 |
+
if self.sd_model.use_distilled_cfg_scale:
|
| 1439 |
+
self.extra_generation_params["Hires Distilled CFG Scale"] = self.hr_distilled_cfg
|
| 1440 |
+
|
| 1441 |
+
return self.sample_hr_pass(samples, decoded_samples, seeds, subseeds, subseed_strength, prompts)
|
| 1442 |
+
|
| 1443 |
+
def sample_hr_pass(self, samples, decoded_samples, seeds, subseeds, subseed_strength, prompts):
|
| 1444 |
+
if shared.state.interrupted:
|
| 1445 |
+
return samples
|
| 1446 |
+
|
| 1447 |
+
self.is_hr_pass = True
|
| 1448 |
+
target_width = self.hr_upscale_to_x
|
| 1449 |
+
target_height = self.hr_upscale_to_y
|
| 1450 |
+
|
| 1451 |
+
def save_intermediate(image, index):
|
| 1452 |
+
"""saves image before applying hires fix, if enabled in options; takes as an argument either an image or batch with latent space images"""
|
| 1453 |
+
|
| 1454 |
+
if not self.save_samples() or not opts.save_images_before_highres_fix:
|
| 1455 |
+
return
|
| 1456 |
+
|
| 1457 |
+
if not isinstance(image, Image.Image):
|
| 1458 |
+
image = sd_samplers.sample_to_image(image, index, approximation=0)
|
| 1459 |
+
|
| 1460 |
+
info = create_infotext(self, self.all_prompts, self.all_seeds, self.all_subseeds, [], iteration=self.iteration, position_in_batch=index)
|
| 1461 |
+
images.save_image(image, self.outpath_samples, "", seeds[index], prompts[index], opts.samples_format, info=info, p=self, suffix="-before-highres-fix")
|
| 1462 |
+
|
| 1463 |
+
img2img_sampler_name = self.hr_sampler_name or self.sampler_name
|
| 1464 |
+
|
| 1465 |
+
self.sampler = sd_samplers.create_sampler(img2img_sampler_name, self.sd_model)
|
| 1466 |
+
|
| 1467 |
+
if self.latent_scale_mode is not None:
|
| 1468 |
+
for i in range(samples.shape[0]):
|
| 1469 |
+
save_intermediate(samples, i)
|
| 1470 |
+
|
| 1471 |
+
samples = torch.nn.functional.interpolate(samples, size=(target_height // opt_f, target_width // opt_f), mode=self.latent_scale_mode["mode"], antialias=self.latent_scale_mode["antialias"])
|
| 1472 |
+
|
| 1473 |
+
# Avoid making the inpainting conditioning unless necessary as
|
| 1474 |
+
# this does need some extra compute to decode / encode the image again.
|
| 1475 |
+
if getattr(self, "inpainting_mask_weight", shared.opts.inpainting_mask_weight) < 1.0:
|
| 1476 |
+
image_conditioning = self.img2img_image_conditioning(decode_first_stage(self.sd_model, samples), samples)
|
| 1477 |
+
else:
|
| 1478 |
+
image_conditioning = self.txt2img_image_conditioning(samples)
|
| 1479 |
+
else:
|
| 1480 |
+
lowres_samples = torch.clamp((decoded_samples + 1.0) / 2.0, min=0.0, max=1.0)
|
| 1481 |
+
|
| 1482 |
+
batch_images = []
|
| 1483 |
+
for i, x_sample in enumerate(lowres_samples):
|
| 1484 |
+
x_sample = 255.0 * np.moveaxis(x_sample.cpu().numpy(), 0, 2)
|
| 1485 |
+
x_sample = x_sample.astype(np.uint8)
|
| 1486 |
+
image = Image.fromarray(x_sample)
|
| 1487 |
+
|
| 1488 |
+
save_intermediate(image, i)
|
| 1489 |
+
|
| 1490 |
+
image = images.resize_image(0, image, target_width, target_height, upscaler_name=self.hr_upscaler)
|
| 1491 |
+
image = np.array(image).astype(np.float32) / 255.0
|
| 1492 |
+
image = np.moveaxis(image, 2, 0)
|
| 1493 |
+
batch_images.append(image)
|
| 1494 |
+
|
| 1495 |
+
decoded_samples = torch.from_numpy(np.array(batch_images))
|
| 1496 |
+
decoded_samples = decoded_samples.to(shared.device, dtype=torch.float32)
|
| 1497 |
+
|
| 1498 |
+
if opts.sd_vae_encode_method != "Full":
|
| 1499 |
+
self.extra_generation_params["VAE Encoder"] = opts.sd_vae_encode_method
|
| 1500 |
+
samples = images_tensor_to_samples(decoded_samples, approximation_indexes.get(opts.sd_vae_encode_method))
|
| 1501 |
+
|
| 1502 |
+
image_conditioning = self.img2img_image_conditioning(decoded_samples, samples)
|
| 1503 |
+
|
| 1504 |
+
shared.state.nextjob()
|
| 1505 |
+
|
| 1506 |
+
samples = samples[:, :, self.truncate_y // 2 : samples.shape[2] - (self.truncate_y + 1) // 2, self.truncate_x // 2 : samples.shape[3] - (self.truncate_x + 1) // 2]
|
| 1507 |
+
|
| 1508 |
+
self.rng = rng.ImageRNG(samples.shape[1:], self.seeds, subseeds=self.subseeds, subseed_strength=self.subseed_strength, seed_resize_from_h=self.seed_resize_from_h, seed_resize_from_w=self.seed_resize_from_w)
|
| 1509 |
+
noise = self.rng.next()
|
| 1510 |
+
|
| 1511 |
+
# GC now before running the next img2img to prevent running out of memory
|
| 1512 |
+
devices.torch_gc()
|
| 1513 |
+
|
| 1514 |
+
if not self.disable_extra_networks:
|
| 1515 |
+
with devices.autocast():
|
| 1516 |
+
extra_networks.activate(self, self.hr_extra_network_data)
|
| 1517 |
+
|
| 1518 |
+
with devices.autocast():
|
| 1519 |
+
self.calculate_hr_conds()
|
| 1520 |
+
|
| 1521 |
+
if self.scripts is not None:
|
| 1522 |
+
self.scripts.before_hr(self)
|
| 1523 |
+
self.scripts.process_before_every_sampling(
|
| 1524 |
+
p=self,
|
| 1525 |
+
x=samples,
|
| 1526 |
+
noise=noise,
|
| 1527 |
+
c=self.hr_c,
|
| 1528 |
+
uc=self.hr_uc,
|
| 1529 |
+
)
|
| 1530 |
+
|
| 1531 |
+
self.sd_model.forge_objects = self.sd_model.forge_objects_after_applying_lora.shallow_copy()
|
| 1532 |
+
apply_token_merging(self.sd_model, self.get_token_merging_ratio(for_hr=True))
|
| 1533 |
+
|
| 1534 |
+
if self.scripts is not None:
|
| 1535 |
+
self.scripts.process_before_every_sampling(self, x=samples, noise=noise, c=self.hr_c, uc=self.hr_uc)
|
| 1536 |
+
|
| 1537 |
+
if self.modified_noise is not None:
|
| 1538 |
+
noise = self.modified_noise
|
| 1539 |
+
self.modified_noise = None
|
| 1540 |
+
|
| 1541 |
+
samples = self.sampler.sample_img2img(self, samples, noise, self.hr_c, self.hr_uc, steps=self.hr_second_pass_steps or self.steps, image_conditioning=image_conditioning)
|
| 1542 |
+
|
| 1543 |
+
self.sampler = None
|
| 1544 |
+
devices.torch_gc()
|
| 1545 |
+
|
| 1546 |
+
decoded_samples = decode_latent_batch(self.sd_model, samples, target_device=devices.cpu, check_for_nans=True)
|
| 1547 |
+
|
| 1548 |
+
self.is_hr_pass = False
|
| 1549 |
+
return decoded_samples
|
| 1550 |
+
|
| 1551 |
+
def close(self):
|
| 1552 |
+
super().close()
|
| 1553 |
+
self.hr_c = None
|
| 1554 |
+
self.hr_uc = None
|
| 1555 |
+
if not opts.persistent_cond_cache:
|
| 1556 |
+
StableDiffusionProcessingTxt2Img.cached_hr_uc = [None, None]
|
| 1557 |
+
StableDiffusionProcessingTxt2Img.cached_hr_c = [None, None]
|
| 1558 |
+
|
| 1559 |
+
def setup_prompts(self):
|
| 1560 |
+
super().setup_prompts()
|
| 1561 |
+
|
| 1562 |
+
if not self.enable_hr:
|
| 1563 |
+
return
|
| 1564 |
+
|
| 1565 |
+
if self.hr_prompt == "":
|
| 1566 |
+
self.hr_prompt = self.prompt
|
| 1567 |
+
|
| 1568 |
+
if self.hr_negative_prompt == "":
|
| 1569 |
+
self.hr_negative_prompt = self.negative_prompt
|
| 1570 |
+
|
| 1571 |
+
if isinstance(self.hr_prompt, list):
|
| 1572 |
+
self.all_hr_prompts = self.hr_prompt
|
| 1573 |
+
else:
|
| 1574 |
+
self.all_hr_prompts = self.batch_size * self.n_iter * [self.hr_prompt]
|
| 1575 |
+
|
| 1576 |
+
if isinstance(self.hr_negative_prompt, list):
|
| 1577 |
+
self.all_hr_negative_prompts = self.hr_negative_prompt
|
| 1578 |
+
else:
|
| 1579 |
+
self.all_hr_negative_prompts = self.batch_size * self.n_iter * [self.hr_negative_prompt]
|
| 1580 |
+
|
| 1581 |
+
self.all_hr_prompts = [shared.prompt_styles.apply_styles_to_prompt(x, self.styles) for x in self.all_hr_prompts]
|
| 1582 |
+
self.all_hr_negative_prompts = [shared.prompt_styles.apply_negative_styles_to_prompt(x, self.styles) for x in self.all_hr_negative_prompts]
|
| 1583 |
+
|
| 1584 |
+
def calculate_hr_conds(self):
|
| 1585 |
+
if self.hr_c is not None:
|
| 1586 |
+
return
|
| 1587 |
+
|
| 1588 |
+
hr_prompts = prompt_parser.SdConditioning(self.hr_prompts, width=self.hr_upscale_to_x, height=self.hr_upscale_to_y, distilled_cfg_scale=self.hr_distilled_cfg)
|
| 1589 |
+
hr_negative_prompts = prompt_parser.SdConditioning(self.hr_negative_prompts, width=self.hr_upscale_to_x, height=self.hr_upscale_to_y, is_negative_prompt=True, distilled_cfg_scale=self.hr_distilled_cfg)
|
| 1590 |
+
|
| 1591 |
+
sampler_config = sd_samplers.find_sampler_config(self.hr_sampler_name or self.sampler_name)
|
| 1592 |
+
steps = self.hr_second_pass_steps or self.steps
|
| 1593 |
+
total_steps = sampler_config.total_steps(steps) if sampler_config else steps
|
| 1594 |
+
|
| 1595 |
+
if self.hr_cfg == 1:
|
| 1596 |
+
self.hr_uc = None
|
| 1597 |
+
print("Skipping unconditional conditioning (HR pass) when CFG = 1. Negative Prompts are ignored.")
|
| 1598 |
+
else:
|
| 1599 |
+
self.hr_uc = self.get_conds_with_caching(prompt_parser.get_learned_conditioning, hr_negative_prompts, self.firstpass_steps, [self.cached_hr_uc, self.cached_uc], self.hr_extra_network_data, total_steps)
|
| 1600 |
+
|
| 1601 |
+
self.hr_c = self.get_conds_with_caching(prompt_parser.get_multicond_learned_conditioning, hr_prompts, self.firstpass_steps, [self.cached_hr_c, self.cached_c], self.hr_extra_network_data, total_steps)
|
| 1602 |
+
|
| 1603 |
+
def setup_conds(self):
|
| 1604 |
+
if self.is_hr_pass:
|
| 1605 |
+
# if we are in hr pass right now, the call is being made from the refiner, and we don't need to setup firstpass cons or switch model
|
| 1606 |
+
self.hr_c = None
|
| 1607 |
+
self.calculate_hr_conds()
|
| 1608 |
+
return
|
| 1609 |
+
|
| 1610 |
+
super().setup_conds()
|
| 1611 |
+
|
| 1612 |
+
self.hr_uc = None
|
| 1613 |
+
self.hr_c = None
|
| 1614 |
+
|
| 1615 |
+
if self.enable_hr and self.hr_checkpoint_info is None:
|
| 1616 |
+
if shared.opts.hires_fix_use_firstpass_conds:
|
| 1617 |
+
self.calculate_hr_conds()
|
| 1618 |
+
else:
|
| 1619 |
+
with devices.autocast():
|
| 1620 |
+
extra_networks.activate(self, self.hr_extra_network_data)
|
| 1621 |
+
|
| 1622 |
+
self.calculate_hr_conds()
|
| 1623 |
+
|
| 1624 |
+
with devices.autocast():
|
| 1625 |
+
extra_networks.activate(self, self.extra_network_data)
|
| 1626 |
+
|
| 1627 |
+
def get_conds(self):
|
| 1628 |
+
if self.is_hr_pass:
|
| 1629 |
+
return self.hr_c, self.hr_uc
|
| 1630 |
+
|
| 1631 |
+
return super().get_conds()
|
| 1632 |
+
|
| 1633 |
+
def parse_extra_network_prompts(self):
|
| 1634 |
+
res = super().parse_extra_network_prompts()
|
| 1635 |
+
|
| 1636 |
+
if self.enable_hr:
|
| 1637 |
+
self.hr_prompts = self.all_hr_prompts[self.iteration * self.batch_size : (self.iteration + 1) * self.batch_size]
|
| 1638 |
+
self.hr_negative_prompts = self.all_hr_negative_prompts[self.iteration * self.batch_size : (self.iteration + 1) * self.batch_size]
|
| 1639 |
+
|
| 1640 |
+
self.hr_prompts, self.hr_extra_network_data = extra_networks.parse_prompts(self.hr_prompts)
|
| 1641 |
+
|
| 1642 |
+
return res
|
| 1643 |
+
|
| 1644 |
+
|
| 1645 |
+
@dataclass(repr=False)
|
| 1646 |
+
class StableDiffusionProcessingImg2Img(StableDiffusionProcessing):
|
| 1647 |
+
init_images: list = None
|
| 1648 |
+
resize_mode: int = 0
|
| 1649 |
+
denoising_strength: float = 0.75
|
| 1650 |
+
image_cfg_scale: float = None
|
| 1651 |
+
mask: Any = None
|
| 1652 |
+
mask_blur_x: int = 4
|
| 1653 |
+
mask_blur_y: int = 4
|
| 1654 |
+
mask_blur: int = None
|
| 1655 |
+
mask_round: bool = True
|
| 1656 |
+
inpainting_fill: int = 0
|
| 1657 |
+
inpaint_full_res: bool = True
|
| 1658 |
+
inpaint_full_res_padding: int = 0
|
| 1659 |
+
inpainting_mask_invert: int = 0
|
| 1660 |
+
initial_noise_multiplier: float = None
|
| 1661 |
+
latent_mask: Image = None
|
| 1662 |
+
force_task_id: str = None
|
| 1663 |
+
|
| 1664 |
+
hr_distilled_cfg: float = 3.5 # needed here for cached_params
|
| 1665 |
+
|
| 1666 |
+
image_mask: Any = field(default=None, init=False)
|
| 1667 |
+
|
| 1668 |
+
nmask: torch.Tensor = field(default=None, init=False)
|
| 1669 |
+
image_conditioning: torch.Tensor = field(default=None, init=False)
|
| 1670 |
+
init_img_hash: str = field(default=None, init=False)
|
| 1671 |
+
mask_for_overlay: Image = field(default=None, init=False)
|
| 1672 |
+
init_latent: torch.Tensor = field(default=None, init=False)
|
| 1673 |
+
|
| 1674 |
+
def __post_init__(self):
|
| 1675 |
+
super().__post_init__()
|
| 1676 |
+
|
| 1677 |
+
self.image_mask = self.mask
|
| 1678 |
+
self.mask = None
|
| 1679 |
+
self.initial_noise_multiplier = opts.initial_noise_multiplier if self.initial_noise_multiplier is None else self.initial_noise_multiplier
|
| 1680 |
+
|
| 1681 |
+
@property
|
| 1682 |
+
def mask_blur(self):
|
| 1683 |
+
if self.mask_blur_x == self.mask_blur_y:
|
| 1684 |
+
return self.mask_blur_x
|
| 1685 |
+
return None
|
| 1686 |
+
|
| 1687 |
+
@mask_blur.setter
|
| 1688 |
+
def mask_blur(self, value):
|
| 1689 |
+
if isinstance(value, int):
|
| 1690 |
+
self.mask_blur_x = value
|
| 1691 |
+
self.mask_blur_y = value
|
| 1692 |
+
|
| 1693 |
+
def init(self, all_prompts, all_seeds, all_subseeds):
|
| 1694 |
+
self.extra_generation_params["Denoising strength"] = self.denoising_strength
|
| 1695 |
+
|
| 1696 |
+
self.image_cfg_scale: float = None
|
| 1697 |
+
|
| 1698 |
+
self.sampler = sd_samplers.create_sampler(self.sampler_name, self.sd_model)
|
| 1699 |
+
crop_region = None
|
| 1700 |
+
|
| 1701 |
+
image_mask = self.image_mask
|
| 1702 |
+
|
| 1703 |
+
if image_mask is not None:
|
| 1704 |
+
# image_mask is passed in as RGBA by Gradio to support alpha masks,
|
| 1705 |
+
# but we still want to support binary masks.
|
| 1706 |
+
image_mask = create_binary_mask(image_mask, round=self.mask_round)
|
| 1707 |
+
|
| 1708 |
+
if self.inpainting_mask_invert:
|
| 1709 |
+
image_mask = ImageOps.invert(image_mask)
|
| 1710 |
+
self.extra_generation_params["Mask mode"] = "Inpaint not masked"
|
| 1711 |
+
|
| 1712 |
+
if self.mask_blur_x > 0:
|
| 1713 |
+
np_mask = np.array(image_mask)
|
| 1714 |
+
kernel_size = 2 * int(2.5 * self.mask_blur_x + 0.5) + 1
|
| 1715 |
+
np_mask = cv2.GaussianBlur(np_mask, (kernel_size, 1), self.mask_blur_x)
|
| 1716 |
+
image_mask = Image.fromarray(np_mask)
|
| 1717 |
+
|
| 1718 |
+
if self.mask_blur_y > 0:
|
| 1719 |
+
np_mask = np.array(image_mask)
|
| 1720 |
+
kernel_size = 2 * int(2.5 * self.mask_blur_y + 0.5) + 1
|
| 1721 |
+
np_mask = cv2.GaussianBlur(np_mask, (1, kernel_size), self.mask_blur_y)
|
| 1722 |
+
image_mask = Image.fromarray(np_mask)
|
| 1723 |
+
|
| 1724 |
+
if self.mask_blur_x > 0 or self.mask_blur_y > 0:
|
| 1725 |
+
self.extra_generation_params["Mask blur"] = self.mask_blur
|
| 1726 |
+
|
| 1727 |
+
if self.inpaint_full_res:
|
| 1728 |
+
self.mask_for_overlay = image_mask
|
| 1729 |
+
mask = image_mask.convert("L")
|
| 1730 |
+
crop_region = masking.get_crop_region_v2(mask, self.inpaint_full_res_padding)
|
| 1731 |
+
if crop_region:
|
| 1732 |
+
crop_region = masking.expand_crop_region(crop_region, self.width, self.height, mask.width, mask.height)
|
| 1733 |
+
x1, y1, x2, y2 = crop_region
|
| 1734 |
+
mask = mask.crop(crop_region)
|
| 1735 |
+
image_mask = images.resize_image(2, mask, self.width, self.height)
|
| 1736 |
+
self.paste_to = (x1, y1, x2 - x1, y2 - y1)
|
| 1737 |
+
self.extra_generation_params["Inpaint area"] = "Only masked"
|
| 1738 |
+
self.extra_generation_params["Masked area padding"] = self.inpaint_full_res_padding
|
| 1739 |
+
else:
|
| 1740 |
+
crop_region = None
|
| 1741 |
+
image_mask = None
|
| 1742 |
+
self.mask_for_overlay = None
|
| 1743 |
+
self.inpaint_full_res = False
|
| 1744 |
+
massage = 'Unable to perform "Inpaint Only mask" because mask is blank, switch to img2img mode.'
|
| 1745 |
+
self.sd_model.comments.append(massage)
|
| 1746 |
+
logging.info(massage)
|
| 1747 |
+
else:
|
| 1748 |
+
image_mask = images.resize_image(self.resize_mode, image_mask, self.width, self.height)
|
| 1749 |
+
np_mask = np.array(image_mask)
|
| 1750 |
+
np_mask = np.clip((np_mask.astype(np.float32)) * 2, 0, 255).astype(np.uint8)
|
| 1751 |
+
self.mask_for_overlay = Image.fromarray(np_mask)
|
| 1752 |
+
|
| 1753 |
+
self.overlay_images = []
|
| 1754 |
+
|
| 1755 |
+
latent_mask = self.latent_mask if self.latent_mask is not None else image_mask
|
| 1756 |
+
|
| 1757 |
+
if self.scripts is not None:
|
| 1758 |
+
self.scripts.before_process_init_images(self, dict(crop_region=crop_region, image_mask=image_mask))
|
| 1759 |
+
|
| 1760 |
+
add_color_corrections = opts.img2img_color_correction and self.color_corrections is None
|
| 1761 |
+
if add_color_corrections:
|
| 1762 |
+
self.color_corrections = []
|
| 1763 |
+
imgs = []
|
| 1764 |
+
for img in self.init_images:
|
| 1765 |
+
self.init_img_hash = hashlib.md5(img.tobytes()).hexdigest()
|
| 1766 |
+
|
| 1767 |
+
# Save init image
|
| 1768 |
+
if opts.save_init_img:
|
| 1769 |
+
images.save_image(img, path=opts.outdir_init_images, basename=None, forced_filename=self.init_img_hash, save_to_dirs=False, existing_info=img.info)
|
| 1770 |
+
|
| 1771 |
+
image = images.flatten(img, opts.img2img_background_color)
|
| 1772 |
+
|
| 1773 |
+
if crop_region is None and self.resize_mode != 3:
|
| 1774 |
+
image = images.resize_image(self.resize_mode, image, self.width, self.height)
|
| 1775 |
+
|
| 1776 |
+
if image_mask is not None:
|
| 1777 |
+
if self.mask_for_overlay.size != (image.width, image.height):
|
| 1778 |
+
self.mask_for_overlay = images.resize_image(self.resize_mode, self.mask_for_overlay, image.width, image.height)
|
| 1779 |
+
image_masked = Image.new("RGBa", (image.width, image.height))
|
| 1780 |
+
image_masked.paste(image.convert("RGBA").convert("RGBa"), mask=ImageOps.invert(self.mask_for_overlay.convert("L")))
|
| 1781 |
+
|
| 1782 |
+
self.overlay_images.append(image_masked.convert("RGBA"))
|
| 1783 |
+
|
| 1784 |
+
# crop_region is not None if we are doing inpaint full res
|
| 1785 |
+
if crop_region is not None:
|
| 1786 |
+
image = image.crop(crop_region)
|
| 1787 |
+
image = images.resize_image(2, image, self.width, self.height)
|
| 1788 |
+
|
| 1789 |
+
if image_mask is not None:
|
| 1790 |
+
if self.inpainting_fill != 1:
|
| 1791 |
+
image = masking.fill(image, latent_mask)
|
| 1792 |
+
|
| 1793 |
+
if self.inpainting_fill == 0:
|
| 1794 |
+
self.extra_generation_params["Masked content"] = "fill"
|
| 1795 |
+
|
| 1796 |
+
if add_color_corrections:
|
| 1797 |
+
self.color_corrections.append(setup_color_correction(image))
|
| 1798 |
+
|
| 1799 |
+
image = np.array(image).astype(np.float32) / 255.0
|
| 1800 |
+
image = np.moveaxis(image, 2, 0)
|
| 1801 |
+
|
| 1802 |
+
imgs.append(image)
|
| 1803 |
+
|
| 1804 |
+
if len(imgs) == 1:
|
| 1805 |
+
batch_images = np.expand_dims(imgs[0], axis=0).repeat(self.batch_size, axis=0)
|
| 1806 |
+
if self.overlay_images is not None:
|
| 1807 |
+
self.overlay_images = self.overlay_images * self.batch_size
|
| 1808 |
+
|
| 1809 |
+
if self.color_corrections is not None and len(self.color_corrections) == 1:
|
| 1810 |
+
self.color_corrections = self.color_corrections * self.batch_size
|
| 1811 |
+
|
| 1812 |
+
elif len(imgs) <= self.batch_size:
|
| 1813 |
+
self.batch_size = len(imgs)
|
| 1814 |
+
batch_images = np.array(imgs)
|
| 1815 |
+
else:
|
| 1816 |
+
raise RuntimeError(f"bad number of images passed: {len(imgs)}; expecting {self.batch_size} or less")
|
| 1817 |
+
|
| 1818 |
+
image = torch.from_numpy(batch_images)
|
| 1819 |
+
image = image.to(shared.device, dtype=torch.float32)
|
| 1820 |
+
|
| 1821 |
+
if opts.sd_vae_encode_method != "Full":
|
| 1822 |
+
self.extra_generation_params["VAE Encoder"] = opts.sd_vae_encode_method
|
| 1823 |
+
|
| 1824 |
+
self.init_latent = images_tensor_to_samples(image, approximation_indexes.get(opts.sd_vae_encode_method), self.sd_model)
|
| 1825 |
+
devices.torch_gc()
|
| 1826 |
+
|
| 1827 |
+
if self.resize_mode == 3:
|
| 1828 |
+
self.init_latent = torch.nn.functional.interpolate(self.init_latent, size=(self.height // opt_f, self.width // opt_f), mode="bilinear")
|
| 1829 |
+
|
| 1830 |
+
if image_mask is not None:
|
| 1831 |
+
init_mask = latent_mask
|
| 1832 |
+
latmask = init_mask.convert("RGB").resize((self.init_latent.shape[-1], self.init_latent.shape[-2]))
|
| 1833 |
+
latmask = np.moveaxis(np.array(latmask, dtype=np.float32), 2, 0) / 255
|
| 1834 |
+
latmask = latmask[0]
|
| 1835 |
+
if self.mask_round:
|
| 1836 |
+
latmask = np.around(latmask)
|
| 1837 |
+
latmask = np.tile(latmask[None], (self.init_latent.shape[1], 1, 1))
|
| 1838 |
+
|
| 1839 |
+
self.mask = torch.asarray(1.0 - latmask).to(shared.device).type(devices.dtype)
|
| 1840 |
+
self.nmask = torch.asarray(latmask).to(shared.device).type(devices.dtype)
|
| 1841 |
+
|
| 1842 |
+
if len(self.mask.shape) != len(self.init_latent.shape):
|
| 1843 |
+
x_dims = self.init_latent.dim()
|
| 1844 |
+
if x_dims == 4:
|
| 1845 |
+
self.nmask = self.nmask[None, :, :, :]
|
| 1846 |
+
self.mask = self.mask[None, :, :, :]
|
| 1847 |
+
elif x_dims == 5:
|
| 1848 |
+
self.nmask = self.nmask[None, :, None, :, :]
|
| 1849 |
+
self.mask = self.mask[None, :, None, :, :]
|
| 1850 |
+
|
| 1851 |
+
# this needs to be fixed to be done in sample() using actual seeds for batches
|
| 1852 |
+
if self.inpainting_fill == 2:
|
| 1853 |
+
_dim = (self.init_latent.shape[1], self.init_latent.shape[-2], self.init_latent.shape[-1])
|
| 1854 |
+
self.init_latent = self.init_latent * self.mask + create_random_tensors(_dim, all_seeds[0 : self.init_latent.shape[0]]) * self.nmask
|
| 1855 |
+
self.extra_generation_params["Masked content"] = "latent noise"
|
| 1856 |
+
|
| 1857 |
+
elif self.inpainting_fill == 3:
|
| 1858 |
+
self.init_latent = self.init_latent * self.mask
|
| 1859 |
+
self.extra_generation_params["Masked content"] = "latent nothing"
|
| 1860 |
+
|
| 1861 |
+
self.image_conditioning = self.img2img_image_conditioning(image * 2 - 1, self.init_latent, image_mask, self.mask_round)
|
| 1862 |
+
|
| 1863 |
+
def sample(self, conditioning, unconditional_conditioning, seeds, subseeds, subseed_strength, prompts):
|
| 1864 |
+
x = self.rng.next()
|
| 1865 |
+
if shared.sd_model.is_wan: # enforce batch_size of 1
|
| 1866 |
+
x = x[0].unsqueeze(0)
|
| 1867 |
+
|
| 1868 |
+
if self.initial_noise_multiplier != 1.0:
|
| 1869 |
+
self.extra_generation_params["Noise multiplier"] = self.initial_noise_multiplier
|
| 1870 |
+
x *= self.initial_noise_multiplier
|
| 1871 |
+
|
| 1872 |
+
self.sd_model.forge_objects = self.sd_model.forge_objects_after_applying_lora.shallow_copy()
|
| 1873 |
+
apply_token_merging(self.sd_model, self.get_token_merging_ratio())
|
| 1874 |
+
|
| 1875 |
+
if self.scripts is not None:
|
| 1876 |
+
self.scripts.process_before_every_sampling(self, x=self.init_latent, noise=x, c=conditioning, uc=unconditional_conditioning)
|
| 1877 |
+
|
| 1878 |
+
if self.modified_noise is not None:
|
| 1879 |
+
x = self.modified_noise
|
| 1880 |
+
self.modified_noise = None
|
| 1881 |
+
|
| 1882 |
+
samples = self.sampler.sample_img2img(self, self.init_latent, x, conditioning, unconditional_conditioning, image_conditioning=self.image_conditioning)
|
| 1883 |
+
|
| 1884 |
+
if self.mask is not None:
|
| 1885 |
+
blended_samples = samples * self.nmask + self.init_latent * self.mask
|
| 1886 |
+
|
| 1887 |
+
if self.scripts is not None:
|
| 1888 |
+
mba = scripts.MaskBlendArgs(samples, self.nmask, self.init_latent, self.mask, blended_samples)
|
| 1889 |
+
self.scripts.on_mask_blend(self, mba)
|
| 1890 |
+
blended_samples = mba.blended_latent
|
| 1891 |
+
|
| 1892 |
+
samples = blended_samples
|
| 1893 |
+
|
| 1894 |
+
del x
|
| 1895 |
+
devices.torch_gc()
|
| 1896 |
+
|
| 1897 |
+
return samples
|
| 1898 |
+
|
| 1899 |
+
def get_token_merging_ratio(self, for_hr=False):
|
| 1900 |
+
return self.token_merging_ratio or ("token_merging_ratio" in self.override_settings and opts.token_merging_ratio) or opts.token_merging_ratio_img2img or opts.token_merging_ratio
|
modules/processing_scripts/comments.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
from typing import TYPE_CHECKING
|
| 3 |
+
|
| 4 |
+
from modules import scripts, shared
|
| 5 |
+
|
| 6 |
+
if TYPE_CHECKING:
|
| 7 |
+
from modules.processing import StableDiffusionProcessing
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def strip_comments(text: str) -> str:
|
| 11 |
+
if not shared.opts.enable_prompt_comments:
|
| 12 |
+
return text
|
| 13 |
+
|
| 14 |
+
# multi line comment (/* */)
|
| 15 |
+
text = re.sub(r"\/\*.*?\*\/", "", text, flags=re.DOTALL)
|
| 16 |
+
# single line comment (# | //)
|
| 17 |
+
text = re.sub(r"[^\S\n]*(\#|\/\/).*", "", text)
|
| 18 |
+
|
| 19 |
+
return text
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class ScriptComments(scripts.Script):
|
| 23 |
+
def title(self):
|
| 24 |
+
return "Comments"
|
| 25 |
+
|
| 26 |
+
def show(self, is_img2img):
|
| 27 |
+
return scripts.AlwaysVisible
|
| 28 |
+
|
| 29 |
+
def process(self, p: "StableDiffusionProcessing", *args):
|
| 30 |
+
if not shared.opts.enable_prompt_comments:
|
| 31 |
+
return
|
| 32 |
+
|
| 33 |
+
if shared.opts.save_prompt_comments:
|
| 34 |
+
p._all_prompts_c = p.all_prompts.copy()
|
| 35 |
+
p._all_negative_prompts_c = p.all_negative_prompts.copy()
|
| 36 |
+
|
| 37 |
+
p.all_prompts = [strip_comments(x) for x in p.all_prompts]
|
| 38 |
+
p.all_negative_prompts = [strip_comments(x) for x in p.all_negative_prompts]
|
| 39 |
+
|
| 40 |
+
p.main_prompt = strip_comments(p.main_prompt)
|
| 41 |
+
p.main_negative_prompt = strip_comments(p.main_negative_prompt)
|
| 42 |
+
|
| 43 |
+
if getattr(p, "enable_hr", False):
|
| 44 |
+
p.all_hr_prompts = [strip_comments(x) for x in p.all_hr_prompts]
|
| 45 |
+
p.all_hr_negative_prompts = [strip_comments(x) for x in p.all_hr_negative_prompts]
|
| 46 |
+
|
| 47 |
+
p.hr_prompt = strip_comments(p.hr_prompt)
|
| 48 |
+
p.hr_negative_prompt = strip_comments(p.hr_negative_prompt)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
shared.options_templates.update(
|
| 52 |
+
shared.options_section(
|
| 53 |
+
("ui_comments", "Comments", "ui"),
|
| 54 |
+
{
|
| 55 |
+
"enable_prompt_comments": shared.OptionInfo(True, "Remove Comments from Prompts").html(
|
| 56 |
+
"""
|
| 57 |
+
<b>Comment Syntax:</b><br>
|
| 58 |
+
<ul style='margin-left: 2em'>
|
| 59 |
+
<li># ...</li>
|
| 60 |
+
<li>// ...</li>
|
| 61 |
+
<li>/* ... */</li>
|
| 62 |
+
</ul>
|
| 63 |
+
"""
|
| 64 |
+
),
|
| 65 |
+
"save_prompt_comments": shared.OptionInfo(False, "Save Raw Comments").info("include the comments in Infotext"),
|
| 66 |
+
},
|
| 67 |
+
)
|
| 68 |
+
)
|
modules/processing_scripts/mahiro.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# https://github.com/comfyanonymous/ComfyUI/blob/v0.3.64/comfy_extras/nodes_mahiro.py
|
| 2 |
+
|
| 3 |
+
import gradio as gr
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
|
| 7 |
+
from modules import scripts
|
| 8 |
+
from modules.infotext_utils import PasteField
|
| 9 |
+
from modules.shared import opts
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class ScriptMahiro(scripts.ScriptBuiltinUI):
|
| 13 |
+
section = "cfg"
|
| 14 |
+
create_group = False
|
| 15 |
+
sorting_priority = 1
|
| 16 |
+
|
| 17 |
+
def title(self):
|
| 18 |
+
return "MaHiRo"
|
| 19 |
+
|
| 20 |
+
def show(self, is_img2img):
|
| 21 |
+
return scripts.AlwaysVisible if opts.show_mahiro else None
|
| 22 |
+
|
| 23 |
+
def ui(self, is_img2img):
|
| 24 |
+
enable = gr.Checkbox(
|
| 25 |
+
value=False,
|
| 26 |
+
label="MaHiRo",
|
| 27 |
+
elem_id=f"{'img2img' if is_img2img else 'txt2img'}_enable_mahiro",
|
| 28 |
+
scale=1,
|
| 29 |
+
)
|
| 30 |
+
self.infotext_fields = [PasteField(enable, "MaHiRo", api="mahiro")]
|
| 31 |
+
return [enable]
|
| 32 |
+
|
| 33 |
+
def after_extra_networks_activate(self, p, enable, *args, **kwargs):
|
| 34 |
+
if enable:
|
| 35 |
+
p.extra_generation_params.update({"MaHiRo": enable})
|
| 36 |
+
p.mahiro = True
|
| 37 |
+
|
| 38 |
+
def process_before_every_sampling(self, p, *args, **kwargs):
|
| 39 |
+
if str(getattr(p, "mahiro", False)) != "True":
|
| 40 |
+
return
|
| 41 |
+
|
| 42 |
+
@torch.inference_mode()
|
| 43 |
+
def mahiro_normd(args: dict):
|
| 44 |
+
scale: float = args["cond_scale"]
|
| 45 |
+
cond_p: torch.Tensor = args["cond_denoised"]
|
| 46 |
+
uncond_p: torch.Tensor = args["uncond_denoised"]
|
| 47 |
+
leap = cond_p * scale
|
| 48 |
+
u_leap = uncond_p * scale
|
| 49 |
+
cfg: torch.Tensor = args["denoised"]
|
| 50 |
+
merge = (leap + cfg) / 2
|
| 51 |
+
normu = torch.sqrt(u_leap.abs()) * u_leap.sign()
|
| 52 |
+
normm = torch.sqrt(merge.abs()) * merge.sign()
|
| 53 |
+
sim = F.cosine_similarity(normu, normm).mean()
|
| 54 |
+
simsc = 2 * (sim + 1)
|
| 55 |
+
wm = (simsc * cfg + (4 - simsc) * leap) / 4
|
| 56 |
+
return wm
|
| 57 |
+
|
| 58 |
+
unet = p.sd_model.forge_objects.unet.clone()
|
| 59 |
+
unet.set_model_sampler_post_cfg_function(mahiro_normd)
|
| 60 |
+
p.sd_model.forge_objects.unet = unet
|
| 61 |
+
|
| 62 |
+
print("using MaHiRo")
|
modules/processing_scripts/refiner.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
|
| 3 |
+
from modules import scripts, sd_models
|
| 4 |
+
from modules.infotext_utils import PasteField
|
| 5 |
+
from modules.shared import opts
|
| 6 |
+
from modules.ui_common import create_refresh_button
|
| 7 |
+
from modules.ui_components import InputAccordion
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class ScriptRefiner(scripts.ScriptBuiltinUI):
|
| 11 |
+
section = "accordions"
|
| 12 |
+
create_group = False
|
| 13 |
+
ckpts = []
|
| 14 |
+
|
| 15 |
+
def title(self):
|
| 16 |
+
return "Refiner"
|
| 17 |
+
|
| 18 |
+
def show(self, is_img2img):
|
| 19 |
+
return scripts.AlwaysVisible if opts.show_refiner else None
|
| 20 |
+
|
| 21 |
+
@classmethod
|
| 22 |
+
def refresh_checkpoints(cls):
|
| 23 |
+
from modules_forge.main_entry import refresh_models
|
| 24 |
+
|
| 25 |
+
ckpt_list, _ = refresh_models()
|
| 26 |
+
cls.ckpts = ["None"] + ckpt_list
|
| 27 |
+
|
| 28 |
+
def ui(self, is_img2img):
|
| 29 |
+
self.refresh_checkpoints()
|
| 30 |
+
with InputAccordion(False, label="Refiner", elem_id=self.elem_id("enable")) as enable_refiner:
|
| 31 |
+
with gr.Row():
|
| 32 |
+
refiner_checkpoint = gr.Dropdown(value="None", label="Checkpoint", info="(use model of same architecture)", elem_id=self.elem_id("checkpoint"), choices=self.ckpts)
|
| 33 |
+
create_refresh_button(refiner_checkpoint, self.refresh_checkpoints, lambda: {"choices": self.ckpts}, self.elem_id("checkpoint_refresh"))
|
| 34 |
+
refiner_switch_at = gr.Slider(value=0.875, label="Switch at", info="(in sigmas)", minimum=0.1, maximum=1.0, step=0.025, elem_id=self.elem_id("switch_at"), tooltip="Wan 2.2 T2V: 0.875 ; Wan 2.2 I2V: 0.9")
|
| 35 |
+
|
| 36 |
+
def lookup_checkpoint(title):
|
| 37 |
+
info = sd_models.get_closet_checkpoint_match(title)
|
| 38 |
+
return None if info is None else info.short_title
|
| 39 |
+
|
| 40 |
+
self.infotext_fields = [
|
| 41 |
+
PasteField(enable_refiner, lambda d: "Refiner" in d),
|
| 42 |
+
PasteField(refiner_checkpoint, lambda d: lookup_checkpoint(d.get("Refiner")), api="refiner_checkpoint"),
|
| 43 |
+
PasteField(refiner_switch_at, "Refiner switch at", api="refiner_switch_at"),
|
| 44 |
+
]
|
| 45 |
+
|
| 46 |
+
return enable_refiner, refiner_checkpoint, refiner_switch_at
|
| 47 |
+
|
| 48 |
+
def setup(self, p, enable_refiner, refiner_checkpoint, refiner_switch_at):
|
| 49 |
+
# the actual implementation is in sd_samplers_common.py apply_refiner()
|
| 50 |
+
if not enable_refiner or refiner_checkpoint in (None, "", "None"):
|
| 51 |
+
p.refiner_checkpoint = None
|
| 52 |
+
p.refiner_switch_at = None
|
| 53 |
+
else:
|
| 54 |
+
p.refiner_checkpoint = refiner_checkpoint
|
| 55 |
+
p.refiner_switch_at = refiner_switch_at
|
modules/processing_scripts/rescale_cfg.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# https://github.com/comfyanonymous/ComfyUI/blob/v0.3.64/comfy_extras/nodes_model_advanced.py#L274
|
| 2 |
+
|
| 3 |
+
import gradio as gr
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
from modules import scripts
|
| 7 |
+
from modules.infotext_utils import PasteField
|
| 8 |
+
from modules.shared import opts
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class ScriptRescaleCFG(scripts.ScriptBuiltinUI):
|
| 12 |
+
section = "cfg"
|
| 13 |
+
create_group = False
|
| 14 |
+
|
| 15 |
+
def title(self):
|
| 16 |
+
return "RescaleCFG"
|
| 17 |
+
|
| 18 |
+
def show(self, is_img2img):
|
| 19 |
+
return scripts.AlwaysVisible if opts.show_rescale_cfg else None
|
| 20 |
+
|
| 21 |
+
def ui(self, is_img2img):
|
| 22 |
+
cfg = gr.Slider(
|
| 23 |
+
value=0.0,
|
| 24 |
+
minimum=0.0,
|
| 25 |
+
maximum=1.0,
|
| 26 |
+
step=0.05,
|
| 27 |
+
label="Rescale CFG",
|
| 28 |
+
elem_id=f"{'img2img' if is_img2img else 'txt2img'}_rescale_cfg_scale",
|
| 29 |
+
scale=4,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
self.infotext_fields = [PasteField(cfg, "Rescale CFG", api="rescale_cfg")]
|
| 33 |
+
|
| 34 |
+
return [cfg]
|
| 35 |
+
|
| 36 |
+
def after_extra_networks_activate(self, p, cfg, *args, **kwargs):
|
| 37 |
+
if cfg > 0.0:
|
| 38 |
+
p.extra_generation_params.update({"Rescale CFG": cfg})
|
| 39 |
+
p.rescale_cfg = cfg
|
| 40 |
+
|
| 41 |
+
def process_before_every_sampling(self, p, *args, **kwargs):
|
| 42 |
+
if getattr(p, "rescale_cfg", 0.0) < 0.05:
|
| 43 |
+
return
|
| 44 |
+
if p.is_hr_pass:
|
| 45 |
+
return
|
| 46 |
+
|
| 47 |
+
self.apply_rescale_cfg(p, p.rescale_cfg)
|
| 48 |
+
|
| 49 |
+
@staticmethod
|
| 50 |
+
def apply_rescale_cfg(p, cfg: float):
|
| 51 |
+
|
| 52 |
+
@torch.inference_mode()
|
| 53 |
+
def rescale_cfg(args):
|
| 54 |
+
cond = args["cond"]
|
| 55 |
+
uncond = args["uncond"]
|
| 56 |
+
cond_scale = args["cond_scale"]
|
| 57 |
+
sigma = args["sigma"]
|
| 58 |
+
sigma = sigma.view(sigma.shape[:1] + (1,) * (cond.ndim - 1))
|
| 59 |
+
x_orig = args["input"]
|
| 60 |
+
|
| 61 |
+
x = x_orig / (sigma * sigma + 1.0)
|
| 62 |
+
cond = ((x - (x_orig - cond)) * (sigma**2 + 1.0) ** 0.5) / (sigma)
|
| 63 |
+
uncond = ((x - (x_orig - uncond)) * (sigma**2 + 1.0) ** 0.5) / (sigma)
|
| 64 |
+
|
| 65 |
+
x_cfg = uncond + cond_scale * (cond - uncond)
|
| 66 |
+
ro_pos = torch.std(cond, dim=(1, 2, 3), keepdim=True)
|
| 67 |
+
ro_cfg = torch.std(x_cfg, dim=(1, 2, 3), keepdim=True)
|
| 68 |
+
|
| 69 |
+
x_rescaled = x_cfg * (ro_pos / ro_cfg)
|
| 70 |
+
x_final = cfg * x_rescaled + (1.0 - cfg) * x_cfg
|
| 71 |
+
|
| 72 |
+
return x_orig - (x - x_final * sigma / (sigma * sigma + 1.0) ** 0.5)
|
| 73 |
+
|
| 74 |
+
unet = p.sd_model.forge_objects.unet.clone()
|
| 75 |
+
unet.set_model_sampler_cfg_function(rescale_cfg)
|
| 76 |
+
p.sd_model.forge_objects.unet = unet
|
| 77 |
+
|
| 78 |
+
print(f"rescale_cfg = {cfg}")
|
modules/processing_scripts/sampler.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
|
| 3 |
+
from modules import scripts, sd_samplers, sd_schedulers
|
| 4 |
+
from modules.infotext_utils import PasteField
|
| 5 |
+
from modules.ui_components import FormRow
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class ScriptSampler(scripts.ScriptBuiltinUI):
|
| 9 |
+
section = "sampler"
|
| 10 |
+
|
| 11 |
+
def __init__(self):
|
| 12 |
+
self.steps = None
|
| 13 |
+
self.sampler_name = None
|
| 14 |
+
self.scheduler = None
|
| 15 |
+
|
| 16 |
+
def title(self):
|
| 17 |
+
return "Sampler"
|
| 18 |
+
|
| 19 |
+
def ui(self, is_img2img):
|
| 20 |
+
sampler_names = [x.name for x in sd_samplers.visible_samplers()]
|
| 21 |
+
scheduler_names = [x.label for x in sd_schedulers.schedulers]
|
| 22 |
+
|
| 23 |
+
with FormRow(elem_id=f"sampler_selection_{self.tabname}"):
|
| 24 |
+
self.sampler_name = gr.Dropdown(label="Sampling method", elem_id=f"{self.tabname}_sampling", choices=sampler_names, value=sampler_names[0])
|
| 25 |
+
self.scheduler = gr.Dropdown(label="Schedule type", elem_id=f"{self.tabname}_scheduler", choices=scheduler_names, value=scheduler_names[0])
|
| 26 |
+
self.steps = gr.Slider(minimum=1, maximum=150, step=1, elem_id=f"{self.tabname}_steps", label="Sampling steps", value=20)
|
| 27 |
+
|
| 28 |
+
self.infotext_fields = [
|
| 29 |
+
PasteField(self.steps, "Steps", api="steps"),
|
| 30 |
+
PasteField(self.sampler_name, sd_samplers.get_sampler_from_infotext, api="sampler_name"),
|
| 31 |
+
PasteField(self.scheduler, sd_samplers.get_scheduler_from_infotext, api="scheduler"),
|
| 32 |
+
]
|
| 33 |
+
|
| 34 |
+
return self.steps, self.sampler_name, self.scheduler
|
| 35 |
+
|
| 36 |
+
def setup(self, p, steps, sampler_name, scheduler):
|
| 37 |
+
p.steps = steps
|
| 38 |
+
p.sampler_name = sampler_name
|
| 39 |
+
p.scheduler = scheduler
|
modules/processing_scripts/seed.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
|
| 3 |
+
import gradio as gr
|
| 4 |
+
|
| 5 |
+
from modules import errors, infotext_utils, scripts, ui
|
| 6 |
+
from modules.infotext_utils import PasteField
|
| 7 |
+
from modules.shared import cmd_opts
|
| 8 |
+
from modules.ui_components import ToolButton
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class ScriptSeed(scripts.ScriptBuiltinUI):
|
| 12 |
+
section = "seed"
|
| 13 |
+
create_group = False
|
| 14 |
+
|
| 15 |
+
def __init__(self):
|
| 16 |
+
self.seed = None
|
| 17 |
+
self.reuse_seed = None
|
| 18 |
+
self.reuse_subseed = None
|
| 19 |
+
|
| 20 |
+
def title(self):
|
| 21 |
+
return "Seed"
|
| 22 |
+
|
| 23 |
+
def show(self, is_img2img):
|
| 24 |
+
return scripts.AlwaysVisible
|
| 25 |
+
|
| 26 |
+
def ui(self, is_img2img):
|
| 27 |
+
with gr.Row(elem_id=self.elem_id("seed_row")):
|
| 28 |
+
if cmd_opts.use_textbox_seed:
|
| 29 |
+
self.seed = gr.Textbox(label="Seed", value="-1", elem_id=self.elem_id("seed"), min_width=100)
|
| 30 |
+
else:
|
| 31 |
+
self.seed = gr.Number(label="Seed", value=-1, elem_id=self.elem_id("seed"), min_width=100, precision=0)
|
| 32 |
+
|
| 33 |
+
random_seed = ToolButton(ui.random_symbol, elem_id=self.elem_id("random_seed"), tooltip="Set seed to -1, which will cause a new random number to be used every time")
|
| 34 |
+
reuse_seed = ToolButton(ui.reuse_symbol, elem_id=self.elem_id("reuse_seed"), tooltip="Reuse seed from last generation, mostly useful if it was randomized")
|
| 35 |
+
|
| 36 |
+
seed_checkbox = gr.Checkbox(label="Extra", elem_id=self.elem_id("subseed_show"), value=False, scale=0, min_width=60)
|
| 37 |
+
|
| 38 |
+
with gr.Group(visible=False, elem_id=self.elem_id("seed_extras")) as seed_extras:
|
| 39 |
+
with gr.Row(elem_id=self.elem_id("subseed_row")):
|
| 40 |
+
subseed = gr.Number(label="Variation seed", value=-1, elem_id=self.elem_id("subseed"), precision=0)
|
| 41 |
+
random_subseed = ToolButton(ui.random_symbol, elem_id=self.elem_id("random_subseed"))
|
| 42 |
+
reuse_subseed = ToolButton(ui.reuse_symbol, elem_id=self.elem_id("reuse_subseed"))
|
| 43 |
+
subseed_strength = gr.Slider(label="Variation strength", value=0.0, minimum=0, maximum=1, step=0.01, elem_id=self.elem_id("subseed_strength"))
|
| 44 |
+
|
| 45 |
+
with gr.Row(elem_id=self.elem_id("seed_resize_from_row")):
|
| 46 |
+
seed_resize_from_w = gr.Slider(minimum=0, maximum=2048, step=8, label="Resize seed from width", value=0, elem_id=self.elem_id("seed_resize_from_w"))
|
| 47 |
+
seed_resize_from_h = gr.Slider(minimum=0, maximum=2048, step=8, label="Resize seed from height", value=0, elem_id=self.elem_id("seed_resize_from_h"))
|
| 48 |
+
|
| 49 |
+
random_seed.click(fn=None, _js=f'() => {{ setRandomSeed("{self.elem_id("seed")}"); }}', show_progress=False, queue=False)
|
| 50 |
+
random_subseed.click(fn=None, _js=f'() => {{ setRandomSeed("{self.elem_id("subseed")}"); }}', show_progress=False, queue=False)
|
| 51 |
+
|
| 52 |
+
seed_checkbox.change(lambda x: gr.update(visible=x), show_progress=False, inputs=[seed_checkbox], outputs=[seed_extras])
|
| 53 |
+
|
| 54 |
+
self.infotext_fields = [
|
| 55 |
+
PasteField(self.seed, "Seed", api="seed"),
|
| 56 |
+
PasteField(seed_checkbox, lambda d: "Variation seed" in d or "Seed resize from-1" in d),
|
| 57 |
+
PasteField(subseed, "Variation seed", api="subseed"),
|
| 58 |
+
PasteField(subseed_strength, "Variation seed strength", api="subseed_strength"),
|
| 59 |
+
PasteField(seed_resize_from_w, "Seed resize from-1", api="seed_resize_from_h"),
|
| 60 |
+
PasteField(seed_resize_from_h, "Seed resize from-2", api="seed_resize_from_w"),
|
| 61 |
+
]
|
| 62 |
+
|
| 63 |
+
self.on_after_component(lambda x: connect_reuse_seed(self.seed, reuse_seed, x.component, False), elem_id=f"generation_info_{self.tabname}")
|
| 64 |
+
self.on_after_component(lambda x: connect_reuse_seed(subseed, reuse_subseed, x.component, True), elem_id=f"generation_info_{self.tabname}")
|
| 65 |
+
|
| 66 |
+
return self.seed, seed_checkbox, subseed, subseed_strength, seed_resize_from_w, seed_resize_from_h
|
| 67 |
+
|
| 68 |
+
def setup(self, p, seed, seed_checkbox, subseed, subseed_strength, seed_resize_from_w, seed_resize_from_h):
|
| 69 |
+
p.seed = seed
|
| 70 |
+
|
| 71 |
+
if seed_checkbox and subseed_strength > 0:
|
| 72 |
+
p.subseed = subseed
|
| 73 |
+
p.subseed_strength = subseed_strength
|
| 74 |
+
|
| 75 |
+
if seed_checkbox and seed_resize_from_w > 0 and seed_resize_from_h > 0:
|
| 76 |
+
p.seed_resize_from_w = seed_resize_from_w
|
| 77 |
+
p.seed_resize_from_h = seed_resize_from_h
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def connect_reuse_seed(seed: gr.Number, reuse_seed: gr.Button, generation_info: gr.Textbox, is_subseed):
|
| 81 |
+
"""
|
| 82 |
+
Connects a "reuse (sub)seed" button's click event so that it copies last used (sub)seed value
|
| 83 |
+
from generation info the to the seed field. If copying subseed and subseed strength was 0,
|
| 84 |
+
i.e. no variation seed was used, it copies the normal seed value instead.
|
| 85 |
+
"""
|
| 86 |
+
|
| 87 |
+
def copy_seed(gen_info_string: str, index):
|
| 88 |
+
res = -1
|
| 89 |
+
try:
|
| 90 |
+
gen_info = json.loads(gen_info_string)
|
| 91 |
+
infotext = gen_info.get("infotexts")[index]
|
| 92 |
+
gen_parameters = infotext_utils.parse_generation_parameters(infotext, [])
|
| 93 |
+
res = int(gen_parameters.get("Variation seed" if is_subseed else "Seed", -1))
|
| 94 |
+
except Exception:
|
| 95 |
+
if gen_info_string:
|
| 96 |
+
errors.report(f"Error retrieving seed from generation info: {gen_info_string}", exc_info=True)
|
| 97 |
+
|
| 98 |
+
return [res, gr.skip()]
|
| 99 |
+
|
| 100 |
+
reuse_seed.click(fn=copy_seed, _js="(x, y) => [x, selected_gallery_index()]", show_progress=False, inputs=[generation_info, seed], outputs=[seed, seed])
|
modules/profiling.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
|
| 3 |
+
from modules import shared, ui_gradio_extensions
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class Profiler:
|
| 7 |
+
def __init__(self):
|
| 8 |
+
if not shared.opts.profiling_enable:
|
| 9 |
+
self.profiler = None
|
| 10 |
+
return
|
| 11 |
+
|
| 12 |
+
activities = []
|
| 13 |
+
if "CPU" in shared.opts.profiling_activities:
|
| 14 |
+
activities.append(torch.profiler.ProfilerActivity.CPU)
|
| 15 |
+
if "CUDA" in shared.opts.profiling_activities:
|
| 16 |
+
activities.append(torch.profiler.ProfilerActivity.CUDA)
|
| 17 |
+
|
| 18 |
+
if not activities:
|
| 19 |
+
self.profiler = None
|
| 20 |
+
return
|
| 21 |
+
|
| 22 |
+
self.profiler = torch.profiler.profile(
|
| 23 |
+
activities=activities,
|
| 24 |
+
record_shapes=shared.opts.profiling_record_shapes,
|
| 25 |
+
profile_memory=shared.opts.profiling_profile_memory,
|
| 26 |
+
with_stack=shared.opts.profiling_with_stack,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
def __enter__(self):
|
| 30 |
+
if self.profiler:
|
| 31 |
+
self.profiler.__enter__()
|
| 32 |
+
|
| 33 |
+
return self
|
| 34 |
+
|
| 35 |
+
def __exit__(self, exc_type, exc, exc_tb):
|
| 36 |
+
if self.profiler:
|
| 37 |
+
shared.state.textinfo = "Finishing profile..."
|
| 38 |
+
|
| 39 |
+
self.profiler.__exit__(exc_type, exc, exc_tb)
|
| 40 |
+
|
| 41 |
+
self.profiler.export_chrome_trace(shared.opts.profiling_filename)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def webpath():
|
| 45 |
+
return ui_gradio_extensions.webpath(shared.opts.profiling_filename)
|
modules/progress.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import base64
|
| 4 |
+
import io
|
| 5 |
+
import random
|
| 6 |
+
import string
|
| 7 |
+
import time
|
| 8 |
+
from collections import OrderedDict
|
| 9 |
+
from typing import List
|
| 10 |
+
|
| 11 |
+
import gradio as gr
|
| 12 |
+
from pydantic import BaseModel, Field
|
| 13 |
+
|
| 14 |
+
import modules.shared as shared
|
| 15 |
+
from modules.shared import opts
|
| 16 |
+
|
| 17 |
+
current_task = None
|
| 18 |
+
pending_tasks = OrderedDict()
|
| 19 |
+
finished_tasks = []
|
| 20 |
+
recorded_results = []
|
| 21 |
+
recorded_results_limit = 2
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def start_task(id_task):
|
| 25 |
+
global current_task
|
| 26 |
+
|
| 27 |
+
current_task = id_task
|
| 28 |
+
pending_tasks.pop(id_task, None)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def finish_task(id_task):
|
| 32 |
+
global current_task
|
| 33 |
+
|
| 34 |
+
if current_task == id_task:
|
| 35 |
+
current_task = None
|
| 36 |
+
|
| 37 |
+
finished_tasks.append(id_task)
|
| 38 |
+
if len(finished_tasks) > 16:
|
| 39 |
+
finished_tasks.pop(0)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def create_task_id(task_type):
|
| 43 |
+
N = 7
|
| 44 |
+
res = "".join(random.choices(string.ascii_uppercase + string.digits, k=N))
|
| 45 |
+
return f"task({task_type}-{res})"
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def record_results(id_task, res):
|
| 49 |
+
recorded_results.append((id_task, res))
|
| 50 |
+
if len(recorded_results) > recorded_results_limit:
|
| 51 |
+
recorded_results.pop(0)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def add_task_to_queue(id_job):
|
| 55 |
+
pending_tasks[id_job] = time.time()
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class PendingTasksResponse(BaseModel):
|
| 59 |
+
size: int = Field(title="Pending task size")
|
| 60 |
+
tasks: List[str] = Field(title="Pending task ids")
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class ProgressRequest(BaseModel):
|
| 64 |
+
id_task: str = Field(default=None, title="Task ID", description="id of the task to get progress for")
|
| 65 |
+
id_live_preview: int = Field(default=-1, title="Live preview image ID", description="id of last received last preview image")
|
| 66 |
+
live_preview: bool = Field(default=True, title="Include live preview", description="boolean flag indicating whether to include the live preview image")
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class ProgressResponse(BaseModel):
|
| 70 |
+
active: bool = Field(title="Whether the task is being worked on right now")
|
| 71 |
+
queued: bool = Field(title="Whether the task is in queue")
|
| 72 |
+
completed: bool = Field(title="Whether the task has already finished")
|
| 73 |
+
progress: float | None = Field(default=None, title="Progress", description="The progress with a range of 0 to 1")
|
| 74 |
+
eta: float | None = Field(default=None, title="ETA in secs")
|
| 75 |
+
live_preview: str | None = Field(default=None, title="Live preview image", description="Current live preview; a data: uri")
|
| 76 |
+
id_live_preview: int | None = Field(default=None, title="Live preview image ID", description="Send this together with next request to prevent receiving same image")
|
| 77 |
+
textinfo: str | None = Field(default=None, title="Info text", description="Info text used by WebUI.")
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def setup_progress_api(app):
|
| 81 |
+
app.add_api_route("/internal/pending-tasks", get_pending_tasks, methods=["GET"])
|
| 82 |
+
return app.add_api_route("/internal/progress", progressapi, methods=["POST"], response_model=ProgressResponse)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def get_pending_tasks():
|
| 86 |
+
pending_tasks_ids = list(pending_tasks)
|
| 87 |
+
pending_len = len(pending_tasks_ids)
|
| 88 |
+
return PendingTasksResponse(size=pending_len, tasks=pending_tasks_ids)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def progressapi(req: ProgressRequest):
|
| 92 |
+
active = req.id_task == current_task
|
| 93 |
+
queued = req.id_task in pending_tasks
|
| 94 |
+
completed = req.id_task in finished_tasks
|
| 95 |
+
|
| 96 |
+
if not active:
|
| 97 |
+
textinfo = "Waiting..."
|
| 98 |
+
if queued:
|
| 99 |
+
sorted_queued = sorted(pending_tasks.keys(), key=lambda x: pending_tasks[x])
|
| 100 |
+
queue_index = sorted_queued.index(req.id_task)
|
| 101 |
+
textinfo = "In queue: {}/{}".format(queue_index + 1, len(sorted_queued))
|
| 102 |
+
return ProgressResponse(active=active, queued=queued, completed=completed, id_live_preview=-1, textinfo=textinfo)
|
| 103 |
+
|
| 104 |
+
progress = 0
|
| 105 |
+
|
| 106 |
+
job_count, job_no = shared.state.job_count, shared.state.job_no
|
| 107 |
+
sampling_steps, sampling_step = shared.state.sampling_steps, shared.state.sampling_step
|
| 108 |
+
|
| 109 |
+
if job_count > 0:
|
| 110 |
+
progress += job_no / job_count
|
| 111 |
+
if sampling_steps > 0 and job_count > 0:
|
| 112 |
+
progress += 1 / job_count * sampling_step / sampling_steps
|
| 113 |
+
|
| 114 |
+
progress = min(progress, 1)
|
| 115 |
+
|
| 116 |
+
elapsed_since_start = time.time() - shared.state.time_start
|
| 117 |
+
predicted_duration = elapsed_since_start / progress if progress > 0 else None
|
| 118 |
+
eta = predicted_duration - elapsed_since_start if predicted_duration is not None else None
|
| 119 |
+
|
| 120 |
+
live_preview = None
|
| 121 |
+
id_live_preview = req.id_live_preview
|
| 122 |
+
|
| 123 |
+
if opts.live_previews_enable and req.live_preview:
|
| 124 |
+
shared.state.set_current_image()
|
| 125 |
+
if shared.state.id_live_preview != req.id_live_preview:
|
| 126 |
+
image = shared.state.current_image
|
| 127 |
+
if image is not None:
|
| 128 |
+
buffered = io.BytesIO()
|
| 129 |
+
|
| 130 |
+
if opts.live_previews_image_format == "png":
|
| 131 |
+
# using optimize for large images takes an enormous amount of time
|
| 132 |
+
if max(*image.size) <= 256:
|
| 133 |
+
save_kwargs = {"optimize": True}
|
| 134 |
+
else:
|
| 135 |
+
save_kwargs = {"optimize": False, "compress_level": 1}
|
| 136 |
+
|
| 137 |
+
else:
|
| 138 |
+
image = image.convert("RGB")
|
| 139 |
+
save_kwargs = {}
|
| 140 |
+
|
| 141 |
+
image.save(buffered, format=opts.live_previews_image_format, **save_kwargs)
|
| 142 |
+
base64_image = base64.b64encode(buffered.getvalue()).decode("ascii")
|
| 143 |
+
live_preview = f"data:image/{opts.live_previews_image_format};base64,{base64_image}"
|
| 144 |
+
id_live_preview = shared.state.id_live_preview
|
| 145 |
+
|
| 146 |
+
return ProgressResponse(active=active, queued=queued, completed=completed, progress=progress, eta=eta, live_preview=live_preview, id_live_preview=id_live_preview, textinfo=shared.state.textinfo)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def restore_progress(id_task):
|
| 150 |
+
while id_task == current_task or id_task in pending_tasks:
|
| 151 |
+
time.sleep(0.1)
|
| 152 |
+
|
| 153 |
+
res = next(iter([x[1] for x in recorded_results if id_task == x[0]]), None)
|
| 154 |
+
if res is not None:
|
| 155 |
+
return res
|
| 156 |
+
|
| 157 |
+
return gr.skip(), gr.skip(), gr.skip(), f"Couldn't restore progress for {id_task}: results either have been discarded or never were obtained"
|
modules/prompt_parser.py
ADDED
|
@@ -0,0 +1,490 @@
|
|
|
|
|
|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with a [mountain:lake:0.25] and [an oak:a christmas tree:0.75] [in foreground::0.6] [:in background:0.25] [shoddy:masterful:0.5]"
|
| 10 |
+
# will be represented with prompt_schedule like this (assuming steps=100):
|
| 11 |
+
# [25, 'fantasy landscape with a mountain and an oak in foreground shoddy']
|
| 12 |
+
# [50, 'fantasy landscape with a lake and an oak in foreground in background shoddy']
|
| 13 |
+
# [60, 'fantasy landscape with a lake and an oak in foreground in background masterful']
|
| 14 |
+
# [75, 'fantasy landscape with a lake and an oak in background masterful']
|
| 15 |
+
# [100, 'fantasy landscape with a lake and a christmas tree in background masterful']
|
| 16 |
+
|
| 17 |
+
schedule_parser = lark.Lark(
|
| 18 |
+
r"""
|
| 19 |
+
!start: (prompt | /[][():]/+)*
|
| 20 |
+
prompt: (emphasized | scheduled | alternate | plain | WHITESPACE)*
|
| 21 |
+
!emphasized: "(" prompt ")"
|
| 22 |
+
| "(" prompt ":" prompt ")"
|
| 23 |
+
| "[" prompt "]"
|
| 24 |
+
scheduled: "[" [prompt ":"] prompt ":" [WHITESPACE] NUMBER [WHITESPACE] "]"
|
| 25 |
+
alternate: "[" prompt ("|" [prompt])+ "]"
|
| 26 |
+
WHITESPACE: /\s+/
|
| 27 |
+
plain: /([^\\\[\]():|]|\\.)+/
|
| 28 |
+
%import common.SIGNED_NUMBER -> NUMBER
|
| 29 |
+
"""
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def get_learned_conditioning_prompt_schedules(prompts, base_steps, hires_steps=None, use_old_scheduling=False):
|
| 34 |
+
r"""
|
| 35 |
+
>>> g = lambda p: get_learned_conditioning_prompt_schedules([p], 10)[0]
|
| 36 |
+
>>> g("test")
|
| 37 |
+
[[10, 'test']]
|
| 38 |
+
>>> g("a [b:3]")
|
| 39 |
+
[[3, 'a '], [10, 'a b']]
|
| 40 |
+
>>> g("a [b: 3]")
|
| 41 |
+
[[3, 'a '], [10, 'a b']]
|
| 42 |
+
>>> g("a [[[b]]:2]")
|
| 43 |
+
[[2, 'a '], [10, 'a [[b]]']]
|
| 44 |
+
>>> g("[(a:2):3]")
|
| 45 |
+
[[3, ''], [10, '(a:2)']]
|
| 46 |
+
>>> g("a [b : c : 1] d")
|
| 47 |
+
[[1, 'a b d'], [10, 'a c d']]
|
| 48 |
+
>>> g("a[b:[c:d:2]:1]e")
|
| 49 |
+
[[1, 'abe'], [2, 'ace'], [10, 'ade']]
|
| 50 |
+
>>> g("a [unbalanced")
|
| 51 |
+
[[10, 'a [unbalanced']]
|
| 52 |
+
>>> g("a [b:.5] c")
|
| 53 |
+
[[5, 'a c'], [10, 'a b c']]
|
| 54 |
+
>>> g("a [{b|d{:.5] c") # not handling this right now
|
| 55 |
+
[[5, 'a c'], [10, 'a {b|d{ c']]
|
| 56 |
+
>>> g("((a][:b:c [d:3]")
|
| 57 |
+
[[3, '((a][:b:c '], [10, '((a][:b:c d']]
|
| 58 |
+
>>> g("[a|(b:1.1)]")
|
| 59 |
+
[[1, 'a'], [2, '(b:1.1)'], [3, 'a'], [4, '(b:1.1)'], [5, 'a'], [6, '(b:1.1)'], [7, 'a'], [8, '(b:1.1)'], [9, 'a'], [10, '(b:1.1)']]
|
| 60 |
+
>>> g("[fe|]male")
|
| 61 |
+
[[1, 'female'], [2, 'male'], [3, 'female'], [4, 'male'], [5, 'female'], [6, 'male'], [7, 'female'], [8, 'male'], [9, 'female'], [10, 'male']]
|
| 62 |
+
>>> g("[fe|||]male")
|
| 63 |
+
[[1, 'female'], [2, 'male'], [3, 'male'], [4, 'male'], [5, 'female'], [6, 'male'], [7, 'male'], [8, 'male'], [9, 'female'], [10, 'male']]
|
| 64 |
+
>>> g = lambda p: get_learned_conditioning_prompt_schedules([p], 10, 10)[0]
|
| 65 |
+
>>> g("a [b:.5] c")
|
| 66 |
+
[[10, 'a b c']]
|
| 67 |
+
>>> g("a [b:1.5] c")
|
| 68 |
+
[[5, 'a c'], [10, 'a b c']]
|
| 69 |
+
"""
|
| 70 |
+
|
| 71 |
+
if hires_steps is None or use_old_scheduling:
|
| 72 |
+
int_offset = 0
|
| 73 |
+
flt_offset = 0
|
| 74 |
+
steps = base_steps
|
| 75 |
+
else:
|
| 76 |
+
int_offset = base_steps
|
| 77 |
+
flt_offset = 1.0
|
| 78 |
+
steps = hires_steps
|
| 79 |
+
|
| 80 |
+
def collect_steps(steps, tree):
|
| 81 |
+
res = [steps]
|
| 82 |
+
|
| 83 |
+
class CollectSteps(lark.Visitor):
|
| 84 |
+
def scheduled(self, tree):
|
| 85 |
+
s = tree.children[-2]
|
| 86 |
+
v = float(s)
|
| 87 |
+
if use_old_scheduling:
|
| 88 |
+
v = v * steps if v < 1 else v
|
| 89 |
+
else:
|
| 90 |
+
if "." in s:
|
| 91 |
+
v = (v - flt_offset) * steps
|
| 92 |
+
else:
|
| 93 |
+
v = v - int_offset
|
| 94 |
+
tree.children[-2] = min(steps, int(v))
|
| 95 |
+
if tree.children[-2] >= 1:
|
| 96 |
+
res.append(tree.children[-2])
|
| 97 |
+
|
| 98 |
+
def alternate(self, tree):
|
| 99 |
+
res.extend(range(1, steps + 1))
|
| 100 |
+
|
| 101 |
+
CollectSteps().visit(tree)
|
| 102 |
+
return sorted(set(res))
|
| 103 |
+
|
| 104 |
+
def at_step(step, tree):
|
| 105 |
+
class AtStep(lark.Transformer):
|
| 106 |
+
def scheduled(self, args):
|
| 107 |
+
before, after, _, when, _ = args
|
| 108 |
+
yield before or () if step <= when else after
|
| 109 |
+
|
| 110 |
+
def alternate(self, args):
|
| 111 |
+
args = ["" if not arg else arg for arg in args]
|
| 112 |
+
yield args[(step - 1) % len(args)]
|
| 113 |
+
|
| 114 |
+
def start(self, args):
|
| 115 |
+
def flatten(x):
|
| 116 |
+
if isinstance(x, str):
|
| 117 |
+
yield x
|
| 118 |
+
else:
|
| 119 |
+
for gen in x:
|
| 120 |
+
yield from flatten(gen)
|
| 121 |
+
|
| 122 |
+
return "".join(flatten(args))
|
| 123 |
+
|
| 124 |
+
def plain(self, args):
|
| 125 |
+
yield args[0].value
|
| 126 |
+
|
| 127 |
+
def __default__(self, data, children, meta):
|
| 128 |
+
for child in children:
|
| 129 |
+
yield child
|
| 130 |
+
|
| 131 |
+
return AtStep().transform(tree)
|
| 132 |
+
|
| 133 |
+
def get_schedule(prompt):
|
| 134 |
+
try:
|
| 135 |
+
tree = schedule_parser.parse(prompt)
|
| 136 |
+
except lark.exceptions.LarkError:
|
| 137 |
+
if 0:
|
| 138 |
+
import traceback
|
| 139 |
+
|
| 140 |
+
traceback.print_exc()
|
| 141 |
+
return [[steps, prompt]]
|
| 142 |
+
return [[t, at_step(t, tree)] for t in collect_steps(steps, tree)]
|
| 143 |
+
|
| 144 |
+
promptdict = {prompt: get_schedule(prompt) for prompt in set(prompts)}
|
| 145 |
+
return [promptdict[prompt] for prompt in prompts]
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
ScheduledPromptConditioning = namedtuple("ScheduledPromptConditioning", ["end_at_step", "cond"])
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
class SdConditioning(list):
|
| 152 |
+
"""
|
| 153 |
+
A list with prompts for stable diffusion's conditioner model.
|
| 154 |
+
Can also specify width and height of created image - SDXL needs it.
|
| 155 |
+
"""
|
| 156 |
+
|
| 157 |
+
def __init__(self, prompts, is_negative_prompt=False, width=None, height=None, copy_from=None, distilled_cfg_scale=None):
|
| 158 |
+
super().__init__()
|
| 159 |
+
self.extend(prompts)
|
| 160 |
+
|
| 161 |
+
if copy_from is None:
|
| 162 |
+
copy_from = prompts
|
| 163 |
+
|
| 164 |
+
self.is_negative_prompt = is_negative_prompt or getattr(copy_from, "is_negative_prompt", False)
|
| 165 |
+
self.width = width or getattr(copy_from, "width", None)
|
| 166 |
+
self.height = height or getattr(copy_from, "height", None)
|
| 167 |
+
self.distilled_cfg_scale = distilled_cfg_scale or getattr(copy_from, "distilled_cfg_scale", None)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def get_learned_conditioning(model, prompts: SdConditioning | list[str], steps, hires_steps=None, use_old_scheduling=False):
|
| 171 |
+
r"""
|
| 172 |
+
converts a list of prompts into a list of prompt schedules - each schedule is a list of ScheduledPromptConditioning,
|
| 173 |
+
specifying the condition (cond), and the sampling step at which this condition is to be replaced by the next one.
|
| 174 |
+
|
| 175 |
+
Input:
|
| 176 |
+
(model, ['a red crown', 'a [blue:green:5] jeweled crown'], 20)
|
| 177 |
+
|
| 178 |
+
Output:
|
| 179 |
+
[
|
| 180 |
+
[
|
| 181 |
+
ScheduledPromptConditioning(end_at_step=20, cond=tensor([[-0.3886, 0.0229, -0.0523, ..., -0.4901, -0.3066, 0.0674], ..., [ 0.3317, -0.5102, -0.4066, ..., 0.4119, -0.7647, -1.0160]], device='cuda:0'))
|
| 182 |
+
],
|
| 183 |
+
[
|
| 184 |
+
ScheduledPromptConditioning(end_at_step=5, cond=tensor([[-0.3886, 0.0229, -0.0522, ..., -0.4901, -0.3067, 0.0673], ..., [-0.0192, 0.3867, -0.4644, ..., 0.1135, -0.3696, -0.4625]], device='cuda:0')),
|
| 185 |
+
ScheduledPromptConditioning(end_at_step=20, cond=tensor([[-0.3886, 0.0229, -0.0522, ..., -0.4901, -0.3067, 0.0673], ..., [-0.7352, -0.4356, -0.7888, ..., 0.6994, -0.4312, -1.2593]], device='cuda:0'))
|
| 186 |
+
]
|
| 187 |
+
]
|
| 188 |
+
"""
|
| 189 |
+
res = []
|
| 190 |
+
|
| 191 |
+
prompt_schedules = get_learned_conditioning_prompt_schedules(prompts, steps, hires_steps, use_old_scheduling)
|
| 192 |
+
cache = {}
|
| 193 |
+
|
| 194 |
+
for prompt, prompt_schedule in zip(prompts, prompt_schedules):
|
| 195 |
+
|
| 196 |
+
cached = cache.get(prompt, None)
|
| 197 |
+
if cached is not None:
|
| 198 |
+
res.append(cached)
|
| 199 |
+
continue
|
| 200 |
+
|
| 201 |
+
texts = SdConditioning([x[1] for x in prompt_schedule], copy_from=prompts)
|
| 202 |
+
conds = model.get_learned_conditioning(texts)
|
| 203 |
+
|
| 204 |
+
cond_schedule = []
|
| 205 |
+
for i, (end_at_step, _) in enumerate(prompt_schedule):
|
| 206 |
+
if isinstance(conds, dict):
|
| 207 |
+
cond = {k: v[i] for k, v in conds.items()}
|
| 208 |
+
else:
|
| 209 |
+
cond = conds[i]
|
| 210 |
+
|
| 211 |
+
cond_schedule.append(ScheduledPromptConditioning(end_at_step, cond))
|
| 212 |
+
|
| 213 |
+
cache[prompt] = cond_schedule
|
| 214 |
+
res.append(cond_schedule)
|
| 215 |
+
|
| 216 |
+
return res
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
re_AND = re.compile(r"\bAND\b")
|
| 220 |
+
re_weight = re.compile(r"^((?:\s|.)*?)(?:\s*:\s*([-+]?(?:\d+\.?|\d*\.\d+)))?\s*$")
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def get_multicond_prompt_list(prompts: SdConditioning | list[str]):
|
| 224 |
+
res_indexes = []
|
| 225 |
+
|
| 226 |
+
prompt_indexes = {}
|
| 227 |
+
prompt_flat_list = SdConditioning(prompts)
|
| 228 |
+
prompt_flat_list.clear()
|
| 229 |
+
|
| 230 |
+
for prompt in prompts:
|
| 231 |
+
subprompts = re_AND.split(prompt)
|
| 232 |
+
|
| 233 |
+
indexes = []
|
| 234 |
+
for subprompt in subprompts:
|
| 235 |
+
match = re_weight.search(subprompt)
|
| 236 |
+
|
| 237 |
+
text, weight = match.groups() if match is not None else (subprompt, 1.0)
|
| 238 |
+
|
| 239 |
+
weight = float(weight) if weight is not None else 1.0
|
| 240 |
+
|
| 241 |
+
index = prompt_indexes.get(text, None)
|
| 242 |
+
if index is None:
|
| 243 |
+
index = len(prompt_flat_list)
|
| 244 |
+
prompt_flat_list.append(text)
|
| 245 |
+
prompt_indexes[text] = index
|
| 246 |
+
|
| 247 |
+
indexes.append((index, weight))
|
| 248 |
+
|
| 249 |
+
res_indexes.append(indexes)
|
| 250 |
+
|
| 251 |
+
return res_indexes, prompt_flat_list, prompt_indexes
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
class ComposableScheduledPromptConditioning:
|
| 255 |
+
def __init__(self, schedules, weight=1.0):
|
| 256 |
+
self.schedules: list[ScheduledPromptConditioning] = schedules
|
| 257 |
+
self.weight: float = weight
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
class MulticondLearnedConditioning:
|
| 261 |
+
def __init__(self, shape, batch):
|
| 262 |
+
self.shape: tuple = shape # the shape field is needed to send this object to DDIM/PLMS
|
| 263 |
+
self.batch: list[list[ComposableScheduledPromptConditioning]] = batch
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
def get_multicond_learned_conditioning(model, prompts, steps, hires_steps=None, use_old_scheduling=False) -> MulticondLearnedConditioning:
|
| 267 |
+
"""
|
| 268 |
+
same as get_learned_conditioning, but returns a list of ScheduledPromptConditioning along with the weight objects for each prompt.
|
| 269 |
+
For each prompt, the list is obtained by splitting the prompt using the AND separator.
|
| 270 |
+
"""
|
| 271 |
+
|
| 272 |
+
res_indexes, prompt_flat_list, prompt_indexes = get_multicond_prompt_list(prompts)
|
| 273 |
+
|
| 274 |
+
learned_conditioning = get_learned_conditioning(model, prompt_flat_list, steps, hires_steps, use_old_scheduling)
|
| 275 |
+
|
| 276 |
+
res = []
|
| 277 |
+
for indexes in res_indexes:
|
| 278 |
+
res.append([ComposableScheduledPromptConditioning(learned_conditioning[i], weight) for i, weight in indexes])
|
| 279 |
+
|
| 280 |
+
return MulticondLearnedConditioning(shape=(len(prompts),), batch=res)
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
class DictWithShape(dict):
|
| 284 |
+
def __init__(self, x, shape=None):
|
| 285 |
+
super().__init__()
|
| 286 |
+
self.update(x)
|
| 287 |
+
|
| 288 |
+
@property
|
| 289 |
+
def shape(self):
|
| 290 |
+
return self["crossattn"].shape
|
| 291 |
+
|
| 292 |
+
def to(self, *args, **kwargs):
|
| 293 |
+
for k in self.keys():
|
| 294 |
+
if isinstance(self[k], torch.Tensor):
|
| 295 |
+
self[k] = self[k].to(*args, **kwargs)
|
| 296 |
+
return self
|
| 297 |
+
|
| 298 |
+
def advanced_indexing(self, item):
|
| 299 |
+
result = {}
|
| 300 |
+
for k in self.keys():
|
| 301 |
+
if isinstance(self[k], torch.Tensor):
|
| 302 |
+
result[k] = self[k][item]
|
| 303 |
+
return DictWithShape(result)
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
def reconstruct_cond_batch(c: list[list[ScheduledPromptConditioning]], current_step):
|
| 307 |
+
param = c[0][0].cond
|
| 308 |
+
is_dict = isinstance(param, dict)
|
| 309 |
+
|
| 310 |
+
if is_dict:
|
| 311 |
+
dict_cond = param
|
| 312 |
+
res = {k: torch.zeros((len(c),) + param.shape, device=param.device, dtype=param.dtype) for k, param in dict_cond.items()}
|
| 313 |
+
res = DictWithShape(res)
|
| 314 |
+
else:
|
| 315 |
+
res = torch.zeros((len(c),) + param.shape, device=param.device, dtype=param.dtype)
|
| 316 |
+
|
| 317 |
+
for i, cond_schedule in enumerate(c):
|
| 318 |
+
target_index = 0
|
| 319 |
+
for current, entry in enumerate(cond_schedule):
|
| 320 |
+
if current_step <= entry.end_at_step:
|
| 321 |
+
target_index = current
|
| 322 |
+
break
|
| 323 |
+
|
| 324 |
+
if is_dict:
|
| 325 |
+
for k, param in cond_schedule[target_index].cond.items():
|
| 326 |
+
res[k][i] = param
|
| 327 |
+
else:
|
| 328 |
+
res[i] = cond_schedule[target_index].cond
|
| 329 |
+
|
| 330 |
+
return res
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def stack_conds(tensors):
|
| 334 |
+
try:
|
| 335 |
+
result = torch.stack(tensors)
|
| 336 |
+
except:
|
| 337 |
+
# if prompts have wildly different lengths above the limit we'll get tensors of different shapes
|
| 338 |
+
# and won't be able to torch.stack them. So this fixes that.
|
| 339 |
+
token_count = max([x.shape[0] for x in tensors])
|
| 340 |
+
for i in range(len(tensors)):
|
| 341 |
+
if tensors[i].shape[0] != token_count:
|
| 342 |
+
last_vector = tensors[i][-1:]
|
| 343 |
+
last_vector_repeated = last_vector.repeat([token_count - tensors[i].shape[0], 1])
|
| 344 |
+
tensors[i] = torch.vstack([tensors[i], last_vector_repeated])
|
| 345 |
+
result = torch.stack(tensors)
|
| 346 |
+
return result
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
def reconstruct_multicond_batch(c: MulticondLearnedConditioning, current_step):
|
| 350 |
+
param = c.batch[0][0].schedules[0].cond
|
| 351 |
+
|
| 352 |
+
tensors = []
|
| 353 |
+
conds_list = []
|
| 354 |
+
|
| 355 |
+
for composable_prompts in c.batch:
|
| 356 |
+
conds_for_batch = []
|
| 357 |
+
|
| 358 |
+
for composable_prompt in composable_prompts:
|
| 359 |
+
target_index = 0
|
| 360 |
+
for current, entry in enumerate(composable_prompt.schedules):
|
| 361 |
+
if current_step <= entry.end_at_step:
|
| 362 |
+
target_index = current
|
| 363 |
+
break
|
| 364 |
+
|
| 365 |
+
conds_for_batch.append((len(tensors), composable_prompt.weight))
|
| 366 |
+
tensors.append(composable_prompt.schedules[target_index].cond)
|
| 367 |
+
|
| 368 |
+
conds_list.append(conds_for_batch)
|
| 369 |
+
|
| 370 |
+
if isinstance(tensors[0], dict):
|
| 371 |
+
keys = list(tensors[0].keys())
|
| 372 |
+
stacked = {k: stack_conds([x[k] for x in tensors]) for k in keys}
|
| 373 |
+
stacked = DictWithShape(stacked)
|
| 374 |
+
else:
|
| 375 |
+
stacked = stack_conds(tensors).to(device=param.device, dtype=param.dtype)
|
| 376 |
+
|
| 377 |
+
return conds_list, stacked
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
re_attention = re.compile(
|
| 381 |
+
r"""
|
| 382 |
+
\\\(|
|
| 383 |
+
\\\)|
|
| 384 |
+
\\\[|
|
| 385 |
+
\\]|
|
| 386 |
+
\\\\|
|
| 387 |
+
\\|
|
| 388 |
+
\(|
|
| 389 |
+
\[|
|
| 390 |
+
:\s*([+-]?[.\d]+)\s*\)|
|
| 391 |
+
\)|
|
| 392 |
+
]|
|
| 393 |
+
[^\\()\[\]:]+|
|
| 394 |
+
:
|
| 395 |
+
""",
|
| 396 |
+
re.X,
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
re_break = re.compile(r"\s*\bBREAK\b\s*", re.S)
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
def parse_prompt_attention(text):
|
| 403 |
+
r"""
|
| 404 |
+
Parses a string with attention tokens and returns a list of pairs: text and its associated weight.
|
| 405 |
+
Accepted tokens are:
|
| 406 |
+
(abc) - increases attention to abc by a multiplier of 1.1
|
| 407 |
+
(abc:3.12) - increases attention to abc by a multiplier of 3.12
|
| 408 |
+
[abc] - decreases attention to abc by a multiplier of 1.1
|
| 409 |
+
\( - literal character '('
|
| 410 |
+
\[ - literal character '['
|
| 411 |
+
\) - literal character ')'
|
| 412 |
+
\] - literal character ']'
|
| 413 |
+
\\ - literal character '\'
|
| 414 |
+
anything else - just text
|
| 415 |
+
|
| 416 |
+
>>> parse_prompt_attention('normal text')
|
| 417 |
+
[['normal text', 1.0]]
|
| 418 |
+
>>> parse_prompt_attention('an (important) word')
|
| 419 |
+
[['an ', 1.0], ['important', 1.1], [' word', 1.0]]
|
| 420 |
+
>>> parse_prompt_attention('(unbalanced')
|
| 421 |
+
[['unbalanced', 1.1]]
|
| 422 |
+
>>> parse_prompt_attention('\(literal\]')
|
| 423 |
+
[['(literal]', 1.0]]
|
| 424 |
+
>>> parse_prompt_attention('(unnecessary)(parens)')
|
| 425 |
+
[['unnecessaryparens', 1.1]]
|
| 426 |
+
>>> parse_prompt_attention('a (((house:1.3)) [on] a (hill:0.5), sun, (((sky))).')
|
| 427 |
+
[['a ', 1.0],
|
| 428 |
+
['house', 1.5730000000000004],
|
| 429 |
+
[' ', 1.1],
|
| 430 |
+
['on', 1.0],
|
| 431 |
+
[' a ', 1.1],
|
| 432 |
+
['hill', 0.55],
|
| 433 |
+
[', sun, ', 1.1],
|
| 434 |
+
['sky', 1.4641000000000006],
|
| 435 |
+
['.', 1.1]]
|
| 436 |
+
"""
|
| 437 |
+
|
| 438 |
+
res = []
|
| 439 |
+
round_brackets = []
|
| 440 |
+
square_brackets = []
|
| 441 |
+
|
| 442 |
+
round_bracket_multiplier = 1.1
|
| 443 |
+
square_bracket_multiplier = 1 / 1.1
|
| 444 |
+
|
| 445 |
+
def multiply_range(start_position, multiplier):
|
| 446 |
+
for p in range(start_position, len(res)):
|
| 447 |
+
res[p][1] *= multiplier
|
| 448 |
+
|
| 449 |
+
for m in re_attention.finditer(text):
|
| 450 |
+
text = m.group(0)
|
| 451 |
+
weight = m.group(1)
|
| 452 |
+
|
| 453 |
+
if text.startswith("\\"):
|
| 454 |
+
res.append([text[1:], 1.0])
|
| 455 |
+
elif text == "(":
|
| 456 |
+
round_brackets.append(len(res))
|
| 457 |
+
elif text == "[":
|
| 458 |
+
square_brackets.append(len(res))
|
| 459 |
+
elif weight is not None and round_brackets:
|
| 460 |
+
multiply_range(round_brackets.pop(), float(weight))
|
| 461 |
+
elif text == ")" and round_brackets:
|
| 462 |
+
multiply_range(round_brackets.pop(), round_bracket_multiplier)
|
| 463 |
+
elif text == "]" and square_brackets:
|
| 464 |
+
multiply_range(square_brackets.pop(), square_bracket_multiplier)
|
| 465 |
+
else:
|
| 466 |
+
parts = re.split(re_break, text)
|
| 467 |
+
for i, part in enumerate(parts):
|
| 468 |
+
if i > 0:
|
| 469 |
+
res.append(["BREAK", -1])
|
| 470 |
+
res.append([part, 1.0])
|
| 471 |
+
|
| 472 |
+
for pos in round_brackets:
|
| 473 |
+
multiply_range(pos, round_bracket_multiplier)
|
| 474 |
+
|
| 475 |
+
for pos in square_brackets:
|
| 476 |
+
multiply_range(pos, square_bracket_multiplier)
|
| 477 |
+
|
| 478 |
+
if len(res) == 0:
|
| 479 |
+
res = [["", 1.0]]
|
| 480 |
+
|
| 481 |
+
# merge runs of identical weights
|
| 482 |
+
i = 0
|
| 483 |
+
while i + 1 < len(res):
|
| 484 |
+
if res[i][1] == res[i + 1][1]:
|
| 485 |
+
res[i][0] += res[i + 1][0]
|
| 486 |
+
res.pop(i + 1)
|
| 487 |
+
else:
|
| 488 |
+
i += 1
|
| 489 |
+
|
| 490 |
+
return res
|