ui_settings.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. import gradio as gr
  2. from modules import ui_common, shared, script_callbacks, scripts, sd_models, sysinfo
  3. from modules.call_queue import wrap_gradio_call
  4. from modules.shared import opts
  5. from modules.ui_components import FormRow
  6. from modules.ui_gradio_extensions import reload_javascript
  7. def get_value_for_setting(key):
  8. value = getattr(opts, key)
  9. info = opts.data_labels[key]
  10. args = info.component_args() if callable(info.component_args) else info.component_args or {}
  11. args = {k: v for k, v in args.items() if k not in {'precision'}}
  12. return gr.update(value=value, **args)
  13. def create_setting_component(key, is_quicksettings=False):
  14. def fun():
  15. return opts.data[key] if key in opts.data else opts.data_labels[key].default
  16. info = opts.data_labels[key]
  17. t = type(info.default)
  18. args = info.component_args() if callable(info.component_args) else info.component_args
  19. if info.component is not None:
  20. comp = info.component
  21. elif t == str:
  22. comp = gr.Textbox
  23. elif t == int:
  24. comp = gr.Number
  25. elif t == bool:
  26. comp = gr.Checkbox
  27. else:
  28. raise Exception(f'bad options item type: {t} for key {key}')
  29. elem_id = f"setting_{key}"
  30. if info.refresh is not None:
  31. if is_quicksettings:
  32. res = comp(label=info.label, value=fun(), elem_id=elem_id, **(args or {}))
  33. ui_common.create_refresh_button(res, info.refresh, info.component_args, f"refresh_{key}")
  34. else:
  35. with FormRow():
  36. res = comp(label=info.label, value=fun(), elem_id=elem_id, **(args or {}))
  37. ui_common.create_refresh_button(res, info.refresh, info.component_args, f"refresh_{key}")
  38. else:
  39. res = comp(label=info.label, value=fun(), elem_id=elem_id, **(args or {}))
  40. return res
  41. class UiSettings:
  42. submit = None
  43. result = None
  44. interface = None
  45. components = None
  46. component_dict = None
  47. dummy_component = None
  48. quicksettings_list = None
  49. quicksettings_names = None
  50. text_settings = None
  51. def run_settings(self, *args):
  52. changed = []
  53. for key, value, comp in zip(opts.data_labels.keys(), args, self.components):
  54. assert comp == self.dummy_component or opts.same_type(value, opts.data_labels[key].default), f"Bad value for setting {key}: {value}; expecting {type(opts.data_labels[key].default).__name__}"
  55. for key, value, comp in zip(opts.data_labels.keys(), args, self.components):
  56. if comp == self.dummy_component:
  57. continue
  58. if opts.set(key, value):
  59. changed.append(key)
  60. try:
  61. opts.save(shared.config_filename)
  62. except RuntimeError:
  63. return opts.dumpjson(), f'{len(changed)} settings changed without save: {", ".join(changed)}.'
  64. return opts.dumpjson(), f'{len(changed)} settings changed{": " if changed else ""}{", ".join(changed)}.'
  65. def run_settings_single(self, value, key):
  66. if not opts.same_type(value, opts.data_labels[key].default):
  67. return gr.update(visible=True), opts.dumpjson()
  68. if not opts.set(key, value):
  69. return gr.update(value=getattr(opts, key)), opts.dumpjson()
  70. opts.save(shared.config_filename)
  71. return get_value_for_setting(key), opts.dumpjson()
  72. def create_ui(self, loadsave, dummy_component):
  73. self.components = []
  74. self.component_dict = {}
  75. self.dummy_component = dummy_component
  76. shared.settings_components = self.component_dict
  77. script_callbacks.ui_settings_callback()
  78. opts.reorder()
  79. with gr.Blocks(analytics_enabled=False) as settings_interface:
  80. with gr.Row():
  81. with gr.Column(scale=6):
  82. self.submit = gr.Button(value="Apply settings", variant='primary', elem_id="settings_submit")
  83. with gr.Column():
  84. restart_gradio = gr.Button(value='Reload UI', variant='primary', elem_id="settings_restart_gradio")
  85. self.result = gr.HTML(elem_id="settings_result")
  86. self.quicksettings_names = opts.quicksettings_list
  87. self.quicksettings_names = {x: i for i, x in enumerate(self.quicksettings_names) if x != 'quicksettings'}
  88. self.quicksettings_list = []
  89. previous_section = None
  90. current_tab = None
  91. current_row = None
  92. with gr.Tabs(elem_id="settings"):
  93. for i, (k, item) in enumerate(opts.data_labels.items()):
  94. section_must_be_skipped = item.section[0] is None
  95. if previous_section != item.section and not section_must_be_skipped:
  96. elem_id, text = item.section
  97. if current_tab is not None:
  98. current_row.__exit__()
  99. current_tab.__exit__()
  100. gr.Group()
  101. current_tab = gr.TabItem(elem_id=f"settings_{elem_id}", label=text)
  102. current_tab.__enter__()
  103. current_row = gr.Column(variant='compact')
  104. current_row.__enter__()
  105. previous_section = item.section
  106. if k in self.quicksettings_names and not shared.cmd_opts.freeze_settings:
  107. self.quicksettings_list.append((i, k, item))
  108. self.components.append(dummy_component)
  109. elif section_must_be_skipped:
  110. self.components.append(dummy_component)
  111. else:
  112. component = create_setting_component(k)
  113. self.component_dict[k] = component
  114. self.components.append(component)
  115. if current_tab is not None:
  116. current_row.__exit__()
  117. current_tab.__exit__()
  118. with gr.TabItem("Defaults", id="defaults", elem_id="settings_tab_defaults"):
  119. loadsave.create_ui()
  120. with gr.TabItem("Sysinfo", id="sysinfo", elem_id="settings_tab_sysinfo"):
  121. gr.HTML('<a href="./internal/sysinfo-download" class="sysinfo_big_link" download>Download system info</a><br /><a href="./internal/sysinfo">(or open as text in a new page)</a>', elem_id="sysinfo_download")
  122. with gr.Row():
  123. with gr.Column(scale=1):
  124. sysinfo_check_file = gr.File(label="Check system info for validity", type='binary')
  125. with gr.Column(scale=1):
  126. sysinfo_check_output = gr.HTML("", elem_id="sysinfo_validity")
  127. with gr.Column(scale=100):
  128. pass
  129. with gr.TabItem("Actions", id="actions", elem_id="settings_tab_actions"):
  130. request_notifications = gr.Button(value='Request browser notifications', elem_id="request_notifications")
  131. download_localization = gr.Button(value='Download localization template', elem_id="download_localization")
  132. reload_script_bodies = gr.Button(value='Reload custom script bodies (No ui updates, No restart)', variant='secondary', elem_id="settings_reload_script_bodies")
  133. with gr.Row():
  134. unload_sd_model = gr.Button(value='Unload SD checkpoint to free VRAM', elem_id="sett_unload_sd_model")
  135. reload_sd_model = gr.Button(value='Reload the last SD checkpoint back into VRAM', elem_id="sett_reload_sd_model")
  136. with gr.TabItem("Licenses", id="licenses", elem_id="settings_tab_licenses"):
  137. gr.HTML(shared.html("licenses.html"), elem_id="licenses")
  138. gr.Button(value="Show all pages", elem_id="settings_show_all_pages")
  139. self.text_settings = gr.Textbox(elem_id="settings_json", value=lambda: opts.dumpjson(), visible=False)
  140. unload_sd_model.click(
  141. fn=sd_models.unload_model_weights,
  142. inputs=[],
  143. outputs=[]
  144. )
  145. reload_sd_model.click(
  146. fn=sd_models.reload_model_weights,
  147. inputs=[],
  148. outputs=[]
  149. )
  150. request_notifications.click(
  151. fn=lambda: None,
  152. inputs=[],
  153. outputs=[],
  154. _js='function(){}'
  155. )
  156. download_localization.click(
  157. fn=lambda: None,
  158. inputs=[],
  159. outputs=[],
  160. _js='download_localization'
  161. )
  162. def reload_scripts():
  163. scripts.reload_script_body_only()
  164. reload_javascript() # need to refresh the html page
  165. reload_script_bodies.click(
  166. fn=reload_scripts,
  167. inputs=[],
  168. outputs=[]
  169. )
  170. restart_gradio.click(
  171. fn=shared.state.request_restart,
  172. _js='restart_reload',
  173. inputs=[],
  174. outputs=[],
  175. )
  176. def check_file(x):
  177. if x is None:
  178. return ''
  179. if sysinfo.check(x.decode('utf8', errors='ignore')):
  180. return 'Valid'
  181. return 'Invalid'
  182. sysinfo_check_file.change(
  183. fn=check_file,
  184. inputs=[sysinfo_check_file],
  185. outputs=[sysinfo_check_output],
  186. )
  187. self.interface = settings_interface
  188. def add_quicksettings(self):
  189. with gr.Row(elem_id="quicksettings", variant="compact"):
  190. for _i, k, _item in sorted(self.quicksettings_list, key=lambda x: self.quicksettings_names.get(x[1], x[0])):
  191. component = create_setting_component(k, is_quicksettings=True)
  192. self.component_dict[k] = component
  193. def add_functionality(self, demo):
  194. self.submit.click(
  195. fn=wrap_gradio_call(lambda *args: self.run_settings(*args), extra_outputs=[gr.update()]),
  196. inputs=self.components,
  197. outputs=[self.text_settings, self.result],
  198. )
  199. for _i, k, _item in self.quicksettings_list:
  200. component = self.component_dict[k]
  201. info = opts.data_labels[k]
  202. if isinstance(component, gr.Textbox):
  203. methods = [component.submit, component.blur]
  204. elif hasattr(component, 'release'):
  205. methods = [component.release]
  206. else:
  207. methods = [component.change]
  208. for method in methods:
  209. method(
  210. fn=lambda value, k=k: self.run_settings_single(value, key=k),
  211. inputs=[component],
  212. outputs=[component, self.text_settings],
  213. show_progress=info.refresh is not None,
  214. )
  215. button_set_checkpoint = gr.Button('Change checkpoint', elem_id='change_checkpoint', visible=False)
  216. button_set_checkpoint.click(
  217. fn=lambda value, _: self.run_settings_single(value, key='sd_model_checkpoint'),
  218. _js="function(v){ var res = desiredCheckpointName; desiredCheckpointName = ''; return [res || v, null]; }",
  219. inputs=[self.component_dict['sd_model_checkpoint'], self.dummy_component],
  220. outputs=[self.component_dict['sd_model_checkpoint'], self.text_settings],
  221. )
  222. component_keys = [k for k in opts.data_labels.keys() if k in self.component_dict]
  223. def get_settings_values():
  224. return [get_value_for_setting(key) for key in component_keys]
  225. demo.load(
  226. fn=get_settings_values,
  227. inputs=[],
  228. outputs=[self.component_dict[k] for k in component_keys],
  229. queue=False,
  230. )