Skip to content

Pipelines

The decorators that build a pipeline, the pipeline object they return, and the errors raised while building or running it. See the Decorators and Snapshots & sweeps guides for usage.

Decorators

interactive

interactive(inplace: Union[bool, Callable] = False, **decorator_controls: Any)

Declare controls bound to a filter's keyword arguments.

The decorated function keeps working as a plain function, but when used inside an @interactive_pipeline the declared controls appear as GUI widgets. Unlike @interact, no GUI is launched at decoration time, so the filter can be reused across pipelines.

Controls can also be declared by the filter's own annotations (see docs/guide/controls.md): Annotated[float, (0.0, 3.0)], Annotated[bool, "label"], Annotated[T, Control(...)], Literal["a", "b"] and Enum hints make widgets, the default comes from the signature. A plain gain: float = 1.0 makes no widget. A decorator argument wins over an annotation. @interactive also works without parentheses.

Parameters:

Name Type Description Default
inplace Union[bool, Callable]

Declare that this filter mutates its input buffers. The engine then hands it private writable copies instead of read-only views. Prefer copying explicitly (img = img.copy()) in new code.

False
**decorator_controls Any

Mapping of keyword-argument name to a control declaration — a Control instance (or subclass such as KeyboardControl), the (default, [min, max]) tuple shorthand, or a bare bool for a checkbox (flip=True). A bare number or string raises ValueError: a slider needs a range, a dropdown a list of choices.

{}
Example
@interactive(gain=(1.0, [0.0, 3.0]))
def amplify(img, gain=1.0):
    return gain * img


@interactive()
def amplify_typed(img, gain: Annotated[float, (0.0, 3.0)] = 1.0):
    return gain * img
Source code in src/interactive_pipe/helper/filter_decorator.py
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
def interactive(inplace: Union[bool, Callable] = False, **decorator_controls: Any):
    """Declare controls bound to a filter's keyword arguments.

    The decorated function keeps working as a plain function, but when used
    inside an ``@interactive_pipeline`` the declared controls appear as GUI
    widgets. Unlike ``@interact``, no GUI is launched at decoration time,
    so the filter can be reused across pipelines.

    Controls can also be declared by the filter's own annotations (see
    ``docs/guide/controls.md``): ``Annotated[float, (0.0, 3.0)]``,
    ``Annotated[bool, "label"]``, ``Annotated[T, Control(...)]``,
    ``Literal["a", "b"]`` and ``Enum`` hints make widgets, the default comes from
    the signature. A plain ``gain: float = 1.0`` makes no widget. A decorator
    argument wins over an annotation. ``@interactive`` also works without
    parentheses.

    Args:
        inplace: Declare that this filter mutates its input buffers. The
            engine then hands it private writable copies instead of
            read-only views. Prefer copying explicitly
            (``img = img.copy()``) in new code.
        **decorator_controls: Mapping of keyword-argument name to a control
            declaration — a ``Control`` instance (or subclass such as
            ``KeyboardControl``), the ``(default, [min, max])`` tuple
            shorthand, or a bare bool for a checkbox (``flip=True``). A bare
            number or string raises ``ValueError``: a slider needs a range,
            a dropdown a list of choices.

    Example:
        ```python
        @interactive(gain=(1.0, [0.0, 3.0]))
        def amplify(img, gain=1.0):
            return gain * img


        @interactive()
        def amplify_typed(img, gain: Annotated[float, (0.0, 3.0)] = 1.0):
            return gain * img
        ```
    """

    def wrapper(func, localns=None):
        if localns is None:
            localns = _caller_namespace(1)
        controls = analyze_filter_controls(func, decorator_controls, localns=localns)
        inner = _annotated_filter_wrapper(func, controls, use_controls=True)

        # picked up by HeadlessPipeline.from_function when building the FilterCore
        setattr(inner, "__interactive_pipe_inplace__", inplace)
        # inner.snapshot / .sweep / .describe / .summary / .interact (GitHub issue #21)
        attach_filter_entry_points(inner)
        return inner

    if callable(inplace) and not isinstance(inplace, bool):
        # bare @interactive (no parentheses): the decorated function comes in as `inplace`
        func, inplace = inplace, False
        return wrapper(func, localns=_caller_namespace(1))
    return wrapper

interactive_pipeline

interactive_pipeline(gui: Union[str, Backend, None] = 'auto', safe_input_buffer_deepcopy: Optional[bool] = None, cache: Union[bool, str] = False, readonly_inputs: bool = True, context: Optional[dict] = None, markdown_description: Optional[str] = None, name: Optional[str] = None, **kwargs_gui: Any) -> Callable[[Callable[..., Any]], Union[HeadlessPipeline, Callable[..., Any]]]

Decorator turning a pipeline function into an interactive GUI application.

The decorated function chains filters (typically declared with @interactive) and is analyzed statically to build the execution graph. Its body must therefore contain only filter-function calls (possibly nested, with literal keyword arguments such as amplify(img, gain=2.0)), assignments and one final return — no control flow (if/for/while) or arithmetic; put such logic inside the filters themselves. Anything else raises PipelineSyntaxError at decoration time, naming the line and the fix.

Parameters:

Name Type Description Default
gui Union[str, Backend, None]

Backend used to display the pipeline. One of "auto", "qt", "mpl", "nb" (Jupyter widgets), "gradio" or a Backend enum value. None or "headless" returns a HeadlessPipeline without launching any GUI.

'auto'
safe_input_buffer_deepcopy Optional[bool]

Deep-copy the input buffers before each run. None (default) copies only inputs that the read-only machinery cannot protect (anything but numpy arrays / torch tensors when readonly_inputs is True); True always copies (one full copy of the inputs per run); False never copies.

None
readonly_inputs bool

Hand filters their numpy inputs as read-only views (default True), so in-place mutation (img += 1) raises immediately instead of silently corrupting sibling filters or cached buffers. Declare @interactive(inplace=True) on a filter that intentionally mutates its inputs (it then receives private writable copies), or pass False to restore the permissive behavior.

True
cache Union[bool, str]

Cache intermediate filter outputs between runs. - False (default): recompute every filter on every interaction. - True: sequential prefix cache - a change recomputes every filter after it in source order. - "graph": dependency-aware cache - only filters actually affected by a change are recomputed, following the data-flow graph and runtime-tracked context usage. - "graph-strict": same as "graph", but context reads return numpy arrays as read-only views so accidental in-place mutation raises at the offending line (debug helper).

False
context Optional[dict]

Initial content of the shared context dictionary, readable and writable from filters through the context proxy.

None
markdown_description Optional[str]

Description displayed by backends that support it (e.g. Gradio).

None
name Optional[str]

Window/application title. Defaults to the function name.

None
**kwargs_gui Any

Extra options forwarded to the GUI backend, e.g. size ((w, h), "fullscreen" or "maximized"), or restore_session=True to remember the slider values between launches (saved on exit to ~/.interactive_pipe/sessions/<name>.yaml unless session_path is given), or actual_size="window" (Qt, dpg) so that key 1 also resizes the cells and the window to the native size of the images (by default it zooms them to 100% in place).

{}

Environment overrides (read when the decorator is applied): INTERACTIVE_PIPE_GUI (auto/qt/dpg/mpl/nb/gradio/headless/none) replaces gui when it is "auto" (the default), and INTERACTIVE_PIPE_SIZE ("fullscreen", "maximized" or "WxH") provides size when none is given. Explicit arguments win over the environment; interactive_pipe.cli.parse_gui_args values are explicit arguments, so the command line wins over both.

``INTERACTIVE_PIPE_SNAPSHOT`` (a PNG path or folder, ``{name}`` is
replaced by the function name): when set, any GUI ``gui`` value
returns a launcher that renders a snapshot there and returns the
results instead of opening a window (``gui=None`` is unaffected).

Returns:

Type Description
Callable[[Callable[..., Any]], Union[HeadlessPipeline, Callable[..., Any]]]

A decorator. Applied to a pipeline function it returns either a

Callable[[Callable[..., Any]], Union[HeadlessPipeline, Callable[..., Any]]]

HeadlessPipeline (when gui is None or "headless") or a

Callable[[Callable[..., Any]], Union[HeadlessPipeline, Callable[..., Any]]]

callable that launches the GUI when invoked with the pipeline inputs.

Callable[[Callable[..., Any]], Union[HeadlessPipeline, Callable[..., Any]]]

Both have .headless, the HeadlessPipeline itself:

Callable[[Callable[..., Any]], Union[HeadlessPipeline, Callable[..., Any]]]

my_pipeline.headless(img, gain=2.0) returns the outputs without

Callable[[Callable[..., Any]], Union[HeadlessPipeline, Callable[..., Any]]]

opening a window (whatever gui), .snapshot / .sweep /

Callable[[Callable[..., Any]], Union[HeadlessPipeline, Callable[..., Any]]]

.describe / .summary render or describe it.

Raises:

Type Description
TypeError

If a removed pre-0.9.0 context alias (global_params, state, ...) is passed; use context={...} instead.

PipelineSyntaxError

If the pipeline body contains a statement the static analysis cannot express (see the guide).

Example
@interactive_pipeline(gui="qt", cache=True)
def my_pipeline(img):
    flipped = flip(img)
    amplified = amplify(flipped)
    return flipped, amplified

