utils.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. from importlib import util
  2. import os
  3. import re
  4. import sys
  5. import subprocess
  6. from config import TOOLS_DIR, FUNCTIONS_DIR
  7. def extract_frontmatter(file_path):
  8. """
  9. Extract frontmatter as a dictionary from the specified file path.
  10. """
  11. frontmatter = {}
  12. frontmatter_started = False
  13. frontmatter_ended = False
  14. frontmatter_pattern = re.compile(r"^\s*([a-z_]+):\s*(.*)\s*$", re.IGNORECASE)
  15. try:
  16. with open(file_path, "r", encoding="utf-8") as file:
  17. first_line = file.readline()
  18. if first_line.strip() != '"""':
  19. # The file doesn't start with triple quotes
  20. return {}
  21. frontmatter_started = True
  22. for line in file:
  23. if '"""' in line:
  24. if frontmatter_started:
  25. frontmatter_ended = True
  26. break
  27. if frontmatter_started and not frontmatter_ended:
  28. match = frontmatter_pattern.match(line)
  29. if match:
  30. key, value = match.groups()
  31. frontmatter[key.strip()] = value.strip()
  32. except FileNotFoundError:
  33. print(f"Error: The file {file_path} does not exist.")
  34. return {}
  35. except Exception as e:
  36. print(f"An error occurred: {e}")
  37. return {}
  38. return frontmatter
  39. def load_toolkit_module_by_id(toolkit_id):
  40. toolkit_path = os.path.join(TOOLS_DIR, f"{toolkit_id}.py")
  41. spec = util.spec_from_file_location(toolkit_id, toolkit_path)
  42. module = util.module_from_spec(spec)
  43. frontmatter = extract_frontmatter(toolkit_path)
  44. try:
  45. install_frontmatter_requirements(frontmatter.get("requirements", ""))
  46. spec.loader.exec_module(module)
  47. print(f"Loaded module: {module.__name__}")
  48. if hasattr(module, "Tools"):
  49. return module.Tools(), frontmatter
  50. else:
  51. raise Exception("No Tools class found")
  52. except Exception as e:
  53. print(f"Error loading module: {toolkit_id}")
  54. # Move the file to the error folder
  55. os.rename(toolkit_path, f"{toolkit_path}.error")
  56. raise e
  57. def load_function_module_by_id(function_id):
  58. function_path = os.path.join(FUNCTIONS_DIR, f"{function_id}.py")
  59. spec = util.spec_from_file_location(function_id, function_path)
  60. module = util.module_from_spec(spec)
  61. frontmatter = extract_frontmatter(function_path)
  62. try:
  63. install_frontmatter_requirements(frontmatter.get("requirements", ""))
  64. spec.loader.exec_module(module)
  65. print(f"Loaded module: {module.__name__}")
  66. if hasattr(module, "Pipe"):
  67. return module.Pipe(), "pipe", frontmatter
  68. elif hasattr(module, "Filter"):
  69. return module.Filter(), "filter", frontmatter
  70. elif hasattr(module, "Action"):
  71. return module.Action(), "action", frontmatter
  72. else:
  73. raise Exception("No Function class found")
  74. except Exception as e:
  75. print(f"Error loading module: {function_id}")
  76. # Move the file to the error folder
  77. os.rename(function_path, f"{function_path}.error")
  78. raise e
  79. def install_frontmatter_requirements(requirements):
  80. if requirements:
  81. req_list = [req.strip() for req in requirements.split(",")]
  82. for req in req_list:
  83. print(f"Installing requirement: {req}")
  84. subprocess.check_call([sys.executable, "-m", "pip", "install", req])
  85. else:
  86. print("No requirements found in frontmatter.")