Skip to content

Image Pipeline Playground

feat(backend/nodes): require output folder on Save Image node

Mohammad Rajaei032d277580e9
diff --git a/backend/app/nodes/io.py b/backend/app/nodes/io.py
index b70dc31..6f42c45 100644
--- a/backend/app/nodes/io.py
+++ b/backend/app/nodes/io.py
@@ -131,18 +131,24 @@ class SaveImageNode(BaseNode):
label = "Save Image"
category = "io"
description = (
- "Write image(s) to disk. Path supports templates: "
- "{filename}, {time}, {index}."
+ "Write image(s) into a selected output folder. "
+ "Filename supports templates: {filename}, {time}, {index}."
)
cacheable = False
ports = [image_in(), image_out()]
params = [
string_param(
- "path",
- "Path",
- "output/{filename}_{index}.png",
+ "directory",
+ "Output folder",
+ "",
+ description="Required. Choose a root folder to save into.",
+ ),
+ string_param(
+ "filename",
+ "Filename",
+ "{filename}_{index}.png",
description="Templates: {filename}, {time}, {index}",
- )
+ ),
]
def execute(
@@ -151,10 +157,14 @@ class SaveImageNode(BaseNode):
params: dict[str, Any],
seed: int = 0,
) -> dict[str, np.ndarray | list[np.ndarray]]:
+ directory = str(params.get("directory", "")).strip()
+ if not directory:
+ raise ValueError("Save Image requires an output folder — choose one in the inspector")
image = require_image(inputs)
sample_index = current_sample_index.get()
path = resolve_save_path(
- str(params["path"]),
+ directory,
+ str(params.get("filename") or "{filename}_{index}.png"),
index=sample_index,
filename=source_stem_for_sample(sample_index),
when=datetime.now(),
@@ -171,24 +181,30 @@ class SaveImageNode(BaseNode):
input_vars: dict[str, str],
output_vars: dict[str, str],
) -> list[str]:
- template = str(params["path"])
+ directory = str(params.get("directory", "")).strip()
+ name_template = str(params.get("filename") or "{filename}_{index}.png")
src = input_vars["image"]
dst = output_vars["image"]
return [
"from datetime import datetime",
- f"_template = {template!r}",
+ f"_dir = Path({directory!r})",
+ f"_name_template = {name_template!r}",
"_index = 0 # set per sample when batching",
"_filename = 'image'",
"_time = datetime.now().strftime('%Y%m%d_%H%M%S')",
(
- "_path = Path(_template.replace('{filename}', _filename)"
+ "_name = (_name_template.replace('{filename}', _filename)"
".replace('{time}', _time).replace('{index}', str(_index)))"
),
+ "_name = Path(_name).name",
(
- "if _index > 0 and '{index}' not in _template "
- "and '{time}' not in _template and '{filename}' not in _template:"
+ "if _index > 0 and '{index}' not in _name_template "
+ "and '{time}' not in _name_template and '{filename}' not in _name_template:"
),
- " _path = _path.with_name(f'{_path.stem}_{_index}{_path.suffix}')",
+ " _stem = Path(_name).stem",
+ " _suffix = Path(_name).suffix",
+ " _name = f'{_stem}_{_index}{_suffix}'",
+ "_path = _dir / _name",
"_path.parent.mkdir(parents=True, exist_ok=True)",
f"cv2.imwrite(str(_path), {src})",
f"{dst} = {src}",
@@ -196,29 +212,34 @@ class SaveImageNode(BaseNode):
def resolve_save_path(
- template: str,
+ directory: str,
+ name_template: str,
*,
index: int,
filename: str,
when: datetime,
) -> Path:
- """Expand {filename}, {time}, {index} in a save path template."""
+ """Join a root folder with an expanded filename template."""
+ root = str(directory).strip()
+ if not root:
+ raise ValueError("Output folder is required")
safe_name = Path(filename).stem or "image"
- # Strip path separators from injected filename so templates stay under the intended folder.
safe_name = safe_name.replace("/", "_").replace("\\", "_")
time_token = when.strftime("%Y%m%d_%H%M%S")
expanded = (
- template.replace("{filename}", safe_name)
+ name_template.replace("{filename}", safe_name)
.replace("{time}", time_token)
.replace("{index}", str(index))
)
- path = Path(expanded)
+ # Filename only — ignore any directory components in the template.
+ name = Path(expanded).name or f"image_{index}.png"
has_unique_token = any(
- token in template for token in ("{index}", "{time}", "{filename}")
+ token in name_template for token in ("{index}", "{time}", "{filename}")
)
if index > 0 and not has_unique_token:
- path = path.with_name(f"{path.stem}_{index}{path.suffix}")
- return path
+ path_name = Path(name)
+ name = f"{path_name.stem}_{index}{path_name.suffix}"
+ return Path(root) / name
class PreviewNode(BaseNode):
diff --git a/backend/tests/test_io_save_image.py b/backend/tests/test_io_save_image.py
index 20bd28f..cea57f9 100644
--- a/backend/tests/test_io_save_image.py
+++ b/backend/tests/test_io_save_image.py
@@ -7,28 +7,33 @@ from pathlib import Path
import cv2
import numpy as np
+import pytest
+from fastapi.testclient import TestClient
from app.engine.executor import DagExecutor
from app.engine.registry import registry
from app.engine.run_context import current_sample_index, current_source_stems
+from app.main import app
from app.models.graph import Edge, ExecuteRequest, Graph, NodeInstance
from app.nodes import register_builtin_nodes
from app.nodes.io import resolve_save_path
-def test_resolve_save_path_templates() -> None:
+def test_resolve_save_path_templates(tmp_path) -> None:
when = datetime(2026, 7, 30, 22, 55, 1)
path = resolve_save_path(
- "out/{filename}_{index}_{time}.png",
+ str(tmp_path),
+ "{filename}_{index}_{time}.png",
index=2,
filename="lena",
when=when,
)
- assert path == Path("out/lena_2_20260730_225501.png")
+ assert path == tmp_path / "lena_2_20260730_225501.png"
-def test_resolve_save_path_auto_index_when_missing() -> None:
+def test_resolve_save_path_auto_index_when_missing(tmp_path) -> None:
path = resolve_save_path(
+ str(tmp_path),
"output.png",
index=3,
filename="x",
@@ -37,6 +42,28 @@ def test_resolve_save_path_auto_index_when_missing() -> None:
assert path.name == "output_3.png"
+def test_resolve_save_path_requires_directory() -> None:
+ with pytest.raises(ValueError, match="Output folder is required"):
+ resolve_save_path(
+ " ",
+ "{index}.png",
+ index=0,
+ filename="a",
+ when=datetime(2026, 1, 1, 0, 0, 0),
+ )
+
+
+def test_save_image_requires_directory() -> None:
+ register_builtin_nodes()
+ image = np.zeros((2, 2, 3), dtype=np.uint8)
+ with pytest.raises(ValueError, match="output folder"):
+ registry.get("save_image").execute(
+ {"image": image},
+ {"directory": "", "filename": "{index}.png"},
+ seed=0,
+ )
+
+
def test_save_image_uses_templates(tmp_path) -> None:
register_builtin_nodes()
image = np.zeros((4, 4, 3), dtype=np.uint8)
@@ -46,7 +73,7 @@ def test_save_image_uses_templates(tmp_path) -> None:
try:
out = registry.get("save_image").execute(
{"image": image},
- {"path": str(tmp_path / "{filename}_{index}.png")},
+ {"directory": str(tmp_path), "filename": "{filename}_{index}.png"},
seed=0,
)["image"]
finally:
@@ -69,6 +96,8 @@ def test_save_image_batch_writes_unique_files(tmp_path) -> None:
path_b = tmp_path / "b.png"
cv2.imwrite(str(path_a), a)
cv2.imwrite(str(path_b), b)
+ out_dir = tmp_path / "out"
+ out_dir.mkdir()
request = ExecuteRequest(
graph=Graph(
@@ -81,7 +110,10 @@ def test_save_image_batch_writes_unique_files(tmp_path) -> None:
NodeInstance(
id="save",
type="save_image",
- params={"path": str(tmp_path / "out" / "{filename}_{index}.png")},
+ params={
+ "directory": str(out_dir),
+ "filename": "{filename}_{index}.png",
+ },
),
],
edges=[
@@ -101,5 +133,16 @@ def test_save_image_batch_writes_unique_files(tmp_path) -> None:
executor = DagExecutor(tmp_path / "cache", node_registry=registry)
executor.execute(request)
- assert (tmp_path / "out" / "a_0.png").is_file()
- assert (tmp_path / "out" / "b_1.png").is_file()
+ assert (out_dir / "a_0.png").is_file()
+ assert (out_dir / "b_1.png").is_file()
+
+
+def test_create_output_directory(tmp_path, monkeypatch) -> None:
+ outputs = tmp_path / "outputs"
+ monkeypatch.setattr("app.api.routes.OUTPUT_DIR", outputs)
+ client = TestClient(app)
+ response = client.post("/api/outputs")
+ assert response.status_code == 200
+ body = response.json()
+ assert Path(body["path"]).is_dir()
+ assert Path(body["path"]).parent == outputs.resolve()