scripts.py 28 KB

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