my_pipeline(input_image)  # opens the interactive window
Source code in src/interactive_pipe/helper/pipeline_decorator.py
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
def interactive_pipeline(
    gui: Union[str, Backend, None] = "auto",
    safe_input_buffer_deepcopy: Optional[bool] = None,
    cache: Union[bool, str] = False,
    readonly_inputs: bool = True,
    context: Optional[dict] = None,
    markdown_description: Optional[str] = None,
    name: Optional[str] = None,
    **kwargs_gui: Any,
) -> Callable[[Callable[..., Any]], Union[HeadlessPipeline, Callable[..., Any]]]:
    """Decorator turning a pipeline function into an interactive GUI application.

    The decorated function chains filters (typically declared with
    ``@interactive``) and is analyzed statically to build the execution
    graph. Its body must therefore contain only filter-function calls
    (possibly nested, with literal keyword arguments such as
    ``amplify(img, gain=2.0)``), assignments and one final return — no
    control flow (if/for/while) or arithmetic; put such logic inside the
    filters themselves. Anything else raises ``PipelineSyntaxError`` at
    decoration time, naming the line and the fix.

    Args:
        gui: Backend used to display the pipeline. One of ``"auto"``,
            ``"qt"``, ``"mpl"``, ``"nb"`` (Jupyter widgets), ``"gradio"``
            or a ``Backend`` enum value. ``None`` or ``"headless"``
            returns a ``HeadlessPipeline`` without launching any GUI.
        safe_input_buffer_deepcopy: Deep-copy the input buffers before each
            run. None (default) copies only inputs that the read-only
            machinery cannot protect (anything but numpy arrays / torch
            tensors when ``readonly_inputs`` is True); True always copies
            (one full copy of the inputs per run); False never copies.
        readonly_inputs: Hand filters their numpy inputs as read-only views
            (default True), so in-place mutation (``img += 1``) raises
            immediately instead of silently corrupting sibling filters or
            cached buffers. Declare ``@interactive(inplace=True)`` on a filter
            that intentionally mutates its inputs (it then receives private
            writable copies), or pass False to restore the permissive
            behavior.
        cache: Cache intermediate filter outputs between runs.
            - False (default): recompute every filter on every interaction.
            - True: sequential prefix cache - a change recomputes every
              filter after it in source order.
            - "graph": dependency-aware cache - only filters actually
              affected by a change are recomputed, following the data-flow
              graph and runtime-tracked ``context`` usage.
            - "graph-strict": same as "graph", but context reads return
              numpy arrays as read-only views so accidental in-place
              mutation raises at the offending line (debug helper).
        context: Initial content of the shared context dictionary, readable
            and writable from filters through the ``context`` proxy.
        markdown_description: Description displayed by backends that support
            it (e.g. Gradio).
        name: Window/application title. Defaults to the function name.
        **kwargs_gui: Extra options forwarded to the GUI backend,
            e.g. ``size`` (``(w, h)``, ``"fullscreen"`` or ``"maximized"``),
            or ``restore_session=True`` to remember the slider values
            between launches (saved on exit to
            ``~/.interactive_pipe/sessions/<name>.yaml`` unless
            ``session_path`` is given), or ``actual_size="window"`` (Qt, dpg)
            so that key 1 also resizes the cells and the window to the native
            size of the images (by default it zooms them to 100% in place).

    Environment overrides (read when the decorator is applied):
        ``INTERACTIVE_PIPE_GUI`` (auto/qt/dpg/mpl/nb/gradio/headless/none)
        replaces ``gui`` when it is ``"auto"`` (the default), and
        ``INTERACTIVE_PIPE_SIZE`` ("fullscreen", "maximized" or "WxH")
        provides ``size`` when none is given. Explicit arguments win over
        the environment; ``interactive_pipe.cli.parse_gui_args`` values are
        explicit arguments, so the command line wins over both.

        ``INTERACTIVE_PIPE_SNAPSHOT`` (a PNG path or folder, ``{name}`` is
        replaced by the function name): when set, any GUI ``gui`` value
        returns a launcher that renders a snapshot there and returns the
        results instead of opening a window (``gui=None`` is unaffected).

    Returns:
        A decorator. Applied to a pipeline function it returns either a
        ``HeadlessPipeline`` (when ``gui`` is None or ``"headless"``) or a
        callable that launches the GUI when invoked with the pipeline inputs.
        Both have ``.headless``, the ``HeadlessPipeline`` itself:
        ``my_pipeline.headless(img, gain=2.0)`` returns the outputs without
        opening a window (whatever ``gui``), ``.snapshot`` / ``.sweep`` /
        ``.describe`` / ``.summary`` render or describe it.

    Raises:
        TypeError: If a removed pre-0.9.0 context alias (``global_params``,
            ``state``, ...) is passed; use ``context={...}`` instead.
        PipelineSyntaxError: If the pipeline body contains a statement the
            static analysis cannot express (see the guide).

    Example:
        ```python
        @interactive_pipeline(gui="qt", cache=True)
        def my_pipeline(img):
            flipped = flip(img)
            amplified = amplify(flipped)
            return flipped, amplified

        my_pipeline(input_image)  # opens the interactive window
        ```
    """
    # Reject removed aliases of the 'context' parameter with a clear message
    for alias in REMOVED_CONTEXT_ALIASES:
        if alias in kwargs_gui:
            raise TypeError(
                f"@interactive_pipeline: '{alias}' argument was removed in interactive_pipe 0.9.0; "
                "pass context={...} instead."
            )

    def wrapper(pipeline_function: Callable[..., Any]) -> Union[HeadlessPipeline, Callable[..., Any]]:
        def build() -> HeadlessPipeline:
            return HeadlessPipeline.from_function(
                pipeline_function,
                safe_input_buffer_deepcopy=safe_input_buffer_deepcopy,
                cache=cache,
                readonly_inputs=readonly_inputs,
                context=context,
            )

        headless_pipeline = build()
        # Environment overrides (INTERACTIVE_PIPE_GUI / INTERACTIVE_PIPE_SIZE), see interactive_pipe.cli
        selected_gui = resolve_gui(gui)
        if selected_gui is None or selected_gui == "headless":
            return headless_pipeline
        from interactive_pipe.headless.pointer import check_targets

        check_targets(headless_pipeline)  # with a window, an unknown on= output fails at decoration
        if snapshot_requested():
            # INTERACTIVE_PIPE_SNAPSHOT: render a PNG instead of opening a window
            return _snapshot_launcher(
                pipeline_function,
                headless_pipeline,
                _gui_for_snapshot(
                    selected_gui, headless_pipeline, markdown_description, name, pipeline_function, dict(kwargs_gui)
                ),
                build(),
            )
        else:
            gui_options = dict(kwargs_gui)
            if gui_options.get("size") is None:
                env_size = size_from_env()
                if env_size is not None:
                    gui_options["size"] = env_size
            InteractivePipeGui = get_interactive_pipeline_class(selected_gui)
            gui_pipeline = InteractivePipeGui(
                pipeline=headless_pipeline,
                markdown_description=markdown_description,
                name=name if name is not None else pipeline_function.__name__,
                **gui_options,
            )

        @functools.wraps(pipeline_function)
        def inner(*args: Any, **kwargs: Any) -> Any:
            return gui_pipeline.__call__(*args, **kwargs)

        # Attach the GUI pipeline object to the function so users can access methods like graph_representation
        setattr(inner, "pipeline", gui_pipeline)
        # the same pipeline without a window: demo.headless(img, gain=2.0) returns the outputs
        attach_headless(inner, pipeline_function.__name__, build())
        setattr(inner, "graph_representation", gui_pipeline.graph_representation)
        # See-the-result loop without opening the window (same calls as on a HeadlessPipeline)
        for method_name in SEE_THE_RESULT_METHODS:
            setattr(inner, method_name, getattr(headless_pipeline, method_name))

        return inner

    return wrapper

interact

interact(*decorator_args: Any, gui: str = 'auto', disable: bool = False, output_routing: Optional[List[str]] = None, size: Union[str, Tuple[int, int], None] = None, inplace: bool = False, **decorator_controls: Any)

Launch a GUI from a single decorated function (one-shot decorator).

Unlike @interactive, decorating a function with @interact immediately runs it inside a GUI: widgets are created for the declared controls and the window opens right away. Inspired by the ipywidgets interact function, except that returning numpy arrays or Curve instances handles the display automatically — no matplotlib boilerplate.

Parameters:

Name Type Description Default
*decorator_args Any

Positional inputs passed to the function (e.g. the input image).

()
gui str

Backend, same values as interactive_pipeline (default "auto").

'auto'
disable bool

When True, return the function untouched (no GUI).

False
output_routing Optional[List[str]]

Names of the outputs, when they cannot be deduced from a dry run.

None
size Union[str, Tuple[int, int], None]

Window/figure size hint forwarded to the backend.

None
**decorator_controls Any

Controls bound to keyword arguments by name (Control instances or the (default, [min, max]) tuple shorthand).

{}
Example
@interact(image, gain=(1.0, [0.0, 3.0]))
def show(img, gain=1.0):
    return img * gain
Source code in src/interactive_pipe/helper/filter_decorator.py
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
def interact(
    *decorator_args: Any,
    gui: str = "auto",
    disable: bool = False,
    output_routing: Optional[List[str]] = None,
    size: Union[str, Tuple[int, int], None] = None,
    inplace: bool = False,
    **decorator_controls: Any,
):
    """Launch a GUI from a single decorated function (one-shot decorator).

    Unlike ``@interactive``, decorating a function with ``@interact``
    immediately runs it inside a GUI: widgets are created for the declared
    controls and the window opens right away. Inspired by the ipywidgets
    ``interact`` function, except that returning numpy arrays or ``Curve``
    instances handles the display automatically — no matplotlib boilerplate.

    Args:
        *decorator_args: Positional inputs passed to the function
            (e.g. the input image).
        gui: Backend, same values as ``interactive_pipeline``
            (default ``"auto"``).
        disable: When True, return the function untouched (no GUI).
        output_routing: Names of the outputs, when they cannot be deduced
            from a dry run.
        size: Window/figure size hint forwarded to the backend.
        **decorator_controls: Controls bound to keyword arguments by name
            (``Control`` instances or the ``(default, [min, max])`` tuple
            shorthand).

    Example:
        ```python
        @interact(image, gain=(1.0, [0.0, 3.0]))
        def show(img, gain=1.0):
            return img * gain
        ```
    """
    omitted_parentheses_flag = False

    def wrapper(func):
        if disable:
            return func
        # this will run the GUI automatically
        filter_instance = filter_from_function(func, inplace=inplace, **decorator_controls)
        filter_instance.run_gui(
            *(decorator_args if not omitted_parentheses_flag else decorator_args[1:]),
            gui=gui,
            output_routing=output_routing,
            size=size,
        )
        # return the original function if you want to keep using it afterwards
        return func

    if len(decorator_args) == 1 and callable(decorator_args[0]):
        omitted_parentheses_flag = True
        return wrapper(decorator_args[0])  # no parenthesis
    return wrapper

Pipeline object

@interactive_pipeline(gui=None) returns a HeadlessPipeline; HeadlessPipeline.from_function(fn) builds one without the decorator. GUI pipelines expose snapshot, sweep, describe and summary too, and every @interactive filter has .snapshot(), .sweep(), .describe(), .summary() and .interact(img) running it alone.

HeadlessPipeline

Bases: PipelineCore

PipelineCore extensions - saving/loading to disk - graphs - init from interpreted functions

Adds some powerful features to the pipeline core such as: - creating a pipeline from a function as a sequential filter - importing/exporting parameters ("tuning") as json or yaml - saving output images - printing current parameters in the terminal - graph representation

