extensions.py 1.9 KB

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