scripts.py 21 KB

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