Source code in src/interactive_pipe/headless/pipeline.py
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
class HeadlessPipeline(PipelineCore):
    """PipelineCore extensions - saving/loading to disk - graphs - init from interpreted functions

    Adds some powerful features to the pipeline core such as:
    - creating a pipeline from a function as a sequential filter
    - importing/exporting parameters ("tuning") as json or yaml
    - saving output images
    - printing current parameters in the terminal
    - graph representation
    """

    controls: List[Control]  # List of controls connected to filters

    @property
    def parameters(self):
        """Get current parameters from all filters"""
        return super().parameters

    @parameters.setter
    def parameters(self, new_parameters):
        """Override to also update control values when parameters are set"""
        # Call parent setter to update filter values using the descriptor protocol
        PipelineCore.parameters.__set__(self, new_parameters)
        # Update control values to match the new parameters
        if hasattr(self, "controls"):
            for ctrl in self.controls:
                for filt, param_name in ctrl.targets:
                    if filt.name in new_parameters and param_name in new_parameters[filt.name]:
                        ctrl.value = new_parameters[filt.name][param_name]

    @property
    def inputs(self):
        return PipelineCore.inputs.fget(self)  # type: ignore[attr-defined]

    @inputs.setter
    def inputs(self, inputs):
        """Set the inputs; a ``Video`` or ``AudioClip`` input gets a filter and the timeline
        (``headless/timeline.py``), a ``Webcam`` input a frame filter and the live clock (``headless/live.py``)."""
        PipelineCore.inputs.fset(self, inputs)  # type: ignore[attr-defined]
        from interactive_pipe.data_objects.webcam import Webcam
        from interactive_pipe.headless.live import install_webcams
        from interactive_pipe.headless.timeline import install_timeline, is_timeline_input

        given = getattr(self, "_PipelineCore__inputs", None) or {}  # None: a pipeline without inputs
        install_timeline(self, {name: value for name, value in given.items() if is_timeline_input(value)})
        install_webcams(self, {name: value for name, value in given.items() if isinstance(value, Webcam)})

    def adopt_video_inputs(self, input_values: Any = None, inputs: Optional[dict] = None) -> None:
        """Install the timeline of the ``Video`` / ``AudioClip`` inputs about to be given,
        before the keyword arguments naming it (``frame=10``) are checked. Nothing
        happens without one among them (the inputs may be reused)."""
        from interactive_pipe.headless.live import install_webcams, webcams_in
        from interactive_pipe.headless.timeline import install_timeline, media_in

        values = inputs if inputs is not None else list(input_values or [])
        media = media_in(self.inputs_routing, values)
        if media:
            install_timeline(self, media)
        webcams = webcams_in(self.inputs_routing, values)  # a Webcam input brings its live clock
        if webcams:  # removal: the inputs setter (here the inputs may be reused, not given)
            install_webcams(self, webcams)

    @property
    def timeline(self):
        """The ``TimelineControl`` of the ``Video`` / ``AudioClip`` inputs (None without one)."""
        from interactive_pipe.headless.timeline import timeline_of

        return timeline_of(self)

    @property
    def headless(self) -> "HeadlessPipeline":
        """This pipeline (``my_pipeline.headless(img)`` works whatever the ``gui``:
        a GUI-decorated function's ``.headless`` is its HeadlessPipeline)."""
        return self

    @property
    def styles(self) -> Dict[str, Dict[str, Any]]:
        """``layout.style`` options of each output after the last run, as
        ``{output name: {"title": ..., "colormap": ..., ...}}`` (a copy).

        Readouts written in titles are testable without a window::

            out = my_pipeline.headless(img, radius=2)
            assert my_pipeline.headless.styles["overlay"]["title"] == "mean IoU 0.80"

        An output whose filter did not re-run (cache) keeps the style of the
        run that produced it; an output never styled is absent.
        """
        return {name: dict(style) for name, style in self.framework_state.output_styles.items()}

    @staticmethod
    def routing_indexes(inputs_names, all_variables):
        if not inputs_names:
            return None
        return [all_variables[input_name] for input_name in inputs_names]

    @classmethod
    def from_function(cls, pipe: Callable[..., Any], inputs=None, *, _routing_by_indexes=False, **kwargs):
        if not isinstance(pipe, Callable):
            raise TypeError(f"pipe must be Callable, got {type(pipe)}")
        graph = get_call_graph(pipe)
        all_variables = {}
        total_index = 0
        function_inputs = {}
        input_routing = []
        for input_index, input_name in enumerate(graph["args"]):
            all_variables[input_name] = total_index
            function_inputs[input_name] = total_index
            if _routing_by_indexes:
                input_routing.append(total_index)
            else:
                input_routing.append(input_name)
            total_index += 1
        for filt_dict in graph["call_graph"]:
            for key in ["args", "returns"]:
                for variable_name in filt_dict[key] or []:
                    if variable_name not in all_variables:
                        all_variables[variable_name] = total_index
                        total_index += 1

        filters = []
        filters_count = {}
        filters_names = []
        bindings = []  # (filter, parameter name, control), connected once names are resolved
        seen_function_ids = set()
        # The pipeline owns clones of the declared controls (two pipelines built
        # from one filter never share values). One clone per share key and
        # filter instance suffix: the same declared Control object used by
        # several filters is one widget driving all of them.
        pipeline_clones: dict = {}

        def pipeline_control(declared: Control, suffix: str, filter_name: str, param_name: str) -> Control:
            key = (declared.share_key, suffix)
            clone = pipeline_clones.get(key)
            if clone is None:
                # first instance: starts from the declared control's value; repeats from the default
                clone = declared._clone_unconnected(declared.name + suffix, keep_value=not suffix)
                clone._declared_by = f"{filter_name}.{param_name}"  # type: ignore[attr-defined]
                pipeline_clones[key] = clone
            elif clone.value_default != declared.value_default:
                raise ValueError(
                    f"control '{clone.name}' is shared by {clone._declared_by} and {filter_name}.{param_name} "  # type: ignore[attr-defined]
                    f"with different defaults ({clone.value_default!r} and {declared.value_default!r}): "
                    "one widget has one default, give both parameters the same default"
                )
            return clone

        for filt_dict in graph["call_graph"]:
            # avoid duplicate filters names
            filt_name = filt_dict["function_name"]
            filter_count = filters_count.get(filt_name, -1)
            if filter_count >= 0:
                filters_count[filt_name] += 1
                filt_name = filt_name + f"_{filters_count[filt_name]}"
            else:
                filters_count[filt_name] = 0
            if _routing_by_indexes:
                inputs_filt = HeadlessPipeline.routing_indexes(filt_dict["args"], all_variables)
                outputs_filt = HeadlessPipeline.routing_indexes(filt_dict["returns"], all_variables)
            else:
                inputs_filt = filt_dict["args"]
                outputs_filt = filt_dict["returns"]
            logging.debug(f"-----------------> {filt_name} {inputs_filt} {outputs_filt}")
            if isinstance(filt_dict["function_object"], FilterCore):
                filt = filt_dict["function_object"]
                filt.inputs = inputs_filt
                filt.outputs = outputs_filt
                filt.name = filt_name
                # EnhancedFilterCore (filter_from_function) carries its controls; a plain FilterCore has none
                params_to_analyze = dict(getattr(filt, "controls", None) or {})
            else:
                # when using the @interactive decorator
                filt = FilterCore(
                    name=filt_name,
                    inputs=inputs_filt,
                    outputs=outputs_filt,
                    apply_fn=filt_dict["function_object"],
                    inplace=bool(getattr(filt_dict["function_object"], "__interactive_pipe_inplace__", False)),
                )
                func_kwargs = analyze_apply_fn_signature(filt_dict["function_object"])[1]
                declared_controls = Control.get_controls(filt_dict["function_object"])
                if id(filt_dict["function_object"]) not in seen_function_ids:
                    suffix = ""
                else:
                    # Repeated filter: each repeat gets its own clones, suffixed
                    # like the filter name ("amount" -> "amount_1"). Key/timer-bound
                    # controls are not cloned - their key bindings would collide -
                    # so repeats run those with default values.
                    suffix = f"_{filters_count[filt_dict['function_name']]}"
                    declared_controls = {
                        param_name: ctrl
                        for param_name, ctrl in declared_controls.items()
                        if not isinstance(ctrl, (KeyboardControl, TimeControl))
                    }
                registered_controls = {
                    param_name: pipeline_control(ctrl, suffix, filt_name, param_name)
                    for param_name, ctrl in declared_controls.items()
                }
                params_to_analyze = {**func_kwargs, **registered_controls}
            # Literal keyword arguments in the pipeline body (`amplify(img, gain=2.5)`)
            # set this instance's value; a bound control gets a per-instance clone
            # with that default so the other instances keep theirs.
            literal_kwargs = filt_dict.get("kwargs") or {}
            for param_name, literal_value in literal_kwargs.items():
                bound_control = params_to_analyze.get(param_name)
                if isinstance(bound_control, Control):
                    try:
                        params_to_analyze[param_name] = bound_control._clone_with_default(literal_value)
                    except (TypeError, ValueError) as exc:
                        raise PipelineSyntaxError(
                            f"invalid value for '{param_name}' of filter '{filt_dict['function_name']}': {exc}",
                            hint="use a value accepted by the control, or change the control declaration",
                            **filt_dict.get("location", {}),
                        ) from None
            for param_name, param_value in params_to_analyze.items():
                if isinstance(param_value, Control):
                    bindings.append((filt, param_name, param_value))
            filt.values = {
                param_name: literal_value
                for param_name, literal_value in literal_kwargs.items()
                if not isinstance(params_to_analyze.get(param_name), Control)
            }
            # the pipeline line calling this filter: output count checks and messages
            filt.call_location = filt_dict.get("location")
            filters.append(filt)
            filters_names.append(filt_name)
            seen_function_ids.add(id(filt_dict["function_object"]))
        logging.debug(filters_count)
        logging.debug(filters_names)

        bindings = cls._disambiguate_control_names(bindings)
        control_list = []
        connected = set()
        for filt, param_name, ctrl in bindings:
            if id(ctrl) in connected:
                ctrl._add_target(filt, param_name)  # one control shared by several filters
            else:
                ctrl.connect_filter(filt, param_name)
                connected.add(id(ctrl))
                control_list.append(ctrl)
            filt.values = {param_name: ctrl.value_default}

        # GUI widgets are keyed by control name: distinct controls sharing a
        # name within one pipeline would silently drive the wrong filter.
        controls_by_name = {}
        for ctrl in control_list:
            previous = controls_by_name.get(ctrl.name)
            if previous is not None and previous is not ctrl:
                where = ", ".join(f"{f.name}.{p}" for f, p in previous.targets + ctrl.targets)
                raise ValueError(
                    f"Duplicate control name '{ctrl.name}' in pipeline '{pipe.__name__}' ({where}): "
                    "two different controls cannot have the same name. "
                    "To drive several filters with one widget, declare the control once and pass the same object "
                    f"to each filter (band = Control(...); @interactive(band=band) on both); "
                    "otherwise pass a distinct name=... to one of them."
                )
            controls_by_name[ctrl.name] = ctrl

        # Helper function to convert nested output names to indexes
        def convert_outputs_to_indexes(output_structure):
            if isinstance(output_structure, str):
                return all_variables[output_structure]
            elif isinstance(output_structure, list):
                return [convert_outputs_to_indexes(item) for item in output_structure]
            else:
                return output_structure

        if _routing_by_indexes:
            outputs = convert_outputs_to_indexes(graph["returns"])
        else:
            outputs = graph["returns"]
        if len(function_inputs) == 0 and inputs is None:
            logging.info("Auto deduced that there are no arguments provided to the function")
        data_class = cls(
            filters=filters,
            name=graph["function_name"],
            inputs=input_routing,
            outputs=outputs,
            **kwargs,
        )
        data_class.controls = control_list
        # a point / region control aimed (on=...) at an output the pipeline does not produce:
        # a warning here (a headless test pipeline may reuse the filter without that output);
        # @interactive_pipeline with a GUI and every GUI construction raise
        from interactive_pipe.headless.pointer import check_targets

        check_targets(data_class, strict=False)
        if len(function_inputs) == 0 and inputs is None:
            # nothing to wait for: run() and export_animation() work before the first call
            data_class.inputs = None
        return data_class

    @staticmethod
    def _disambiguate_control_names(bindings: list) -> list:
        """Rename auto-named controls whose name collides with another control of the pipeline.

        Two filters each declaring a ``gain`` control is the normal case: every
        auto-named control bound to a colliding parameter name becomes
        ``"<filter>.<param>"`` (``amplify.gain``, ``blend.gain``; a repeated
        filter's ``gain_1`` becomes ``amplify_1.gain``), so the widget label
        says which filter it drives and matches
        ``parameters={"<filter>": {"<param>": value}}``. Repeats of a single
        filter without any other collision keep the ``gain``, ``gain_1``
        suffixes. Controls named explicitly (``name=...``) are never renamed;
        if they still collide, the caller raises.

        A control shared by several filters (the same declared object) is
        never renamed. Renamed controls are clones: the declared control is
        never mutated, and building the same pipeline twice gives the same names.
        """
        uses: dict = {}
        for _filt, _param, ctrl in bindings:
            uses[id(ctrl)] = uses.get(id(ctrl), 0) + 1
        by_name: dict = {}
        for binding in bindings:
            ctrl = binding[2]
            group = by_name.setdefault(ctrl.name, [])
            if all(other[2] is not ctrl for other in group):
                group.append(binding)
        colliding_params = set()
        for group in by_name.values():
            if len(group) < 2:
                continue
            for _filt, param_name, ctrl in group:
                # a control shared by several filters keeps its name (it is one widget)
                if ctrl._auto_named and uses[id(ctrl)] == 1:
                    colliding_params.add(param_name)
        if not colliding_params:
            return bindings
        renamed = []
        for filt, param_name, ctrl in bindings:
            if ctrl._auto_named and uses[id(ctrl)] == 1 and param_name in colliding_params:
                ctrl = ctrl._clone_unconnected(f"{filt.name}.{param_name}")
            renamed.append((filt, param_name, ctrl))
        return renamed

    def export_tuning(self, path: Optional[Path] = None, override=False) -> None:
        """Export the current parameters of every filter to a json/yaml file"""
        if path is not None:
            Parameters(self.parameters).save(path, override=override)

    def import_tuning(self, path: Optional[Path] = None) -> None:
        """Open a json/yaml tuning file and set parameters"""
        try:
            self.parameters = Parameters.from_file(path).data
        except Exception:
            # Broad on purpose: best-effort load, a corrupt/missing tuning file
            # must not crash the app (bound to a GUI key).
            logging.exception(f"Cannot load parameters from {path}")

    def load_tuning(self, path: Path) -> None:
        """Load a json/yaml tuning file written by ``export_tuning`` (alias of ``import_tuning``).

        Example:
            ```python
            pipe.export_tuning("my_tuning.yaml")
            pipe.load_tuning("my_tuning.yaml")
            ```
        """
        self.import_tuning(path)

    def __repr__(self):
        """Describe filters routing and tuning parameters"""
        ret = "\n".join(repr(filt) for filt in self.filters)
        ret += "\n{\n"
        for sl in self.filters:
            ret += f"{sl.name} : {sl.values},\n"
        ret = ret[:-2] + "\n"  # remove comma for yaml
        ret += "}"
        return ret

    def update_parameters_from_controls(self):
        if not hasattr(self, "controls"):
            # Not having .controls attribute
            # This happens for headless pipelines which have no list of controls
            return
        # Merge control values into existing parameters instead of replacing
        current_params = self.parameters  # Get current parameters
        for ctrl in self.controls:
            for filt, param_name in ctrl.targets:
                current_params.setdefault(filt.name, {})[param_name] = ctrl.value
        # Assign once, after every control has been merged, and to the filters only:
        # the HeadlessPipeline setter also writes the values back into the controls,
        # which would overwrite a control changed meanwhile (GUI thread while a
        # threaded run reads them, or not-yet-merged controls after a GUI reset).
        PipelineCore.parameters.__set__(self, current_params)  # type: ignore[attr-defined]

    def _collect(self, result_full: dict, output_indexes: Any) -> Any:
        """Outputs named by ``output_indexes`` (flat: a tuple; 2D: a list of rows)."""
        if not output_indexes:
            return None
        if isinstance(output_indexes[0], list):
            # 2D layout: keep None placeholders so (row, col) positions stay aligned
            # with the layout (empty cells are skipped by the GUI)
            return [
                [None if out_index is None else result_full.get(out_index) for out_index in row]
                for row in output_indexes
                if isinstance(row, (list, tuple))
            ]
        return tuple(result_full[idx] for idx in output_indexes if idx in result_full)

    def _run_full(self) -> dict:
        self.update_parameters_from_controls()
        result_full = super().run()
        _release_pyplot_figures(result_full.values())
        self._last_result_full = result_full
        return result_full

    def run(self):
        """Run once; the outputs in the display layout (``self.outputs``, which
        ``layout.grid`` and the GUIs change), as the windows and snapshots show them."""
        result_full = self._run_full()
        # read after the run: a layout.grid call during it changes the layout
        output_indexes = self.outputs if self.outputs is not None else self.filters[-1].outputs
        self.results = self._collect(result_full, output_indexes)
        return self.results

    def _returned_results(self) -> Any:
        """Outputs of the last run in the pipeline function's ``return`` order and shape."""
        return self._collect(self._last_result_full, self.returned_outputs)

    def save(
        self,
        path: Optional[Path] = None,
        data_wrapper_fn: Optional[Callable[..., Any]] = None,
        output_indexes: Optional[list] = None,
        save_entire_buffer: bool = False,
    ) -> List[Path]:
        """Run the pipeline and write its outputs (and the tuning) next to ``path``.

        Output ``name`` is written to ``<stem>_<name><suffix>``, the current
        parameters to ``<stem>.yaml``. The format follows the output type:

        - numpy image (``(H, W)``, ``(H, W, 1|3|4)``; float in ``[0, 1]``,
          uint8, uint16 or bool) -> image file through ``Image`` (``path``'s
          suffix if it is ``.png``/``.jpg``/``.tif``, else ``.png``)
        - 1D numpy array -> ``.csv``; any other numpy array -> ``.npy``
        - ``Image``, ``Curve``, ``SingleCurve``, ``Table`` -> their own ``save``
          (``path``'s suffix when they support it, else their default one)
        - ``str`` -> ``.txt``

        Other output types are skipped with a single warning. Pass
        ``data_wrapper_fn`` to wrap every output yourself (it must return an
        object with a ``save(path)`` method).

        Args:
            path: Base file path, e.g. ``"out/result.png"``.
            data_wrapper_fn: Optional wrapper applied to each output.
            output_indexes: Names (or indexes) of the buffers to save;
                defaults to the pipeline outputs.
            save_entire_buffer: Save every intermediate buffer.

        Returns:
            The list of written output files (the tuning file excluded).
        """
        if output_indexes is None:
            output_indexes = self.returned_outputs  # whatever layout.grid displays
        if save_entire_buffer:
            output_indexes = None  # you may force specific buffer index you'd like to save
        wanted = None if output_indexes is None else set(_flatten_outputs(output_indexes))
        if path is None:
            raise ValueError("path must be provided for saving")
        # as run(): with the current control values (and pyplot figures released)
        result_full = self._run_full()
        if result_full is None:
            return []
        if not isinstance(path, Path):
            path = Path(path)
        self.export_tuning(path.with_suffix(".yaml"))
        if not isinstance(result_full, dict):
            raise RuntimeError(f"Expected dict from pipeline run, got {type(result_full)}")
        written: List[Path] = []
        skipped = []
        for num, res_current in result_full.items():
            if wanted is not None and num not in wanted:
                continue
            if res_current is None or (isinstance(res_current, list) and len(res_current) == 0):
                continue
            current_name = path.with_name(f"{path.stem}_{_safe_file_part(num)}{path.suffix}")
            try:
                if data_wrapper_fn is not None:
                    to_save = data_wrapper_fn(res_current)
                    if not hasattr(to_save, "save"):
                        raise AttributeError(f"Result object {type(to_save)} has no 'save' method")
                    to_save.save(current_name)  # type: ignore
                    saved_path = getattr(to_save, "path", None) or current_name
                else:
                    saved_path = _save_output(res_current, current_name)
                    if saved_path is None:
                        skipped.append(f"{num} ({type(res_current).__name__})")
                        continue
            except Exception:
                # Broad on purpose: one failed output must not abort the
                # whole batch save; continue with the remaining outputs.
                logging.exception(f"Cannot save output {num} to {current_name}")
                continue
            written.append(Path(saved_path))
            logging.info(f"saved output {num} to {saved_path}")
        if skipped:
            logging.warning(
                f"Not saved (unsupported output type): {', '.join(skipped)}. "
                "Supported: numpy arrays, Image, Curve, SingleCurve, Table, str - "
                "or pass data_wrapper_fn=... returning an object with a save(path) method."
            )
        return written

    def parameters_from_keyword_args(self, **kwargs) -> dict:
        """Map ``pipeline(img, gain=2.0)`` keyword arguments to ``{filter: {param: value}}``.

        Same spellings as ``snapshot`` / ``sweep``: a parameter name sets it in
        every filter that has one, a control name (``exposure``, ``gain_1``,
        ``amplify.gain``) sets the parameter it drives, ``"filter.param"``
        (``pipe(img, **{"amplify.gain": 2.0})``) sets one filter only.

        Raises:
            TypeError: if a keyword matches no parameter.
        """
        from interactive_pipe.headless.explore import resolve_names

        resolved = resolve_names(
            self,
            list(kwargs),
            caller=f"pipeline '{self.name}'",
            reserved=("inputs", "parameters", "context"),
        )
        new_param_dict: dict = {}
        for key, value in kwargs.items():
            for filter_name, param_name in resolved[key]:
                new_param_dict.setdefault(filter_name, {})[param_name] = value
        return new_param_dict

    def __call__(self, *inputs_tuple, inputs=None, parameters=None, context=None, **kwargs) -> Any:
        """Run the pipeline once and return its outputs.

        Example:
            ```python
            blurred, edges = pipe(img, sigma=2.0)
            (single,) = pipe1(img)  # always a tuple, even for one output
            ```

        Args:
            *inputs_tuple: Pipeline inputs, in the order of the pipeline function's arguments.
            inputs: Inputs as a ``{input_name: value}`` dict instead.
            parameters: ``{filter_name: {parameter: value}}``, validated before anything changes.
            context: Values merged into the shared ``context`` before the run (they are
                also part of the fresh context ``snapshot`` / ``sweep`` start from).
            **kwargs: Parameter values: a parameter name (every filter having it), a
                control name or ``"filter.parameter"``. Like a slider move, the value
                is kept for the next runs.

        Returns:
            A tuple of the outputs in ``return`` order (a list of rows when the
            function returns a 2D list), or None when the pipeline returns
            nothing. A ``layout.grid`` call changes what is displayed, not this.

        Raises:
            TypeError: unknown keyword / wrong number of inputs.
            FilterError: a filter raised (the message names the filter and the line).
        """
        self.adopt_video_inputs(inputs_tuple, inputs)  # frame=... names the timeline of a Video input
        # validated first: an unknown keyword raises before anything is changed
        kwargs_params = self.parameters_from_keyword_args(**kwargs)
        if parameters is not None:
            from interactive_pipe.headless.explore import check_parameters_dict

            check_parameters_dict(self, parameters, f"pipeline '{self.name}'")
        if inputs is not None:
            if not isinstance(inputs, dict):
                raise TypeError(f"inputs must be a dict, got {type(inputs)}")
            self.inputs = inputs  # type: ignore
            logging.debug(f"Dict style inputs {list(inputs.keys())}")
        else:
            # the inputs setter validates the count against inputs_routing
            self.inputs = list(inputs_tuple) if inputs_tuple else None  # type: ignore
        # Handle context parameter - update user context if provided
        self.update_user_context(context)
        # Only update self.parameters if parameters argument is explicitly provided
        if parameters is not None:
            self.parameters = parameters
        # Merge in any keyword arguments as parameters
        if kwargs_params:
            # Get current parameters, merge, and re-set to trigger the setter
            current_params = self.parameters  # Calls getter
            for filter_name, params in kwargs_params.items():
                if filter_name not in current_params:
                    current_params[filter_name] = {}
                current_params[filter_name].update(params)
            self.parameters = current_params  # Calls setter to apply to filters
        self.run()
        # the pipeline's return order and shape, not the display layout (layout.grid)
        return self._returned_results()

    def graph_representation(self, path=None, ortho=True, view=False, format=None):
        """Draw the pipeline graph: inputs, filters (with their parameters), outputs.

        By default writes one standalone HTML page (inline SVG, no dependency,
        opens in any browser) and returns its ``Path``.

        Args:
            path: file to write. Default: ``<pipeline name>.html``. A path
                without ``.html`` suffix gets one, unless its suffix names a
                graphviz format (``.svg``, ``.png``, ``.pdf``...).
            ortho: graphviz only: orthogonal edges.
            view: open the result (the HTML page in the web browser; never
                under ``INTERACTIVE_PIPE_SNAPSHOT``).
            format: ``"html"`` (default) or a graphviz output format (``"svg"``,
                ``"png"``, ``"pdf"``...), which needs the ``graphviz`` package
                and system executables and returns the ``graphviz.Digraph``
                (None when graphviz is missing, as before).

        Example:
            ```python
            path = pipe.graph_representation("my_pipeline.html")
            dot = pipe.graph_representation("my_pipeline", format="pdf")  # graphviz
            ```
        """
        from interactive_pipe.headless.graph_html import write_graph_html

        suffix = Path(str(path)).suffix.lower().lstrip(".") if path is not None else ""
        if format is None:
            format = suffix if suffix in GRAPHVIZ_FORMATS else "html"
        format = str(format).lower().lstrip(".")
        if format != "html":
            if path is not None and suffix == format:
                path = str(Path(str(path)).with_suffix(""))
            return self._graphviz_representation(path=path, ortho=ortho, view=view, format=format)
        if path is None:
            path = "".join(char if char.isalnum() or char in "-_." else "_" for char in str(self.name)) or "pipeline"
        path = Path(path)
        if path.suffix.lower() not in (".html", ".htm"):
            path = path.with_name(path.name + ".html")
        written = write_graph_html(self, path)
        if view:
            _open_in_browser(written)
        return written

    def _graphviz_representation(self, path=None, ortho=True, view=False, format="pdf"):
        """graphviz rendering of ``pipeline_graph`` (optional dependency)."""
        from interactive_pipe.headless.graph_html import pipeline_graph

        graphviz_hint = (
            "Graphviz executables not found. Please install Graphviz system package:\n"
            "  - Ubuntu/Debian: sudo apt-get install graphviz\n"
            "  - macOS: brew install graphviz\n"
            "  - Windows: Download from https://graphviz.org/download/\n"
            "or use the dependency-free HTML graph: graph_representation('graph.html')"
        )
        try:
            import graphviz
        except ImportError as exc:
            logging.warning("cannot generate pipeline graph, need to install graphviz (or use format='html')")
            logging.warning(exc)
            return None

        # Try to import ExecutableNotFound, but handle if it's not available
        try:
            from graphviz.backend.execute import ExecutableNotFound
        except (ImportError, AttributeError):
            ExecutableNotFound = None

        if self.inputs_routing is None:
            raise ValueError("Cannot plot graph: input routing is not provided")
        if self.outputs is None:
            raise ValueError("Cannot generate graph: outputs not defined")
        graph = pipeline_graph(self)
        ids = {node.id: f"node{idx}" for idx, node in enumerate(graph.nodes)}  # ":" means a port to graphviz
        dot = graphviz.Digraph(comment=self.name)
        if ortho:
            dot.attr(splines="ortho")
        with dot.subgraph(name="cluster_in") as inputs_graph:  # type: ignore[reportAssignmentType]
            inputs_graph.attr(style="dashed", color="gray", label="Inputs")  # type: ignore[reportAttributeAccessIssue]
            for node in graph.nodes:
                if node.kind == "input":
                    inputs_graph.node(ids[node.id], f"🖴 {node.name}", shape="rect", color="gray", styleItem="dash")  # type: ignore[reportAttributeAccessIssue]
        with dot.subgraph(name="cluster_filters") as filter_graphs:  # type: ignore[reportAssignmentType]
            filter_graphs.attr(color="gray", style="dashed", label=self.name)  # type: ignore[reportAttributeAccessIssue]
            for node in graph.nodes:
                if node.kind == "filter":
                    params = "".join(f"\n✔️ {main}" for main, _detail in node.lines)
                    filter_graphs.node(ids[node.id], f"⚙️ {node.name}" + params, shape="rect")  # type: ignore[reportAttributeAccessIssue]
        with dot.subgraph(name="cluster_out") as out_graph:  # type: ignore[reportAssignmentType]
            out_graph.attr(style="dashed", color="gray", label="Outputs")  # type: ignore[reportAttributeAccessIssue]
            for node in graph.nodes:
                if node.kind == "output":
                    out_graph.node(ids[node.id], f"🛢️ {node.name}", shape="rect", color="gray")  # type: ignore[reportAttributeAccessIssue]
        for edge in graph.edges:
            dot.edge(ids[edge.source], ids[edge.target], label=f"[{edge.label}]")
        try:
            dot.render(path if path is not None else self.name, view=view, format=format)
        except Exception as exc:
            # Broad on purpose: graph rendering is a best-effort extra; the
            # string matching below handles ExecutableNotFound even when the
            # optional import above failed.
            exc_type_name = type(exc).__name__
            if (ExecutableNotFound and isinstance(exc, ExecutableNotFound)) or "ExecutableNotFound" in exc_type_name:
                logging.error(graphviz_hint)
            else:
                logging.error(f"Failed to render graph: {exc}")
            return None
        return dot

    # See-the-result loop: render runs to PNG files (interactive_pipe.headless.explore)
    from interactive_pipe.headless.describe import describe, summary
    from interactive_pipe.headless.explore import snapshot, sweep

