controlnet.py 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083
  1. import gc
  2. import os
  3. import logging
  4. from collections import OrderedDict
  5. from copy import copy
  6. from typing import Dict, Optional, Tuple
  7. import modules.scripts as scripts
  8. from modules import shared, devices, script_callbacks, processing, masking, images
  9. import gradio as gr
  10. from einops import rearrange
  11. from scripts import global_state, hook, external_code, processor, batch_hijack, controlnet_version, utils
  12. from scripts.controlnet_ui import controlnet_ui_group
  13. from scripts.cldm import PlugableControlModel
  14. from scripts.processor import *
  15. from scripts.adapter import PlugableAdapter
  16. from scripts.utils import load_state_dict, get_unique_axis0
  17. from scripts.hook import ControlParams, UnetHook, ControlModelType
  18. from scripts.controlnet_ui.controlnet_ui_group import ControlNetUiGroup, UiControlNetUnit
  19. from scripts.logging import logger
  20. from modules.processing import StableDiffusionProcessingImg2Img, StableDiffusionProcessingTxt2Img
  21. from modules.images import save_image
  22. import cv2
  23. import numpy as np
  24. import torch
  25. from pathlib import Path
  26. from PIL import Image, ImageFilter, ImageOps
  27. from scripts.lvminthin import lvmin_thin, nake_nms
  28. from scripts.processor import model_free_preprocessors
  29. gradio_compat = True
  30. try:
  31. from distutils.version import LooseVersion
  32. from importlib_metadata import version
  33. if LooseVersion(version("gradio")) < LooseVersion("3.10"):
  34. gradio_compat = False
  35. except ImportError:
  36. pass
  37. # Gradio 3.32 bug fix
  38. import tempfile
  39. gradio_tempfile_path = os.path.join(tempfile.gettempdir(), 'gradio')
  40. os.makedirs(gradio_tempfile_path, exist_ok=True)
  41. def find_closest_lora_model_name(search: str):
  42. if not search:
  43. return None
  44. if search in global_state.cn_models:
  45. return search
  46. search = search.lower()
  47. if search in global_state.cn_models_names:
  48. return global_state.cn_models_names.get(search)
  49. applicable = [name for name in global_state.cn_models_names.keys()
  50. if search in name.lower()]
  51. if not applicable:
  52. return None
  53. applicable = sorted(applicable, key=lambda name: len(name))
  54. return global_state.cn_models_names[applicable[0]]
  55. def swap_img2img_pipeline(p: processing.StableDiffusionProcessingImg2Img):
  56. p.__class__ = processing.StableDiffusionProcessingTxt2Img
  57. dummy = processing.StableDiffusionProcessingTxt2Img()
  58. for k,v in dummy.__dict__.items():
  59. if hasattr(p, k):
  60. continue
  61. setattr(p, k, v)
  62. global_state.update_cn_models()
  63. def image_dict_from_any(image) -> Optional[Dict[str, np.ndarray]]:
  64. if image is None:
  65. return None
  66. if isinstance(image, (tuple, list)):
  67. image = {'image': image[0], 'mask': image[1]}
  68. elif not isinstance(image, dict):
  69. image = {'image': image, 'mask': None}
  70. else: # type(image) is dict
  71. # copy to enable modifying the dict and prevent response serialization error
  72. image = dict(image)
  73. if isinstance(image['image'], str):
  74. if os.path.exists(image['image']):
  75. image['image'] = np.array(Image.open(image['image'])).astype('uint8')
  76. elif image['image']:
  77. image['image'] = external_code.to_base64_nparray(image['image'])
  78. else:
  79. image['image'] = None
  80. # If there is no image, return image with None image and None mask
  81. if image['image'] is None:
  82. image['mask'] = None
  83. return image
  84. if isinstance(image['mask'], str):
  85. if os.path.exists(image['mask']):
  86. image['mask'] = np.array(Image.open(image['mask'])).astype('uint8')
  87. elif image['mask']:
  88. image['mask'] = external_code.to_base64_nparray(image['mask'])
  89. else:
  90. image['mask'] = np.zeros_like(image['image'], dtype=np.uint8)
  91. elif image['mask'] is None:
  92. image['mask'] = np.zeros_like(image['image'], dtype=np.uint8)
  93. return image
  94. def image_has_mask(input_image: np.ndarray) -> bool:
  95. """
  96. Determine if an image has an alpha channel (mask) that is not empty.
  97. The function checks if the input image has three dimensions (height, width, channels),
  98. and if the third dimension (channel dimension) is of size 4 (presumably RGB + alpha).
  99. Then it checks if the maximum value in the alpha channel is greater than 127. This is
  100. presumably to check if there is any non-transparent (or semi-transparent) pixel in the
  101. image. A pixel is considered non-transparent if its alpha value is above 127.
  102. Args:
  103. input_image (np.ndarray): A 3D numpy array representing an image. The dimensions
  104. should represent [height, width, channels].
  105. Returns:
  106. bool: True if the image has a non-empty alpha channel, False otherwise.
  107. """
  108. return (
  109. input_image.ndim == 3 and
  110. input_image.shape[2] == 4 and
  111. np.max(input_image[:, :, 3]) > 127
  112. )
  113. def prepare_mask(
  114. mask: Image.Image, p: processing.StableDiffusionProcessing
  115. ) -> Image.Image:
  116. """
  117. Prepare an image mask for the inpainting process.
  118. This function takes as input a PIL Image object and an instance of the
  119. StableDiffusionProcessing class, and performs the following steps to prepare the mask:
  120. 1. Convert the mask to grayscale (mode "L").
  121. 2. If the 'inpainting_mask_invert' attribute of the processing instance is True,
  122. invert the mask colors.
  123. 3. If the 'mask_blur' attribute of the processing instance is greater than 0,
  124. apply a Gaussian blur to the mask with a radius equal to 'mask_blur'.
  125. Args:
  126. mask (Image.Image): The input mask as a PIL Image object.
  127. p (processing.StableDiffusionProcessing): An instance of the StableDiffusionProcessing class
  128. containing the processing parameters.
  129. Returns:
  130. mask (Image.Image): The prepared mask as a PIL Image object.
  131. """
  132. mask = mask.convert("L")
  133. if getattr(p, "inpainting_mask_invert", False):
  134. mask = ImageOps.invert(mask)
  135. if hasattr(p, 'mask_blur_x'):
  136. if getattr(p, "mask_blur_x", 0) > 0:
  137. np_mask = np.array(mask)
  138. kernel_size = 2 * int(2.5 * p.mask_blur_x + 0.5) + 1
  139. np_mask = cv2.GaussianBlur(np_mask, (kernel_size, 1), p.mask_blur_x)
  140. mask = Image.fromarray(np_mask)
  141. if getattr(p, "mask_blur_y", 0) > 0:
  142. np_mask = np.array(mask)
  143. kernel_size = 2 * int(2.5 * p.mask_blur_y + 0.5) + 1
  144. np_mask = cv2.GaussianBlur(np_mask, (1, kernel_size), p.mask_blur_y)
  145. mask = Image.fromarray(np_mask)
  146. else:
  147. if getattr(p, "mask_blur", 0) > 0:
  148. mask = mask.filter(ImageFilter.GaussianBlur(p.mask_blur))
  149. return mask
  150. def set_numpy_seed(p: processing.StableDiffusionProcessing) -> Optional[int]:
  151. """
  152. Set the random seed for NumPy based on the provided parameters.
  153. Args:
  154. p (processing.StableDiffusionProcessing): The instance of the StableDiffusionProcessing class.
  155. Returns:
  156. Optional[int]: The computed random seed if successful, or None if an exception occurs.
  157. This function sets the random seed for NumPy using the seed and subseed values from the given instance of
  158. StableDiffusionProcessing. If either seed or subseed is -1, it uses the first value from `all_seeds`.
  159. Otherwise, it takes the maximum of the provided seed value and 0.
  160. The final random seed is computed by adding the seed and subseed values, applying a bitwise AND operation
  161. with 0xFFFFFFFF to ensure it fits within a 32-bit integer.
  162. """
  163. try:
  164. tmp_seed = int(p.all_seeds[0] if p.seed == -1 else max(int(p.seed), 0))
  165. tmp_subseed = int(p.all_seeds[0] if p.subseed == -1 else max(int(p.subseed), 0))
  166. seed = (tmp_seed + tmp_subseed) & 0xFFFFFFFF
  167. np.random.seed(seed)
  168. return seed
  169. except Exception as e:
  170. logger.warning(e)
  171. logger.warning('Warning: Failed to use consistent random seed.')
  172. return None
  173. class Script(scripts.Script, metaclass=(
  174. utils.TimeMeta if logger.level == logging.DEBUG else type)):
  175. model_cache = OrderedDict()
  176. def __init__(self) -> None:
  177. super().__init__()
  178. self.latest_network = None
  179. self.preprocessor = global_state.cache_preprocessors(global_state.cn_preprocessor_modules)
  180. self.unloadable = global_state.cn_preprocessor_unloadable
  181. self.input_image = None
  182. self.latest_model_hash = ""
  183. self.enabled_units = []
  184. self.detected_map = []
  185. self.post_processors = []
  186. batch_hijack.instance.process_batch_callbacks.append(self.batch_tab_process)
  187. batch_hijack.instance.process_batch_each_callbacks.append(self.batch_tab_process_each)
  188. batch_hijack.instance.postprocess_batch_each_callbacks.insert(0, self.batch_tab_postprocess_each)
  189. batch_hijack.instance.postprocess_batch_callbacks.insert(0, self.batch_tab_postprocess)
  190. def title(self):
  191. return "ControlNet"
  192. def show(self, is_img2img):
  193. return scripts.AlwaysVisible
  194. @staticmethod
  195. def get_default_ui_unit(is_ui=True):
  196. cls = UiControlNetUnit if is_ui else external_code.ControlNetUnit
  197. return cls(
  198. enabled=False,
  199. module="none",
  200. model="None"
  201. )
  202. def uigroup(self, tabname: str, is_img2img: bool, elem_id_tabname: str):
  203. group = ControlNetUiGroup(
  204. gradio_compat,
  205. self.infotext_fields,
  206. Script.get_default_ui_unit(),
  207. self.preprocessor,
  208. )
  209. group.render(tabname, elem_id_tabname)
  210. group.register_callbacks(is_img2img)
  211. return group.render_and_register_unit(tabname, is_img2img)
  212. def ui(self, is_img2img):
  213. """this function should create gradio UI elements. See https://gradio.app/docs/#components
  214. The return value should be an array of all components that are used in processing.
  215. Values of those returned components will be passed to run() and process() functions.
  216. """
  217. self.infotext_fields = []
  218. self.paste_field_names = []
  219. controls = ()
  220. max_models = shared.opts.data.get("control_net_max_models_num", 1)
  221. elem_id_tabname = ("img2img" if is_img2img else "txt2img") + "_controlnet"
  222. with gr.Group(elem_id=elem_id_tabname):
  223. with gr.Accordion(f"ControlNet {controlnet_version.version_flag}", open = False, elem_id="controlnet"):
  224. if max_models > 1:
  225. with gr.Tabs(elem_id=f"{elem_id_tabname}_tabs"):
  226. for i in range(max_models):
  227. with gr.Tab(f"ControlNet Unit {i}",
  228. elem_classes=['cnet-unit-tab']):
  229. controls += (self.uigroup(f"ControlNet-{i}", is_img2img, elem_id_tabname),)
  230. else:
  231. with gr.Column():
  232. controls += (self.uigroup(f"ControlNet", is_img2img, elem_id_tabname),)
  233. if shared.opts.data.get("control_net_sync_field_args", False):
  234. for _, field_name in self.infotext_fields:
  235. self.paste_field_names.append(field_name)
  236. return controls
  237. @staticmethod
  238. def clear_control_model_cache():
  239. Script.model_cache.clear()
  240. gc.collect()
  241. devices.torch_gc()
  242. @staticmethod
  243. def load_control_model(p, unet, model, lowvram):
  244. if model in Script.model_cache:
  245. logger.info(f"Loading model from cache: {model}")
  246. return Script.model_cache[model]
  247. # Remove model from cache to clear space before building another model
  248. if len(Script.model_cache) > 0 and len(Script.model_cache) >= shared.opts.data.get("control_net_model_cache_size", 2):
  249. Script.model_cache.popitem(last=False)
  250. gc.collect()
  251. devices.torch_gc()
  252. model_net = Script.build_control_model(p, unet, model, lowvram)
  253. if shared.opts.data.get("control_net_model_cache_size", 2) > 0:
  254. Script.model_cache[model] = model_net
  255. return model_net
  256. @staticmethod
  257. def build_control_model(p, unet, model, lowvram):
  258. if model is None or model == 'None':
  259. raise RuntimeError(f"You have not selected any ControlNet Model.")
  260. model_path = global_state.cn_models.get(model, None)
  261. if model_path is None:
  262. model = find_closest_lora_model_name(model)
  263. model_path = global_state.cn_models.get(model, None)
  264. if model_path is None:
  265. raise RuntimeError(f"model not found: {model}")
  266. # trim '"' at start/end
  267. if model_path.startswith("\"") and model_path.endswith("\""):
  268. model_path = model_path[1:-1]
  269. if not os.path.exists(model_path):
  270. raise ValueError(f"file not found: {model_path}")
  271. logger.info(f"Loading model: {model}")
  272. state_dict = load_state_dict(model_path)
  273. network_module = PlugableControlModel
  274. network_config = shared.opts.data.get("control_net_model_config", global_state.default_conf)
  275. if not os.path.isabs(network_config):
  276. network_config = os.path.join(global_state.script_dir, network_config)
  277. if any([k.startswith("body.") or k == 'style_embedding' for k, v in state_dict.items()]):
  278. # adapter model
  279. network_module = PlugableAdapter
  280. network_config = shared.opts.data.get("control_net_model_adapter_config", global_state.default_conf_adapter)
  281. if not os.path.isabs(network_config):
  282. network_config = os.path.join(global_state.script_dir, network_config)
  283. model_path = os.path.abspath(model_path)
  284. model_stem = Path(model_path).stem
  285. model_dir_name = os.path.dirname(model_path)
  286. possible_config_filenames = [
  287. os.path.join(model_dir_name, model_stem + ".yaml"),
  288. os.path.join(global_state.script_dir, 'models', model_stem + ".yaml"),
  289. os.path.join(model_dir_name, model_stem.replace('_fp16', '') + ".yaml"),
  290. os.path.join(global_state.script_dir, 'models', model_stem.replace('_fp16', '') + ".yaml"),
  291. os.path.join(model_dir_name, model_stem.replace('_diff', '') + ".yaml"),
  292. os.path.join(global_state.script_dir, 'models', model_stem.replace('_diff', '') + ".yaml"),
  293. os.path.join(model_dir_name, model_stem.replace('-fp16', '') + ".yaml"),
  294. os.path.join(global_state.script_dir, 'models', model_stem.replace('-fp16', '') + ".yaml"),
  295. os.path.join(model_dir_name, model_stem.replace('-diff', '') + ".yaml"),
  296. os.path.join(global_state.script_dir, 'models', model_stem.replace('-diff', '') + ".yaml")
  297. ]
  298. override_config = possible_config_filenames[0]
  299. for possible_config_filename in possible_config_filenames:
  300. if os.path.exists(possible_config_filename):
  301. override_config = possible_config_filename
  302. break
  303. if 'v11' in model_stem.lower() or 'shuffle' in model_stem.lower():
  304. assert os.path.exists(override_config), f'Error: The model config {override_config} is missing. ControlNet 1.1 must have configs.'
  305. if os.path.exists(override_config):
  306. network_config = override_config
  307. else:
  308. # Note: This error is triggered in unittest, but not caught.
  309. # TODO: Replace `print` with `logger.error`.
  310. print(f'ERROR: ControlNet cannot find model config [{override_config}] \n'
  311. f'ERROR: ControlNet will use a WRONG config [{network_config}] to load your model. \n'
  312. f'ERROR: The WRONG config may not match your model. The generated results can be bad. \n'
  313. f'ERROR: You are using a ControlNet model [{model_stem}] without correct YAML config file. \n'
  314. f'ERROR: The performance of this model may be worse than your expectation. \n'
  315. f'ERROR: If this model cannot get good results, the reason is that you do not have a YAML file for the model. \n'
  316. f'Solution: Please download YAML file, or ask your model provider to provide [{override_config}] for you to download.\n'
  317. f'Hint: You can take a look at [{os.path.join(global_state.script_dir, "models")}] to find many existing YAML files.\n')
  318. logger.info(f"Loading config: {network_config}")
  319. network = network_module(
  320. state_dict=state_dict,
  321. config_path=network_config,
  322. lowvram=lowvram,
  323. base_model=unet,
  324. )
  325. network.to(p.sd_model.device, dtype=p.sd_model.dtype)
  326. logger.info(f"ControlNet model {model} loaded.")
  327. return network
  328. @staticmethod
  329. def get_remote_call(p, attribute, default=None, idx=0, strict=False, force=False):
  330. if not force and not shared.opts.data.get("control_net_allow_script_control", False):
  331. return default
  332. def get_element(obj, strict=False):
  333. if not isinstance(obj, list):
  334. return obj if not strict or idx == 0 else None
  335. elif idx < len(obj):
  336. return obj[idx]
  337. else:
  338. return None
  339. attribute_value = get_element(getattr(p, attribute, None), strict)
  340. default_value = get_element(default)
  341. return attribute_value if attribute_value is not None else default_value
  342. @staticmethod
  343. def parse_remote_call(p, unit: external_code.ControlNetUnit, idx):
  344. selector = Script.get_remote_call
  345. unit.enabled = selector(p, "control_net_enabled", unit.enabled, idx, strict=True)
  346. unit.module = selector(p, "control_net_module", unit.module, idx)
  347. unit.model = selector(p, "control_net_model", unit.model, idx)
  348. unit.weight = selector(p, "control_net_weight", unit.weight, idx)
  349. unit.image = selector(p, "control_net_image", unit.image, idx)
  350. unit.resize_mode = selector(p, "control_net_resize_mode", unit.resize_mode, idx)
  351. unit.low_vram = selector(p, "control_net_lowvram", unit.low_vram, idx)
  352. unit.processor_res = selector(p, "control_net_pres", unit.processor_res, idx)
  353. unit.threshold_a = selector(p, "control_net_pthr_a", unit.threshold_a, idx)
  354. unit.threshold_b = selector(p, "control_net_pthr_b", unit.threshold_b, idx)
  355. unit.guidance_start = selector(p, "control_net_guidance_start", unit.guidance_start, idx)
  356. unit.guidance_end = selector(p, "control_net_guidance_end", unit.guidance_end, idx)
  357. # Backward compatibility. See https://github.com/Mikubill/sd-webui-controlnet/issues/1740
  358. # for more details.
  359. unit.guidance_end = selector(p, "control_net_guidance_strength", unit.guidance_end, idx)
  360. unit.control_mode = selector(p, "control_net_control_mode", unit.control_mode, idx)
  361. unit.pixel_perfect = selector(p, "control_net_pixel_perfect", unit.pixel_perfect, idx)
  362. return unit
  363. @staticmethod
  364. def detectmap_proc(detected_map, module, resize_mode, h, w):
  365. if 'inpaint' in module:
  366. detected_map = detected_map.astype(np.float32)
  367. else:
  368. detected_map = HWC3(detected_map)
  369. def safe_numpy(x):
  370. # A very safe method to make sure that Apple/Mac works
  371. y = x
  372. # below is very boring but do not change these. If you change these Apple or Mac may fail.
  373. y = y.copy()
  374. y = np.ascontiguousarray(y)
  375. y = y.copy()
  376. return y
  377. def get_pytorch_control(x):
  378. # A very safe method to make sure that Apple/Mac works
  379. y = x
  380. # below is very boring but do not change these. If you change these Apple or Mac may fail.
  381. y = torch.from_numpy(y)
  382. y = y.float() / 255.0
  383. y = rearrange(y, 'h w c -> 1 c h w')
  384. y = y.clone()
  385. y = y.to(devices.get_device_for("controlnet"))
  386. y = y.clone()
  387. return y
  388. def high_quality_resize(x, size):
  389. # Written by lvmin
  390. # Super high-quality control map up-scaling, considering binary, seg, and one-pixel edges
  391. inpaint_mask = None
  392. if x.ndim == 3 and x.shape[2] == 4:
  393. inpaint_mask = x[:, :, 3]
  394. x = x[:, :, 0:3]
  395. new_size_is_smaller = (size[0] * size[1]) < (x.shape[0] * x.shape[1])
  396. new_size_is_bigger = (size[0] * size[1]) > (x.shape[0] * x.shape[1])
  397. unique_color_count = len(get_unique_axis0(x.reshape(-1, x.shape[2])))
  398. is_one_pixel_edge = False
  399. is_binary = False
  400. if unique_color_count == 2:
  401. is_binary = np.min(x) < 16 and np.max(x) > 240
  402. if is_binary:
  403. xc = x
  404. xc = cv2.erode(xc, np.ones(shape=(3, 3), dtype=np.uint8), iterations=1)
  405. xc = cv2.dilate(xc, np.ones(shape=(3, 3), dtype=np.uint8), iterations=1)
  406. one_pixel_edge_count = np.where(xc < x)[0].shape[0]
  407. all_edge_count = np.where(x > 127)[0].shape[0]
  408. is_one_pixel_edge = one_pixel_edge_count * 2 > all_edge_count
  409. if 2 < unique_color_count < 200:
  410. interpolation = cv2.INTER_NEAREST
  411. elif new_size_is_smaller:
  412. interpolation = cv2.INTER_AREA
  413. else:
  414. interpolation = cv2.INTER_CUBIC # Must be CUBIC because we now use nms. NEVER CHANGE THIS
  415. y = cv2.resize(x, size, interpolation=interpolation)
  416. if inpaint_mask is not None:
  417. inpaint_mask = cv2.resize(inpaint_mask, size, interpolation=interpolation)
  418. if is_binary:
  419. y = np.mean(y.astype(np.float32), axis=2).clip(0, 255).astype(np.uint8)
  420. if is_one_pixel_edge:
  421. y = nake_nms(y)
  422. _, y = cv2.threshold(y, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
  423. y = lvmin_thin(y, prunings=new_size_is_bigger)
  424. else:
  425. _, y = cv2.threshold(y, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
  426. y = np.stack([y] * 3, axis=2)
  427. if inpaint_mask is not None:
  428. inpaint_mask = (inpaint_mask > 127).astype(np.float32) * 255.0
  429. inpaint_mask = inpaint_mask[:, :, None].clip(0, 255).astype(np.uint8)
  430. y = np.concatenate([y, inpaint_mask], axis=2)
  431. return y
  432. if resize_mode == external_code.ResizeMode.RESIZE:
  433. detected_map = high_quality_resize(detected_map, (w, h))
  434. detected_map = safe_numpy(detected_map)
  435. return get_pytorch_control(detected_map), detected_map
  436. old_h, old_w, _ = detected_map.shape
  437. old_w = float(old_w)
  438. old_h = float(old_h)
  439. k0 = float(h) / old_h
  440. k1 = float(w) / old_w
  441. safeint = lambda x: int(np.round(x))
  442. if resize_mode == external_code.ResizeMode.OUTER_FIT:
  443. k = min(k0, k1)
  444. borders = np.concatenate([detected_map[0, :, :], detected_map[-1, :, :], detected_map[:, 0, :], detected_map[:, -1, :]], axis=0)
  445. high_quality_border_color = np.median(borders, axis=0).astype(detected_map.dtype)
  446. if len(high_quality_border_color) == 4:
  447. # Inpaint hijack
  448. high_quality_border_color[3] = 255
  449. high_quality_background = np.tile(high_quality_border_color[None, None], [h, w, 1])
  450. detected_map = high_quality_resize(detected_map, (safeint(old_w * k), safeint(old_h * k)))
  451. new_h, new_w, _ = detected_map.shape
  452. pad_h = max(0, (h - new_h) // 2)
  453. pad_w = max(0, (w - new_w) // 2)
  454. high_quality_background[pad_h:pad_h + new_h, pad_w:pad_w + new_w] = detected_map
  455. detected_map = high_quality_background
  456. detected_map = safe_numpy(detected_map)
  457. return get_pytorch_control(detected_map), detected_map
  458. else:
  459. k = max(k0, k1)
  460. detected_map = high_quality_resize(detected_map, (safeint(old_w * k), safeint(old_h * k)))
  461. new_h, new_w, _ = detected_map.shape
  462. pad_h = max(0, (new_h - h) // 2)
  463. pad_w = max(0, (new_w - w) // 2)
  464. detected_map = detected_map[pad_h:pad_h+h, pad_w:pad_w+w]
  465. detected_map = safe_numpy(detected_map)
  466. return get_pytorch_control(detected_map), detected_map
  467. @staticmethod
  468. def get_enabled_units(p):
  469. units = external_code.get_all_units_in_processing(p)
  470. enabled_units = []
  471. if len(units) == 0:
  472. # fill a null group
  473. remote_unit = Script.parse_remote_call(p, Script.get_default_ui_unit(), 0)
  474. if remote_unit.enabled:
  475. units.append(remote_unit)
  476. for idx, unit in enumerate(units):
  477. unit = Script.parse_remote_call(p, unit, idx)
  478. if not unit.enabled:
  479. continue
  480. enabled_units.append(copy(unit))
  481. if len(units) != 1:
  482. log_key = f"ControlNet {idx}"
  483. else:
  484. log_key = "ControlNet"
  485. log_value = {
  486. "preprocessor": unit.module,
  487. "model": unit.model,
  488. "weight": unit.weight,
  489. "starting/ending": str((unit.guidance_start, unit.guidance_end)),
  490. "resize mode": str(unit.resize_mode),
  491. "pixel perfect": str(unit.pixel_perfect),
  492. "control mode": str(unit.control_mode),
  493. "preprocessor params": str((unit.processor_res, unit.threshold_a, unit.threshold_b)),
  494. }
  495. log_value = str(log_value).replace('\'', '').replace('{', '').replace('}', '')
  496. p.extra_generation_params.update({log_key: log_value})
  497. return enabled_units
  498. @staticmethod
  499. def choose_input_image(
  500. p: processing.StableDiffusionProcessing,
  501. unit: external_code.ControlNetUnit,
  502. idx: int
  503. ) -> Tuple[np.ndarray, bool]:
  504. """ Choose input image from following sources with descending priority:
  505. - p.image_control: [Deprecated] Lagacy way to pass image to controlnet.
  506. - p.control_net_input_image: [Deprecated] Lagacy way to pass image to controlnet.
  507. - unit.image:
  508. - ControlNet tab input image.
  509. - Input image from API call.
  510. - p.init_images: A1111 img2img tab input image.
  511. Returns:
  512. - The input image in ndarray form.
  513. - Whether input image is from A1111.
  514. """
  515. image_from_a1111 = False
  516. p_input_image = Script.get_remote_call(p, "control_net_input_image", None, idx)
  517. image = image_dict_from_any(unit.image)
  518. if batch_hijack.instance.is_batch and getattr(p, "image_control", None) is not None:
  519. logger.warning("Warn: Using legacy field 'p.image_control'.")
  520. input_image = HWC3(np.asarray(p.image_control))
  521. elif p_input_image is not None:
  522. logger.warning("Warn: Using legacy field 'p.controlnet_input_image'")
  523. if isinstance(p_input_image, dict) and "mask" in p_input_image and "image" in p_input_image:
  524. color = HWC3(np.asarray(p_input_image['image']))
  525. alpha = np.asarray(p_input_image['mask'])[..., None]
  526. input_image = np.concatenate([color, alpha], axis=2)
  527. else:
  528. input_image = HWC3(np.asarray(p_input_image))
  529. elif image is not None:
  530. while len(image['mask'].shape) < 3:
  531. image['mask'] = image['mask'][..., np.newaxis]
  532. # Need to check the image for API compatibility
  533. if isinstance(image['image'], str):
  534. from modules.api.api import decode_base64_to_image
  535. input_image = HWC3(np.asarray(decode_base64_to_image(image['image'])))
  536. else:
  537. input_image = HWC3(image['image'])
  538. have_mask = 'mask' in image and not (
  539. (image['mask'][:, :, 0] <= 5).all() or
  540. (image['mask'][:, :, 0] >= 250).all()
  541. )
  542. if 'inpaint' in unit.module:
  543. logger.info("using inpaint as input")
  544. color = HWC3(image['image'])
  545. if have_mask:
  546. alpha = image['mask'][:, :, 0:1]
  547. else:
  548. alpha = np.zeros_like(color)[:, :, 0:1]
  549. input_image = np.concatenate([color, alpha], axis=2)
  550. else:
  551. if have_mask and not shared.opts.data.get("controlnet_ignore_noninpaint_mask", False):
  552. logger.info("using mask as input")
  553. input_image = HWC3(image['mask'][:, :, 0])
  554. unit.module = 'none' # Always use black bg and white line
  555. else:
  556. # use img2img init_image as default
  557. input_image = getattr(p, "init_images", [None])[0]
  558. if input_image is None:
  559. if batch_hijack.instance.is_batch:
  560. shared.state.interrupted = True
  561. raise ValueError('controlnet is enabled but no input image is given')
  562. input_image = HWC3(np.asarray(input_image))
  563. image_from_a1111 = True
  564. assert isinstance(input_image, np.ndarray)
  565. return input_image, image_from_a1111
  566. @staticmethod
  567. def bound_check_params(unit: external_code.ControlNetUnit) -> None:
  568. """
  569. Checks and corrects negative parameters in ControlNetUnit 'unit'.
  570. Parameters 'processor_res', 'threshold_a', 'threshold_b' are reset to
  571. their default values if negative.
  572. Args:
  573. unit (external_code.ControlNetUnit): The ControlNetUnit instance to check.
  574. """
  575. cfg = preprocessor_sliders_config.get(
  576. global_state.get_module_basename(unit.module), [])
  577. defaults = {
  578. param: cfg_default['value']
  579. for param, cfg_default in zip(
  580. ("processor_res", 'threshold_a', 'threshold_b'), cfg)
  581. if cfg_default is not None
  582. }
  583. for param, default_value in defaults.items():
  584. value = getattr(unit, param)
  585. if value < 0:
  586. setattr(unit, param, default_value)
  587. logger.warning(f'[{unit.module}.{param}] Invalid value({value}), using default value {default_value}.')
  588. def process(self, p, *args):
  589. """
  590. This function is called before processing begins for AlwaysVisible scripts.
  591. You can modify the processing object (p) here, inject hooks, etc.
  592. args contains all values returned by components from ui()
  593. """
  594. sd_ldm = p.sd_model
  595. unet = sd_ldm.model.diffusion_model
  596. setattr(p, 'controlnet_initial_noise_modifier', None)
  597. if self.latest_network is not None:
  598. # always restore (~0.05s)
  599. self.latest_network.restore(unet)
  600. if not batch_hijack.instance.is_batch:
  601. self.enabled_units = Script.get_enabled_units(p)
  602. if len(self.enabled_units) == 0:
  603. self.latest_network = None
  604. return
  605. is_sdxl = getattr(p.sd_model, 'is_sdxl', False)
  606. if is_sdxl:
  607. logger.warning('ControlNet does not support SDXL -- disabling')
  608. return
  609. detected_maps = []
  610. forward_params = []
  611. post_processors = []
  612. # cache stuff
  613. if self.latest_model_hash != p.sd_model.sd_model_hash:
  614. Script.clear_control_model_cache()
  615. # unload unused preproc
  616. module_list = [unit.module for unit in self.enabled_units]
  617. for key in self.unloadable:
  618. if key not in module_list:
  619. self.unloadable.get(key, lambda:None)()
  620. self.latest_model_hash = p.sd_model.sd_model_hash
  621. for idx, unit in enumerate(self.enabled_units):
  622. Script.bound_check_params(unit)
  623. unit.module = global_state.get_module_basename(unit.module)
  624. resize_mode = external_code.resize_mode_from_value(unit.resize_mode)
  625. control_mode = external_code.control_mode_from_value(unit.control_mode)
  626. if unit.module in model_free_preprocessors:
  627. model_net = None
  628. else:
  629. model_net = Script.load_control_model(p, unet, unit.model, unit.low_vram)
  630. model_net.reset()
  631. input_image, image_from_a1111 = Script.choose_input_image(p, unit, idx)
  632. if image_from_a1111:
  633. a1111_i2i_resize_mode = getattr(p, "resize_mode", None)
  634. if a1111_i2i_resize_mode is not None:
  635. resize_mode = external_code.resize_mode_from_value(a1111_i2i_resize_mode)
  636. a1111_mask_image : Optional[Image.Image] = getattr(p, "image_mask", None)
  637. if 'inpaint' in unit.module and not image_has_mask(input_image) and a1111_mask_image is not None:
  638. a1111_mask = np.array(prepare_mask(a1111_mask_image, p))
  639. if a1111_mask.ndim == 2:
  640. if a1111_mask.shape[0] == input_image.shape[0]:
  641. if a1111_mask.shape[1] == input_image.shape[1]:
  642. input_image = np.concatenate([input_image[:, :, 0:3], a1111_mask[:, :, None]], axis=2)
  643. a1111_i2i_resize_mode = getattr(p, "resize_mode", None)
  644. if a1111_i2i_resize_mode is not None:
  645. resize_mode = external_code.resize_mode_from_value(a1111_i2i_resize_mode)
  646. if 'reference' not in unit.module and issubclass(type(p), StableDiffusionProcessingImg2Img) \
  647. and p.inpaint_full_res and a1111_mask_image is not None:
  648. logger.debug("A1111 inpaint mask START")
  649. input_image = [input_image[:, :, i] for i in range(input_image.shape[2])]
  650. input_image = [Image.fromarray(x) for x in input_image]
  651. mask = prepare_mask(a1111_mask_image, p)
  652. crop_region = masking.get_crop_region(np.array(mask), p.inpaint_full_res_padding)
  653. crop_region = masking.expand_crop_region(crop_region, p.width, p.height, mask.width, mask.height)
  654. input_image = [
  655. images.resize_image(resize_mode.int_value(), i, mask.width, mask.height)
  656. for i in input_image
  657. ]
  658. input_image = [x.crop(crop_region) for x in input_image]
  659. input_image = [
  660. images.resize_image(external_code.ResizeMode.OUTER_FIT.int_value(), x, p.width, p.height)
  661. for x in input_image
  662. ]
  663. input_image = [np.asarray(x)[:, :, 0] for x in input_image]
  664. input_image = np.stack(input_image, axis=2)
  665. logger.debug("A1111 inpaint mask END")
  666. if 'inpaint_only' == unit.module and issubclass(type(p), StableDiffusionProcessingImg2Img) and p.image_mask is not None:
  667. logger.warning('A1111 inpaint and ControlNet inpaint duplicated. ControlNet support enabled.')
  668. unit.module = 'inpaint'
  669. # safe numpy
  670. logger.debug("Safe numpy convertion START")
  671. input_image = np.ascontiguousarray(input_image.copy()).copy()
  672. logger.debug("Safe numpy convertion END")
  673. logger.info(f"Loading preprocessor: {unit.module}")
  674. preprocessor = self.preprocessor[unit.module]
  675. high_res_fix = isinstance(p, StableDiffusionProcessingTxt2Img) and getattr(p, 'enable_hr', False)
  676. h = (p.height // 8) * 8
  677. w = (p.width // 8) * 8
  678. if high_res_fix:
  679. if p.hr_resize_x == 0 and p.hr_resize_y == 0:
  680. hr_y = int(p.height * p.hr_scale)
  681. hr_x = int(p.width * p.hr_scale)
  682. else:
  683. hr_y, hr_x = p.hr_resize_y, p.hr_resize_x
  684. hr_y = (hr_y // 8) * 8
  685. hr_x = (hr_x // 8) * 8
  686. else:
  687. hr_y = h
  688. hr_x = w
  689. if unit.module == 'inpaint_only+lama' and resize_mode == external_code.ResizeMode.OUTER_FIT:
  690. # inpaint_only+lama is special and required outpaint fix
  691. _, input_image = Script.detectmap_proc(input_image, unit.module, resize_mode, hr_y, hr_x)
  692. preprocessor_resolution = unit.processor_res
  693. if unit.pixel_perfect:
  694. preprocessor_resolution = external_code.pixel_perfect_resolution(
  695. input_image,
  696. target_H=h,
  697. target_W=w,
  698. resize_mode=resize_mode
  699. )
  700. logger.info(f'preprocessor resolution = {preprocessor_resolution}')
  701. # Preprocessor result may depend on numpy random operations, use the
  702. # random seed in `StableDiffusionProcessing` to make the
  703. # preprocessor result reproducable.
  704. # Currently following preprocessors use numpy random:
  705. # - shuffle
  706. seed = set_numpy_seed(p)
  707. logger.debug(f"Use numpy seed {seed}.")
  708. detected_map, is_image = preprocessor(
  709. input_image,
  710. res=preprocessor_resolution,
  711. thr_a=unit.threshold_a,
  712. thr_b=unit.threshold_b,
  713. )
  714. if unit.module == "none" and "style" in unit.model:
  715. detected_map_bytes = detected_map[:,:,0].tobytes()
  716. detected_map = np.ndarray((round(input_image.shape[0]/4),input_image.shape[1]),dtype="float32",buffer=detected_map_bytes)
  717. detected_map = torch.Tensor(detected_map).to(devices.get_device_for("controlnet"))
  718. is_image = False
  719. if high_res_fix:
  720. if is_image:
  721. hr_control, hr_detected_map = Script.detectmap_proc(detected_map, unit.module, resize_mode, hr_y, hr_x)
  722. detected_maps.append((hr_detected_map, unit.module))
  723. else:
  724. hr_control = detected_map
  725. else:
  726. hr_control = None
  727. if is_image:
  728. control, detected_map = Script.detectmap_proc(detected_map, unit.module, resize_mode, h, w)
  729. detected_maps.append((detected_map, unit.module))
  730. else:
  731. control = detected_map
  732. if unit.module == 'clip_vision':
  733. detected_maps.append((processor.clip_vision_visualization(detected_map), unit.module))
  734. control_model_type = ControlModelType.ControlNet
  735. if isinstance(model_net, PlugableAdapter):
  736. control_model_type = ControlModelType.T2I_Adapter
  737. if getattr(model_net, "target", None) == "scripts.adapter.StyleAdapter":
  738. control_model_type = ControlModelType.T2I_StyleAdapter
  739. if 'reference' in unit.module:
  740. control_model_type = ControlModelType.AttentionInjection
  741. global_average_pooling = False
  742. if model_net is not None:
  743. if model_net.config.model.params.get("global_average_pooling", False):
  744. global_average_pooling = True
  745. preprocessor_dict = dict(
  746. name=unit.module,
  747. preprocessor_resolution=preprocessor_resolution,
  748. threshold_a=unit.threshold_a,
  749. threshold_b=unit.threshold_b
  750. )
  751. forward_param = ControlParams(
  752. control_model=model_net,
  753. preprocessor=preprocessor_dict,
  754. hint_cond=control,
  755. weight=unit.weight,
  756. guidance_stopped=False,
  757. start_guidance_percent=unit.guidance_start,
  758. stop_guidance_percent=unit.guidance_end,
  759. advanced_weighting=None,
  760. control_model_type=control_model_type,
  761. global_average_pooling=global_average_pooling,
  762. hr_hint_cond=hr_control,
  763. soft_injection=control_mode != external_code.ControlMode.BALANCED,
  764. cfg_injection=control_mode == external_code.ControlMode.CONTROL,
  765. )
  766. forward_params.append(forward_param)
  767. if 'inpaint_only' in unit.module:
  768. final_inpaint_feed = hr_control if hr_control is not None else control
  769. final_inpaint_feed = final_inpaint_feed.detach().cpu().numpy()
  770. final_inpaint_feed = np.ascontiguousarray(final_inpaint_feed).copy()
  771. final_inpaint_mask = final_inpaint_feed[0, 3, :, :].astype(np.float32)
  772. final_inpaint_raw = final_inpaint_feed[0, :3].astype(np.float32)
  773. sigma = shared.opts.data.get("control_net_inpaint_blur_sigma", 7)
  774. final_inpaint_mask = cv2.dilate(final_inpaint_mask, np.ones((sigma, sigma), dtype=np.uint8))
  775. final_inpaint_mask = cv2.blur(final_inpaint_mask, (sigma, sigma))[None]
  776. _, Hmask, Wmask = final_inpaint_mask.shape
  777. final_inpaint_raw = torch.from_numpy(np.ascontiguousarray(final_inpaint_raw).copy())
  778. final_inpaint_mask = torch.from_numpy(np.ascontiguousarray(final_inpaint_mask).copy())
  779. def inpaint_only_post_processing(x):
  780. _, H, W = x.shape
  781. if Hmask != H or Wmask != W:
  782. logger.error('Error: ControlNet find post-processing resolution mismatch. This could be related to other extensions hacked processing.')
  783. return x
  784. r = final_inpaint_raw.to(x.dtype).to(x.device)
  785. m = final_inpaint_mask.to(x.dtype).to(x.device)
  786. y = m * x.clip(0, 1) + (1 - m) * r
  787. y = y.clip(0, 1)
  788. return y
  789. post_processors.append(inpaint_only_post_processing)
  790. if '+lama' in unit.module:
  791. forward_param.used_hint_cond_latent = hook.UnetHook.call_vae_using_process(p, control)
  792. setattr(p, 'controlnet_initial_noise_modifier', forward_param.used_hint_cond_latent)
  793. del model_net
  794. self.latest_network = UnetHook(lowvram=any(unit.low_vram for unit in self.enabled_units))
  795. self.latest_network.hook(model=unet, sd_ldm=sd_ldm, control_params=forward_params, process=p)
  796. self.detected_map = detected_maps
  797. self.post_processors = post_processors
  798. def postprocess_batch(self, p, *args, **kwargs):
  799. images = kwargs.get('images', [])
  800. for post_processor in self.post_processors:
  801. for i in range(len(images)):
  802. images[i] = post_processor(images[i])
  803. return
  804. def postprocess(self, p, processed, *args):
  805. self.post_processors = []
  806. setattr(p, 'controlnet_initial_noise_modifier', None)
  807. setattr(p, 'controlnet_vae_cache', None)
  808. processor_params_flag = (', '.join(getattr(processed, 'extra_generation_params', []))).lower()
  809. self.post_processors = []
  810. if not batch_hijack.instance.is_batch:
  811. self.enabled_units.clear()
  812. if shared.opts.data.get("control_net_detectmap_autosaving", False) and self.latest_network is not None:
  813. for detect_map, module in self.detected_map:
  814. detectmap_dir = os.path.join(shared.opts.data.get("control_net_detectedmap_dir", ""), module)
  815. if not os.path.isabs(detectmap_dir):
  816. detectmap_dir = os.path.join(p.outpath_samples, detectmap_dir)
  817. if module != "none":
  818. os.makedirs(detectmap_dir, exist_ok=True)
  819. img = Image.fromarray(np.ascontiguousarray(detect_map.clip(0, 255).astype(np.uint8)).copy())
  820. save_image(img, detectmap_dir, module)
  821. if self.latest_network is None:
  822. return
  823. if not batch_hijack.instance.is_batch:
  824. if not shared.opts.data.get("control_net_no_detectmap", False):
  825. if 'sd upscale' not in processor_params_flag:
  826. if self.detected_map is not None:
  827. for detect_map, module in self.detected_map:
  828. if detect_map is None:
  829. continue
  830. detect_map = np.ascontiguousarray(detect_map.copy()).copy()
  831. detect_map = external_code.visualize_inpaint_mask(detect_map)
  832. processed.images.extend([
  833. Image.fromarray(
  834. detect_map.clip(0, 255).astype(np.uint8)
  835. )
  836. ])
  837. self.input_image = None
  838. self.latest_network.restore(p.sd_model.model.diffusion_model)
  839. self.latest_network = None
  840. self.detected_map.clear()
  841. gc.collect()
  842. devices.torch_gc()
  843. def batch_tab_process(self, p, batches, *args, **kwargs):
  844. self.enabled_units = self.get_enabled_units(p)
  845. for unit_i, unit in enumerate(self.enabled_units):
  846. unit.batch_images = iter([batch[unit_i] for batch in batches])
  847. def batch_tab_process_each(self, p, *args, **kwargs):
  848. for unit_i, unit in enumerate(self.enabled_units):
  849. if getattr(unit, 'loopback', False) and batch_hijack.instance.batch_index > 0: continue
  850. unit.image = next(unit.batch_images)
  851. def batch_tab_postprocess_each(self, p, processed, *args, **kwargs):
  852. for unit_i, unit in enumerate(self.enabled_units):
  853. if getattr(unit, 'loopback', False):
  854. output_images = getattr(processed, 'images', [])[processed.index_of_first_image:]
  855. if output_images:
  856. unit.image = np.array(output_images[0])
  857. else:
  858. logger.warning(f'Warning: No loopback image found for controlnet unit {unit_i}. Using control map from last batch iteration instead')
  859. def batch_tab_postprocess(self, p, *args, **kwargs):
  860. self.enabled_units.clear()
  861. self.input_image = None
  862. if self.latest_network is None: return
  863. self.latest_network.restore(shared.sd_model.model.diffusion_model)
  864. self.latest_network = None
  865. self.detected_map.clear()
  866. def on_ui_settings():
  867. section = ('control_net', "ControlNet")
  868. shared.opts.add_option("control_net_model_config", shared.OptionInfo(
  869. global_state.default_conf, "Config file for Control Net models", section=section))
  870. shared.opts.add_option("control_net_model_adapter_config", shared.OptionInfo(
  871. global_state.default_conf_adapter, "Config file for Adapter models", section=section))
  872. shared.opts.add_option("control_net_detectedmap_dir", shared.OptionInfo(
  873. global_state.default_detectedmap_dir, "Directory for detected maps auto saving", section=section))
  874. shared.opts.add_option("control_net_models_path", shared.OptionInfo(
  875. "", "Extra path to scan for ControlNet models (e.g. training output directory)", section=section))
  876. shared.opts.add_option("control_net_modules_path", shared.OptionInfo(
  877. "", "Path to directory containing annotator model directories (requires restart, overrides corresponding command line flag)", section=section))
  878. shared.opts.add_option("control_net_max_models_num", shared.OptionInfo(
  879. 3, "Multi ControlNet: Max models amount (requires restart)", gr.Slider, {"minimum": 1, "maximum": 10, "step": 1}, section=section))
  880. shared.opts.add_option("control_net_model_cache_size", shared.OptionInfo(
  881. 1, "Model cache size (requires restart)", gr.Slider, {"minimum": 1, "maximum": 5, "step": 1}, section=section))
  882. shared.opts.add_option("control_net_inpaint_blur_sigma", shared.OptionInfo(
  883. 7, "ControlNet inpainting Gaussian blur sigma", gr.Slider, {"minimum": 0, "maximum": 64, "step": 1}, section=section))
  884. shared.opts.add_option("control_net_no_high_res_fix", shared.OptionInfo(
  885. False, "Do not apply ControlNet during highres fix", gr.Checkbox, {"interactive": True}, section=section))
  886. shared.opts.add_option("control_net_no_detectmap", shared.OptionInfo(
  887. False, "Do not append detectmap to output", gr.Checkbox, {"interactive": True}, section=section))
  888. shared.opts.add_option("control_net_detectmap_autosaving", shared.OptionInfo(
  889. False, "Allow detectmap auto saving", gr.Checkbox, {"interactive": True}, section=section))
  890. shared.opts.add_option("control_net_allow_script_control", shared.OptionInfo(
  891. False, "Allow other script to control this extension", gr.Checkbox, {"interactive": True}, section=section))
  892. shared.opts.add_option("control_net_sync_field_args", shared.OptionInfo(
  893. False, "Passing ControlNet parameters with \"Send to img2img\"", gr.Checkbox, {"interactive": True}, section=section))
  894. shared.opts.add_option("controlnet_show_batch_images_in_ui", shared.OptionInfo(
  895. False, "Show batch images in gradio gallery output", gr.Checkbox, {"interactive": True}, section=section))
  896. shared.opts.add_option("controlnet_increment_seed_during_batch", shared.OptionInfo(
  897. False, "Increment seed after each controlnet batch iteration", gr.Checkbox, {"interactive": True}, section=section))
  898. shared.opts.add_option("controlnet_disable_control_type", shared.OptionInfo(
  899. False, "Disable control type selection", gr.Checkbox, {"interactive": True}, section=section))
  900. shared.opts.add_option("controlnet_disable_openpose_edit", shared.OptionInfo(
  901. False, "Disable openpose edit", gr.Checkbox, {"interactive": True}, section=section))
  902. shared.opts.add_option("controlnet_ignore_noninpaint_mask", shared.OptionInfo(
  903. False, "Ignore mask on ControlNet input image if control type is not inpaint",
  904. gr.Checkbox, {"interactive": True}, section=section))
  905. batch_hijack.instance.do_hijack()
  906. script_callbacks.on_ui_settings(on_ui_settings)
  907. script_callbacks.on_after_component(ControlNetUiGroup.on_after_component)