utils.py 2.8 KB

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