Skip to content

Image Pipeline Playground

feat: introduce Custom Python node for user-defined image transformations

Mohammad Rajaei213bbf1b8eed
diff --git a/backend/app/engine/executor.py b/backend/app/engine/executor.py
index 8f8c712..cac02eb 100644
--- a/backend/app/engine/executor.py
+++ b/backend/app/engine/executor.py
@@ -31,6 +31,7 @@ from app.models.graph import (
NodeInstance,
PortDirection,
)
+from app.nodes.custom import graph_has_custom_python
class DagValidationError(ValueError):
@@ -353,6 +354,11 @@ class DagExecutor:
cancel: CancellationToken | None = None,
) -> dict[str, Any]:
cancel = cancel or CancellationToken()
+ if graph_has_custom_python(request.graph.nodes) and not request.allow_custom_code:
+ raise DagValidationError(
+ "This workflow includes Custom Python nodes. "
+ "Trust the custom code before running (allow_custom_code)."
+ )
nodes = validate_graph(request.graph, self.registry)
order = topological_sort(request.graph)
if request.target_node_id:
diff --git a/backend/app/models/graph.py b/backend/app/models/graph.py
index 2e8066b..96b300f 100644
--- a/backend/app/models/graph.py
+++ b/backend/app/models/graph.py
@@ -50,6 +50,8 @@ class ExecuteRequest(BaseModel):
sample_count: int = 1
cache: bool = True
target_node_id: str | None = None
+ # Required when the graph contains custom_python nodes (frontend trust gate).
+ allow_custom_code: bool = False
class ExecutionEventType(StrEnum):
diff --git a/backend/app/nodes/__init__.py b/backend/app/nodes/__init__.py
index 7e059bf..1c79263 100644
--- a/backend/app/nodes/__init__.py
+++ b/backend/app/nodes/__init__.py
@@ -28,6 +28,7 @@ from app.nodes.color import (
ToYCrCbNode,
ToYuvNode,
)
+from app.nodes.custom import CustomPythonNode
from app.nodes.filters import (
BilateralFilterNode,
BoxBlurNode,
@@ -73,6 +74,7 @@ def register_builtin_nodes() -> None:
AnnotationsNode(),
SaveImageNode(),
PreviewNode(),
+ CustomPythonNode(),
ToGrayNode(),
ToHsvNode(),
ToRgbNode(),
diff --git a/backend/app/nodes/custom.py b/backend/app/nodes/custom.py
new file mode 100644
index 0000000..ed937df
--- /dev/null
+++ b/backend/app/nodes/custom.py
@@ -0,0 +1,110 @@
+"""User-authored Python transform node (image in → image out)."""
+
+from __future__ import annotations
+
+from typing import Any
+
+import cv2
+import numpy as np
+
+from app.engine.registry import BaseNode
+from app.nodes.common import image_in, image_out, require_image, string_param
+
+DEFAULT_CUSTOM_CODE = """\
+def process(image, seed=0):
+ # image: BGR uint8 numpy array (H, W, C)
+ # return: ndarray (same dtype preferred)
+ return image
+"""
+
+CUSTOM_PYTHON_TYPE = "custom_python"
+
+
+def graph_has_custom_python(nodes: list[Any]) -> bool:
+ """True if any node instance is a custom_python node."""
+ for node in nodes:
+ node_type = node.type if hasattr(node, "type") else node.get("type")
+ if node_type == CUSTOM_PYTHON_TYPE:
+ return True
+ return False
+
+
+class CustomPythonNode(BaseNode):
+ type = CUSTOM_PYTHON_TYPE
+ label = "Custom Python"
+ category = "script"
+ description = (
+ "Run your own Python transform. Define process(image, seed=0) and return a BGR ndarray. "
+ "Code runs with full local privileges — only trust workflows you understand."
+ )
+ ports = [image_in(), image_out()]
+ params = [
+ string_param(
+ "code",
+ "Code",
+ DEFAULT_CUSTOM_CODE,
+ description="Python source that defines process(image, seed=0).",
+ ),
+ ]
+ cacheable = True
+
+ def execute(
+ self,
+ inputs: dict[str, np.ndarray | list[np.ndarray] | None],
+ params: dict[str, Any],
+ seed: int = 0,
+ ) -> dict[str, np.ndarray | list[np.ndarray]]:
+ image = require_image(inputs)
+ code = str(params.get("code") or "")
+ if not code.strip():
+ raise ValueError("Custom Python node has empty code")
+
+ namespace: dict[str, Any] = {
+ "__builtins__": __builtins__,
+ "cv2": cv2,
+ "np": np,
+ "numpy": np,
+ }
+ try:
+ compiled = compile(code, "<custom_python>", "exec")
+ exec(compiled, namespace, namespace) # noqa: S102 — intentional user code
+ except SyntaxError as exc:
+ raise ValueError(f"Custom Python syntax error: {exc}") from exc
+ except Exception as exc: # noqa: BLE001
+ raise ValueError(f"Custom Python failed while loading: {exc}") from exc
+
+ process = namespace.get("process")
+ if not callable(process):
+ raise ValueError("Custom Python code must define a callable process(image, seed=0)")
+
+ try:
+ result = process(image, seed=seed)
+ except TypeError:
+ try:
+ result = process(image)
+ except Exception as exc: # noqa: BLE001
+ raise ValueError(f"Custom Python process() failed: {exc}") from exc
+ except Exception as exc: # noqa: BLE001
+ raise ValueError(f"Custom Python process() failed: {exc}") from exc
+
+ if not isinstance(result, np.ndarray):
+ raise TypeError(
+ f"Custom Python process() must return a numpy ndarray, got {type(result).__name__}"
+ )
+ return {"image": result}
+
+ def emit_python(
+ self,
+ node_id: str,
+ params: dict[str, Any],
+ input_vars: dict[str, str],
+ output_vars: dict[str, str],
+ ) -> list[str]:
+ code = str(params.get("code") or DEFAULT_CUSTOM_CODE).rstrip()
+ lines = [
+ f"# --- custom_python: {node_id} ---",
+ *code.splitlines(),
+ f"{output_vars['image']} = process({input_vars['image']}, seed=seed)",
+ f"# --- end custom_python: {node_id} ---",
+ ]
+ return lines
diff --git a/backend/tests/test_custom_python_node.py b/backend/tests/test_custom_python_node.py
new file mode 100644
index 0000000..ef7cef5
--- /dev/null
+++ b/backend/tests/test_custom_python_node.py
@@ -0,0 +1,140 @@
+"""Tests for Custom Python node."""
+
+from __future__ import annotations
+
+import numpy as np
+import pytest
+
+from app.engine.executor import DagExecutor, DagValidationError
+from app.engine.registry import registry
+from app.models.graph import (
+ Edge,
+ ExecuteRequest,
+ Graph,
+ NodeInstance,
+)
+from app.nodes import register_builtin_nodes
+from app.nodes.custom import DEFAULT_CUSTOM_CODE
+
+
+def test_custom_python_registered() -> None:
+ register_builtin_nodes()
+ assert "custom_python" in {meta.type for meta in registry.list_metadata()}
+
+
+def test_custom_python_identity() -> None:
+ register_builtin_nodes()
+ image = np.zeros((8, 8, 3), dtype=np.uint8)
+ image[2:6, 2:6] = (10, 20, 30)
+ result = registry.get("custom_python").execute(
+ {"image": image},
+ {"code": DEFAULT_CUSTOM_CODE},
+ seed=0,
+ )["image"]
+ np.testing.assert_array_equal(result, image)
+
+
+def test_custom_python_simple_transform() -> None:
+ register_builtin_nodes()
+ image = np.full((4, 4, 3), 10, dtype=np.uint8)
+ code = """
+def process(image, seed=0):
+ return image + 5
+"""
+ result = registry.get("custom_python").execute(
+ {"image": image},
+ {"code": code},
+ seed=0,
+ )["image"]
+ np.testing.assert_array_equal(result, image + 5)
+
+
+def test_custom_python_bad_syntax() -> None:
+ register_builtin_nodes()
+ image = np.zeros((4, 4, 3), dtype=np.uint8)
+ with pytest.raises(ValueError, match="syntax error"):
+ registry.get("custom_python").execute(
+ {"image": image},
+ {"code": "def process(image, seed=0\n return image"},
+ seed=0,
+ )
+
+
+def test_custom_python_missing_process() -> None:
+ register_builtin_nodes()
+ image = np.zeros((4, 4, 3), dtype=np.uint8)
+ with pytest.raises(ValueError, match="process"):
+ registry.get("custom_python").execute(
+ {"image": image},
+ {"code": "x = 1"},
+ seed=0,
+ )
+
+
+def test_custom_python_wrong_return_type() -> None:
+ register_builtin_nodes()
+ image = np.zeros((4, 4, 3), dtype=np.uint8)
+ with pytest.raises(TypeError, match="ndarray"):
+ registry.get("custom_python").execute(
+ {"image": image},
+ {"code": "def process(image, seed=0):\n return 42"},
+ seed=0,
+ )
+
+
+def test_executor_rejects_custom_python_without_allow(tmp_path) -> None:
+ register_builtin_nodes()
+ request = ExecuteRequest(
+ graph=Graph(
+ nodes=[
+ NodeInstance(id="src", type="blank_image", params={"width": 8, "height": 8}),
+ NodeInstance(
+ id="custom",
+ type="custom_python",
+ params={"code": DEFAULT_CUSTOM_CODE},
+ ),
+ ],
+ edges=[
+ Edge(
+ id="e1",
+ source="src",
+ source_port="image",
+ target="custom",
+ target_port="image",
+ ),
+ ],
+ ),
+ allow_custom_code=False,
+ )
+ executor = DagExecutor(tmp_path / "cache")
+ with pytest.raises(DagValidationError, match="Trust the custom code"):
+ executor.execute(request)
+
+
+def test_executor_runs_custom_python_when_allowed(tmp_path) -> None:
+ register_builtin_nodes()
+ request = ExecuteRequest(
+ graph=Graph(
+ nodes=[
+ NodeInstance(id="src", type="blank_image", params={"width": 8, "height": 8}),
+ NodeInstance(
+ id="custom",
+ type="custom_python",
+ params={"code": DEFAULT_CUSTOM_CODE},
+ ),
+ ],
+ edges=[
+ Edge(
+ id="e1",
+ source="src",
+ source_port="image",
+ target="custom",
+ target_port="image",
+ ),
+ ],
+ ),
+ allow_custom_code=True,
+ )
+ executor = DagExecutor(tmp_path / "cache")
+ result = executor.execute(request)
+ assert "order" in result
diff --git a/backend/tests/test_nodes.py b/backend/tests/test_nodes.py
index 95fd94a..6d546bc 100644
--- a/backend/tests/test_nodes.py
+++ b/backend/tests/test_nodes.py
@@ -15,6 +15,7 @@ def test_builtin_nodes_registered() -> None:
"blank_image",
"save_image",
"preview",
+ "custom_python",
"to_gray",
"to_hsv",
"to_rgb",