Image Pipeline Playground
feat(backend/engine): cache and preview non-image ports
Mohammad Rajaei5963bc2eff3a
diff --git a/backend/app/engine/cache.py b/backend/app/engine/cache.pyindex b06a71b..21efbd5 100644--- a/backend/app/engine/cache.py+++ b/backend/app/engine/cache.py@@ -1,4 +1,4 @@-"""Content-addressed filesystem cache for intermediate images."""+"""Content-addressed filesystem cache for intermediate images and annotations."""from __future__ import annotations@@ -11,15 +11,24 @@ import cv2import numpy as np+def is_image_value(value: Any) -> bool:+ """Return True when value is an ndarray or a non-empty list of ndarrays."""+ if isinstance(value, np.ndarray):+ return True+ if isinstance(value, list) and value and all(isinstance(item, np.ndarray) for item in value):+ return True+ return False++class CacheManager:- """Stores and retrieves numpy images keyed by content hashes."""+ """Stores and retrieves numpy images and JSON annotation payloads."""def __init__(self, root: Path | str) -> None:self.root = Path(root)self.root.mkdir(parents=True, exist_ok=True)@staticmethod- def hash_payload(payload: dict[str, Any]) -> str:+ def hash_payload(payload: Any) -> str:encoded = json.dumps(payload, sort_keys=True, default=str).encode("utf-8")return hashlib.sha256(encoded).hexdigest()@@ -31,6 +40,17 @@ class CacheManager:digest.update(np.ascontiguousarray(image).tobytes())return digest.hexdigest()+ def hash_value(self, value: Any) -> str:+ if value is None:+ return "none"+ if isinstance(value, np.ndarray):+ return self.hash_image(value)+ if isinstance(value, list) and value and all(+ isinstance(item, np.ndarray) for item in value+ ):+ return self.hash_payload([self.hash_image(item) for item in value])+ return self.hash_payload(value)+def make_key(self,node_type: str,@@ -57,6 +77,9 @@ class CacheManager:def _port_path(self, key: str, port: str) -> Path:return self._base(key).parent / f"{key}__{port}.png"+ def _annotation_path(self, key: str, port: str) -> Path:+ return self._base(key).parent / f"{key}__{port}.json"+def get(self, key: str) -> np.ndarray | None:image_path, meta_path = self._paths(key)if not image_path.exists() or not meta_path.exists():@@ -78,23 +101,27 @@ class CacheManager:def put_outputs(self,key: str,- outputs: dict[str, np.ndarray | list[np.ndarray]],+ outputs: dict[str, Any],meta: dict[str, Any] | None = None,) -> None:normalized: dict[str, np.ndarray] = {}list_ports: dict[str, int] = {}+ annotations: dict[str, Any] = {}+for port, value in outputs.items():- if isinstance(value, list):- if not value:- continue+ if isinstance(value, np.ndarray):+ normalized[port] = value+ elif isinstance(value, list) and value and all(+ isinstance(item, np.ndarray) for item in value+ ):list_ports[port] = len(value)for index, image in enumerate(value):normalized[f"{port}#{index}"] = imageelse:- normalized[port] = value+ annotations[port] = value- if not normalized:- raise ValueError(f"No images to cache for key {key}")+ if not normalized and not annotations:+ raise ValueError(f"No outputs to cache for key {key}")base = self._base(key)base.parent.mkdir(parents=True, exist_ok=True)@@ -103,26 +130,32 @@ class CacheManager:if not cv2.imwrite(str(path), image):raise RuntimeError(f"Failed to write cache image for key {key} port {port}")- if "image" in normalized and len(normalized) == 1:+ for port, payload in annotations.items():+ path = self._annotation_path(key, port)+ path.write_text(json.dumps(payload), encoding="utf-8")++ if "image" in normalized and len(normalized) == 1 and not annotations:legacy, _ = self._paths(key)cv2.imwrite(str(legacy), normalized["image"])- payload = {+ meta_payload = {"key": key,"ports": sorted(normalized.keys()),"list_ports": list_ports,+ "annotation_ports": sorted(annotations.keys()),**(meta or {}),}- base.with_suffix(".json").write_text(json.dumps(payload), encoding="utf-8")+ base.with_suffix(".json").write_text(json.dumps(meta_payload), encoding="utf-8")- def get_outputs(self, key: str) -> dict[str, np.ndarray | list[np.ndarray]] | None:+ def get_outputs(self, key: str) -> dict[str, Any] | None:_, meta_path = self._paths(key)if not meta_path.exists():return Nonemeta = json.loads(meta_path.read_text(encoding="utf-8"))ports = meta.get("ports") or []list_ports = meta.get("list_ports") or {}- if not ports:+ annotation_ports = meta.get("annotation_ports") or []+ if not ports and not annotation_ports:image = self.get(key)return {"image": image} if image is not None else None@@ -139,7 +172,7 @@ class CacheManager:return Noneflat[port] = image- outputs: dict[str, np.ndarray | list[np.ndarray]] = {}+ outputs: dict[str, Any] = {}consumed: set[str] = set()for port, count in list_ports.items():items: list[np.ndarray] = []@@ -153,6 +186,13 @@ class CacheManager:for port, image in flat.items():if port not in consumed:outputs[port] = image++ for port in annotation_ports:+ path = self._annotation_path(key, port)+ if not path.exists():+ return None+ outputs[port] = json.loads(path.read_text(encoding="utf-8"))+return outputsdef has_outputs(self, key: str) -> bool:diff --git a/backend/app/engine/executor.py b/backend/app/engine/executor.pyindex 1a394d8..af2bf16 100644--- a/backend/app/engine/executor.py+++ b/backend/app/engine/executor.py@@ -13,7 +13,7 @@ from typing import Anyimport cv2import numpy as np-from app.engine.cache import CacheManager+from app.engine.cache import CacheManager, is_image_valuefrom app.engine.registry import NodeRegistry, registryfrom app.engine.run_context import current_sample_indexfrom app.engine.save_bundle import SaveBundle, current_save_bundle@@ -51,12 +51,47 @@ class CancellationToken:ProgressCallback = Callable[[ExecutionEvent], None]-def _as_image(value: np.ndarray | list[np.ndarray] | None) -> np.ndarray | None:- if value is None:+def _as_image(value: Any) -> np.ndarray | None:+ if value is None or not is_image_value(value):return Noneif isinstance(value, list):return value[0] if value else None- return value+ return value if isinstance(value, np.ndarray) else None+++def _draw_annotation_overlay(+ image: np.ndarray,+ bboxes: list[Any] | None = None,+ keypoints: list[Any] | None = None,+) -> np.ndarray:+ """Draw Pascal-VOC bboxes and xy keypoints onto a BGR copy of image."""+ canvas = image if image.ndim == 3 else cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)+ canvas = canvas.copy()+ if bboxes:+ for box in bboxes:+ if not isinstance(box, (list, tuple)) or len(box) < 4:+ continue+ x1, y1, x2, y2 = (int(round(float(v))) for v in box[:4])+ cv2.rectangle(canvas, (x1, y1), (x2, y2), (0, 220, 80), 2)+ if len(box) >= 5:+ label = str(box[4])+ cv2.putText(+ canvas,+ label,+ (x1, max(0, y1 - 4)),+ cv2.FONT_HERSHEY_SIMPLEX,+ 0.4,+ (0, 220, 80),+ 1,+ cv2.LINE_AA,+ )+ if keypoints:+ for point in keypoints:+ if not isinstance(point, (list, tuple)) or len(point) < 2:+ continue+ x, y = int(round(float(point[0]))), int(round(float(point[1])))+ cv2.circle(canvas, (x, y), 4, (40, 120, 255), -1, lineType=cv2.LINE_AA)+ return canvasdef validate_graph(graph: Graph, node_registry: NodeRegistry = registry) -> dict[str, NodeInstance]:@@ -153,12 +188,12 @@ def _encode_preview(image: np.ndarray) -> str:def _collect_inputs(node_id: str,edges: list[Edge],- outputs: dict[str, dict[str, np.ndarray | list[np.ndarray]]],+ outputs: dict[str, dict[str, Any]],sample_index: int = 0,-) -> dict[str, np.ndarray | list[np.ndarray] | None]:+) -> dict[str, Any]:incoming = [edge for edge in edges if edge.target == node_id]- inputs: dict[str, np.ndarray | list[np.ndarray] | None] = {}- grouped: dict[str, list[np.ndarray]] = defaultdict(list)+ inputs: dict[str, Any] = {}+ grouped: dict[str, list[Any]] = defaultdict(list)for edge in incoming:source_outputs = outputs.get(edge.source, {})@@ -167,10 +202,12 @@ def _collect_inputs(value = next(iter(source_outputs.values()))if value is None:continue- # Fan-out batch inputs one image per sample so unary nodes keep working.- if isinstance(value, list):- if not value:- continue+ # Fan-out batch image inputs one image per sample so unary nodes keep working.+ if (+ isinstance(value, list)+ and value+ and all(isinstance(item, np.ndarray) for item in value)+ ):grouped[edge.target_port].append(value[sample_index % len(value)])else:grouped[edge.target_port].append(value)@@ -182,65 +219,86 @@ def _collect_inputs(def _input_hashes(- inputs: dict[str, np.ndarray | list[np.ndarray] | None],+ inputs: dict[str, Any],cache: CacheManager,) -> dict[str, str]:- hashes: dict[str, str] = {}- for port, value in inputs.items():- if value is None:- hashes[port] = "none"- elif isinstance(value, list):- hashes[port] = cache.hash_payload([cache.hash_image(item) for item in value])- else:- hashes[port] = cache.hash_image(value)- return hashes+ return {port: cache.hash_value(value) for port, value in inputs.items()}def _emit_port_previews(*,emit: ProgressCallback,node_id: str,- produced: dict[str, np.ndarray | list[np.ndarray]],+ produced: dict[str, Any],sample_index: int,cache_hit: bool,sample_previews: dict[str, Any],) -> None:port_previews: dict[str, Any] = {}+ annotation_data: dict[str, Any] = {}+ bboxes = produced.get("bboxes") if isinstance(produced.get("bboxes"), list) else None+ keypoints = produced.get("keypoints") if isinstance(produced.get("keypoints"), list) else None+for port_id, value in produced.items():- if isinstance(value, list):- encoded_list: list[str] = []- for index, image in enumerate(value):- preview = _encode_preview(image)- encoded_list.append(preview)- emit(- ExecutionEvent(- type=ExecutionEventType.PREVIEW,- node_id=node_id,- port_id=port_id,- image_b64=preview,- sample_index=index,- cache_hit=cache_hit,+ if is_image_value(value):+ if isinstance(value, list):+ encoded_list: list[str] = []+ for index, image in enumerate(value):+ preview = _encode_preview(image)+ encoded_list.append(preview)+ emit(+ ExecutionEvent(+ type=ExecutionEventType.PREVIEW,+ node_id=node_id,+ port_id=port_id,+ image_b64=preview,+ sample_index=index,+ cache_hit=cache_hit,+ ))+ if encoded_list:+ port_previews[port_id] = encoded_list+ continue++ image = _as_image(value)+ if image is None:+ continue+ if port_id == "image" and (bboxes or keypoints):+ image = _draw_annotation_overlay(image, bboxes=bboxes, keypoints=keypoints)+ preview = _encode_preview(image)+ port_previews[port_id] = preview+ emit(+ ExecutionEvent(+ type=ExecutionEventType.PREVIEW,+ node_id=node_id,+ port_id=port_id,+ image_b64=preview,+ sample_index=sample_index,+ cache_hit=cache_hit,+ data=(+ {"bboxes": bboxes, "keypoints": keypoints}+ if port_id == "image" and (bboxes or keypoints)+ else None+ ),)- if encoded_list:- port_previews[port_id] = encoded_list+ )continue- image = _as_image(value)- if image is None:- continue- preview = _encode_preview(image)- port_previews[port_id] = preview+ # Annotation payloads (bboxes / keypoints / other JSON-serializable).+ annotation_data[port_id] = valueemit(ExecutionEvent(type=ExecutionEventType.PREVIEW,node_id=node_id,port_id=port_id,- image_b64=preview,sample_index=sample_index,cache_hit=cache_hit,+ data={port_id: value},))++ if annotation_data:+ port_previews["__annotations__"] = annotation_dataif port_previews:sample_previews[node_id] = port_previews@@ -280,7 +338,7 @@ class DagExecutor:cancel.check()sample_seed = request.seed + sample_indexsample_token = current_sample_index.set(sample_index)- outputs: dict[str, dict[str, np.ndarray | list[np.ndarray]]] = {}+ outputs: dict[str, dict[str, Any]] = {}sample_previews: dict[str, Any] = {}try:@@ -312,7 +370,7 @@ class DagExecutor:)cache_hit = False- produced: dict[str, np.ndarray | list[np.ndarray]]+ produced: dict[str, Any]started = time.perf_counter()use_cache = request.cache and node_impl.cacheableif use_cache and self.cache.has_outputs(cache_key):diff --git a/backend/app/engine/registry.py b/backend/app/engine/registry.pyindex 379c0f9..4b37137 100644--- a/backend/app/engine/registry.py+++ b/backend/app/engine/registry.py@@ -5,8 +5,6 @@ from __future__ import annotationsfrom abc import ABC, abstractmethodfrom typing import Any-import numpy as np-from app.models.graph import NodeMetadata, ParamField, PortSpec@@ -58,11 +56,11 @@ class BaseNode(ABC):@abstractmethoddef execute(self,- inputs: dict[str, np.ndarray | list[np.ndarray] | None],+ inputs: dict[str, Any],params: dict[str, Any],seed: int = 0,- ) -> dict[str, np.ndarray | list[np.ndarray]]:- """Run the node and return output port mapping."""+ ) -> dict[str, Any]:+ """Run the node and return output port mapping (images and/or annotations)."""@abstractmethoddef emit_python(diff --git a/backend/tests/test_cache.py b/backend/tests/test_cache.pyindex f931c76..b7fa4d0 100644--- a/backend/tests/test_cache.py+++ b/backend/tests/test_cache.py@@ -29,3 +29,31 @@ def test_cache_key_changes_with_params(tmp_path) -> None:key_c = cache.make_key("blur", {"ksize": 3}, inputs, seed=1)assert key_a != key_bassert key_a != key_c+++def test_cache_mixed_image_and_annotation_ports(tmp_path) -> None:+ cache = CacheManager(tmp_path)+ image = np.zeros((4, 4, 3), dtype=np.uint8)+ image[:, :] = (1, 2, 3)+ bboxes = [[0, 0, 2, 2, "cat"]]+ keypoints = [[1.5, 1.5]]+ key = cache.make_key(+ "albu_flip",+ {"p": 1.0},+ {+ "image": cache.hash_value(image),+ "bboxes": cache.hash_value(bboxes),+ "keypoints": cache.hash_value(keypoints),+ },+ seed=0,+ )+ cache.put_outputs(+ key,+ {"image": image, "bboxes": bboxes, "keypoints": keypoints},+ meta={"type": "albu_horizontal_flip"},+ )+ loaded = cache.get_outputs(key)+ assert loaded is not None+ assert np.array_equal(loaded["image"], image)+ assert loaded["bboxes"] == bboxes+ assert loaded["keypoints"] == keypoints