extensions.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import gradio as gr
  2. import extensions
  3. import modules.shared as shared
  4. state = {}
  5. available_extensions = []
  6. def load_extensions():
  7. global state
  8. for i, name in enumerate(shared.args.extensions):
  9. if name in available_extensions:
  10. print(f'Loading the extension "{name}"... ', end='')
  11. exec(f"import extensions.{name}.script")
  12. state[name] = [True, i]
  13. print('Ok.')
  14. # This iterator returns the extensions in the order specified in the command-line
  15. def iterator():
  16. for name in sorted(state, key=lambda x : state[x][1]):
  17. if state[name][0] == True:
  18. yield eval(f"extensions.{name}.script"), name
  19. # Extension functions that map string -> string
  20. def apply_extensions(text, typ):
  21. for extension, _ in iterator():
  22. if typ == "input" and hasattr(extension, "input_modifier"):
  23. text = extension.input_modifier(text)
  24. elif typ == "output" and hasattr(extension, "output_modifier"):
  25. text = extension.output_modifier(text)
  26. elif typ == "bot_prefix" and hasattr(extension, "bot_prefix_modifier"):
  27. text = extension.bot_prefix_modifier(text)
  28. return text
  29. def create_extensions_block():
  30. # Updating the default values
  31. for extension, name in iterator():
  32. if hasattr(extension, 'params'):
  33. for param in extension.params:
  34. _id = f"{name}-{param}"
  35. if _id in shared.settings:
  36. extension.params[param] = shared.settings[_id]
  37. # Creating the extension ui elements
  38. with gr.Box(elem_id="#extensions"):
  39. gr.Markdown("Extensions")
  40. for extension, name in iterator():
  41. if hasattr(extension, "ui"):
  42. extension.ui()