utils.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. from importlib import util
  2. import os
  3. import re
  4. from config import TOOLS_DIR, FUNCTIONS_DIR
  5. def extract_frontmatter(file_path):
  6. """
  7. Extract frontmatter as a dictionary from the specified file path.
  8. """
  9. frontmatter = {}
  10. frontmatter_pattern = re.compile(r"^([a-z_]+):\s*(.*)\s*$", re.IGNORECASE)
  11. with open(file_path, "r", encoding="utf-8") as file:
  12. for line in file:
  13. if line.strip() == '"""':
  14. # End of frontmatter section
  15. break
  16. match = frontmatter_pattern.match(line)
  17. if match:
  18. key, value = match.groups()
  19. frontmatter[key] = value
  20. return frontmatter
  21. def load_toolkit_module_by_id(toolkit_id):
  22. toolkit_path = os.path.join(TOOLS_DIR, f"{toolkit_id}.py")
  23. spec = util.spec_from_file_location(toolkit_id, toolkit_path)
  24. module = util.module_from_spec(spec)
  25. frontmatter = extract_frontmatter(toolkit_path)
  26. try:
  27. spec.loader.exec_module(module)
  28. print(f"Loaded module: {module.__name__}")
  29. if hasattr(module, "Tools"):
  30. return module.Tools(), frontmatter
  31. else:
  32. raise Exception("No Tools class found")
  33. except Exception as e:
  34. print(f"Error loading module: {toolkit_id}")
  35. # Move the file to the error folder
  36. os.rename(toolkit_path, f"{toolkit_path}.error")
  37. raise e
  38. def load_function_module_by_id(function_id):
  39. function_path = os.path.join(FUNCTIONS_DIR, f"{function_id}.py")
  40. spec = util.spec_from_file_location(function_id, function_path)
  41. module = util.module_from_spec(spec)
  42. frontmatter = extract_frontmatter(function_path)
  43. try:
  44. spec.loader.exec_module(module)
  45. print(f"Loaded module: {module.__name__}")
  46. if hasattr(module, "Pipe"):
  47. return module.Pipe(), "pipe", frontmatter
  48. elif hasattr(module, "Filter"):
  49. return module.Filter(), "filter", frontmatter
  50. else:
  51. raise Exception("No Function class found")
  52. except Exception as e:
  53. print(f"Error loading module: {function_id}")
  54. # Move the file to the error folder
  55. os.rename(function_path, f"{function_path}.error")
  56. raise e