scripts.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984
  1. import os
  2. import re
  3. import sys
  4. import inspect
  5. from collections import namedtuple
  6. from dataclasses import dataclass
  7. import gradio as gr
  8. from modules import shared, paths, script_callbacks, extensions, script_loading, scripts_postprocessing, errors, timer
  9. AlwaysVisible = object()
  10. class MaskBlendArgs:
  11. def __init__(self, current_latent, nmask, init_latent, mask, blended_latent, denoiser=None, sigma=None):
  12. self.current_latent = current_latent
  13. self.nmask = nmask
  14. self.init_latent = init_latent
  15. self.mask = mask
  16. self.blended_latent = blended_latent
  17. self.denoiser = denoiser
  18. self.is_final_blend = denoiser is None
  19. self.sigma = sigma
  20. class PostSampleArgs:
  21. def __init__(self, samples):
  22. self.samples = samples
  23. class PostprocessImageArgs:
  24. def __init__(self, image):
  25. self.image = image
  26. class PostProcessMaskOverlayArgs:
  27. def __init__(self, index, mask_for_overlay, overlay_image):
  28. self.index = index
  29. self.mask_for_overlay = mask_for_overlay
  30. self.overlay_image = overlay_image
  31. class PostprocessBatchListArgs:
  32. def __init__(self, images):
  33. self.images = images
  34. @dataclass
  35. class OnComponent:
  36. component: gr.blocks.Block
  37. class Script:
  38. name = None
  39. """script's internal name derived from title"""
  40. section = None
  41. """name of UI section that the script's controls will be placed into"""
  42. filename = None
  43. args_from = None
  44. args_to = None
  45. alwayson = False
  46. is_txt2img = False
  47. is_img2img = False
  48. tabname = None
  49. group = None
  50. """A gr.Group component that has all script's UI inside it."""
  51. create_group = True
  52. """If False, for alwayson scripts, a group component will not be created."""
  53. infotext_fields = None
  54. """if set in ui(), this is a list of pairs of gradio component + text; the text will be used when
  55. parsing infotext to set the value for the component; see ui.py's txt2img_paste_fields for an example
  56. """
  57. paste_field_names = None
  58. """if set in ui(), this is a list of names of infotext fields; the fields will be sent through the
  59. various "Send to <X>" buttons when clicked
  60. """
  61. api_info = None
  62. """Generated value of type modules.api.models.ScriptInfo with information about the script for API"""
  63. on_before_component_elem_id = None
  64. """list of callbacks to be called before a component with an elem_id is created"""
  65. on_after_component_elem_id = None
  66. """list of callbacks to be called after a component with an elem_id is created"""
  67. setup_for_ui_only = False
  68. """If true, the script setup will only be run in Gradio UI, not in API"""
  69. controls = None
  70. """A list of controls retured by the ui()."""
  71. def title(self):
  72. """this function should return the title of the script. This is what will be displayed in the dropdown menu."""
  73. raise NotImplementedError()
  74. def ui(self, is_img2img):
  75. """this function should create gradio UI elements. See https://gradio.app/docs/#components
  76. The return value should be an array of all components that are used in processing.
  77. Values of those returned components will be passed to run() and process() functions.
  78. """
  79. pass
  80. def show(self, is_img2img):
  81. """
  82. is_img2img is True if this function is called for the img2img interface, and Fasle otherwise
  83. This function should return:
  84. - False if the script should not be shown in UI at all
  85. - True if the script should be shown in UI if it's selected in the scripts dropdown
  86. - script.AlwaysVisible if the script should be shown in UI at all times
  87. """
  88. return True
  89. def run(self, p, *args):
  90. """
  91. This function is called if the script has been selected in the script dropdown.
  92. It must do all processing and return the Processed object with results, same as
  93. one returned by processing.process_images.
  94. Usually the processing is done by calling the processing.process_images function.
  95. args contains all values returned by components from ui()
  96. """
  97. pass
  98. def setup(self, p, *args):
  99. """For AlwaysVisible scripts, this function is called when the processing object is set up, before any processing starts.
  100. args contains all values returned by components from ui().
  101. """
  102. pass
  103. def before_process(self, p, *args):
  104. """
  105. This function is called very early during processing begins for AlwaysVisible scripts.
  106. You can modify the processing object (p) here, inject hooks, etc.
  107. args contains all values returned by components from ui()
  108. """
  109. pass
  110. def process(self, p, *args):
  111. """
  112. This function is called before processing begins for AlwaysVisible scripts.
  113. You can modify the processing object (p) here, inject hooks, etc.
  114. args contains all values returned by components from ui()
  115. """
  116. pass
  117. def before_process_batch(self, p, *args, **kwargs):
  118. """
  119. Called before extra networks are parsed from the prompt, so you can add
  120. new extra network keywords to the prompt with this callback.
  121. **kwargs will have those items:
  122. - batch_number - index of current batch, from 0 to number of batches-1
  123. - prompts - list of prompts for current batch; you can change contents of this list but changing the number of entries will likely break things
  124. - seeds - list of seeds for current batch
  125. - subseeds - list of subseeds for current batch
  126. """
  127. pass
  128. def after_extra_networks_activate(self, p, *args, **kwargs):
  129. """
  130. Called after extra networks activation, before conds calculation
  131. allow modification of the network after extra networks activation been applied
  132. won't be call if p.disable_extra_networks
  133. **kwargs will have those items:
  134. - batch_number - index of current batch, from 0 to number of batches-1
  135. - prompts - list of prompts for current batch; you can change contents of this list but changing the number of entries will likely break things
  136. - seeds - list of seeds for current batch
  137. - subseeds - list of subseeds for current batch
  138. - extra_network_data - list of ExtraNetworkParams for current stage
  139. """
  140. pass
  141. def process_batch(self, p, *args, **kwargs):
  142. """
  143. Same as process(), but called for every batch.
  144. **kwargs will have those items:
  145. - batch_number - index of current batch, from 0 to number of batches-1
  146. - prompts - list of prompts for current batch; you can change contents of this list but changing the number of entries will likely break things
  147. - seeds - list of seeds for current batch
  148. - subseeds - list of subseeds for current batch
  149. """
  150. pass
  151. def postprocess_batch(self, p, *args, **kwargs):
  152. """
  153. Same as process_batch(), but called for every batch after it has been generated.
  154. **kwargs will have same items as process_batch, and also:
  155. - batch_number - index of current batch, from 0 to number of batches-1
  156. - images - torch tensor with all generated images, with values ranging from 0 to 1;
  157. """
  158. pass
  159. def postprocess_batch_list(self, p, pp: PostprocessBatchListArgs, *args, **kwargs):
  160. """
  161. Same as postprocess_batch(), but receives batch images as a list of 3D tensors instead of a 4D tensor.
  162. This is useful when you want to update the entire batch instead of individual images.
  163. You can modify the postprocessing object (pp) to update the images in the batch, remove images, add images, etc.
  164. If the number of images is different from the batch size when returning,
  165. then the script has the responsibility to also update the following attributes in the processing object (p):
  166. - p.prompts
  167. - p.negative_prompts
  168. - p.seeds
  169. - p.subseeds
  170. **kwargs will have same items as process_batch, and also:
  171. - batch_number - index of current batch, from 0 to number of batches-1
  172. """
  173. pass
  174. def on_mask_blend(self, p, mba: MaskBlendArgs, *args):
  175. """
  176. Called in inpainting mode when the original content is blended with the inpainted content.
  177. This is called at every step in the denoising process and once at the end.
  178. If is_final_blend is true, this is called for the final blending stage.
  179. Otherwise, denoiser and sigma are defined and may be used to inform the procedure.
  180. """
  181. pass
  182. def post_sample(self, p, ps: PostSampleArgs, *args):
  183. """
  184. Called after the samples have been generated,
  185. but before they have been decoded by the VAE, if applicable.
  186. Check getattr(samples, 'already_decoded', False) to test if the images are decoded.
  187. """
  188. pass
  189. def postprocess_image(self, p, pp: PostprocessImageArgs, *args):
  190. """
  191. Called for every image after it has been generated.
  192. """
  193. pass
  194. def postprocess_maskoverlay(self, p, ppmo: PostProcessMaskOverlayArgs, *args):
  195. """
  196. Called for every image after it has been generated.
  197. """
  198. pass
  199. def postprocess_image_after_composite(self, p, pp: PostprocessImageArgs, *args):
  200. """
  201. Called for every image after it has been generated.
  202. Same as postprocess_image but after inpaint_full_res composite
  203. So that it operates on the full image instead of the inpaint_full_res crop region.
  204. """
  205. pass
  206. def postprocess(self, p, processed, *args):
  207. """
  208. This function is called after processing ends for AlwaysVisible scripts.
  209. args contains all values returned by components from ui()
  210. """
  211. pass
  212. def before_component(self, component, **kwargs):
  213. """
  214. Called before a component is created.
  215. Use elem_id/label fields of kwargs to figure out which component it is.
  216. This can be useful to inject your own components somewhere in the middle of vanilla UI.
  217. You can return created components in the ui() function to add them to the list of arguments for your processing functions
  218. """
  219. pass
  220. def after_component(self, component, **kwargs):
  221. """
  222. Called after a component is created. Same as above.
  223. """
  224. pass
  225. def on_before_component(self, callback, *, elem_id):
  226. """
  227. Calls callback before a component is created. The callback function is called with a single argument of type OnComponent.
  228. May be called in show() or ui() - but it may be too late in latter as some components may already be created.
  229. This function is an alternative to before_component in that it also cllows to run before a component is created, but
  230. it doesn't require to be called for every created component - just for the one you need.
  231. """
  232. if self.on_before_component_elem_id is None:
  233. self.on_before_component_elem_id = []
  234. self.on_before_component_elem_id.append((elem_id, callback))
  235. def on_after_component(self, callback, *, elem_id):
  236. """
  237. Calls callback after a component is created. The callback function is called with a single argument of type OnComponent.
  238. """
  239. if self.on_after_component_elem_id is None:
  240. self.on_after_component_elem_id = []
  241. self.on_after_component_elem_id.append((elem_id, callback))
  242. def describe(self):
  243. """unused"""
  244. return ""
  245. def elem_id(self, item_id):
  246. """helper function to generate id for a HTML element, constructs final id out of script name, tab and user-supplied item_id"""
  247. need_tabname = self.show(True) == self.show(False)
  248. tabkind = 'img2img' if self.is_img2img else 'txt2img'
  249. tabname = f"{tabkind}_" if need_tabname else ""
  250. title = re.sub(r'[^a-z_0-9]', '', re.sub(r'\s', '_', self.title().lower()))
  251. return f'script_{tabname}{title}_{item_id}'
  252. def before_hr(self, p, *args):
  253. """
  254. This function is called before hires fix start.
  255. """
  256. pass
  257. class ScriptBuiltinUI(Script):
  258. setup_for_ui_only = True
  259. def elem_id(self, item_id):
  260. """helper function to generate id for a HTML element, constructs final id out of tab and user-supplied item_id"""
  261. need_tabname = self.show(True) == self.show(False)
  262. tabname = ('img2img' if self.is_img2img else 'txt2img') + "_" if need_tabname else ""
  263. return f'{tabname}{item_id}'
  264. current_basedir = paths.script_path
  265. def basedir():
  266. """returns the base directory for the current script. For scripts in the main scripts directory,
  267. this is the main directory (where webui.py resides), and for scripts in extensions directory
  268. (ie extensions/aesthetic/script/aesthetic.py), this is extension's directory (extensions/aesthetic)
  269. """
  270. return current_basedir
  271. ScriptFile = namedtuple("ScriptFile", ["basedir", "filename", "path"])
  272. scripts_data = []
  273. postprocessing_scripts_data = []
  274. ScriptClassData = namedtuple("ScriptClassData", ["script_class", "path", "basedir", "module"])
  275. def topological_sort(dependencies):
  276. """Accepts a dictionary mapping name to its dependencies, returns a list of names ordered according to dependencies.
  277. Ignores errors relating to missing dependeencies or circular dependencies
  278. """
  279. visited = {}
  280. result = []
  281. def inner(name):
  282. visited[name] = True
  283. for dep in dependencies.get(name, []):
  284. if dep in dependencies and dep not in visited:
  285. inner(dep)
  286. result.append(name)
  287. for depname in dependencies:
  288. if depname not in visited:
  289. inner(depname)
  290. return result
  291. @dataclass
  292. class ScriptWithDependencies:
  293. script_canonical_name: str
  294. file: ScriptFile
  295. requires: list
  296. load_before: list
  297. load_after: list
  298. def list_scripts(scriptdirname, extension, *, include_extensions=True):
  299. scripts = {}
  300. loaded_extensions = {ext.canonical_name: ext for ext in extensions.active()}
  301. loaded_extensions_scripts = {ext.canonical_name: [] for ext in extensions.active()}
  302. # build script dependency map
  303. root_script_basedir = os.path.join(paths.script_path, scriptdirname)
  304. if os.path.exists(root_script_basedir):
  305. for filename in sorted(os.listdir(root_script_basedir)):
  306. if not os.path.isfile(os.path.join(root_script_basedir, filename)):
  307. continue
  308. if os.path.splitext(filename)[1].lower() != extension:
  309. continue
  310. script_file = ScriptFile(paths.script_path, filename, os.path.join(root_script_basedir, filename))
  311. scripts[filename] = ScriptWithDependencies(filename, script_file, [], [], [])
  312. if include_extensions:
  313. for ext in extensions.active():
  314. extension_scripts_list = ext.list_files(scriptdirname, extension)
  315. for extension_script in extension_scripts_list:
  316. if not os.path.isfile(extension_script.path):
  317. continue
  318. script_canonical_name = ("builtin/" if ext.is_builtin else "") + ext.canonical_name + "/" + extension_script.filename
  319. relative_path = scriptdirname + "/" + extension_script.filename
  320. script = ScriptWithDependencies(
  321. script_canonical_name=script_canonical_name,
  322. file=extension_script,
  323. requires=ext.metadata.get_script_requirements("Requires", relative_path, scriptdirname),
  324. load_before=ext.metadata.get_script_requirements("Before", relative_path, scriptdirname),
  325. load_after=ext.metadata.get_script_requirements("After", relative_path, scriptdirname),
  326. )
  327. scripts[script_canonical_name] = script
  328. loaded_extensions_scripts[ext.canonical_name].append(script)
  329. for script_canonical_name, script in scripts.items():
  330. # load before requires inverse dependency
  331. # in this case, append the script name into the load_after list of the specified script
  332. for load_before in script.load_before:
  333. # if this requires an individual script to be loaded before
  334. other_script = scripts.get(load_before)
  335. if other_script:
  336. other_script.load_after.append(script_canonical_name)
  337. # if this requires an extension
  338. other_extension_scripts = loaded_extensions_scripts.get(load_before)
  339. if other_extension_scripts:
  340. for other_script in other_extension_scripts:
  341. other_script.load_after.append(script_canonical_name)
  342. # if After mentions an extension, remove it and instead add all of its scripts
  343. for load_after in list(script.load_after):
  344. if load_after not in scripts and load_after in loaded_extensions_scripts:
  345. script.load_after.remove(load_after)
  346. for other_script in loaded_extensions_scripts.get(load_after, []):
  347. script.load_after.append(other_script.script_canonical_name)
  348. dependencies = {}
  349. for script_canonical_name, script in scripts.items():
  350. for required_script in script.requires:
  351. if required_script not in scripts and required_script not in loaded_extensions:
  352. errors.report(f'Script "{script_canonical_name}" requires "{required_script}" to be loaded, but it is not.', exc_info=False)
  353. dependencies[script_canonical_name] = script.load_after
  354. ordered_scripts = topological_sort(dependencies)
  355. scripts_list = [scripts[script_canonical_name].file for script_canonical_name in ordered_scripts]
  356. return scripts_list
  357. def list_files_with_name(filename):
  358. res = []
  359. dirs = [paths.script_path] + [ext.path for ext in extensions.active()]
  360. for dirpath in dirs:
  361. if not os.path.isdir(dirpath):
  362. continue
  363. path = os.path.join(dirpath, filename)
  364. if os.path.isfile(path):
  365. res.append(path)
  366. return res
  367. def load_scripts():
  368. global current_basedir
  369. scripts_data.clear()
  370. postprocessing_scripts_data.clear()
  371. script_callbacks.clear_callbacks()
  372. scripts_list = list_scripts("scripts", ".py") + list_scripts("modules/processing_scripts", ".py", include_extensions=False)
  373. syspath = sys.path
  374. def register_scripts_from_module(module):
  375. for script_class in module.__dict__.values():
  376. if not inspect.isclass(script_class):
  377. continue
  378. if issubclass(script_class, Script):
  379. scripts_data.append(ScriptClassData(script_class, scriptfile.path, scriptfile.basedir, module))
  380. elif issubclass(script_class, scripts_postprocessing.ScriptPostprocessing):
  381. postprocessing_scripts_data.append(ScriptClassData(script_class, scriptfile.path, scriptfile.basedir, module))
  382. # here the scripts_list is already ordered
  383. # processing_script is not considered though
  384. for scriptfile in scripts_list:
  385. try:
  386. if scriptfile.basedir != paths.script_path:
  387. sys.path = [scriptfile.basedir] + sys.path
  388. current_basedir = scriptfile.basedir
  389. script_module = script_loading.load_module(scriptfile.path)
  390. register_scripts_from_module(script_module)
  391. except Exception:
  392. errors.report(f"Error loading script: {scriptfile.filename}", exc_info=True)
  393. finally:
  394. sys.path = syspath
  395. current_basedir = paths.script_path
  396. timer.startup_timer.record(scriptfile.filename)
  397. global scripts_txt2img, scripts_img2img, scripts_postproc
  398. scripts_txt2img = ScriptRunner()
  399. scripts_img2img = ScriptRunner()
  400. scripts_postproc = scripts_postprocessing.ScriptPostprocessingRunner()
  401. def wrap_call(func, filename, funcname, *args, default=None, **kwargs):
  402. try:
  403. return func(*args, **kwargs)
  404. except Exception:
  405. errors.report(f"Error calling: {filename}/{funcname}", exc_info=True)
  406. return default
  407. class ScriptRunner:
  408. def __init__(self):
  409. self.scripts = []
  410. self.selectable_scripts = []
  411. self.alwayson_scripts = []
  412. self.titles = []
  413. self.title_map = {}
  414. self.infotext_fields = []
  415. self.paste_field_names = []
  416. self.inputs = [None]
  417. self.on_before_component_elem_id = {}
  418. """dict of callbacks to be called before an element is created; key=elem_id, value=list of callbacks"""
  419. self.on_after_component_elem_id = {}
  420. """dict of callbacks to be called after an element is created; key=elem_id, value=list of callbacks"""
  421. def initialize_scripts(self, is_img2img):
  422. from modules import scripts_auto_postprocessing
  423. self.scripts.clear()
  424. self.alwayson_scripts.clear()
  425. self.selectable_scripts.clear()
  426. auto_processing_scripts = scripts_auto_postprocessing.create_auto_preprocessing_script_data()
  427. for script_data in auto_processing_scripts + scripts_data:
  428. try:
  429. script = script_data.script_class()
  430. except Exception:
  431. errors.report(f"Error # failed to initialize Script {script_data.module}: ", exc_info=True)
  432. continue
  433. script.filename = script_data.path
  434. script.is_txt2img = not is_img2img
  435. script.is_img2img = is_img2img
  436. script.tabname = "img2img" if is_img2img else "txt2img"
  437. visibility = script.show(script.is_img2img)
  438. if visibility == AlwaysVisible:
  439. self.scripts.append(script)
  440. self.alwayson_scripts.append(script)
  441. script.alwayson = True
  442. elif visibility:
  443. self.scripts.append(script)
  444. self.selectable_scripts.append(script)
  445. self.apply_on_before_component_callbacks()
  446. def apply_on_before_component_callbacks(self):
  447. for script in self.scripts:
  448. on_before = script.on_before_component_elem_id or []
  449. on_after = script.on_after_component_elem_id or []
  450. for elem_id, callback in on_before:
  451. if elem_id not in self.on_before_component_elem_id:
  452. self.on_before_component_elem_id[elem_id] = []
  453. self.on_before_component_elem_id[elem_id].append((callback, script))
  454. for elem_id, callback in on_after:
  455. if elem_id not in self.on_after_component_elem_id:
  456. self.on_after_component_elem_id[elem_id] = []
  457. self.on_after_component_elem_id[elem_id].append((callback, script))
  458. on_before.clear()
  459. on_after.clear()
  460. def create_script_ui(self, script):
  461. script.args_from = len(self.inputs)
  462. script.args_to = len(self.inputs)
  463. try:
  464. self.create_script_ui_inner(script)
  465. except Exception:
  466. errors.report(f"Error creating UI for {script.name}: ", exc_info=True)
  467. def create_script_ui_inner(self, script):
  468. import modules.api.models as api_models
  469. controls = wrap_call(script.ui, script.filename, "ui", script.is_img2img)
  470. script.controls = controls
  471. if controls is None:
  472. return
  473. script.name = wrap_call(script.title, script.filename, "title", default=script.filename).lower()
  474. api_args = []
  475. for control in controls:
  476. control.custom_script_source = os.path.basename(script.filename)
  477. arg_info = api_models.ScriptArg(label=control.label or "")
  478. for field in ("value", "minimum", "maximum", "step"):
  479. v = getattr(control, field, None)
  480. if v is not None:
  481. setattr(arg_info, field, v)
  482. choices = getattr(control, 'choices', None) # as of gradio 3.41, some items in choices are strings, and some are tuples where the first elem is the string
  483. if choices is not None:
  484. arg_info.choices = [x[0] if isinstance(x, tuple) else x for x in choices]
  485. api_args.append(arg_info)
  486. script.api_info = api_models.ScriptInfo(
  487. name=script.name,
  488. is_img2img=script.is_img2img,
  489. is_alwayson=script.alwayson,
  490. args=api_args,
  491. )
  492. if script.infotext_fields is not None:
  493. self.infotext_fields += script.infotext_fields
  494. if script.paste_field_names is not None:
  495. self.paste_field_names += script.paste_field_names
  496. self.inputs += controls
  497. script.args_to = len(self.inputs)
  498. def setup_ui_for_section(self, section, scriptlist=None):
  499. if scriptlist is None:
  500. scriptlist = self.alwayson_scripts
  501. for script in scriptlist:
  502. if script.alwayson and script.section != section:
  503. continue
  504. if script.create_group:
  505. with gr.Group(visible=script.alwayson) as group:
  506. self.create_script_ui(script)
  507. script.group = group
  508. else:
  509. self.create_script_ui(script)
  510. def prepare_ui(self):
  511. self.inputs = [None]
  512. def setup_ui(self):
  513. all_titles = [wrap_call(script.title, script.filename, "title") or script.filename for script in self.scripts]
  514. self.title_map = {title.lower(): script for title, script in zip(all_titles, self.scripts)}
  515. self.titles = [wrap_call(script.title, script.filename, "title") or f"{script.filename} [error]" for script in self.selectable_scripts]
  516. self.setup_ui_for_section(None)
  517. dropdown = gr.Dropdown(label="Script", elem_id="script_list", choices=["None"] + self.titles, value="None", type="index")
  518. self.inputs[0] = dropdown
  519. self.setup_ui_for_section(None, self.selectable_scripts)
  520. def select_script(script_index):
  521. if script_index is None:
  522. script_index = 0
  523. selected_script = self.selectable_scripts[script_index - 1] if script_index>0 else None
  524. return [gr.update(visible=selected_script == s) for s in self.selectable_scripts]
  525. def init_field(title):
  526. """called when an initial value is set from ui-config.json to show script's UI components"""
  527. if title == 'None':
  528. return
  529. script_index = self.titles.index(title)
  530. self.selectable_scripts[script_index].group.visible = True
  531. dropdown.init_field = init_field
  532. dropdown.change(
  533. fn=select_script,
  534. inputs=[dropdown],
  535. outputs=[script.group for script in self.selectable_scripts]
  536. )
  537. self.script_load_ctr = 0
  538. def onload_script_visibility(params):
  539. title = params.get('Script', None)
  540. if title:
  541. title_index = self.titles.index(title)
  542. visibility = title_index == self.script_load_ctr
  543. self.script_load_ctr = (self.script_load_ctr + 1) % len(self.titles)
  544. return gr.update(visible=visibility)
  545. else:
  546. return gr.update(visible=False)
  547. self.infotext_fields.append((dropdown, lambda x: gr.update(value=x.get('Script', 'None'))))
  548. self.infotext_fields.extend([(script.group, onload_script_visibility) for script in self.selectable_scripts])
  549. self.apply_on_before_component_callbacks()
  550. return self.inputs
  551. def run(self, p, *args):
  552. script_index = args[0]
  553. if script_index == 0 or script_index is None:
  554. return None
  555. script = self.selectable_scripts[script_index-1]
  556. if script is None:
  557. return None
  558. script_args = args[script.args_from:script.args_to]
  559. processed = script.run(p, *script_args)
  560. shared.total_tqdm.clear()
  561. return processed
  562. def before_process(self, p):
  563. for script in self.alwayson_scripts:
  564. try:
  565. script_args = p.script_args[script.args_from:script.args_to]
  566. script.before_process(p, *script_args)
  567. except Exception:
  568. errors.report(f"Error running before_process: {script.filename}", exc_info=True)
  569. def process(self, p):
  570. for script in self.alwayson_scripts:
  571. try:
  572. script_args = p.script_args[script.args_from:script.args_to]
  573. script.process(p, *script_args)
  574. except Exception:
  575. errors.report(f"Error running process: {script.filename}", exc_info=True)
  576. def before_process_batch(self, p, **kwargs):
  577. for script in self.alwayson_scripts:
  578. try:
  579. script_args = p.script_args[script.args_from:script.args_to]
  580. script.before_process_batch(p, *script_args, **kwargs)
  581. except Exception:
  582. errors.report(f"Error running before_process_batch: {script.filename}", exc_info=True)
  583. def after_extra_networks_activate(self, p, **kwargs):
  584. for script in self.alwayson_scripts:
  585. try:
  586. script_args = p.script_args[script.args_from:script.args_to]
  587. script.after_extra_networks_activate(p, *script_args, **kwargs)
  588. except Exception:
  589. errors.report(f"Error running after_extra_networks_activate: {script.filename}", exc_info=True)
  590. def process_batch(self, p, **kwargs):
  591. for script in self.alwayson_scripts:
  592. try:
  593. script_args = p.script_args[script.args_from:script.args_to]
  594. script.process_batch(p, *script_args, **kwargs)
  595. except Exception:
  596. errors.report(f"Error running process_batch: {script.filename}", exc_info=True)
  597. def postprocess(self, p, processed):
  598. for script in self.alwayson_scripts:
  599. try:
  600. script_args = p.script_args[script.args_from:script.args_to]
  601. script.postprocess(p, processed, *script_args)
  602. except Exception:
  603. errors.report(f"Error running postprocess: {script.filename}", exc_info=True)
  604. def postprocess_batch(self, p, images, **kwargs):
  605. for script in self.alwayson_scripts:
  606. try:
  607. script_args = p.script_args[script.args_from:script.args_to]
  608. script.postprocess_batch(p, *script_args, images=images, **kwargs)
  609. except Exception:
  610. errors.report(f"Error running postprocess_batch: {script.filename}", exc_info=True)
  611. def postprocess_batch_list(self, p, pp: PostprocessBatchListArgs, **kwargs):
  612. for script in self.alwayson_scripts:
  613. try:
  614. script_args = p.script_args[script.args_from:script.args_to]
  615. script.postprocess_batch_list(p, pp, *script_args, **kwargs)
  616. except Exception:
  617. errors.report(f"Error running postprocess_batch_list: {script.filename}", exc_info=True)
  618. def post_sample(self, p, ps: PostSampleArgs):
  619. for script in self.alwayson_scripts:
  620. try:
  621. script_args = p.script_args[script.args_from:script.args_to]
  622. script.post_sample(p, ps, *script_args)
  623. except Exception:
  624. errors.report(f"Error running post_sample: {script.filename}", exc_info=True)
  625. def on_mask_blend(self, p, mba: MaskBlendArgs):
  626. for script in self.alwayson_scripts:
  627. try:
  628. script_args = p.script_args[script.args_from:script.args_to]
  629. script.on_mask_blend(p, mba, *script_args)
  630. except Exception:
  631. errors.report(f"Error running post_sample: {script.filename}", exc_info=True)
  632. def postprocess_image(self, p, pp: PostprocessImageArgs):
  633. for script in self.alwayson_scripts:
  634. try:
  635. script_args = p.script_args[script.args_from:script.args_to]
  636. script.postprocess_image(p, pp, *script_args)
  637. except Exception:
  638. errors.report(f"Error running postprocess_image: {script.filename}", exc_info=True)
  639. def postprocess_maskoverlay(self, p, ppmo: PostProcessMaskOverlayArgs):
  640. for script in self.alwayson_scripts:
  641. try:
  642. script_args = p.script_args[script.args_from:script.args_to]
  643. script.postprocess_maskoverlay(p, ppmo, *script_args)
  644. except Exception:
  645. errors.report(f"Error running postprocess_image: {script.filename}", exc_info=True)
  646. def postprocess_image_after_composite(self, p, pp: PostprocessImageArgs):
  647. for script in self.alwayson_scripts:
  648. try:
  649. script_args = p.script_args[script.args_from:script.args_to]
  650. script.postprocess_image_after_composite(p, pp, *script_args)
  651. except Exception:
  652. errors.report(f"Error running postprocess_image_after_composite: {script.filename}", exc_info=True)
  653. def before_component(self, component, **kwargs):
  654. for callback, script in self.on_before_component_elem_id.get(kwargs.get("elem_id"), []):
  655. try:
  656. callback(OnComponent(component=component))
  657. except Exception:
  658. errors.report(f"Error running on_before_component: {script.filename}", exc_info=True)
  659. for script in self.scripts:
  660. try:
  661. script.before_component(component, **kwargs)
  662. except Exception:
  663. errors.report(f"Error running before_component: {script.filename}", exc_info=True)
  664. def after_component(self, component, **kwargs):
  665. for callback, script in self.on_after_component_elem_id.get(component.elem_id, []):
  666. try:
  667. callback(OnComponent(component=component))
  668. except Exception:
  669. errors.report(f"Error running on_after_component: {script.filename}", exc_info=True)
  670. for script in self.scripts:
  671. try:
  672. script.after_component(component, **kwargs)
  673. except Exception:
  674. errors.report(f"Error running after_component: {script.filename}", exc_info=True)
  675. def script(self, title):
  676. return self.title_map.get(title.lower())
  677. def reload_sources(self, cache):
  678. for si, script in list(enumerate(self.scripts)):
  679. args_from = script.args_from
  680. args_to = script.args_to
  681. filename = script.filename
  682. module = cache.get(filename, None)
  683. if module is None:
  684. module = script_loading.load_module(script.filename)
  685. cache[filename] = module
  686. for script_class in module.__dict__.values():
  687. if type(script_class) == type and issubclass(script_class, Script):
  688. self.scripts[si] = script_class()
  689. self.scripts[si].filename = filename
  690. self.scripts[si].args_from = args_from
  691. self.scripts[si].args_to = args_to
  692. def before_hr(self, p):
  693. for script in self.alwayson_scripts:
  694. try:
  695. script_args = p.script_args[script.args_from:script.args_to]
  696. script.before_hr(p, *script_args)
  697. except Exception:
  698. errors.report(f"Error running before_hr: {script.filename}", exc_info=True)
  699. def setup_scrips(self, p, *, is_ui=True):
  700. for script in self.alwayson_scripts:
  701. if not is_ui and script.setup_for_ui_only:
  702. continue
  703. try:
  704. script_args = p.script_args[script.args_from:script.args_to]
  705. script.setup(p, *script_args)
  706. except Exception:
  707. errors.report(f"Error running setup: {script.filename}", exc_info=True)
  708. def set_named_arg(self, args, script_name, arg_elem_id, value, fuzzy=False):
  709. """Locate an arg of a specific script in script_args and set its value
  710. Args:
  711. args: all script args of process p, p.script_args
  712. script_name: the name target script name to
  713. arg_elem_id: the elem_id of the target arg
  714. value: the value to set
  715. fuzzy: if True, arg_elem_id can be a substring of the control.elem_id else exact match
  716. Returns:
  717. Updated script args
  718. when script_name in not found or arg_elem_id is not found in script controls, raise RuntimeError
  719. """
  720. script = next((x for x in self.scripts if x.name == script_name), None)
  721. if script is None:
  722. raise RuntimeError(f"script {script_name} not found")
  723. for i, control in enumerate(script.controls):
  724. if arg_elem_id in control.elem_id if fuzzy else arg_elem_id == control.elem_id:
  725. index = script.args_from + i
  726. if isinstance(args, tuple):
  727. return args[:index] + (value,) + args[index + 1:]
  728. elif isinstance(args, list):
  729. args[index] = value
  730. return args
  731. else:
  732. raise RuntimeError(f"args is not a list or tuple, but {type(args)}")
  733. raise RuntimeError(f"arg_elem_id {arg_elem_id} not found in script {script_name}")
  734. scripts_txt2img: ScriptRunner = None
  735. scripts_img2img: ScriptRunner = None
  736. scripts_postproc: scripts_postprocessing.ScriptPostprocessingRunner = None
  737. scripts_current: ScriptRunner = None
  738. def reload_script_body_only():
  739. cache = {}
  740. scripts_txt2img.reload_sources(cache)
  741. scripts_img2img.reload_sources(cache)
  742. reload_scripts = load_scripts # compatibility alias