-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode.py
More file actions
200 lines (158 loc) · 6.81 KB
/
node.py
File metadata and controls
200 lines (158 loc) · 6.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
"""
Core node classes for workflow designer.
This module provides the base classes for workflow nodes without UI dependencies.
"""
from enum import Enum
from typing import Dict, Any, List, Optional
import uuid
class NodeType(Enum):
"""Types of workflow nodes."""
START = "start"
PROCESS = "process"
DECISION = "decision"
END = "end"
class NodeParameter:
"""Represents a configurable parameter for a node."""
def __init__(self, name: str, param_type: type, default: Any = None, description: str = ""):
self.name = name
self.param_type = param_type
self.default = default
self.description = description
class Node:
"""Base class for workflow nodes (logic only, no UI)."""
def __init__(self, node_id: str = None, node_type: NodeType = NodeType.PROCESS,
title: str = "Node", x: float = 0, y: float = 0):
self.id = node_id or str(uuid.uuid4())
self.node_type = node_type
self.title = title
self.x = x
self.y = y
self.parameters: Dict[str, Any] = {}
self.inputs: List[str] = [] # List of node IDs that connect to this node
self.outputs: List[str] = [] # List of node IDs this node connects to
def get_parameter_definitions(self) -> List[NodeParameter]:
"""Returns the list of configurable parameters for this node."""
return []
def set_parameter(self, name: str, value: Any):
"""Set a parameter value."""
self.parameters[name] = value
def get_parameter(self, name: str, default: Any = None) -> Any:
"""Get a parameter value."""
return self.parameters.get(name, default)
def execute(self, input_data: Any = None) -> Any:
"""Execute the node's logic. Override in subclasses."""
return input_data
def validate(self) -> tuple[bool, str]:
"""Validate the node configuration. Returns (is_valid, error_message)."""
return True, ""
def to_dict(self) -> Dict[str, Any]:
"""Serialize node to dictionary."""
return {
'id': self.id,
'type': self.node_type.value,
'title': self.title,
'x': self.x,
'y': self.y,
'parameters': self.parameters,
'inputs': self.inputs,
'outputs': self.outputs
}
@staticmethod
def from_dict(data: Dict[str, Any]) -> 'Node':
"""Deserialize node from dictionary."""
node = Node(
node_id=data['id'],
node_type=NodeType(data['type']),
title=data['title'],
x=data['x'],
y=data['y']
)
node.parameters = data.get('parameters', {})
node.inputs = data.get('inputs', [])
node.outputs = data.get('outputs', [])
return node
class StartNode(Node):
"""Start node for workflow."""
def __init__(self, node_id: str = None, x: float = 0, y: float = 0):
super().__init__(node_id, NodeType.START, "Start", x, y)
def validate(self) -> tuple[bool, str]:
"""Start node should have no inputs and at least one output."""
if len(self.inputs) > 0:
return False, "Start node cannot have inputs"
if len(self.outputs) == 0:
return False, "Start node must have at least one output"
return True, ""
class ProcessNode(Node):
"""Process node for workflow."""
def __init__(self, node_id: str = None, x: float = 0, y: float = 0):
super().__init__(node_id, NodeType.PROCESS, "Process", x, y)
def get_parameter_definitions(self) -> List[NodeParameter]:
return [
NodeParameter("operation", str, "transform", "Operation to perform"),
NodeParameter("value", str, "", "Value or expression")
]
def validate(self) -> tuple[bool, str]:
"""Process node should have at least one input and one output."""
if len(self.inputs) == 0:
return False, "Process node must have at least one input"
if len(self.outputs) == 0:
return False, "Process node must have at least one output"
return True, ""
def execute(self, input_data: Any = None) -> Any:
"""Execute the process operation."""
operation = self.get_parameter("operation", "transform")
value = self.get_parameter("value", "")
# Simple example execution
return f"{operation}({input_data}, {value})"
class DecisionNode(Node):
"""Decision node for workflow branching."""
def __init__(self, node_id: str = None, x: float = 0, y: float = 0):
super().__init__(node_id, NodeType.DECISION, "Decision", x, y)
def get_parameter_definitions(self) -> List[NodeParameter]:
return [
NodeParameter("condition", str, "", "Condition to evaluate")
]
def validate(self) -> tuple[bool, str]:
"""Decision node should have one input and multiple outputs."""
if len(self.inputs) == 0:
return False, "Decision node must have at least one input"
if len(self.outputs) < 2:
return False, "Decision node should have at least two outputs (true/false branches)"
return True, ""
def execute(self, input_data: Any = None) -> Any:
"""Evaluate the decision condition."""
condition = self.get_parameter("condition", "")
# Simple example - in real implementation, would evaluate condition
return input_data
class EndNode(Node):
"""End node for workflow."""
def __init__(self, node_id: str = None, x: float = 0, y: float = 0):
super().__init__(node_id, NodeType.END, "End", x, y)
def validate(self) -> tuple[bool, str]:
"""End node should have at least one input and no outputs."""
if len(self.inputs) == 0:
return False, "End node must have at least one input"
if len(self.outputs) > 0:
return False, "End node cannot have outputs"
return True, ""
class NodeRegistry:
"""Registry for node types to support extensibility."""
_node_classes: Dict[NodeType, type] = {
NodeType.START: StartNode,
NodeType.PROCESS: ProcessNode,
NodeType.DECISION: DecisionNode,
NodeType.END: EndNode
}
@classmethod
def create_node(cls, node_type: NodeType, **kwargs) -> Node:
"""Create a node of the specified type."""
node_class = cls._node_classes.get(node_type, Node)
return node_class(**kwargs)
@classmethod
def register_node_type(cls, node_type: NodeType, node_class: type):
"""Register a custom node type."""
cls._node_classes[node_type] = node_class
@classmethod
def get_available_types(cls) -> List[NodeType]:
"""Get list of available node types."""
return list(cls._node_classes.keys())