from_function classmethod

from_function(pipe: Callable[..., Any], inputs=None, *, _routing_by_indexes=False, **kwargs)
Source code in src/interactive_pipe/headless/pipeline.py
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
@classmethod
def from_function(cls, pipe: Callable[..., Any], inputs=None, *, _routing_by_indexes=False, **kwargs):
    if not isinstance(pipe, Callable):
        raise TypeError(f"pipe must be Callable, got {type(pipe)}")
    graph = get_call_graph(pipe)
    all_variables = {}
    total_index = 0
    function_inputs = {}
    input_routing = []
    for input_index, input_name in enumerate(graph["args"]):
        all_variables[input_name] = total_index
        function_inputs[input_name] = total_index
        if _routing_by_indexes:
            input_routing.append(total_index)
        else:
            input_routing.append(input_name)
        total_index += 1
    for filt_dict in graph["call_graph"]:
        for key in ["args", "returns"]:
            for variable_name in filt_dict[key] or []:
                if variable_name not in all_variables:
                    all_variables[variable_name] = total_index
                    total_index += 1

    filters = []
    filters_count = {}
    filters_names = []
    bindings = []  # (filter, parameter name, control), connected once names are resolved
    seen_function_ids = set()
    # The pipeline owns clones of the declared controls (two pipelines built
    # from one filter never share values). One clone per share key and
    # filter instance suffix: the same declared Control object used by
    # several filters is one widget driving all of them.
    pipeline_clones: dict = {}

    def pipeline_control(declared: Control, suffix: str, filter_name: str, param_name: str) -> Control:
        key = (declared.share_key, suffix)
        clone = pipeline_clones.get(key)
        if clone is None:
            # first instance: starts from the declared control's value; repeats from the default
            clone = declared._clone_unconnected(declared.name + suffix, keep_value=not suffix)
            clone._declared_by = f"{filter_name}.{param_name}"  # type: ignore[attr-defined]
            pipeline_clones[key] = clone
        elif clone.value_default != declared.value_default:
            raise ValueError(
                f"control '{clone.name}' is shared by {clone._declared_by} and {filter_name}.{param_name} "  # type: ignore[attr-defined]
                f"with different defaults ({clone.value_default!r} and {declared.value_default!r}): "
                "one widget has one default, give both parameters the same default"
            )
        return clone

    for filt_dict in graph["call_graph"]:
        # avoid duplicate filters names
        filt_name = filt_dict["function_name"]
        filter_count = filters_count.get(filt_name, -1)
        if filter_count >= 0:
            filters_count[filt_name] += 1
            filt_name = filt_name + f"_{filters_count[filt_name]}"
        else:
            filters_count[filt_name] = 0
        if _routing_by_indexes:
            inputs_filt = HeadlessPipeline.routing_indexes(filt_dict["args"], all_variables)
            outputs_filt = HeadlessPipeline.routing_indexes(filt_dict["returns"], all_variables)
        else:
            inputs_filt = filt_dict["args"]
            outputs_filt = filt_dict["returns"]
        logging.debug(f"-----------------> {filt_name} {inputs_filt} {outputs_filt}")
        if isinstance(filt_dict["function_object"], FilterCore):
            filt = filt_dict["function_object"]
            filt.inputs = inputs_filt
            filt.outputs = outputs_filt
            filt.name = filt_name
            # EnhancedFilterCore (filter_from_function) carries its controls; a plain FilterCore has none
            params_to_analyze = dict(getattr(filt, "controls", None) or {})
        else:
            # when using the @interactive decorator
            filt = FilterCore(
                name=filt_name,
                inputs=inputs_filt,
                outputs=outputs_filt,
                apply_fn=filt_dict["function_object"],
                inplace=bool(getattr(filt_dict["function_object"], "__interactive_pipe_inplace__", False)),
            )
            func_kwargs = analyze_apply_fn_signature(filt_dict["function_object"])[1]
            declared_controls = Control.get_controls(filt_dict["function_object"])
            if id(filt_dict["function_object"]) not in seen_function_ids:
                suffix = ""
            else:
                # Repeated filter: each repeat gets its own clones, suffixed
                # like the filter name ("amount" -> "amount_1"). Key/timer-bound
                # controls are not cloned - their key bindings would collide -
                # so repeats run those with default values.
                suffix = f"_{filters_count[filt_dict['function_name']]}"
                declared_controls = {
                    param_name: ctrl
                    for param_name, ctrl in declared_controls.items()
                    if not isinstance(ctrl, (KeyboardControl, TimeControl))
                }
            registered_controls = {
                param_name: pipeline_control(ctrl, suffix, filt_name, param_name)
                for param_name, ctrl in declared_controls.items()
            }
            params_to_analyze = {**func_kwargs, **registered_controls}
        # Literal keyword arguments in the pipeline body (`amplify(img, gain=2.5)`)
        # set this instance's value; a bound control gets a per-instance clone
        # with that default so the other instances keep theirs.
        literal_kwargs = filt_dict.get("kwargs") or {}
        for param_name, literal_value in literal_kwargs.items():
            bound_control = params_to_analyze.get(param_name)
            if isinstance(bound_control, Control):
                try:
                    params_to_analyze[param_name] = bound_control._clone_with_default(literal_value)
                except (TypeError, ValueError) as exc:
                    raise PipelineSyntaxError(
                        f"invalid value for '{param_name}' of filter '{filt_dict['function_name']}': {exc}",
                        hint="use a value accepted by the control, or change the control declaration",
                        **filt_dict.get("location", {}),
                    ) from None
        for param_name, param_value in params_to_analyze.items():
            if isinstance(param_value, Control):
                bindings.append((filt, param_name, param_value))
        filt.values = {
            param_name: literal_value
            for param_name, literal_value in literal_kwargs.items()
            if not isinstance(params_to_analyze.get(param_name), Control)
        }
        # the pipeline line calling this filter: output count checks and messages
        filt.call_location = filt_dict.get("location")
        filters.append(filt)
        filters_names.append(filt_name)
        seen_function_ids.add(id(filt_dict["function_object"]))
    logging.debug(filters_count)
    logging.debug(filters_names)

    bindings = cls._disambiguate_control_names(bindings)
    control_list = []
    connected = set()
    for filt, param_name, ctrl in bindings:
        if id(ctrl) in connected:
            ctrl._add_target(filt, param_name)  # one control shared by several filters
        else:
            ctrl.connect_filter(filt, param_name)
            connected.add(id(ctrl))
            control_list.append(ctrl)
        filt.values = {param_name: ctrl.value_default}

    # GUI widgets are keyed by control name: distinct controls sharing a
    # name within one pipeline would silently drive the wrong filter.
    controls_by_name = {}
    for ctrl in control_list:
        previous = controls_by_name.get(ctrl.name)
        if previous is not None and previous is not ctrl:
            where = ", ".join(f"{f.name}.{p}" for f, p in previous.targets + ctrl.targets)
            raise ValueError(
                f"Duplicate control name '{ctrl.name}' in pipeline '{pipe.__name__}' ({where}): "
                "two different controls cannot have the same name. "
                "To drive several filters with one widget, declare the control once and pass the same object "
                f"to each filter (band = Control(...); @interactive(band=band) on both); "
                "otherwise pass a distinct name=... to one of them."
            )
        controls_by_name[ctrl.name] = ctrl

    # Helper function to convert nested output names to indexes
    def convert_outputs_to_indexes(output_structure):
        if isinstance(output_structure, str):
            return all_variables[output_structure]
        elif isinstance(output_structure, list):
            return [convert_outputs_to_indexes(item) for item in output_structure]
        else:
            return output_structure

    if _routing_by_indexes:
        outputs = convert_outputs_to_indexes(graph["returns"])
    else:
        outputs = graph["returns"]
    if len(function_inputs) == 0 and inputs is None:
        logging.info("Auto deduced that there are no arguments provided to the function")
    data_class = cls(
        filters=filters,
        name=graph["function_name"],
        inputs=input_routing,
        outputs=outputs,
        **kwargs,
    )
    data_class.controls = control_list
    # a point / region control aimed (on=...) at an output the pipeline does not produce:
    # a warning here (a headless test pipeline may reuse the filter without that output);
    # @interactive_pipeline with a GUI and every GUI construction raise
    from interactive_pipe.headless.pointer import check_targets

    check_targets(data_class, strict=False)
    if len(function_inputs) == 0 and inputs is None:
        # nothing to wait for: run() and export_animation() work before the first call
        data_class.inputs = None
    return data_class

