scripts.py 24 KB

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