utils.py 2.78 KB
Newer Older
Timothy J. Baek's avatar
Timothy J. Baek committed
1
2
from importlib import util
import os
3
import re
Timothy J. Baek's avatar
Timothy J. Baek committed
4

Timothy J. Baek's avatar
Timothy J. Baek committed
5
from config import TOOLS_DIR, FUNCTIONS_DIR
Timothy J. Baek's avatar
Timothy J. Baek committed
6
7


8
9
10
11
12
def extract_frontmatter(file_path):
    """
    Extract frontmatter as a dictionary from the specified file path.
    """
    frontmatter = {}
Timothy J. Baek's avatar
Timothy J. Baek committed
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
    frontmatter_started = False
    frontmatter_ended = False
    frontmatter_pattern = re.compile(r"^\s*([a-z_]+):\s*(.*)\s*$", re.IGNORECASE)

    try:
        with open(file_path, "r", encoding="utf-8") as file:
            for line in file:
                if '"""' in line:
                    if not frontmatter_started:
                        frontmatter_started = True
                        continue  # skip the line with the opening triple quotes
                    else:
                        frontmatter_ended = True
                        break

                if frontmatter_started and not frontmatter_ended:
                    match = frontmatter_pattern.match(line)
                    if match:
                        key, value = match.groups()
                        frontmatter[key.strip()] = value.strip()
    except FileNotFoundError:
        print(f"Error: The file {file_path} does not exist.")
        return {}
    except Exception as e:
        print(f"An error occurred: {e}")
        return {}
39
40
41
42

    return frontmatter


Timothy J. Baek's avatar
Timothy J. Baek committed
43
44
45
46
def load_toolkit_module_by_id(toolkit_id):
    toolkit_path = os.path.join(TOOLS_DIR, f"{toolkit_id}.py")
    spec = util.spec_from_file_location(toolkit_id, toolkit_path)
    module = util.module_from_spec(spec)
47
    frontmatter = extract_frontmatter(toolkit_path)
Timothy J. Baek's avatar
Timothy J. Baek committed
48
49
50
51
52

    try:
        spec.loader.exec_module(module)
        print(f"Loaded module: {module.__name__}")
        if hasattr(module, "Tools"):
53
            return module.Tools(), frontmatter
Timothy J. Baek's avatar
Timothy J. Baek committed
54
55
56
57
58
59
60
        else:
            raise Exception("No Tools class found")
    except Exception as e:
        print(f"Error loading module: {toolkit_id}")
        # Move the file to the error folder
        os.rename(toolkit_path, f"{toolkit_path}.error")
        raise e
Timothy J. Baek's avatar
Timothy J. Baek committed
61
62
63
64
65
66
67


def load_function_module_by_id(function_id):
    function_path = os.path.join(FUNCTIONS_DIR, f"{function_id}.py")

    spec = util.spec_from_file_location(function_id, function_path)
    module = util.module_from_spec(spec)
68
    frontmatter = extract_frontmatter(function_path)
Timothy J. Baek's avatar
Timothy J. Baek committed
69
70
71
72
73

    try:
        spec.loader.exec_module(module)
        print(f"Loaded module: {module.__name__}")
        if hasattr(module, "Pipe"):
74
            return module.Pipe(), "pipe", frontmatter
Timothy J. Baek's avatar
Timothy J. Baek committed
75
        elif hasattr(module, "Filter"):
76
            return module.Filter(), "filter", frontmatter
Timothy J. Baek's avatar
Timothy J. Baek committed
77
78
79
80
81
82
83
        else:
            raise Exception("No Function class found")
    except Exception as e:
        print(f"Error loading module: {function_id}")
        # Move the file to the error folder
        os.rename(function_path, f"{function_path}.error")
        raise e