__call__

__call__(*inputs_tuple, inputs=None, parameters=None, context=None, **kwargs) -> Any

Run the pipeline once and return its outputs.

Example
blurred, edges = pipe(img, sigma=2.0)
(single,) = pipe1(img)  # always a tuple, even for one output

Parameters:

Name Type Description Default
*inputs_tuple

Pipeline inputs, in the order of the pipeline function's arguments.

()
inputs

Inputs as a {input_name: value} dict instead.

None
parameters

{filter_name: {parameter: value}}, validated before anything changes.

None
context

Values merged into the shared context before the run (they are also part of the fresh context snapshot / sweep start from).

None
**kwargs

Parameter values: a parameter name (every filter having it), a control name or "filter.parameter". Like a slider move, the value is kept for the next runs.

{}

Returns:

Type Description
Any

A tuple of the outputs in return order (a list of rows when the

Any

function returns a 2D list), or None when the pipeline returns

Any

nothing. A layout.grid call changes what is displayed, not this.

Raises:

Type Description
TypeError

unknown keyword / wrong number of inputs.

FilterError

a filter raised (the message names the filter and the line).

Source code in src/interactive_pipe/headless/pipeline.py
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
def __call__(self, *inputs_tuple, inputs=None, parameters=None, context=None, **kwargs) -> Any:
    """Run the pipeline once and return its outputs.

    Example:
        ```python
        blurred, edges = pipe(img, sigma=2.0)
        (single,) = pipe1(img)  # always a tuple, even for one output
        ```

    Args:
        *inputs_tuple: Pipeline inputs, in the order of the pipeline function's arguments.
        inputs: Inputs as a ``{input_name: value}`` dict instead.
        parameters: ``{filter_name: {parameter: value}}``, validated before anything changes.
        context: Values merged into the shared ``context`` before the run (they are
            also part of the fresh context ``snapshot`` / ``sweep`` start from).
        **kwargs: Parameter values: a parameter name (every filter having it), a
            control name or ``"filter.parameter"``. Like a slider move, the value
            is kept for the next runs.

    Returns:
        A tuple of the outputs in ``return`` order (a list of rows when the
        function returns a 2D list), or None when the pipeline returns
        nothing. A ``layout.grid`` call changes what is displayed, not this.

    Raises:
        TypeError: unknown keyword / wrong number of inputs.
        FilterError: a filter raised (the message names the filter and the line).
    """
    self.adopt_video_inputs(inputs_tuple, inputs)  # frame=... names the timeline of a Video input
    # validated first: an unknown keyword raises before anything is changed
    kwargs_params = self.parameters_from_keyword_args(**kwargs)
    if parameters is not None:
        from interactive_pipe.headless.explore import check_parameters_dict

        check_parameters_dict(self, parameters, f"pipeline '{self.name}'")
    if inputs is not None:
        if not isinstance(inputs, dict):
            raise TypeError(f"inputs must be a dict, got {type(inputs)}")
        self.inputs = inputs  # type: ignore
        logging.debug(f"Dict style inputs {list(inputs.keys())}")
    else:
        # the inputs setter validates the count against inputs_routing
        self.inputs = list(inputs_tuple) if inputs_tuple else None  # type: ignore
    # Handle context parameter - update user context if provided
    self.update_user_context(context)
    # Only update self.parameters if parameters argument is explicitly provided
    if parameters is not None:
        self.parameters = parameters
    # Merge in any keyword arguments as parameters
    if kwargs_params:
        # Get current parameters, merge, and re-set to trigger the setter
        current_params = self.parameters  # Calls getter
        for filter_name, params in kwargs_params.items():
            if filter_name not in current_params:
                current_params[filter_name] = {}
            current_params[filter_name].update(params)
        self.parameters = current_params  # Calls setter to apply to filters
    self.run()
    # the pipeline's return order and shape, not the display layout (layout.grid)
    return self._returned_results()

