Skip to content

Image Pipeline Playground

feat(backend/executor): enhance preview event structure with iteration and batch indexing

Mohammad Rajaeidb8e0288126b
diff --git a/backend/app/engine/executor.py b/backend/app/engine/executor.py
index 3d208d4..65781b6 100644
--- a/backend/app/engine/executor.py
+++ b/backend/app/engine/executor.py
@@ -250,6 +250,7 @@ def _emit_port_previews(
node_id: str,
produced: dict[str, Any],
sample_index: int,
+ iteration: int,
batch_index: int,
cache_hit: bool,
sample_previews: dict[str, Any],
@@ -269,8 +270,9 @@ def _emit_port_previews(
continue
preview = _encode_preview(image)
port_previews[port_id] = preview
- # Key source batch previews by batch index so iterations do not
- # duplicate the Load Images thumbnails in the UI.
+ # Load Images (list ports): one UI slide for the batch set.
+ # Key by batch_index and pin iteration=0 so repeats do not
+ # multiply slides.
emit(
ExecutionEvent(
type=ExecutionEventType.PREVIEW,
@@ -278,6 +280,8 @@ def _emit_port_previews(
port_id=port_id,
image_b64=preview,
sample_index=batch_index,
+ iteration=0,
+ batch_index=batch_index,
cache_hit=cache_hit,
)
)
@@ -297,6 +301,8 @@ def _emit_port_previews(
port_id=port_id,
image_b64=preview,
sample_index=sample_index,
+ iteration=iteration,
+ batch_index=batch_index,
cache_hit=cache_hit,
data=(
{"bboxes": bboxes, "keypoints": keypoints}
@@ -315,6 +321,8 @@ def _emit_port_previews(
node_id=node_id,
port_id=port_id,
sample_index=sample_index,
+ iteration=iteration,
+ batch_index=batch_index,
cache_hit=cache_hit,
data={port_id: value},
)
@@ -445,6 +453,7 @@ class DagExecutor:
node_id=node_id,
produced=produced,
sample_index=flat_index,
+ iteration=iteration,
batch_index=batch_index,
cache_hit=cache_hit,
sample_previews=sample_previews,
diff --git a/backend/app/models/graph.py b/backend/app/models/graph.py
index 2b3d78d..9ae9da8 100644
--- a/backend/app/models/graph.py
+++ b/backend/app/models/graph.py
@@ -70,6 +70,8 @@ class ExecutionEvent(BaseModel):
progress: float | None = None
image_b64: str | None = None
sample_index: int | None = None
+ iteration: int | None = None
+ batch_index: int | None = None
cache_hit: bool | None = None
duration_ms: float | None = None
data: dict[str, Any] | None = None
diff --git a/backend/tests/test_executor_batch.py b/backend/tests/test_executor_batch.py
index 68d996d..8f02833 100644
--- a/backend/tests/test_executor_batch.py
+++ b/backend/tests/test_executor_batch.py
@@ -118,3 +118,61 @@ def test_two_iterations_repeat_full_set_with_seed_offset(tmp_path) -> None:
]
# Load Images previews stay keyed by batch index (not flat iteration×batch).
assert sorted(set(load_preview_indices)) == [0, 1]
+
+
+def test_preview_events_expose_iteration_and_batch(tmp_path) -> None:
+ register_builtin_nodes()
+ for index, value in enumerate((5, 9)):
+ image = np.full((4, 4, 3), value, dtype=np.uint8)
+ cv2.imwrite(str(tmp_path / f"img{index}.png"), image)
+
+ request = ExecuteRequest(
+ graph=Graph(
+ nodes=[
+ NodeInstance(
+ id="load",
+ type="load_image",
+ params={"path": str(tmp_path)},
+ ),
+ NodeInstance(
+ id="blur",
+ type="gaussian_blur",
+ params={"ksize": 3, "sigma": 0},
+ ),
+ ],
+ edges=[
+ Edge(
+ id="e1",
+ source="load",
+ source_port="image",
+ target="blur",
+ target_port="image",
+ )
+ ],
+ ),
+ seed=0,
+ sample_count=2,
+ cache=False,
+ )
+
+ load_meta: list[tuple[int | None, int | None]] = []
+ blur_meta: list[tuple[int | None, int | None]] = []
+ DagExecutor(tmp_path / "cache", node_registry=registry).execute(
+ request,
+ on_event=lambda event: (
+ load_meta.append((event.iteration, event.batch_index))
+ if event.type.value == "preview"
+ and event.node_id == "load"
+ and event.image_b64
+ else blur_meta.append((event.iteration, event.batch_index))
+ if event.type.value == "preview"
+ and event.node_id == "blur"
+ and event.image_b64
+ else None
+ ),
+ )
+
+ # Load: always iteration 0; one entry per batch image (may repeat across iters).
+ assert set(load_meta) == {(0, 0), (0, 1)}
+ # Results: one preview per (iteration, batch).
+ assert blur_meta == [(0, 0), (0, 1), (1, 0), (1, 1)]
diff --git a/frontend/src/features/canvas/PipelineNode.tsx b/frontend/src/features/canvas/PipelineNode.tsx
index e1b0ae8..31be4f0 100644
--- a/frontend/src/features/canvas/PipelineNode.tsx
+++ b/frontend/src/features/canvas/PipelineNode.tsx
@@ -12,7 +12,6 @@ import {
DialogContent,
DialogTitle,
IconButton,
- Slider,
Stack,
Typography,
} from '@mui/material'
@@ -120,6 +119,17 @@ function imagesForPort(entry: NodeImageState, portId: string): string[] {
return []
}
+/** Iterations (slides) × batch images (rows) for a port. */
+function iterationsForPort(entry: NodeImageState, portId: string): string[][] {
+ const nested = entry.portIterations?.[portId]
+ if (nested && nested.some((iteration) => iteration?.some(Boolean))) {
+ return nested
+ }
+ // Fallback: treat flat samples as one slide with all images stacked.
+ const flat = imagesForPort(entry, portId)
+ return flat.length > 0 ? [flat] : []
+}
+
function buildRowsFromColumns(
columns: string[],
columnImages: string[][],
@@ -155,7 +165,7 @@ function buildPreviewGrid({
entry: NodeImageState | undefined
outputPorts: PortSpec[]
localPreviewUrls: string[]
-}): { columns: string[]; rows: ImageItem[][]; sectionPorts: PortSpec[] } {
+}): { columns: string[]; slides: ImageItem[][][]; sectionPorts: PortSpec[] } {
// Prefer image-like output ports for the preview grid; annotation ports are
// overlaid on the image by the backend and shown as caption chips.
const imagePorts = outputPorts.filter((port) => isImageLikePort(port.data_type))
@@ -180,12 +190,19 @@ function buildPreviewGrid({
: [sectionPorts[0]?.id ?? 'image']
if (entry) {
- const columnImages = columns.map((portId) => imagesForPort(entry, portId))
- const rows = buildRowsFromColumns(columns, columnImages, sectionPorts)
- if (rows.length > 0) return { columns, rows, sectionPorts }
+ const columnIterations = columns.map((portId) => iterationsForPort(entry, portId))
+ const slideCount = Math.max(0, ...columnIterations.map((iters) => iters.length))
+ const slides: ImageItem[][][] = []
+ for (let slide = 0; slide < slideCount; slide += 1) {
+ const columnImages = columnIterations.map((iters) => iters[slide] ?? [])
+ const rows = buildRowsFromColumns(columns, columnImages, sectionPorts)
+ if (rows.length > 0) slides.push(rows)
+ }
+ if (slides.length > 0) return { columns, slides, sectionPorts }
}
if (localPreviewUrls.length > 0) {
+ // Local load previews: one slide, images stacked vertically.
const rows = localPreviewUrls.map((src, index) => [
{
src,
@@ -194,10 +211,10 @@ function buildPreviewGrid({
label: undefined as string | undefined,
},
])
- return { columns: [columns[0]], rows, sectionPorts }
+ return { columns: [columns[0]], slides: [rows], sectionPorts }
}
- return { columns, rows: [], sectionPorts }
+ return { columns, slides: [], sectionPorts }
}
function SamplePager({
@@ -220,6 +237,7 @@ function SamplePager({
px: 0.75,
display: 'flex',
alignItems: 'center',
+ justifyContent: 'center',
gap: 0.5,
borderTop: '1px solid rgba(255,255,255,0.08)',
bgcolor: '#171717',
@@ -271,27 +289,6 @@ function SamplePager({
>
›
</IconButton>
- <Slider
- size="small"
- min={0}
- max={total - 1}
- step={1}
- value={index}
- onChange={(_, value) => onChange(Array.isArray(value) ? value[0] : value)}
- sx={{
- flex: 1,
- mx: 0.5,
- color: '#7dcea0',
- py: 0.75,
- '& .MuiSlider-thumb': {
- width: 12,
- height: 12,
- },
- '& .MuiSlider-rail': {
- opacity: 0.35,
- },
- }}
- />
</Box>
)
}
@@ -338,20 +335,21 @@ export function PipelineNodeView({ id, data, selected }: NodeProps<PipelineFlowN
const sectionPorts = grid.sectionPorts
const columnCount = Math.max(1, grid.columns.length)
- const totalSlides = grid.rows.length
+ const totalSlides = grid.slides.length
const hasPager = totalSlides > 1
const activeIndex =
totalSlides === 0 ? 0 : Math.min(Math.max(0, slideIndex), totalSlides - 1)
- const activeRow = totalSlides > 0 ? grid.rows[activeIndex] : []
+ const activeRows = totalSlides > 0 ? grid.slides[activeIndex] : []
+ const rowCount = Math.max(1, activeRows.length)
// Grow the body so every stacked port handle stays inside the node chrome.
const portCount = Math.max(inputPorts.length, outputPorts.length, 1)
- const previewHeight = IMAGE_HEIGHT
+ const previewHeight = IMAGE_HEIGHT * rowCount
const contentHeight = Math.max(
previewHeight + (hasPager ? PAGER_HEIGHT : 0),
portCount * PORT_SLOT,
)
- const nodeWidth = Math.max(columnCount * CELL_WIDTH, hasPager ? 180 : CELL_WIDTH)
+ const nodeWidth = columnCount * CELL_WIDTH
useEffect(() => {
updateNodeInternals(id)
@@ -359,6 +357,7 @@ export function PipelineNodeView({ id, data, selected }: NodeProps<PipelineFlowN
id,
columnCount,
totalSlides,
+ rowCount,
hasPager,
contentHeight,
nodeWidth,
@@ -386,9 +385,18 @@ export function PipelineNodeView({ id, data, selected }: NodeProps<PipelineFlowN
return parts.join(' · ')
}, [id, nodeImages])
+ const firstImageInSlide = (index: number): ImageItem | undefined => {
+ const rows = grid.slides[index]
+ if (!rows) return undefined
+ for (const row of rows) {
+ const hit = row.find((item) => item.src)
+ if (hit) return hit
+ }
+ return rows[0]?.[0]
+ }
+
const openSlide = (index: number) => {
- const row = grid.rows[index]
- const first = row?.find((item) => item.src) ?? row?.[0]
+ const first = firstImageInSlide(index)
if (!first?.src) return
setSlideIndex(index)
setViewer(first)
@@ -593,69 +601,75 @@ export function PipelineNodeView({ id, data, selected }: NodeProps<PipelineFlowN
</Box>
) : (
<>
- <Box
- sx={{
- display: 'grid',
- gridTemplateColumns: `repeat(${columnCount}, ${CELL_WIDTH}px)`,
- height: previewHeight,
- flex: '0 0 auto',
- }}
- >
- {activeRow.map((item, col) => (
+ <Box sx={{ flex: '0 0 auto' }}>
+ {activeRows.map((row, rowIndex) => (
<Box
- key={`${item.portId ?? 'img'}-${activeIndex}-${col}`}
- className="nodrag nopan"
- onClick={(event) => {
- if (!item.src) return
- event.stopPropagation()
- setViewer(item)
- }}
+ key={`slide-${activeIndex}-row-${rowIndex}`}
sx={{
- position: 'relative',
- height: previewHeight,
- borderLeft: col === 0 ? 'none' : '1px solid rgba(255,255,255,0.08)',
- ...checkerboard,
- cursor: item.src ? 'zoom-in' : 'default',
+ display: 'grid',
+ gridTemplateColumns: `repeat(${columnCount}, ${CELL_WIDTH}px)`,
+ height: IMAGE_HEIGHT,
+ borderTop:
+ rowIndex === 0 ? 'none' : '1px solid rgba(255,255,255,0.08)',
}}
>
- {item.src ? (
+ {row.map((item, col) => (
<Box
- component="img"
- src={toSrc(item.src)}
- alt={item.label ?? 'node image'}
- draggable={false}
- sx={{
- width: '100%',
- height: '100%',
- objectFit: 'contain',
- display: 'block',
- pointerEvents: 'none',
+ key={`${item.portId ?? 'img'}-${activeIndex}-${rowIndex}-${col}`}
+ className="nodrag nopan"
+ onClick={(event) => {
+ if (!item.src) return
+ event.stopPropagation()
+ setViewer(item)
}}
- />
- ) : null}
- {(item.label || columnCount > 1) && (
- <Typography
sx={{
- position: 'absolute',
- top: 6,
- left: 6,
- px: 0.7,
- py: 0.15,
- borderRadius: 0.75,
- bgcolor: 'rgba(0,0,0,0.72)',
- color: '#fff',
- fontSize: 10,
- fontWeight: 700,
- letterSpacing: '0.04em',
- textTransform: 'uppercase',
- pointerEvents: 'none',
+ position: 'relative',
+ height: IMAGE_HEIGHT,
+ borderLeft: col === 0 ? 'none' : '1px solid rgba(255,255,255,0.08)',
+ ...checkerboard,
+ cursor: item.src ? 'zoom-in' : 'default',
}}
>
- {item.label ??
- portLabel(item.portId, sectionPorts) ??
- `Out ${col + 1}`}
- </Typography>
- )}
+ {item.src ? (
+ <Box
+ component="img"
+ src={toSrc(item.src)}
+ alt={item.label ?? 'node image'}
+ draggable={false}
+ sx={{
+ width: '100%',
+ height: '100%',
+ objectFit: 'contain',
+ display: 'block',
+ pointerEvents: 'none',
+ }}
+ />
+ ) : null}
+ {(item.label || columnCount > 1) && (
+ <Typography
+ sx={{
+ position: 'absolute',
+ top: 6,
+ left: 6,
+ px: 0.7,
+ py: 0.15,
+ borderRadius: 0.75,
+ bgcolor: 'rgba(0,0,0,0.72)',
+ color: '#fff',
+ fontSize: 10,
+ fontWeight: 700,
+ letterSpacing: '0.04em',
+ textTransform: 'uppercase',
+ pointerEvents: 'none',
+ }}
+ >
+ {item.label ??
+ portLabel(item.portId, sectionPorts) ??
+ `Out ${col + 1}`}
+ </Typography>
+ )}
+ </Box>
+ ))}
</Box>
))}
</Box>
@@ -665,8 +679,7 @@ export function PipelineNodeView({ id, data, selected }: NodeProps<PipelineFlowN
onChange={(next) => {
setSlideIndex(next)
if (viewer) {
- const row = grid.rows[next]
- const first = row?.find((item) => item.src) ?? row?.[0]
+ const first = firstImageInSlide(next)
if (first?.src) setViewer(first)
}
}}
@@ -810,21 +823,6 @@ export function PipelineNodeView({ id, data, selected }: NodeProps<PipelineFlowN
/>
)}
</Box>
- {totalSlides > 1 ? (
- <Box sx={{ px: 1, pt: 1.5, pb: 0.5 }}>
- <Slider
- size="small"
- min={0}
- max={totalSlides - 1}
- step={1}
- value={activeIndex}
- onChange={(_, value) =>
- openSlide(Array.isArray(value) ? value[0] : value)
- }
- sx={{ color: '#7dcea0' }}
- />
- </Box>
- ) : null}
</DialogContent>
</Dialog>
</>
diff --git a/frontend/src/hooks/useExecutionSocket.ts b/frontend/src/hooks/useExecutionSocket.ts
index c9372ed..9e9c0ae 100644
--- a/frontend/src/hooks/useExecutionSocket.ts
+++ b/frontend/src/hooks/useExecutionSocket.ts
@@ -94,6 +94,8 @@ export function useExecutionSocket() {
addPreview({
nodeId: event.node_id,
sampleIndex: event.sample_index ?? 0,
+ iteration: event.iteration ?? undefined,
+ batchIndex: event.batch_index ?? undefined,
imageB64: event.image_b64 ?? '',
portId: event.port_id,
cacheHit: event.cache_hit,
diff --git a/frontend/src/store/graphStore.ts b/frontend/src/store/graphStore.ts
index 56bbf8e..3196f2f 100644
--- a/frontend/src/store/graphStore.ts
+++ b/frontend/src/store/graphStore.ts
@@ -27,8 +27,13 @@ export type NodeImageState = {
samples: string[]
/** Latest image per port (compat / single-sample multiport). */
ports: Record<string, string>
- /** Per-port sample stacks: portId → images[sampleIndex]. */
+ /** Per-port flat stacks: portId → images[sampleIndex] (compat). */
portSamples: Record<string, string[]>
+ /**
+ * Per-port iteration × batch grid: portId → [iteration][batchIndex].
+ * UI slides = iterations; rows within a slide = batch images.
+ */
+ portIterations: Record<string, string[][]>
/** Latest bbox / keypoint payloads from preview events. */
annotations?: {
bboxes?: unknown
@@ -121,7 +126,7 @@ function syncNodeCounter(nodeIds: string[]) {
}
function emptyNodeImages(): NodeImageState {
- return { result: null, samples: [], ports: {}, portSamples: {} }
+ return { result: null, samples: [], ports: {}, portSamples: {}, portIterations: {} }
}
function resultForNode(
@@ -438,6 +443,7 @@ export const useGraphStore = create<GraphState>((set, get) => ({
const existing = get().nodeImages[preview.nodeId] ?? emptyNodeImages()
const ports = { ...existing.ports }
const portSamples = { ...existing.portSamples }
+ const portIterations = { ...existing.portIterations }
const nextSamples = [...existing.samples]
let annotations = existing.annotations
@@ -450,6 +456,20 @@ export const useGraphStore = create<GraphState>((set, get) => ({
portStack[preview.sampleIndex] = preview.imageB64
portSamples[portId] = portStack
+ const iteration = preview.iteration ?? 0
+ const batchIndex = preview.batchIndex ?? preview.sampleIndex
+ const iterStacks = [...(portIterations[portId] ?? [])].map((row) => [...row])
+ while (iterStacks.length <= iteration) {
+ iterStacks.push([])
+ }
+ const batchStack = [...iterStacks[iteration]]
+ while (batchStack.length <= batchIndex) {
+ batchStack.push('')
+ }
+ batchStack[batchIndex] = preview.imageB64
+ iterStacks[iteration] = batchStack
+ portIterations[portId] = iterStacks
+
if (portId === 'image' || Object.keys(ports).length === 1) {
while (nextSamples.length <= preview.sampleIndex) {
nextSamples.push('')
@@ -477,6 +497,7 @@ export const useGraphStore = create<GraphState>((set, get) => ({
samples: nextSamples,
ports,
portSamples,
+ portIterations,
annotations,
},
},
diff --git a/frontend/src/types/graph.ts b/frontend/src/types/graph.ts
index 24b692f..b5a46ec 100644
--- a/frontend/src/types/graph.ts
+++ b/frontend/src/types/graph.ts
@@ -49,6 +49,10 @@ export interface GraphNodeData {
export interface ExecutionPreview {
nodeId: string
sampleIndex: number
+ /** Outer loop index (UI slide). */
+ iteration?: number
+ /** Image within the batch set (row within a slide). */
+ batchIndex?: number
imageB64: string
portId?: string | null
cacheHit?: boolean | null
@@ -72,6 +76,8 @@ export interface ExecutionEvent {
progress?: number | null
image_b64?: string | null
sample_index?: number | null
+ iteration?: number | null
+ batch_index?: number | null
cache_hit?: boolean | null
duration_ms?: number | null
data?: Record<string, unknown> | null