Skip to content

Image Pipeline Playground

feat(backend/assets): register paths and write save folders

Mohammad Rajaeif10c310eab8f
diff --git a/.gitignore b/.gitignore
index 12cca70..239123f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -30,6 +30,7 @@ backend/dist/
/uploads/
/cache/
/outputs/
+/assets/
# Node / frontend
node_modules/
diff --git a/backend/app/api/routes.py b/backend/app/api/routes.py
index b0e94ea..d5587e7 100644
--- a/backend/app/api/routes.py
+++ b/backend/app/api/routes.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import sys
import uuid
from pathlib import Path
+from urllib.parse import unquote
from fastapi import APIRouter, File, HTTPException, UploadFile
from fastapi.responses import FileResponse
@@ -12,10 +13,12 @@ from pydantic import BaseModel
from app.engine.executor import DagExecutor
from app.engine.registry import registry
+from app.models.assets import RegisterAssetsRequest, RegisterAssetsResponse
from app.models.graph import ExecuteRequest, Graph, NodeMetadata
from app.nodes import register_builtin_nodes
from app.nodes.common import IMAGE_EXTENSIONS
from app.paths import cache_dir, output_dir, upload_dir
+from app.services import assets as assets_service
from app.services.codegen import generate_python
router = APIRouter(prefix="/api")
@@ -39,6 +42,7 @@ class UploadResponse(BaseModel):
kind: str
files: list[str]
count: int
+ asset_batch_id: str
class OutputDirResponse(BaseModel):
@@ -83,6 +87,19 @@ def sample_image() -> FileResponse:
return FileResponse(path, media_type="image/png", filename="lena.png")
[email protected]("/assets/sample", response_model=RegisterAssetsResponse)
+def register_sample_image() -> RegisterAssetsResponse:
+ """Register the bundled sample image as an asset batch (no copy)."""
+ path = _sample_lena_path()
+ if path is None:
+ raise HTTPException(status_code=404, detail="Sample image not found")
+ try:
+ batch = assets_service.register_paths([str(path)], kind="external")
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ return RegisterAssetsResponse(batch=batch, count=len(batch.files))
+
+
@router.post("/uploads", response_model=UploadResponse)
async def upload_images(
files: list[UploadFile] = File(...),
@@ -145,21 +162,91 @@ async def upload_images(
if path.is_file() and _allowed_extension(path.name)
)
if as_folder or append_to is not None or len(saved) > 1 or total_in_dir > 1:
- return UploadResponse(
- path=str(batch_dir.resolve()),
- kind="folder",
- files=saved,
- count=len(saved),
- )
+ response_path = str(batch_dir.resolve())
+ response_kind = "folder"
+ else:
+ response_path = saved[0]
+ response_kind = "file"
+
+ try:
+ if append_to is not None or response_kind == "folder":
+ all_files = sorted(
+ path
+ for path in batch_dir.iterdir()
+ if path.is_file() and _allowed_extension(path.name)
+ )
+ batch = assets_service.register_staged_files(all_files, root=batch_dir)
+ else:
+ batch = assets_service.register_staged_files([Path(saved[0])])
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
return UploadResponse(
- path=saved[0],
- kind="file",
+ path=response_path,
+ kind=response_kind,
files=saved,
- count=1,
+ count=len(saved),
+ asset_batch_id=batch.id,
)
[email protected]("/assets/register", response_model=RegisterAssetsResponse)
+def register_assets(body: RegisterAssetsRequest) -> RegisterAssetsResponse:
+ """Register local paths (desktop native pickers) without copying bytes."""
+ try:
+ batch = assets_service.register_paths(
+ body.paths,
+ as_folder=body.as_folder,
+ append_to=body.append_to,
+ kind="folder" if body.as_folder else "external",
+ )
+ except FileNotFoundError as exc:
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ return RegisterAssetsResponse(batch=batch, count=len(batch.files))
+
+
[email protected]("/assets/{batch_id}")
+def get_asset_batch(batch_id: str) -> RegisterAssetsResponse:
+ batch = assets_service.get_batch(batch_id)
+ if batch is None:
+ raise HTTPException(status_code=404, detail="Asset batch not found")
+ return RegisterAssetsResponse(batch=batch, count=len(batch.files))
+
+
[email protected]("/assets/{batch_id}/files/{name}")
+def get_asset_file(batch_id: str, name: str) -> FileResponse:
+ batch = assets_service.get_batch(batch_id)
+ if batch is None:
+ raise HTTPException(status_code=404, detail="Asset batch not found")
+ decoded = unquote(name)
+ match = next((item for item in batch.files if item.name == decoded), None)
+ if match is None:
+ raise HTTPException(status_code=404, detail="Asset file not found")
+ target = Path(match.path)
+ if not target.is_file():
+ raise HTTPException(status_code=404, detail="Asset file missing on disk")
+ return FileResponse(target, filename=match.name)
+
+
[email protected]("/assets/{batch_id}/files/{name}")
+def delete_asset_file(batch_id: str, name: str) -> dict:
+ decoded = unquote(name)
+ try:
+ batch = assets_service.remove_file(batch_id, decoded)
+ except FileNotFoundError as exc:
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
+ if batch is None:
+ return {"status": "deleted", "batch_id": batch_id, "empty": True}
+ return {
+ "status": "deleted",
+ "batch_id": batch_id,
+ "empty": False,
+ "count": len(batch.files),
+ }
+
+
@router.delete("/uploads")
def delete_uploaded_file(path: str) -> dict[str, str]:
"""Remove one previously uploaded image (must live under uploads/)."""
diff --git a/backend/app/engine/executor.py b/backend/app/engine/executor.py
index 65781b6..557d463 100644
--- a/backend/app/engine/executor.py
+++ b/backend/app/engine/executor.py
@@ -16,7 +16,12 @@ import numpy as np
from app.engine.cache import CacheManager, is_image_value
from app.engine.registry import NodeRegistry, registry
from app.engine.run_context import current_sample_index
-from app.engine.save_bundle import SaveBundle, current_save_bundle
+from app.engine.save_bundle import (
+ FolderSaveTracker,
+ SaveBundle,
+ current_folder_saves,
+ current_save_bundle,
+)
from app.models.graph import (
Edge,
ExecuteRequest,
@@ -26,7 +31,6 @@ from app.models.graph import (
NodeInstance,
PortDirection,
)
-from app.nodes.io import list_image_files
class DagValidationError(ValueError):
@@ -221,15 +225,14 @@ def _collect_inputs(
def _batch_size_for_graph(graph: Graph) -> int:
"""Largest Load Images batch in the graph (1 when there is no multi-image source)."""
+ from app.nodes.io import resolve_load_paths
+
size = 1
for node in graph.nodes:
if node.type != "load_image":
continue
- path_value = str(node.params.get("path", "")).strip()
- if not path_value:
- continue
try:
- files = list_image_files(Path(path_value))
+ files = resolve_load_paths(node.params)
except (OSError, ValueError, FileNotFoundError):
continue
if files:
@@ -361,7 +364,9 @@ class DagExecutor:
total_passes = iteration_count * batch_size
results: dict[str, Any] = {"order": order, "samples": []}
save_bundle = SaveBundle()
+ folder_saves = FolderSaveTracker()
bundle_token = current_save_bundle.set(save_bundle)
+ folder_token = current_folder_saves.set(folder_saves)
def emit(event: ExecutionEvent) -> None:
if on_event is not None:
@@ -471,6 +476,18 @@ class DagExecutor:
finally:
current_sample_index.reset(sample_token)
+ if folder_saves.directories:
+ for directory in sorted(folder_saves.directories):
+ emit(
+ ExecutionEvent(
+ type=ExecutionEventType.SAVED,
+ message=f"Saved {len(folder_saves.files)} image(s) to {directory}",
+ saved_dir=directory,
+ data={"count": len(folder_saves.files), "files": folder_saves.files},
+ )
+ )
+ results["saved_dirs"] = sorted(folder_saves.directories)
+
if save_bundle.files:
zip_path = save_bundle.write_zip()
download_name = zip_path.name
@@ -490,3 +507,4 @@ class DagExecutor:
return results
finally:
current_save_bundle.reset(bundle_token)
+ current_folder_saves.reset(folder_token)
diff --git a/backend/app/engine/save_bundle.py b/backend/app/engine/save_bundle.py
index dfd1ca8..89c3982 100644
--- a/backend/app/engine/save_bundle.py
+++ b/backend/app/engine/save_bundle.py
@@ -60,11 +60,29 @@ class SaveBundle:
return out.resolve()
+@dataclass
+class FolderSaveTracker:
+ """Tracks directories written by Save Image when output_dir is set."""
+
+ directories: set[str] = field(default_factory=set)
+ files: list[str] = field(default_factory=list)
+
+ def record(self, path: Path) -> None:
+ resolved = path.resolve()
+ self.files.append(str(resolved))
+ self.directories.add(str(resolved.parent))
+
+
current_save_bundle: ContextVar[SaveBundle | None] = ContextVar(
"current_save_bundle",
default=None,
)
+current_folder_saves: ContextVar[FolderSaveTracker | None] = ContextVar(
+ "current_folder_saves",
+ default=None,
+)
+
def get_save_bundle() -> SaveBundle:
bundle = current_save_bundle.get()
@@ -73,6 +91,13 @@ def get_save_bundle() -> SaveBundle:
return bundle
+def get_folder_saves() -> FolderSaveTracker:
+ tracker = current_folder_saves.get()
+ if tracker is None:
+ raise RuntimeError("Folder save tracker is not available for this run")
+ return tracker
+
+
def zip_bytes(bundle: SaveBundle) -> bytes:
"""Return ZIP contents without writing to disk (tests / helpers)."""
buffer = io.BytesIO()
diff --git a/backend/app/nodes/io.py b/backend/app/nodes/io.py
index 7b97541..af59970 100644
--- a/backend/app/nodes/io.py
+++ b/backend/app/nodes/io.py
@@ -15,7 +15,7 @@ from app.engine.run_context import (
current_source_stems,
source_stem_for_sample,
)
-from app.engine.save_bundle import get_save_bundle
+from app.engine.save_bundle import get_folder_saves, get_save_bundle
from app.nodes.common import (
IMAGE_EXTENSIONS,
file_param,
@@ -71,16 +71,18 @@ class LoadImageNode(BaseNode):
"",
accept=IMAGE_EXTENSIONS,
description="Select multiple images or a folder of images",
- )
+ ),
+ string_param(
+ "asset_batch_id",
+ "Asset Batch",
+ "",
+ description="Registered asset batch id (preferred over path)",
+ ),
]
def prepare_run(self, params: dict[str, Any]) -> None:
- path_value = str(params.get("path", ""))
- if not path_value:
- current_source_stems.set([])
- return
try:
- files = list_image_files(Path(path_value))
+ files = resolve_load_paths(params)
current_source_stems.set([file_path.stem for file_path in files])
except (OSError, ValueError, FileNotFoundError):
current_source_stems.set([])
@@ -91,11 +93,9 @@ class LoadImageNode(BaseNode):
params: dict[str, Any],
seed: int = 0,
) -> dict[str, np.ndarray | list[np.ndarray]]:
- path_value = str(params["path"])
- if not path_value:
+ files = resolve_load_paths(params)
+ if not files:
raise ValueError("Load Images requires a file or folder selection")
- path = Path(path_value)
- files = list_image_files(path)
current_source_stems.set([file_path.stem for file_path in files])
images = [read_image(file_path) for file_path in files]
return {"image": images}
@@ -107,7 +107,7 @@ class LoadImageNode(BaseNode):
input_vars: dict[str, str],
output_vars: dict[str, str],
) -> list[str]:
- path = params["path"]
+ path = str(params.get("path") or "")
dst = output_vars["image"]
return [
f"_path = Path({path!r})",
@@ -127,17 +127,37 @@ class LoadImageNode(BaseNode):
]
+def resolve_load_paths(params: dict[str, Any]) -> list[Path]:
+ """Prefer asset_batch_id; fall back to legacy path param."""
+ batch_id = str(params.get("asset_batch_id") or "").strip()
+ if batch_id:
+ from app.services.assets import list_batch_paths
+
+ return list_batch_paths(batch_id)
+ path_value = str(params.get("path") or "").strip()
+ if not path_value:
+ return []
+ return list_image_files(Path(path_value))
+
+
class SaveImageNode(BaseNode):
type = "save_image"
label = "Save Image"
category = "io"
description = (
- "Collect image(s) into a ZIP download after the run. "
+ "Write image(s) to an output folder after the run "
+ "(or pack into a ZIP when no folder is set). "
"Filename supports templates: {filename}, {time}, {index}."
)
cacheable = False
ports = [image_in(), image_out()]
params = [
+ string_param(
+ "output_dir",
+ "Output Folder",
+ "",
+ description="Local folder for saved images (desktop)",
+ ),
string_param(
"filename",
"Filename",
@@ -160,7 +180,12 @@ class SaveImageNode(BaseNode):
filename=source_stem_for_sample(sample_index),
when=datetime.now(),
)
- get_save_bundle().add_image(name, image)
+ output_dir = str(params.get("output_dir") or "").strip()
+ if output_dir:
+ written = write_image_to_dir(Path(output_dir), name, image)
+ get_folder_saves().record(written)
+ else:
+ get_save_bundle().add_image(name, image)
return {"image": image}
def emit_python(
@@ -171,12 +196,13 @@ class SaveImageNode(BaseNode):
output_vars: dict[str, str],
) -> list[str]:
name_template = str(params.get("filename") or "{filename}_{index}.png")
+ output_dir = str(params.get("output_dir") or "output")
src = input_vars["image"]
dst = output_vars["image"]
return [
"from datetime import datetime",
"from pathlib import Path",
- "_out_dir = Path('output')",
+ f"_out_dir = Path({output_dir!r})",
"_out_dir.mkdir(parents=True, exist_ok=True)",
f"_name_template = {name_template!r}",
"_index = 0 # set per sample when batching",
@@ -199,6 +225,32 @@ class SaveImageNode(BaseNode):
]
+def write_image_to_dir(directory: Path, name: str, image: np.ndarray) -> Path:
+ """Encode and write an image under directory, avoiding name collisions."""
+ directory.mkdir(parents=True, exist_ok=True)
+ safe = Path(name).name or "image.png"
+ suffix = Path(safe).suffix.lower()
+ if suffix not in {".png", ".jpg", ".jpeg", ".bmp", ".webp"}:
+ safe = f"{Path(safe).stem}.png"
+ suffix = ".png"
+ target = directory / safe
+ stem = target.stem
+ file_suffix = target.suffix
+ index = 2
+ while target.exists():
+ target = directory / f"{stem}_{index}{file_suffix}"
+ index += 1
+ encode_ext = ".jpg" if suffix in {".jpg", ".jpeg"} else suffix
+ success, buffer = cv2.imencode(encode_ext, image)
+ if not success:
+ success, buffer = cv2.imencode(".png", image)
+ target = target.with_suffix(".png")
+ if not success:
+ raise RuntimeError(f"Failed to encode image for '{target.name}'")
+ target.write_bytes(buffer.tobytes())
+ return target.resolve()
+
+
def resolve_save_filename(
name_template: str,
*,
diff --git a/backend/app/services/assets.py b/backend/app/services/assets.py
new file mode 100644
index 0000000..b982422
--- /dev/null
+++ b/backend/app/services/assets.py
@@ -0,0 +1,218 @@
+"""In-memory + disk-backed registry of image asset batches."""
+
+from __future__ import annotations
+
+import json
+import threading
+import uuid
+from pathlib import Path
+
+from app.models.assets import AssetBatch, AssetFile, AssetKind
+from app.nodes.common import IMAGE_EXTENSIONS
+from app.paths import data_root
+
+_lock = threading.RLock()
+_batches: dict[str, AssetBatch] = {}
+_loaded = False
+
+
+def _registry_path() -> Path:
+ path = data_root() / "assets"
+ path.mkdir(parents=True, exist_ok=True)
+ return path / "registry.json"
+
+
+def _allowed_extension(filename: str) -> bool:
+ suffix = Path(filename).suffix.lower()
+ return suffix in {ext.lower() for ext in IMAGE_EXTENSIONS}
+
+
+def _ensure_loaded() -> None:
+ global _loaded
+ if _loaded:
+ return
+ with _lock:
+ if _loaded:
+ return
+ path = _registry_path()
+ if path.is_file():
+ try:
+ raw = json.loads(path.read_text(encoding="utf-8"))
+ for item in raw.get("batches", []):
+ batch = AssetBatch.model_validate(item)
+ _batches[batch.id] = batch
+ except (OSError, json.JSONDecodeError, ValueError):
+ _batches.clear()
+ _loaded = True
+
+
+def _persist() -> None:
+ path = _registry_path()
+ payload = {
+ "batches": [batch.model_dump() for batch in _batches.values()],
+ }
+ path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
+
+
+def clear_registry() -> None:
+ """Test helper: drop all batches and reload flag."""
+ global _loaded
+ with _lock:
+ _batches.clear()
+ _loaded = True
+ path = _registry_path()
+ if path.is_file():
+ path.unlink()
+
+
+def get_batch(batch_id: str) -> AssetBatch | None:
+ _ensure_loaded()
+ with _lock:
+ return _batches.get(batch_id)
+
+
+def list_batch_paths(batch_id: str) -> list[Path]:
+ """Resolve a batch to concrete image paths for Load Image."""
+ batch = get_batch(batch_id)
+ if batch is None:
+ raise FileNotFoundError(f"Unknown asset batch '{batch_id}'")
+ if not batch.files:
+ if batch.root:
+ root = Path(batch.root)
+ if root.is_dir():
+ from app.nodes.io import list_image_files
+
+ return list_image_files(root)
+ if root.is_file():
+ return [root]
+ raise FileNotFoundError(f"Asset batch '{batch_id}' has no files")
+ paths: list[Path] = []
+ for item in batch.files:
+ path = Path(item.path)
+ if not path.is_file():
+ raise FileNotFoundError(f"Missing asset file '{item.path}'")
+ paths.append(path)
+ return paths
+
+
+def _unique_name(existing: set[str], filename: str) -> str:
+ if filename not in existing:
+ return filename
+ stem = Path(filename).stem
+ suffix = Path(filename).suffix
+ index = 2
+ while True:
+ candidate = f"{stem}_{index}{suffix}"
+ if candidate not in existing:
+ return candidate
+ index += 1
+
+
+def register_paths(
+ paths: list[str],
+ *,
+ as_folder: bool = False,
+ append_to: str | None = None,
+ kind: AssetKind | None = None,
+) -> AssetBatch:
+ """Register absolute paths as an asset batch (no file copy)."""
+ _ensure_loaded()
+ resolved: list[Path] = []
+ for raw in paths:
+ path = Path(raw).expanduser().resolve()
+ if path.is_dir():
+ from app.nodes.io import list_image_files
+
+ resolved.extend(list_image_files(path))
+ elif path.is_file():
+ if not _allowed_extension(path.name):
+ continue
+ resolved.append(path)
+ if not resolved:
+ raise ValueError("No supported image files to register")
+
+ with _lock:
+ if append_to:
+ batch = _batches.get(append_to)
+ if batch is None:
+ raise FileNotFoundError(f"Unknown asset batch '{append_to}'")
+ names = {item.name for item in batch.files}
+ for path in resolved:
+ name = _unique_name(names, path.name)
+ names.add(name)
+ batch.files.append(AssetFile(name=name, path=str(path)))
+ if batch.root is None and batch.files:
+ batch.root = str(Path(batch.files[0].path).parent)
+ _batches[batch.id] = batch
+ _persist()
+ return batch
+
+ batch_id = uuid.uuid4().hex
+ files: list[AssetFile] = []
+ names: set[str] = set()
+ for path in resolved:
+ name = _unique_name(names, path.name)
+ names.add(name)
+ files.append(AssetFile(name=name, path=str(path)))
+
+ if as_folder or len(files) > 1:
+ roots = {str(Path(item.path).parent) for item in files}
+ root = next(iter(roots)) if len(roots) == 1 else None
+ if as_folder and len(paths) == 1 and Path(paths[0]).is_dir():
+ root = str(Path(paths[0]).expanduser().resolve())
+ resolved_kind: AssetKind = kind or ("folder" if as_folder else "external")
+ else:
+ root = str(Path(files[0].path).parent)
+ resolved_kind = kind or "external"
+
+ batch = AssetBatch(id=batch_id, kind=resolved_kind, files=files, root=root)
+ _batches[batch_id] = batch
+ _persist()
+ return batch
+
+
+def register_staged_files(
+ file_paths: list[Path],
+ *,
+ root: Path | None = None,
+ append_to: str | None = None,
+) -> AssetBatch:
+ """Register files that already live under uploads/ (HTTP upload path)."""
+ return register_paths(
+ [str(path) for path in file_paths],
+ as_folder=len(file_paths) > 1 or root is not None,
+ append_to=append_to,
+ kind="staged",
+ )
+
+
+def remove_file(batch_id: str, name_or_path: str) -> AssetBatch | None:
+ """Remove one file from a batch. Returns updated batch, or None if deleted."""
+ _ensure_loaded()
+ with _lock:
+ batch = _batches.get(batch_id)
+ if batch is None:
+ raise FileNotFoundError(f"Unknown asset batch '{batch_id}'")
+ remaining: list[AssetFile] = []
+ removed: AssetFile | None = None
+ for item in batch.files:
+ if item.name == name_or_path or item.path == name_or_path:
+ removed = item
+ continue
+ remaining.append(item)
+ if removed is None:
+ raise FileNotFoundError(f"File not found in batch '{batch_id}'")
+ if not remaining:
+ del _batches[batch_id]
+ _persist()
+ return None
+ batch.files = remaining
+ _batches[batch_id] = batch
+ _persist()
+ return batch
+
+
+def preview_url(batch_id: str, name: str) -> str:
+ from urllib.parse import quote
+
+ return f"/api/assets/{batch_id}/files/{quote(name)}"
diff --git a/backend/tests/test_assets.py b/backend/tests/test_assets.py
new file mode 100644
index 0000000..db37ed3
--- /dev/null
+++ b/backend/tests/test_assets.py
@@ -0,0 +1,135 @@
+"""Tests for asset registration and Load Image asset_batch_id."""
+
+from __future__ import annotations
+
+import cv2
+import numpy as np
+from fastapi.testclient import TestClient
+
+from app.engine.executor import DagExecutor
+from app.engine.registry import registry
+from app.main import app
+from app.models.graph import Edge, ExecuteRequest, Graph, NodeInstance
+from app.nodes import register_builtin_nodes
+from app.services import assets as assets_service
+
+
+def test_register_local_paths(tmp_path, monkeypatch) -> None:
+ monkeypatch.setenv("IMAGE_PIPES_DATA_DIR", str(tmp_path))
+ assets_service.clear_registry()
+
+ image = np.zeros((4, 4, 3), dtype=np.uint8)
+ file_a = tmp_path / "a.png"
+ file_b = tmp_path / "b.png"
+ cv2.imwrite(str(file_a), image)
+ cv2.imwrite(str(file_b), image)
+
+ client = TestClient(app)
+ response = client.post(
+ "/api/assets/register",
+ json={"paths": [str(file_a), str(file_b)], "as_folder": False},
+ )
+ assert response.status_code == 200
+ body = response.json()
+ assert body["count"] == 2
+ batch_id = body["batch"]["id"]
+
+ listed = client.get(f"/api/assets/{batch_id}")
+ assert listed.status_code == 200
+ assert listed.json()["count"] == 2
+
+ preview = client.get(f"/api/assets/{batch_id}/files/a.png")
+ assert preview.status_code == 200
+
+
+def test_upload_returns_asset_batch_id(tmp_path, monkeypatch) -> None:
+ monkeypatch.setenv("IMAGE_PIPES_DATA_DIR", str(tmp_path))
+ assets_service.clear_registry()
+ uploads = tmp_path / "uploads"
+ uploads.mkdir()
+ monkeypatch.setattr("app.api.routes.UPLOAD_DIR", uploads)
+
+ client = TestClient(app)
+ response = client.post(
+ "/api/uploads",
+ files=[("files", ("a.png", b"\x89PNG\r\n\x1a\n", "image/png"))],
+ )
+ assert response.status_code == 200
+ body = response.json()
+ assert body["asset_batch_id"]
+ assert assets_service.get_batch(body["asset_batch_id"]) is not None
+
+
+def test_load_image_resolves_asset_batch(tmp_path, monkeypatch) -> None:
+ monkeypatch.setenv("IMAGE_PIPES_DATA_DIR", str(tmp_path))
+ assets_service.clear_registry()
+ register_builtin_nodes()
+
+ image = np.full((2, 2, 3), 7, dtype=np.uint8)
+ file_a = tmp_path / "photo.png"
+ cv2.imwrite(str(file_a), image)
+ batch = assets_service.register_paths([str(file_a)])
+
+ out = registry.get("load_image").execute(
+ {},
+ {"path": "", "asset_batch_id": batch.id},
+ seed=0,
+ )["image"]
+ assert isinstance(out, list)
+ assert len(out) == 1
+ assert out[0].shape == (2, 2, 3)
+
+
+def test_save_image_writes_output_dir(tmp_path, monkeypatch) -> None:
+ monkeypatch.setenv("IMAGE_PIPES_DATA_DIR", str(tmp_path))
+ assets_service.clear_registry()
+ register_builtin_nodes()
+
+ image = np.full((2, 2, 3), 3, dtype=np.uint8)
+ src = tmp_path / "in.png"
+ cv2.imwrite(str(src), image)
+ out_dir = tmp_path / "results"
+ events: list[str] = []
+
+ request = ExecuteRequest(
+ graph=Graph(
+ nodes=[
+ NodeInstance(
+ id="load",
+ type="load_image",
+ params={"path": str(src)},
+ ),
+ NodeInstance(
+ id="save",
+ type="save_image",
+ params={
+ "filename": "{filename}_{index}.png",
+ "output_dir": str(out_dir),
+ },
+ ),
+ ],
+ edges=[
+ Edge(
+ id="e1",
+ source="load",
+ source_port="image",
+ target="save",
+ target_port="image",
+ )
+ ],
+ ),
+ seed=0,
+ sample_count=1,
+ cache=False,
+ )
+ executor = DagExecutor(tmp_path / "cache", node_registry=registry)
+ result = executor.execute(
+ request,
+ on_event=lambda event: events.append(event.type.value),
+ )
+
+ assert "saved" in events
+ assert "download" not in events
+ assert "download_url" not in result
+ assert out_dir.is_dir()
+ assert any(out_dir.iterdir())