run

run()

Run once; the outputs in the display layout (self.outputs, which layout.grid and the GUIs change), as the windows and snapshots show them.

Source code in src/interactive_pipe/headless/pipeline.py
551
552
553
554
555
556
557
558
def run(self):
    """Run once; the outputs in the display layout (``self.outputs``, which
    ``layout.grid`` and the GUIs change), as the windows and snapshots show them."""
    result_full = self._run_full()
    # read after the run: a layout.grid call during it changes the layout
    output_indexes = self.outputs if self.outputs is not None else self.filters[-1].outputs
    self.results = self._collect(result_full, output_indexes)
    return self.results

snapshot

snapshot(pipeline: HeadlessPipeline, path: PathLike, *input_values: Any, inputs: Optional[dict] = None, output: OutputSelector = None, params: Optional[Dict[str, Any]] = None, figsize: Optional[Tuple[float, float]] = None, dpi: Optional[float] = None, title: Optional[str] = None, caption: Union[bool, str, None] = True, runs: int = 1, **overrides: Any) -> Union[Path, np.ndarray]

Run the pipeline once and render what the GUI would show to a PNG.

Each call starts like a first run: the context holds only what was given from outside (context= at construction or in a call), not what filters wrote in earlier runs; key-bound events are off and nothing is served from the cache. The pipeline's own context, events and cache are put back afterwards. A pipeline that needs warm-up runs (an accumulator, a simulation) takes runs=N: N runs from that fresh start, the last one shown.

Example
pipe.snapshot("out.png", img, gain=2.0)
rgb = pipe.snapshot(None, img)  # (H, W, 3) uint8 array, no file

Parameters:

Name Type Description Default
path PathLike

PNG file to write (parent folders are created); None returns the rendered image as an (H, W, 3) uint8 array instead.

required
*input_values Any

Pipeline inputs. May be omitted when the pipeline takes none, or to reuse the inputs of the previous call / run.

()
inputs Optional[dict]

Inputs as a {input_name: value} dict instead.

None
output OutputSelector

Render only some outputs: a name, an index (reading order) or a list of them. Default: the whole layout.

None
params Optional[Dict[str, Any]]

Parameter overrides as a dict - use it for names that clash with the options of this method (title, dpi, ...).

None
figsize Optional[Tuple[float, float]]

Figure size in inches. Default: derived from the layout and the image aspect ratios.

None
dpi Optional[float]

Resolution. Default: showing the largest image near its native size (80 to 150 dpi).

None
title Optional[str]

Figure title.

None
caption Union[bool, str, None]

True (default) prints the parameter values used under the grid, False hides them, a string replaces them.

True
runs int

Number of runs from the fresh start (default 1); the last one is shown.

1
**overrides Any

Parameter values for this call only: a keyword-argument name (gain=2.0), a control name or "filter.param".

{}

Returns:

Type Description
Union[Path, ndarray]

The written path, or the image when path is None.

Raises:

Type Description
TypeError

unknown parameter name (the message lists the available ones), or missing inputs.

FilterError

a filter raised during the run (state is restored).

Source code in src/interactive_pipe/headless/explore.py
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
def snapshot(
    pipeline: "HeadlessPipeline",
    path: PathLike,
    *input_values: Any,
    inputs: Optional[dict] = None,
    output: OutputSelector = None,
    params: Optional[Dict[str, Any]] = None,
    figsize: Optional[Tuple[float, float]] = None,
    dpi: Optional[float] = None,
    title: Optional[str] = None,
    caption: Union[bool, str, None] = True,
    runs: int = 1,
    **overrides: Any,
) -> Union[Path, np.ndarray]:
    """Run the pipeline once and render what the GUI would show to a PNG.

    Each call starts like a first run: the ``context`` holds only what was given
    from outside (``context=`` at construction or in a call), not what filters
    wrote in earlier runs; key-bound events are off and nothing is served from
    the cache. The pipeline's own context, events and cache are put back
    afterwards. A pipeline that needs warm-up runs (an accumulator, a
    simulation) takes ``runs=N``: N runs from that fresh start, the last one shown.

    Example:
        ```python
        pipe.snapshot("out.png", img, gain=2.0)
        rgb = pipe.snapshot(None, img)  # (H, W, 3) uint8 array, no file
        ```

    Args:
        path: PNG file to write (parent folders are created); None returns
            the rendered image as an ``(H, W, 3)`` uint8 array instead.
        *input_values: Pipeline inputs. May be omitted when the pipeline
            takes none, or to reuse the inputs of the previous call / run.
        inputs: Inputs as a ``{input_name: value}`` dict instead.
        output: Render only some outputs: a name, an index (reading order)
            or a list of them. Default: the whole layout.
        params: Parameter overrides as a dict - use it for names that clash
            with the options of this method (``title``, ``dpi``, ...).
        figsize: Figure size in inches. Default: derived from the layout and
            the image aspect ratios.
        dpi: Resolution. Default: showing the largest image near its native
            size (80 to 150 dpi).
        title: Figure title.
        caption: True (default) prints the parameter values used under the
            grid, False hides them, a string replaces them.
        runs: Number of runs from the fresh start (default 1); the last one is shown.
        **overrides: Parameter values for this call only: a keyword-argument
            name (``gain=2.0``), a control name or ``"filter.param"``.

    Returns:
        The written path, or the image when ``path`` is None.

    Raises:
        TypeError: unknown parameter name (the message lists the available
            ones), or missing inputs.
        FilterError: a filter raised during the run (state is restored).
    """
    written, _ = run_snapshot(
        pipeline,
        path,
        *input_values,
        inputs=inputs,
        output=output,
        params=params,
        figsize=figsize,
        dpi=dpi,
        title=title,
        caption=caption,
        runs=runs,
        **overrides,
    )
    return written

sweep

sweep(pipeline: HeadlessPipeline, path: PathLike, *input_values: Any, inputs: Optional[dict] = None, output: Any = None, steps: Optional[Dict[str, int]] = None, params: Optional[Dict[str, Any]] = None, figsize: Optional[Tuple[float, float]] = None, dpi: Optional[float] = None, title: Optional[str] = None, caption: Union[bool, str, None] = True, runs: int = 1, **overrides: Any) -> Union[Path, np.ndarray]

Run the pipeline for several parameter values and render a contact sheet.

Every cell starts like a first run (see snapshot): cells are independent of each other and of the runs before the call.

Example
pipe.sweep("sweep.png", img, gain=[0.5, 1, 2])  # one row
pipe.sweep("grid.png", img, gain=[0.5, 2], blur=[1, 3, 5])  # 2 x 3 grid
pipe.sweep("steps.png", img, steps={"gain": 5})  # 5 values over the slider range
pipe.sweep("all.png", img, gain=[0.5, 2], output="all")  # every output per cell

A list, tuple or numpy array is a swept axis; a scalar is a fixed override applied to every cell. For a range parameter (RangeControl) a tuple is one (lo, hi) value: sweep it with a list of pairs.

Parameters:

Name Type Description Default
path PathLike

PNG to write, or None to get the image as an (H, W, 3) uint8 array.

required
*input_values Any

Pipeline inputs (optional when reusing the previous ones).

()
inputs Optional[dict]

Inputs as a dict instead.

None
output Any

Output shown in each cell: a name or an index. Default: the only output, else the first image output that the swept parameters change (downstream of their filters), else the last image output. "all" shows the whole layout in every cell; a list shows several outputs.

None
steps Optional[Dict[str, int]]

{name: count} sweeps a control over its declared range (count evenly spaced values, geometric for a log slider; every choice of a dropdown, both states of a checkbox).

None
params Optional[Dict[str, Any]]

Overrides / axes as a dict (for names clashing with options).

None
figsize Optional[Tuple[float, float]]

As for snapshot.

None
dpi Optional[float]

As for snapshot.

None
title Optional[str]

As for snapshot.

None
caption Union[bool, str, None]

True prints the fixed parameter values under the sheet.

True
runs int

Runs per cell from the fresh start (default 1); the last one is shown.

1
**overrides Any

Swept axes (lists) and fixed overrides (scalars).

{}

Returns:

Type Description
Union[Path, ndarray]

The written path, or the image when path is None.

Raises:

Type Description
ValueError

nothing to sweep, or more than two swept parameters.

TypeError

unknown parameter name, or missing inputs.

FilterError

a filter raised (state is restored).

Source code in src/interactive_pipe/headless/explore.py
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
def sweep(
    pipeline: "HeadlessPipeline",
    path: PathLike,
    *input_values: Any,
    inputs: Optional[dict] = None,
    output: Any = None,
    steps: Optional[Dict[str, int]] = None,
    params: Optional[Dict[str, Any]] = None,
    figsize: Optional[Tuple[float, float]] = None,
    dpi: Optional[float] = None,
    title: Optional[str] = None,
    caption: Union[bool, str, None] = True,
    runs: int = 1,
    **overrides: Any,
) -> Union[Path, np.ndarray]:
    """Run the pipeline for several parameter values and render a contact sheet.

    Every cell starts like a first run (see ``snapshot``): cells are
    independent of each other and of the runs before the call.

    Example:
        ```python
        pipe.sweep("sweep.png", img, gain=[0.5, 1, 2])  # one row
        pipe.sweep("grid.png", img, gain=[0.5, 2], blur=[1, 3, 5])  # 2 x 3 grid
        pipe.sweep("steps.png", img, steps={"gain": 5})  # 5 values over the slider range
        pipe.sweep("all.png", img, gain=[0.5, 2], output="all")  # every output per cell
        ```

    A list, tuple or numpy array is a swept axis; a scalar is a fixed override
    applied to every cell. For a range parameter (``RangeControl``) a tuple is
    one ``(lo, hi)`` value: sweep it with a list of pairs.

    Args:
        path: PNG to write, or None to get the image as an (H, W, 3) uint8 array.
        *input_values: Pipeline inputs (optional when reusing the previous ones).
        inputs: Inputs as a dict instead.
        output: Output shown in each cell: a name or an index. Default: the
            only output, else the first image output that the swept
            parameters change (downstream of their filters), else the last
            image output. ``"all"`` shows the
            whole layout in every cell; a list shows several outputs.
        steps: ``{name: count}`` sweeps a control over its declared range
            (``count`` evenly spaced values, geometric for a log slider; every
            choice of a dropdown, both states of a checkbox).
        params: Overrides / axes as a dict (for names clashing with options).
        figsize: As for ``snapshot``.
        dpi: As for ``snapshot``.
        title: As for ``snapshot``.
        caption: True prints the fixed parameter values under the sheet.
        runs: Runs per cell from the fresh start (default 1); the last one is shown.
        **overrides: Swept axes (lists) and fixed overrides (scalars).

    Returns:
        The written path, or the image when ``path`` is None.

    Raises:
        ValueError: nothing to sweep, or more than two swept parameters.
        TypeError: unknown parameter name, or missing inputs.
        FilterError: a filter raised (state is restored).
    """
    all_overrides = {**(params or {}), **overrides}
    pipeline.adopt_video_inputs(input_values, inputs)  # frame=[...] sweeps the timeline of a Video input
    axes, fixed = split_sweep_arguments(pipeline, all_overrides, steps)
    prepare_inputs(pipeline, input_values, inputs, "sweep")
    names = list(axes)
    combos = list(itertools.product(*(axes[name] for name in names)))
    swept_targets = sorted({target for name in names for target in parameter_targets(pipeline)[name]})
    panels_flat: List[Grid] = []
    run_styles: dict = {}
    with preserved_state(pipeline):
        apply_overrides(pipeline, fixed, "sweep")
        caption_text = _caption(pipeline, caption, exclude=swept_targets)
        chosen_name: Any = None
        for combo in combos:
            apply_overrides(pipeline, dict(zip(names, combo)), "sweep")
            grid = result_grid(pipeline, fresh_run(pipeline, runs, "sweep"))
            run_styles.update(_output_styles(pipeline))  # layout.style calls of this run
            if output is not None:
                panels_flat.append(_panel(grid, output))
                continue
            # default: chosen on the first cell, then kept by name for the others
            # (unless a layout.grid call removed it from this cell's layout)
            cells = flat_cells(grid)
            if chosen_name is None or chosen_name not in [cell.name for cell in cells]:
                changed = outputs_downstream_of(pipeline, {filter_name for filter_name, _ in swept_targets})
                chosen_name = cells[default_sweep_cell(grid, changed)].name
            chosen_cell = next(cell for cell in cells if cell.name == chosen_name)
            panels_flat.append([[chosen_cell]])
    styles = run_styles
    shown = {}  # output name -> first value with a display problem (one warning per output)
    for panel in panels_flat:
        for cell in flat_cells(panel):
            if cell.name not in shown and output_problem(cell.raw, styles.get(cell.name)) is not None:
                shown[cell.name] = cell.raw
    warn_output_problems(shown.items(), "sweep", styles)
    labels = [", ".join(f"{name}={format_value(val)}" for name, val in zip(names, combo)) for combo in combos]
    if len(names) == 1:
        count = len(panels_flat)
        widths, heights = grid_size(panels_flat[0])
        if sum(widths) > 1.5 * sum(heights):
            n_cols = 1  # wide panels (several outputs each): one row per value
        else:
            n_cols = count if count <= 6 else math.ceil(math.sqrt(count))
        panels = [panels_flat[start : start + n_cols] for start in range(0, count, n_cols)]
        cell_labels = [labels[start : start + n_cols] for start in range(0, count, n_cols)]
        fig = render_sweep(panels, cell_labels=cell_labels, figsize=figsize, dpi=dpi, title=title, caption=caption_text)
    else:
        first, second = names
        n_cols = len(axes[second])
        panels = [panels_flat[start : start + n_cols] for start in range(0, len(panels_flat), n_cols)]
        fig = render_sweep(
            panels,
            row_labels=[f"{first}={format_value(val)}" for val in axes[first]],
            column_labels=[f"{second}={format_value(val)}" for val in axes[second]],
            figsize=figsize,
            dpi=dpi,
            title=title,
            caption=caption_text,
        )
    return _export(fig, path)

