scripts.py 20 KB

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