utils.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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_started = False
  11. frontmatter_ended = False
  12. frontmatter_pattern = re.compile(r"^\s*([a-z_]+):\s*(.*)\s*$", re.IGNORECASE)
  13. try:
  14. with open(file_path, "r", encoding="utf-8") as file:
  15. for line in file:
  16. if '"""' in line:
  17. if not frontmatter_started:
  18. frontmatter_started = True
  19. continue # skip the line with the opening triple quotes
  20. else:
  21. frontmatter_ended = True
  22. break
  23. if frontmatter_started and not frontmatter_ended:
  24. match = frontmatter_pattern.match(line)
  25. if match:
  26. key, value = match.groups()
  27. frontmatter[key.strip()] = value.strip()
  28. except FileNotFoundError:
  29. print(f"Error: The file {file_path} does not exist.")
  30. return {}
  31. except Exception as e:
  32. print(f"An error occurred: {e}")
  33. return {}
  34. return frontmatter
  35. def load_toolkit_module_by_id(toolkit_id):
  36. toolkit_path = os.path.join(TOOLS_DIR, f"{toolkit_id}.py")
  37. spec = util.spec_from_file_location(toolkit_id, toolkit_path)
  38. module = util.module_from_spec(spec)
  39. frontmatter = extract_frontmatter(toolkit_path)
  40. try:
  41. spec.loader.exec_module(module)
  42. print(f"Loaded module: {module.__name__}")
  43. if hasattr(module, "Tools"):
  44. return module.Tools(), frontmatter
  45. else:
  46. raise Exception("No Tools class found")
  47. except Exception as e:
  48. print(f"Error loading module: {toolkit_id}")
  49. # Move the file to the error folder
  50. os.rename(toolkit_path, f"{toolkit_path}.error")
  51. raise e
  52. def load_function_module_by_id(function_id):
  53. function_path = os.path.join(FUNCTIONS_DIR, f"{function_id}.py")
  54. spec = util.spec_from_file_location(function_id, function_path)
  55. module = util.module_from_spec(spec)
  56. frontmatter = extract_frontmatter(function_path)
  57. try:
  58. spec.loader.exec_module(module)
  59. print(f"Loaded module: {module.__name__}")
  60. if hasattr(module, "Pipe"):
  61. return module.Pipe(), "pipe", frontmatter
  62. elif hasattr(module, "Filter"):
  63. return module.Filter(), "filter", frontmatter
  64. else:
  65. raise Exception("No Function class found")
  66. except Exception as e:
  67. print(f"Error loading module: {function_id}")
  68. # Move the file to the error folder
  69. os.rename(function_path, f"{function_path}.error")
  70. raise e