describe

describe(pipeline: HeadlessPipeline) -> Dict[str, Any]

Describe the pipeline as a JSON-serialisable dict.

Keys

name: pipeline name. inputs: input names, in call order. outputs: output layout (flat list = one row, list of lists = grid, None = empty cell). filters: in execution order, each with its input / output variable names, current parameter values, control names and docstring line. controls: name, owning filter, parameter, targets (every "filter.parameter" it drives: several for a control shared by several filters), kind (slider / number / checkbox / dropdown / range / text / time / keyboard / point / region, with on: the target output, None for the first image), type, default, current value, range or choices, step, scale: "log" for a log slider, group, key bindings and tooltip when present.

Example
import json

print(json.dumps(pipe.describe(), indent=2))
print(pipe.summary())  # the same, as text
Source code in src/interactive_pipe/headless/describe.py
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
def describe(pipeline: "HeadlessPipeline") -> Dict[str, Any]:
    """Describe the pipeline as a JSON-serialisable dict.

    Keys:
        name: pipeline name.
        inputs: input names, in call order.
        outputs: output layout (flat list = one row, list of lists = grid,
            None = empty cell).
        filters: in execution order, each with its input / output variable
            names, current parameter values, control names and docstring line.
        controls: name, owning filter, parameter, ``targets`` (every
            ``"filter.parameter"`` it drives: several for a control shared by
            several filters), kind (slider / number /
            checkbox / dropdown / range / text / time / keyboard / point /
            region, with ``on``: the target output, None for the first
            image), type,
            default, current value, range or choices, step, ``scale: "log"`` for a
            log slider, group, key
            bindings and tooltip when present.

    Example:
        ```python
        import json

        print(json.dumps(pipe.describe(), indent=2))
        print(pipe.summary())  # the same, as text
        ```
    """
    controls = list(getattr(pipeline, "controls", None) or [])
    check_targets(pipeline, strict=False)
    controls_by_filter: Dict[str, List[str]] = {}
    for ctrl in controls:
        for filt, _param_name in ctrl.targets:
            controls_by_filter.setdefault(filt.name, []).append(ctrl.name)
    filters = []
    for filt in pipeline.filters:
        entry: Dict[str, Any] = {
            "name": filt.name,
            "inputs": to_plain(filt.inputs),
            "outputs": to_plain(filt.outputs),
            "parameters": to_plain(dict(filt.values)),
            "controls": controls_by_filter.get(filt.name, []),
        }
        doc = _doc_line(getattr(filt, "apply", None))
        if doc:
            entry["doc"] = doc
        filters.append(entry)
    return {
        "name": to_plain(pipeline.name),
        "inputs": to_plain(list(pipeline.inputs_routing or [])),
        "outputs": to_plain(pipeline.outputs),
        "filters": filters,
        "controls": [describe_control(ctrl) for ctrl in controls],
    }

summary

summary(pipeline: HeadlessPipeline) -> str

Readable text version of describe() (print(pipe.summary())).

Source code in src/interactive_pipe/headless/describe.py
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
def summary(pipeline: "HeadlessPipeline") -> str:
    """Readable text version of ``describe()`` (``print(pipe.summary())``)."""
    data = describe(pipeline)
    lines = [
        f"Pipeline {data['name']!r}",
        f"  inputs : {', '.join(str(name) for name in data['inputs']) or '(none)'}",
        f"  outputs: {_layout_text(data['outputs'])}",
        "Filters (execution order):",
    ]
    for filt in data["filters"]:
        inputs = ", ".join(str(name) for name in filt["inputs"] or [])
        outputs = ", ".join(str(name) for name in filt["outputs"] or [])
        params = ", ".join(f"{key}={format_value(val)}" for key, val in filt["parameters"].items())
        line = f"  {filt['name']}({inputs}) -> {outputs or '()'}"
        if params:
            line += f"   [{params}]"
        lines.append(line)
        if "doc" in filt:
            lines.append(f"      {filt['doc']}")
    lines.append("Controls:" if data["controls"] else "Controls: (none)")
    width = max([len(str(entry["name"])) for entry in data["controls"]] + [4])
    lines.extend(_control_line(entry, width) for entry in data["controls"])
    return "\n".join(lines)

save

save(path: Optional[Path] = None, data_wrapper_fn: Optional[Callable[..., Any]] = None, output_indexes: Optional[list] = None, save_entire_buffer: bool = False) -> List[Path]

Run the pipeline and write its outputs (and the tuning) next to path.

