scripts.py 33 KB

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