text-generation-webui/modules/extensions.py

63 lines
2.5 KiB
Python
Raw Normal View History

2023-02-24 16:42:43 +01:00
import gradio as gr
import extensions
2023-02-23 18:41:42 +01:00
import modules.shared as shared
2023-02-24 14:01:21 +01:00
state = {}
available_extensions = []
2023-02-23 18:49:02 +01:00
def load_extensions():
2023-02-24 14:01:21 +01:00
global state
for i, name in enumerate(shared.args.extensions):
if name in available_extensions:
print(f'Loading the extension "{name}"... ', end='')
2023-02-24 16:41:27 +01:00
exec(f"import extensions.{name}.script")
2023-02-24 14:01:21 +01:00
state[name] = [True, i]
print('Ok.')
2023-02-23 18:49:02 +01:00
2023-02-24 16:41:27 +01:00
# This iterator returns the extensions in the order specified in the command-line
2023-02-24 14:01:21 +01:00
def iterator():
for name in sorted(state, key=lambda x : state[x][1]):
if state[name][0] == True:
yield eval(f"extensions.{name}.script"), name
2023-02-24 16:41:27 +01:00
# Extension functions that map string -> string
def apply_extensions(text, typ):
2023-02-24 14:01:21 +01:00
for extension, _ in iterator():
if typ == "input" and hasattr(extension, "input_modifier"):
text = extension.input_modifier(text)
elif typ == "output" and hasattr(extension, "output_modifier"):
text = extension.output_modifier(text)
elif typ == "bot_prefix" and hasattr(extension, "bot_prefix_modifier"):
text = extension.bot_prefix_modifier(text)
return text
2023-02-24 14:01:21 +01:00
def update_extensions_parameters(*args):
i = 0
2023-02-24 14:01:21 +01:00
for extension, _ in iterator():
for param in extension.params:
if len(args) >= i+1:
extension.params[param] = eval(f"args[{i}]")
i += 1
2023-02-23 18:55:21 +01:00
def create_extensions_block():
extensions_ui_elements = []
default_values = []
if not (shared.args.chat or shared.args.cai_chat):
gr.Markdown('## Extensions parameters')
2023-02-24 14:01:21 +01:00
for extension, name in iterator():
for param in extension.params:
_id = f"{name}-{param}"
default_value = shared.settings[_id] if _id in shared.settings else extension.params[param]
default_values.append(default_value)
if type(extension.params[param]) == str:
extensions_ui_elements.append(gr.Textbox(value=default_value, label=f"{name}-{param}"))
elif type(extension.params[param]) in [int, float]:
extensions_ui_elements.append(gr.Number(value=default_value, label=f"{name}-{param}"))
elif type(extension.params[param]) == bool:
extensions_ui_elements.append(gr.Checkbox(value=default_value, label=f"{name}-{param}"))
2023-02-23 18:55:21 +01:00
update_extensions_parameters(*default_values)
btn_extensions = gr.Button("Apply")
btn_extensions.click(update_extensions_parameters, [*extensions_ui_elements], [])