Output name is written to <stem>_<name><suffix>, the current parameters to <stem>.yaml. The format follows the output type:

  • numpy image ((H, W), (H, W, 1|3|4); float in [0, 1], uint8, uint16 or bool) -> image file through Image (path's suffix if it is .png/.jpg/.tif, else .png)
  • 1D numpy array -> .csv; any other numpy array -> .npy
  • Image, Curve, SingleCurve, Table -> their own save (path's suffix when they support it, else their default one)
  • str -> .txt

Other output types are skipped with a single warning. Pass data_wrapper_fn to wrap every output yourself (it must return an object with a save(path) method).

Parameters:

Name Type Description Default
path Optional[Path]

Base file path, e.g. "out/result.png".

None
data_wrapper_fn Optional[Callable[..., Any]]

Optional wrapper applied to each output.

None
output_indexes Optional[list]

Names (or indexes) of the buffers to save; defaults to the pipeline outputs.

None
save_entire_buffer bool

Save every intermediate buffer.

False

Returns:

Type Description
List[Path]

The list of written output files (the tuning file excluded).

Source code in src/interactive_pipe/headless/pipeline.py
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
def save(
    self,
    path: Optional[Path] = None,
    data_wrapper_fn: Optional[Callable[..., Any]] = None,
    output_indexes: Optional[list] = None,
    save_entire_buffer: bool = False,
) -> List[Path]:
    """Run the pipeline and write its outputs (and the tuning) next to ``path``.

    Output ``name`` is written to ``<stem>_<name><suffix>``, the current
    parameters to ``<stem>.yaml``. The format follows the output type:

    - numpy image (``(H, W)``, ``(H, W, 1|3|4)``; float in ``[0, 1]``,
      uint8, uint16 or bool) -> image file through ``Image`` (``path``'s
      suffix if it is ``.png``/``.jpg``/``.tif``, else ``.png``)
    - 1D numpy array -> ``.csv``; any other numpy array -> ``.npy``
    - ``Image``, ``Curve``, ``SingleCurve``, ``Table`` -> their own ``save``
      (``path``'s suffix when they support it, else their default one)
    - ``str`` -> ``.txt``

    Other output types are skipped with a single warning. Pass
    ``data_wrapper_fn`` to wrap every output yourself (it must return an
    object with a ``save(path)`` method).

    Args:
        path: Base file path, e.g. ``"out/result.png"``.
        data_wrapper_fn: Optional wrapper applied to each output.
        output_indexes: Names (or indexes) of the buffers to save;
            defaults to the pipeline outputs.
        save_entire_buffer: Save every intermediate buffer.

    Returns:
        The list of written output files (the tuning file excluded).
    """
    if output_indexes is None:
        output_indexes = self.returned_outputs  # whatever layout.grid displays
    if save_entire_buffer:
        output_indexes = None  # you may force specific buffer index you'd like to save
    wanted = None if output_indexes is None else set(_flatten_outputs(output_indexes))
    if path is None:
        raise ValueError("path must be provided for saving")
    # as run(): with the current control values (and pyplot figures released)
    result_full = self._run_full()
    if result_full is None:
        return []
    if not isinstance(path, Path):
        path = Path(path)
    self.export_tuning(path.with_suffix(".yaml"))
    if not isinstance(result_full, dict):
        raise RuntimeError(f"Expected dict from pipeline run, got {type(result_full)}")
    written: List[Path] = []
    skipped = []
    for num, res_current in result_full.items():
        if wanted is not None and num not in wanted:
            continue
        if res_current is None or (isinstance(res_current, list) and len(res_current) == 0):
            continue
        current_name = path.with_name(f"{path.stem}_{_safe_file_part(num)}{path.suffix}")
        try:
            if data_wrapper_fn is not None:
                to_save = data_wrapper_fn(res_current)
                if not hasattr(to_save, "save"):
                    raise AttributeError(f"Result object {type(to_save)} has no 'save' method")
                to_save.save(current_name)  # type: ignore
                saved_path = getattr(to_save, "path", None) or current_name
            else:
                saved_path = _save_output(res_current, current_name)
                if saved_path is None:
                    skipped.append(f"{num} ({type(res_current).__name__})")
                    continue
        except Exception:
            # Broad on purpose: one failed output must not abort the
            # whole batch save; continue with the remaining outputs.
            logging.exception(f"Cannot save output {num} to {current_name}")
            continue
        written.append(Path(saved_path))
        logging.info(f"saved output {num} to {saved_path}")
    if skipped:
        logging.warning(
            f"Not saved (unsupported output type): {', '.join(skipped)}. "
            "Supported: numpy arrays, Image, Curve, SingleCurve, Table, str - "
            "or pass data_wrapper_fn=... returning an object with a save(path) method."
        )
    return written

export_tuning

export_tuning(path: Optional[Path] = None, override=False) -> None

Export the current parameters of every filter to a json/yaml file

Source code in src/interactive_pipe/headless/pipeline.py
479
480
481
482
def export_tuning(self, path: Optional[Path] = None, override=False) -> None:
    """Export the current parameters of every filter to a json/yaml file"""
    if path is not None:
        Parameters(self.parameters).save(path, override=override)

load_tuning

load_tuning(path: Path) -> None

Load a json/yaml tuning file written by export_tuning (alias of import_tuning).

Example
pipe.export_tuning("my_tuning.yaml")
pipe.load_tuning("my_tuning.yaml")
Source code in src/interactive_pipe/headless/pipeline.py
493
494
495
496
497
498
499
500
501
502
def load_tuning(self, path: Path) -> None:
    """Load a json/yaml tuning file written by ``export_tuning`` (alias of ``import_tuning``).

    Example:
        ```python
        pipe.export_tuning("my_tuning.yaml")
        pipe.load_tuning("my_tuning.yaml")
        ```
    """
    self.import_tuning(path)

graph_representation

graph_representation(path=None, ortho=True, view=False, format=None)

Draw the pipeline graph: inputs, filters (with their parameters), outputs.

By default writes one standalone HTML page (inline SVG, no dependency, opens in any browser) and returns its Path.

Parameters:

Name Type Description Default
path

file to write. Default: <pipeline name>.html. A path without .html suffix gets one, unless its suffix names a graphviz format (.svg, .png, .pdf...).

None
ortho

graphviz only: orthogonal edges.

True
view

open the result (the HTML page in the web browser; never under INTERACTIVE_PIPE_SNAPSHOT).

False
format

"html" (default) or a graphviz output format ("svg", "png", "pdf"...), which needs the graphviz package and system executables and returns the graphviz.Digraph (None when graphviz is missing, as before).

None
Example
path = pipe.graph_representation("my_pipeline.html")
dot = pipe.graph_representation("my_pipeline", format="pdf")  # graphviz
Source code in src/interactive_pipe/headless/pipeline.py
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
def graph_representation(self, path=None, ortho=True, view=False, format=None):
    """Draw the pipeline graph: inputs, filters (with their parameters), outputs.

    By default writes one standalone HTML page (inline SVG, no dependency,
    opens in any browser) and returns its ``Path``.

    Args:
        path: file to write. Default: ``<pipeline name>.html``. A path
            without ``.html`` suffix gets one, unless its suffix names a
            graphviz format (``.svg``, ``.png``, ``.pdf``...).
        ortho: graphviz only: orthogonal edges.
        view: open the result (the HTML page in the web browser; never
            under ``INTERACTIVE_PIPE_SNAPSHOT``).
        format: ``"html"`` (default) or a graphviz output format (``"svg"``,
            ``"png"``, ``"pdf"``...), which needs the ``graphviz`` package
            and system executables and returns the ``graphviz.Digraph``
            (None when graphviz is missing, as before).

    Example:
        ```python
        path = pipe.graph_representation("my_pipeline.html")
        dot = pipe.graph_representation("my_pipeline", format="pdf")  # graphviz
        ```
    """
    from interactive_pipe.headless.graph_html import write_graph_html

    suffix = Path(str(path)).suffix.lower().lstrip(".") if path is not None else ""
    if format is None:
        format = suffix if suffix in GRAPHVIZ_FORMATS else "html"
    format = str(format).lower().lstrip(".")
    if format != "html":
        if path is not None and suffix == format:
            path = str(Path(str(path)).with_suffix(""))
        return self._graphviz_representation(path=path, ortho=ortho, view=view, format=format)
    if path is None:
        path = "".join(char if char.isalnum() or char in "-_." else "_" for char in str(self.name)) or "pipeline"
    path = Path(path)
    if path.suffix.lower() not in (".html", ".htm"):
        path = path.with_name(path.name + ".html")
    written = write_graph_html(self, path)
    if view:
        _open_in_browser(written)
    return written

export_animation

export_animation(pipeline: HeadlessPipeline, path: Union[str, Path], *, duration: Optional[float] = None, fps: Optional[float] = None, time_control: Optional[Union[str, TimeControl, TimelineControl]] = None, output: Union[int, Tuple[int, int], None] = None, loop: int = 0) -> Path

Render duration seconds of a TimeControl-driven pipeline to disk.

Frame k is rendered with the time control set to k / fps seconds. A pipeline whose input is a Video (and without TimeControl) renders its timeline instead: every frame by default, at the video frame rate.

Parameters:

Name Type Description Default
pipeline HeadlessPipeline

pipeline holding a TimeControl (e.g. gui.pipeline).

required
path Union[str, Path]

.gif file -> animated GIF (Pillow); a directory, a .png path or a path without suffix -> numbered PNG frames <stem>_0000.png, ... (written inside the directory, or next to the path).

required
duration Optional[float]

animation length in seconds (default 5 s; a video: all of it).

None
fps Optional[float]

frames per second (default 10; a video: its frame rate).

None
time_control Optional[Union[str, TimeControl, TimelineControl]]

name (or instance) of the TimeControl to drive; required only when the pipeline has several. The timeline of a Video input is named frame.

None
output Union[int, Tuple[int, int], None]

which output to record: an index into the output tuple, a (row, col) cell of a 2D layout, or None for the first non-empty one.

None
loop int

GIF loop count (0 = forever).

0

Returns:

Type Description
Path

The written GIF path, or the directory holding the PNG frames.

The control's previous value is restored (and the pipeline re-run) afterwards.

Source code in src/interactive_pipe/headless/animation.py
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
def export_animation(
    pipeline: HeadlessPipeline,
    path: Union[str, Path],
    *,
    duration: Optional[float] = None,
    fps: Optional[float] = None,
    time_control: Optional[Union[str, TimeControl, TimelineControl]] = None,
    output: Union[int, Tuple[int, int], None] = None,
    loop: int = 0,
) -> Path:
    """Render `duration` seconds of a TimeControl-driven pipeline to disk.

    Frame `k` is rendered with the time control set to `k / fps` seconds.
    A pipeline whose input is a ``Video`` (and without TimeControl) renders its
    timeline instead: every frame by default, at the video frame rate.

    Args:
        pipeline: pipeline holding a `TimeControl` (e.g. `gui.pipeline`).
        path: `.gif` file -> animated GIF (Pillow); a directory, a `.png` path or a
            path without suffix -> numbered PNG frames `<stem>_0000.png`, ...
            (written inside the directory, or next to the path).
        duration: animation length in seconds (default 5 s; a video: all of it).
        fps: frames per second (default 10; a video: its frame rate).
        time_control: name (or instance) of the TimeControl to drive; required
            only when the pipeline has several. The timeline of a ``Video``
            input is named ``frame``.
        output: which output to record: an index into the output tuple, a
            `(row, col)` cell of a 2D layout, or None for the first non-empty one.
        loop: GIF loop count (0 = forever).

    Returns:
        The written GIF path, or the directory holding the PNG frames.

    The control's previous value is restored (and the pipeline re-run) afterwards.
    """
    ctrl = _animated_control(pipeline, time_control)
    is_timeline = isinstance(ctrl, TimelineControl)
    if fps is None:
        fps = ctrl.fps if isinstance(ctrl, TimelineControl) else 10.0
    if duration is None:
        duration = ctrl.n_frames / ctrl.fps if isinstance(ctrl, TimelineControl) else 5.0
    if fps <= 0:
        raise ValueError(f"fps must be positive, got {fps}")
    if duration <= 0:
        raise ValueError(f"duration must be positive, got {duration}")
    if loop < 0:
        raise ValueError(f"loop must be >= 0, got {loop}")
    n_frames = int(round(duration * fps, 6))
    if n_frames < 1:
        raise ValueError(f"duration * fps must give at least one frame (duration={duration}, fps={fps})")
    path = Path(path)
    suffix = path.suffix.lower()
    if suffix not in ("", GIF_SUFFIX, PNG_SUFFIX) and not path.is_dir():
        raise ValueError(f"Unsupported animation format {path.suffix!r}: use .gif, .png or a directory")

    from PIL import Image as PILImage

    previous_value = ctrl.value
    # every frame of the video in turn: read ahead (exporting fewer frames, it would decode skipped ones)
    read_ahead = is_timeline and abs(fps - ctrl.fps) < 1e-6
    frames: List[np.ndarray] = []
    try:
        for k in range(n_frames):
            seconds = k / fps
            ctrl.value = min(int(round(seconds * ctrl.fps)), ctrl.n_frames - 1) if is_timeline else seconds
            if read_ahead and isinstance(ctrl, TimelineControl):
                ctrl.preload()  # the next frames decode while this one is processed
            result = _prepared_result(pipeline, pipeline.run())
            frames.append(_to_rgb_uint8(_select_output(result, output)))
    except BaseException:
        ctrl.value = previous_value
        raise
    # Back to the state shown before the export (results, filter parameters)
    ctrl.value = previous_value
    pipeline.run()

    if suffix == GIF_SUFFIX and not path.is_dir():
        path.parent.mkdir(parents=True, exist_ok=True)
        images = [PILImage.fromarray(frame) for frame in frames]
        images[0].save(
            path,
            save_all=True,
            append_images=images[1:],
            duration=1000.0 / fps,
            loop=loop,
        )
        return path
    if path.is_dir() or suffix == "":
        folder, stem = path, path.name or "frame"
    else:
        folder, stem = path.parent, path.stem
    folder.mkdir(parents=True, exist_ok=True)
    for k, frame in enumerate(frames):
        PILImage.fromarray(frame).save(folder / f"{stem}_{k:04d}{PNG_SUFFIX}")
    return folder

Errors

PipelineSyntaxError

Bases: ValueError

A pipeline function contains a statement the static graph analysis cannot express.

Raised when the pipeline is built (decoration time). The message names the pipeline, the file and line, the offending source line and a hint on how to rewrite it. Subclass of ValueError so existing except ValueError code keeps working.

Attributes:

Name Type Description
pipeline_name

Name of the pipeline function.

filename

Source file of the pipeline function.

lineno

Absolute line number of the offending statement in filename.

source_line

The offending source line.

hint

Suggested fix.

Source code in src/interactive_pipe/core/graph.py
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
class PipelineSyntaxError(ValueError):
    """A pipeline function contains a statement the static graph analysis cannot express.

    Raised when the pipeline is built (decoration time). The message names the
    pipeline, the file and line, the offending source line and a hint on how to
    rewrite it. Subclass of ``ValueError`` so existing ``except ValueError``
    code keeps working.

    Attributes:
        pipeline_name: Name of the pipeline function.
        filename: Source file of the pipeline function.
        lineno: Absolute line number of the offending statement in ``filename``.
        source_line: The offending source line.
        hint: Suggested fix.
    """

    def __init__(
        self,
        message: str,
        pipeline_name: Optional[str] = None,
        filename: Optional[str] = None,
        lineno: Optional[int] = None,
        source_line: Optional[str] = None,
        hint: Optional[str] = None,
    ):
        self.pipeline_name = pipeline_name
        self.filename = filename
        self.lineno = lineno
        self.source_line = source_line
        self.hint = hint
        self.reason = message
        location = f"pipeline '{pipeline_name}'" if pipeline_name else "pipeline"
        if filename is not None:
            location += f", {filename}"
            if lineno is not None:
                location += f", line {lineno}"
        full_message = f"{location}: {message}"
        if source_line:
            full_message += f"\n    {source_line.strip()}"
        if hint:
            full_message += f"\nHint: {hint}"
        super().__init__(full_message)

FilterError

Bases: Exception

Clean, user-friendly exception for filter errors.

Displays only the relevant error information without the full framework traceback, making it easier to identify issues in user code.

Source code in src/interactive_pipe/core/engine.py
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
class FilterError(Exception):
    """Clean, user-friendly exception for filter errors.

    Displays only the relevant error information without the full
    framework traceback, making it easier to identify issues in user code.
    """

    def __init__(self, filter_name: str, original_error: Exception, tb=None, hint: Optional[str] = None):
        _install_excepthook()
        self.filter_name = filter_name
        self.original_error = original_error
        self.tb = tb
        self.hint = hint
        self._user_frames = self._extract_user_frames()
        super().__init__(self._format_message())

    def _extract_user_frames(self):
        """Extract relevant frames from the traceback (user code, not framework)."""
        if self.tb is None:
            return []

        if getattr(self.original_error, "framework_check", False):
            # raised by the framework about the filter's result: the message
            # names the pipeline line, a framework traceback would only mislead
            return []
        # Walk through traceback to find the user's code (outside the package directory)
        tb_list = traceback.extract_tb(self.tb)
        user_frames = [frame for frame in tb_list if not os.path.abspath(frame.filename).startswith(_PACKAGE_DIR)]

        # If no user frames found, return last frame from traceback
        if not user_frames and tb_list:
            return [tb_list[-1]]
        return user_frames

    def _format_message(self):
        """Format a clean, readable error message."""
        error_str = str(self.original_error)

        lines = [
            "",
            f"  Filter '{self.filter_name}' raised {type(self.original_error).__name__}:",
            f"    {error_str}",
        ]

        if self._user_frames:
            lines.append("")
            lines.append("  Traceback (user code only):")
            for frame in self._user_frames:
                lines.append(f"    {frame.filename}:{frame.lineno} in {frame.name}()")
                if frame.line:
                    lines.append(f"      >>> {frame.line.strip()}")

        if self.hint:
            lines.append("")
            lines.extend(f"  {line}" for line in self.hint.splitlines())

        lines.append("")
        return "\n".join(lines)

    def print_compact(self, file=None):
        """Print a compact version of the error to stderr or specified file."""
        if file is None:
            file = sys.stderr
        print(f"\n{'=' * 60}", file=file)
        print("PIPELINE ERROR", file=file)
        print(f"{'=' * 60}", file=file)
        print(str(self), file=file)
        print(f"{'=' * 60}\n", file=file)

DisplayError

Bases: ValueError

An output array that cannot be displayed without guessing its layout (channel-first, batch, empty, object / complex dtype...). The message names the output (and the filter returning it) and the fix. Raised by prepare_display: by snapshot / sweep; a GUI window shows the message in the cell instead and keeps running.

Source code in src/interactive_pipe/graphical/display.py
789
790
791
792
793
794
class DisplayError(ValueError):
    """An output array that cannot be displayed without guessing its layout
    (channel-first, batch, empty, object / complex dtype...). The message names
    the output (and the filter returning it) and the fix. Raised by
    ``prepare_display``: by ``snapshot`` / ``sweep``; a GUI window shows the
    message in the cell instead and keeps running."""