Skip to content

Utilities & Menu API Reference

This section provides documentation for the interactive menu features and helpers.

Interactive terminal menu.

Provides a fully interactive UI to select images and build an image processing pipeline.

interactive_menu()

Run the main entry point for the interactive terminal UI.

Handles image selection, pipeline construction, and executes the processing.

Source code in src/image_converter/menu.py
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
def interactive_menu():
    """Run the main entry point for the interactive terminal UI.

    Handles image selection, pipeline construction, and executes the processing.
    """
    try:
        # We don't need the basic print anymore, the menu handles it.
        paths = select_images()
        if not paths:
            console.print("[yellow]No images selected.[/]")
            console.print(
                "[dim white]Please run the command again and select at least one image to process.[/]"
            )
            return

        def _fetch_selected_image_data(p: str) -> dict:
            """Fetch metadata for a selected image file path.

            Args:
                p (str): The path to the image file.

            Returns:
                dict: A dictionary containing image metadata.

            """
            dims, size_str, fmt = _get_image_metadata(p)
            return {
                "name": os.path.basename(p),
                "dims": dims,
                "size": size_str,
                "fmt": fmt,
                "path": p,
            }

        with console.status(
            "[bright_cyan]Loading selected image metadata...[/]", spinner="dots"
        ):
            with concurrent.futures.ThreadPoolExecutor() as executor:
                images_data = list(executor.map(_fetch_selected_image_data, paths))

        ops, extra_args, out_formats, out_qualities = select_manipulations(images_data)

        # Prepare args
        mock_args = SimpleNamespace(
            resample=extra_args.get("resample", "bilinear"),
            threshold=extra_args.get("threshold", 50),
            format=out_formats if out_formats else None,
            quality=out_qualities if out_qualities else None,
            flatten=extra_args.get("flatten", None),
        )

        # Process expects a list of [name, path] lists as per existing logic
        process_images_data = [[img["name"], img["path"]] for img in images_data]
        process_images_and_save(process_images_data, ops, mock_args)

        console.print("\n[bright_green]✨ Processing Complete ✨[/]\n")

    except KeyboardInterrupt:
        console.print("\n[yellow]Cancelled.[/]")
    except Exception as e:
        console.print(f"[red]Error: {e}[/]")

prompt_for_blur_options(extra_args=None)

Prompts the user for a blur radius.

Parameters:

Name Type Description Default
extra_args dict

Shared extra arguments dictionary. Defaults to None.

None

Returns:

Name Type Description
dict dict[str, Any] | None

The operation dictionary for 'blur'.

Source code in src/image_converter/menu.py
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
def prompt_for_blur_options(
    extra_args: dict[str, Any] | None = None,
) -> dict[str, Any] | None:
    """Prompts the user for a blur radius.

    Args:
        extra_args (dict, optional): Shared extra arguments dictionary. Defaults to None.

    Returns:
        dict: The operation dictionary for 'blur'.

    """
    val_str = _ask_text(
        "Enter blur radius (min 0.0)",
        default_val=2.0,
        validate=_validate_number(min_val=0.0, value_type=float, allow_empty=True),
    )
    return {"dest": "blur", "values": [float(val_str) if val_str else 2.0]}

prompt_for_border_options(extra_args=None)

Prompts the user for border thickness, color, and position.

Parameters:

Name Type Description Default
extra_args dict

Shared extra arguments dictionary. Defaults to None.

None

Returns:

Name Type Description
dict dict[str, Any] | None

The operation dictionary for 'border', or None if canceled.

Source code in src/image_converter/menu.py
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
def prompt_for_border_options(
    extra_args: dict[str, Any] | None = None,
) -> dict[str, Any] | None:
    """Prompts the user for border thickness, color, and position.

    Args:
        extra_args (dict, optional): Shared extra arguments dictionary. Defaults to None.

    Returns:
        dict: The operation dictionary for 'border', or None if canceled.

    """
    thickness_str = _ask_text(
        "Enter border thickness (0-500)",
        default_val=10,
        validate=_validate_number(0, 500, allow_empty=True),
    )

    color_str = _ask_text("Enter border color (Name or Hex)", default_val="black")

    position = questionary.select(
        "Border Position:",
        choices=["Expand", "Inside"],
        instruction=INSTR_SELECT,
    ).ask()

    if not position:
        return None

    return {
        "dest": "border",
        "values": [
            int(thickness_str) if thickness_str else 10,
            color_str if color_str else "black",
            position.lower(),
        ],
    }

prompt_for_brightness_options(extra_args=None)

Prompts the user for a brightness adjustment value.

Parameters:

Name Type Description Default
extra_args dict

Shared extra arguments dictionary. Defaults to None.

None

Returns:

Name Type Description
dict dict[str, Any] | None

The operation dictionary for 'brightness'.

Source code in src/image_converter/menu.py
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
def prompt_for_brightness_options(
    extra_args: dict[str, Any] | None = None,
) -> dict[str, Any] | None:
    """Prompts the user for a brightness adjustment value.

    Args:
        extra_args (dict, optional): Shared extra arguments dictionary. Defaults to None.

    Returns:
        dict: The operation dictionary for 'brightness'.

    """
    val_str = _ask_text(
        "Enter brightness value (-100 to 100)",
        default_val=0,
        validate=_validate_number(-100, 100, allow_empty=True),
    )
    return {"dest": "brightness", "values": [int(val_str) if val_str else 0]}

prompt_for_color_balance_options(extra_args=None)

Prompts the user for RGB color balance multipliers.

Parameters:

Name Type Description Default
extra_args dict

Shared extra arguments dictionary. Defaults to None.

None

Returns:

Name Type Description
dict dict[str, Any] | None

The operation dictionary for 'color_balance'.

Source code in src/image_converter/menu.py
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
def prompt_for_color_balance_options(
    extra_args: dict[str, Any] | None = None,
) -> dict[str, Any] | None:
    """Prompts the user for RGB color balance multipliers.

    Args:
        extra_args (dict, optional): Shared extra arguments dictionary. Defaults to None.

    Returns:
        dict: The operation dictionary for 'color_balance'.

    """
    console.print(
        "[dim white]Enter multipliers for Red, Green, and Blue channels (e.g., 1.0 for no change).[/]"
    )

    r_str = _ask_text(
        "Red factor",
        default_val=1.0,
        validate=_validate_number(value_type=float, allow_empty=True),
    )
    g_str = _ask_text(
        "Green factor",
        default_val=1.0,
        validate=_validate_number(value_type=float, allow_empty=True),
    )
    b_str = _ask_text(
        "Blue factor",
        default_val=1.0,
        validate=_validate_number(value_type=float, allow_empty=True),
    )

    return {
        "dest": "color_balance",
        "values": [
            float(r_str) if r_str else 1.0,
            float(g_str) if g_str else 1.0,
            float(b_str) if b_str else 1.0,
        ],
    }

prompt_for_contrast_options(extra_args=None)

Prompts the user for a contrast adjustment value.

Parameters:

Name Type Description Default
extra_args dict

Shared extra arguments dictionary. Defaults to None.

None

Returns:

Name Type Description
dict dict[str, Any] | None

The operation dictionary for 'contrast'.

Source code in src/image_converter/menu.py
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
def prompt_for_contrast_options(
    extra_args: dict[str, Any] | None = None,
) -> dict[str, Any] | None:
    """Prompts the user for a contrast adjustment value.

    Args:
        extra_args (dict, optional): Shared extra arguments dictionary. Defaults to None.

    Returns:
        dict: The operation dictionary for 'contrast'.

    """
    val_str = _ask_text(
        "Enter contrast value (-100 to 100)",
        default_val=0,
        validate=_validate_number(-100, 100, allow_empty=True),
    )
    return {"dest": "contrast", "values": [int(val_str) if val_str else 0]}

prompt_for_edge_detection_options(extra_args=None)

Prompts the user for edge detection method and threshold (if applicable).

Available Methods
  • Sobel: Emphasizes high spatial frequency regions that correspond to edges.
  • Canny: Multi-stage algorithm providing robust and thin edge detection.
  • Kovalevsky: A less common operator designed for optimal noise suppression, requiring an intensity threshold.

Parameters:

Name Type Description Default
extra_args dict

Shared extra arguments dictionary, modified in-place to store 'threshold'. Defaults to None.

None

Returns:

Name Type Description
dict dict[str, Any] | None

The operation dictionary for 'edge_detection', or None if canceled.

Source code in src/image_converter/menu.py
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
def prompt_for_edge_detection_options(
    extra_args: dict[str, Any] | None = None,
) -> dict[str, Any] | None:
    """Prompts the user for edge detection method and threshold (if applicable).

    Available Methods:
        - **Sobel**: Emphasizes high spatial frequency regions that correspond to edges.
        - **Canny**: Multi-stage algorithm providing robust and thin edge detection.
        - **Kovalevsky**: A less common operator designed for optimal noise suppression, requiring an intensity threshold.

    Args:
        extra_args (dict, optional): Shared extra arguments dictionary, modified in-place to store 'threshold'. Defaults to None.

    Returns:
        dict: The operation dictionary for 'edge_detection', or None if canceled.

    """
    method = questionary.select(
        "Select Edge Detection Method:",
        choices=["Sobel", "Canny", "Kovalevsky"],
        instruction=INSTR_SELECT,
    ).ask()

    if not method:
        return None

    method = method.lower()

    if method == "kovalevsky":
        val_str = _ask_text(
            "Enter threshold value (0-255)",
            default_val=50,
            validate=_validate_number(0, 255, allow_empty=True),
        )
        extra_args["threshold"] = int(val_str) if val_str else 50

    return {"dest": "edge_detection", "values": [method]}

prompt_for_flip_options(extra_args=None)

Prompts the user for image flipping options.

Parameters:

Name Type Description Default
extra_args dict

Shared extra arguments dictionary. Defaults to None.

None

Returns:

Name Type Description
dict dict[str, Any] | None

The operation dictionary for 'flip', or None if canceled.

Source code in src/image_converter/menu.py
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
def prompt_for_flip_options(
    extra_args: dict[str, Any] | None = None,
) -> dict[str, Any] | None:
    """Prompts the user for image flipping options.

    Args:
        extra_args (dict, optional): Shared extra arguments dictionary. Defaults to None.

    Returns:
        dict: The operation dictionary for 'flip', or None if canceled.

    """
    choice = questionary.select(
        "Select flip direction:",
        choices=["Horizontal", "Vertical", "Both"],
        instruction=INSTR_SELECT,
    ).ask()
    if not choice:
        return None
    return {"dest": "flip", "values": [choice.lower()]}

prompt_for_hue_rotation_options(extra_args=None)

Prompts the user for hue rotation degrees.

Parameters:

Name Type Description Default
extra_args dict

Shared extra arguments dictionary. Defaults to None.

None

Returns:

Name Type Description
dict dict[str, Any] | None

The operation dictionary for 'hue_rotation'.

Source code in src/image_converter/menu.py
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
def prompt_for_hue_rotation_options(
    extra_args: dict[str, Any] | None = None,
) -> dict[str, Any] | None:
    """Prompts the user for hue rotation degrees.

    Args:
        extra_args (dict, optional): Shared extra arguments dictionary. Defaults to None.

    Returns:
        dict: The operation dictionary for 'hue_rotation'.

    """
    val_str = _ask_text(
        "Enter hue rotation degrees (0-360)",
        default_val=90,
        validate=_validate_number(0, 360, allow_empty=True),
    )
    return {"dest": "hue_rotation", "values": [int(val_str) if val_str else 90]}

prompt_for_posterize_options(extra_args=None)

Prompts the user for the number of bits for posterization.

Parameters:

Name Type Description Default
extra_args dict

Shared extra arguments dictionary. Defaults to None.

None

Returns:

Name Type Description
dict dict[str, Any] | None

The operation dictionary for 'posterize'.

Source code in src/image_converter/menu.py
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
def prompt_for_posterize_options(
    extra_args: dict[str, Any] | None = None,
) -> dict[str, Any] | None:
    """Prompts the user for the number of bits for posterization.

    Args:
        extra_args (dict, optional): Shared extra arguments dictionary. Defaults to None.

    Returns:
        dict: The operation dictionary for 'posterize'.

    """
    val_str = _ask_text(
        "Enter number of bits (1-8)",
        default_val=4,
        validate=_validate_number(1, 8, allow_empty=True),
    )
    return {"dest": "posterize", "values": [int(val_str) if val_str else 4]}

prompt_for_rotation_options(extra_args=None)

Prompts the user for an image rotation angle.

Parameters:

Name Type Description Default
extra_args dict

Shared extra arguments dictionary. Defaults to None.

None

Returns:

Name Type Description
dict dict[str, Any] | None

The operation dictionary for 'rotate'.

Source code in src/image_converter/menu.py
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
def prompt_for_rotation_options(
    extra_args: dict[str, Any] | None = None,
) -> dict[str, Any] | None:
    """Prompts the user for an image rotation angle.

    Args:
        extra_args (dict, optional): Shared extra arguments dictionary. Defaults to None.

    Returns:
        dict: The operation dictionary for 'rotate'.

    """
    angle_str = _ask_text(
        "Enter rotation angle (will clamp to nearest 90)",
        default_val=90,
        validate=_validate_number(-3600, 3600, allow_empty=True),
    )
    return {"dest": "rotate", "values": [int(angle_str) if angle_str else 90]}

prompt_for_saturation_options(extra_args=None)

Prompts the user for a saturation adjustment value.

Parameters:

Name Type Description Default
extra_args dict

Shared extra arguments dictionary. Defaults to None.

None

Returns:

Name Type Description
dict dict[str, Any] | None

The operation dictionary for 'saturation'.

Source code in src/image_converter/menu.py
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
def prompt_for_saturation_options(
    extra_args: dict[str, Any] | None = None,
) -> dict[str, Any] | None:
    """Prompts the user for a saturation adjustment value.

    Args:
        extra_args (dict, optional): Shared extra arguments dictionary. Defaults to None.

    Returns:
        dict: The operation dictionary for 'saturation'.

    """
    val_str = _ask_text(
        "Enter saturation value (-100 to 100)",
        default_val=0,
        validate=_validate_number(-100, 100, allow_empty=True),
    )
    return {"dest": "saturation", "values": [int(val_str) if val_str else 0]}

prompt_for_scale_options(extra_args=None)

Prompts the user for image scaling options and resampling filter.

Parameters:

Name Type Description Default
extra_args dict

Shared extra arguments dictionary, modified in-place to store 'resample'. Defaults to None.

None

Returns:

Name Type Description
dict dict[str, Any] | None

The operation dictionary for 'scale', or None if canceled.

Source code in src/image_converter/menu.py
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
def prompt_for_scale_options(
    extra_args: dict[str, Any] | None = None,
) -> dict[str, Any] | None:
    """Prompts the user for image scaling options and resampling filter.

    Args:
        extra_args (dict, optional): Shared extra arguments dictionary, modified in-place to store 'resample'. Defaults to None.

    Returns:
        dict: The operation dictionary for 'scale', or None if canceled.

    """
    console.print("\n[dim cyan]--- Scale Options ---[/]")

    def scale_validator(val_str: str) -> "bool | str":
        """Validate the string input for scaling factors or specific pixel dimensions.

        Args:
            val_str (str): The string value to validate.

        Returns:
            bool | str: True if valid, or an error message string otherwise.

        """
        if not val_str:
            return "Scale value cannot be empty."
        val_str = val_str.lower().strip()
        parts = val_str.split()

        # Accept:
        #   - scale factor: "1.5" or "1.5x"
        #   - dimensions: "400px 300px"
        if len(parts) == 1:
            token = parts[0]
            if token.endswith("x") and not token.endswith("px"):
                token = token[:-1]
            try:
                float(token)
                return True
            except ValueError:
                return "Invalid format. Use '1.5', '1.5x' or '400px 300px'."

        if len(parts) == 2 and all(p.endswith("px") for p in parts):
            return True

        return "Invalid format. Use '1.5', '1.5x' or '400px 300px'."

    values_str = _ask_text(
        "Enter scale value (e.g., '1.5x' OR '400px 300px')", validate=scale_validator
    )

    if not values_str:
        return None

    values = values_str.lower().split()

    resample_choice = questionary.select(
        "Select Resample Filter:",
        choices=["Nearest", "Bilinear", "Bicubic", "Lanczos"],
        default="Bilinear",
        instruction=INSTR_SELECT,
    ).ask()

    if not resample_choice:
        return None

    extra_args["resample"] = resample_choice.lower()

    return {"dest": "scale", "values": values}

prompt_for_sharpen_options(extra_args=None)

Prompts the user for a sharpness intensity.

Parameters:

Name Type Description Default
extra_args dict

Shared extra arguments dictionary. Defaults to None.

None

Returns:

Name Type Description
dict dict[str, Any] | None

The operation dictionary for 'sharpen'.

Source code in src/image_converter/menu.py
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
def prompt_for_sharpen_options(
    extra_args: dict[str, Any] | None = None,
) -> dict[str, Any] | None:
    """Prompts the user for a sharpness intensity.

    Args:
        extra_args (dict, optional): Shared extra arguments dictionary. Defaults to None.

    Returns:
        dict: The operation dictionary for 'sharpen'.

    """
    val_str = _ask_text(
        "Enter sharpness intensity (0-100)",
        default_val=50,
        validate=_validate_number(0, 100, allow_empty=True),
    )
    return {"dest": "sharpen", "values": [int(val_str) if val_str else 50]}

prompt_for_vignette_options(extra_args=None)

Prompts the user for a vignette intensity.

Parameters:

Name Type Description Default
extra_args dict

Shared extra arguments dictionary. Defaults to None.

None

Returns:

Name Type Description
dict dict[str, Any] | None

The operation dictionary for 'vignette'.

Source code in src/image_converter/menu.py
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
def prompt_for_vignette_options(
    extra_args: dict[str, Any] | None = None,
) -> dict[str, Any] | None:
    """Prompts the user for a vignette intensity.

    Args:
        extra_args (dict, optional): Shared extra arguments dictionary. Defaults to None.

    Returns:
        dict: The operation dictionary for 'vignette'.

    """
    val_str = _ask_text(
        "Enter vignette intensity (0-100)",
        default_val=50,
        validate=_validate_number(0, 100, allow_empty=True),
    )
    return {"dest": "vignette", "values": [int(val_str) if val_str else 50]}

remove_manipulation(operations, extra_args)

Presents a menu to remove a previously added manipulation from the pipeline.

Parameters:

Name Type Description Default
operations list

The list of current operation dictionaries. Modified in-place.

required
extra_args dict

The extra arguments dictionary. Modified in-place to clean up orphaned arguments.

required

Returns:

Name Type Description
list list[dict[str, Any]]

The updated list of operations.

Source code in src/image_converter/menu.py
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
def remove_manipulation(
    operations: list[dict[str, Any]], extra_args: dict[str, Any]
) -> list[dict[str, Any]]:
    """Presents a menu to remove a previously added manipulation from the pipeline.

    Args:
        operations (list): The list of current operation dictionaries. Modified in-place.
        extra_args (dict): The extra arguments dictionary. Modified in-place to clean up orphaned arguments.

    Returns:
        list: The updated list of operations.

    """
    if not operations:
        console.print("\n[yellow]There are no operations to remove.[/]")
        console.print(
            "[dim white]Please select some operations from the menu to build your pipeline first.[/]"
        )
        return operations

    choices = [
        questionary.Choice(title=_format_operation_display(i, op, extra_args), value=i)
        for i, op in enumerate(operations)
    ]
    choices.append(questionary.Choice(title="Cancel", value=-1))

    choice_idx = questionary.select(
        "Select operation to remove:",
        choices=choices,
        instruction=INSTR_SELECT,
    ).ask()

    if choice_idx == -1 or choice_idx is None:
        return operations

    removed_op = operations.pop(choice_idx)
    console.print(f"\n[yellow]Removed '{removed_op['dest']}'.[/]")

    # Cleanup extra args logic
    remaining_dests = set()
    has_kovalevsky = False
    for op in operations:
        dest = op["dest"]
        remaining_dests.add(dest)
        if dest == "edge_detection" and op.get("values", [""])[0] == "kovalevsky":
            has_kovalevsky = True

    if removed_op["dest"] == "scale" and "scale" not in remaining_dests:
        extra_args.pop("resample", None)

    if not has_kovalevsky:
        extra_args.pop("threshold", None)

    return operations

select_images()

Find images in the 'Base Images' directory and prompts the user to select them.

Returns:

Name Type Description
list list[str]

A list of selected image file paths.

Source code in src/image_converter/menu.py
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
def select_images() -> list[str]:
    """Find images in the 'Base Images' directory and prompts the user to select them.

    Returns:
        list: A list of selected image file paths.

    """
    image_dir = "Base Images"
    if not os.path.isdir(image_dir):
        console.print(f"[red]Error: Directory '{image_dir}' not found.[/]")
        console.print(
            "[dim white]Please create the directory, place some images in it, and try again, or specify a path via CLI.[/]\n"
        )
        return []

    try:
        all_files = os.listdir(image_dir)
        image_files = sorted(
            [
                f
                for f in all_files
                if os.path.isfile(os.path.join(image_dir, f))
                and f.lower().endswith(
                    (".png", ".jpg", ".jpeg", ".gif", ".bmp", ".tiff", ".tif", ".webp")
                )
            ]
        )
    except Exception as e:
        console.print(f"[red]Read error: {e}[/]")
        return []

    if not image_files:
        console.print(f"\n[yellow]No images found in '{image_dir}'.[/]")
        console.print(
            "[dim white]Please place some images (e.g., .jpg, .png) in this directory and try again, or specify a path via CLI.[/]\n"
        )
        return []

    while True:
        selected_paths = run_image_selector(image_files, image_dir)

        if selected_paths is None:  # User pressed Ctrl-C
            raise KeyboardInterrupt

        if selected_paths:
            return selected_paths

        confirm = questionary.confirm(
            "No images selected. Re-select images?", default=True
        ).ask()
        if not confirm:
            return []

select_manipulations(images_data)

Presents the main interactive menu for building the image processing pipeline.

Parameters:

Name Type Description Default
images_data list

A list of dictionaries containing metadata for the selected images.

required

Returns:

Name Type Description
tuple tuple[list[dict[str, Any]], dict[str, Any], list[str], list[int]]

A tuple containing the list of selected operations and the extra arguments dictionary.

Source code in src/image_converter/menu.py
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
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
def select_manipulations(
    images_data: list[dict[str, Any]],
) -> tuple[list[dict[str, Any]], dict[str, Any], list[str], list[int]]:
    """Presents the main interactive menu for building the image processing pipeline.

    Args:
        images_data (list): A list of dictionaries containing metadata for the selected images.

    Returns:
        tuple: A tuple containing the list of selected operations and the extra arguments dictionary.

    """
    selected_operations = []
    extra_args = {}
    output_formats = []
    output_qualities = []

    # Define Categories mapping to format the interactive tree
    CATEGORIES = {
        "Color": (
            "🎨 Color",
            [
                "Convert to Grayscale",
                "Invert Colors",
                "Adjust Brightness",
                "Adjust Contrast",
                "Adjust Saturation",
                "Adjust Color Balance",
                "Rotate Hue",
            ],
        ),
        "Transform": ("📐 Transform", ["Scale Image", "Flip Image", "Rotate Image"]),
        "Effects": (
            "✨ Effects & Filters",
            [
                "Remove Background",
                "Apply Gaussian Blur",
                "Apply Sharpen",
                "Apply Edge Detection",
                "Apply Posterize",
                "Add Border",
                "Apply Vignette",
            ],
        ),
    }

    # Map name back to original list index so handlers can be triggered correctly
    name_to_idx = {m["name"]: i for i, m in enumerate(AVAILABLE_MANIPULATIONS)}

    while True:
        # Render the beautiful combined layout first
        render_combined_menu(images_data, selected_operations, extra_args)

        # Build interactive tree as questionary choices
        choices = []

        # Action Groups
        choices.append(questionary.Separator(line="⚡ Actions"))
        choices.append(questionary.Choice("   ▶ Run Processing", value="PROCESS"))
        if selected_operations:
            choices.append(
                questionary.Choice("   ❌ Remove an Operation", value="REMOVE")
            )
        choices.append(questionary.Separator(line=""))

        # Operations Tree Root
        choices.append(questionary.Separator(line="🛠️  Available Operations"))

        cats = list(CATEGORIES.items())
        for c_idx, (cat_key, (cat_label, op_names)) in enumerate(cats):
            is_last_cat = c_idx == len(cats) - 1
            cat_prefix = "└── " if is_last_cat else "├── "

            choices.append(questionary.Separator(line=f"{cat_prefix}{cat_label}"))

            for o_idx, op_name in enumerate(op_names):
                is_last_op = o_idx == len(op_names) - 1

                # Determine proper indentation based on parent branch
                indent = "    " if is_last_cat else "│   "
                op_prefix = "└── " if is_last_op else "├── "

                idx = name_to_idx.get(op_name, -1)
                display_str = f"{indent}{op_prefix}{op_name}"

                # We skip missing operations robustly
                if idx != -1:
                    choices.append(questionary.Choice(display_str, value=idx))

        selection = questionary.select(
            "",
            choices=choices,
            pointer="▶",
            use_indicator=False,
            instruction=INSTR_SELECT,
        ).ask()

        if selection is None:  # C-c
            raise KeyboardInterrupt

        if selection == "PROCESS":
            if not selected_operations:
                confirm = questionary.confirm(
                    "Pipeline is empty. Process anyway?", default=False
                ).ask()
                if not confirm:
                    continue

            # --- Output Format Prompts ---
            console.print("\n[dim cyan]--- Output Format ---[/]")
            available_formats = [
                "PNG",
                "JPG",
                "JPEG",
                "WEBP",
                "BMP",
                "TIFF",
                "GIF",
                "HEIC",
                "AVIF",
            ]

            selected_formats = questionary.checkbox(
                "Select Output Formats (Leave empty for original format):",
                choices=available_formats,
                instruction=INSTR_MULTI_SELECT,
            ).ask()

            if selected_formats:
                output_formats = [f.lower() for f in selected_formats]
                for fmt in output_formats:
                    # Formats that don't support quality setting natively or usually
                    if fmt in ["png", "bmp", "gif", "tiff"]:
                        output_qualities.append(100)
                        continue

                    q_str = _ask_text(
                        f"Enter quality for {fmt.upper()} (1-100)",
                        default_val=90,
                        validate=_validate_number(1, 100, allow_empty=True),
                    )
                    output_qualities.append(int(q_str) if q_str else 90)

            flatten_confirm = questionary.confirm(
                "Flatten transparent backgrounds?", default=False
            ).ask()
            if flatten_confirm:
                flatten_color = _ask_text(
                    "Background color for flattening (Name or Hex)", default_val="white"
                )
                extra_args["flatten"] = flatten_color if flatten_color else "white"

            break
        elif selection == "REMOVE":
            remove_manipulation(selected_operations, extra_args)
        else:
            # It's an index for a manipulation
            idx = selection
            manip = AVAILABLE_MANIPULATIONS[idx]
            handler = manip.get("handler")

            op_details = None
            if handler:
                op_details = handler(extra_args)
            else:
                op_details = {"dest": manip["dest"], "values": []}

            if op_details:
                selected_operations.append(op_details)

    return selected_operations, extra_args, output_formats, output_qualities

rich_menu

Interactive terminal UI formatting and layout components.

Utilizes the rich and questionary libraries to render formatted tables, selection menus, and pipeline summaries for the interactive CLI.

render_combined_menu(images_data, operations, extra_args)

Render the combined menu mockup layout to the console.

Displays a summary of selected images and the current sequence of operations (the pipeline), along with the equivalent CLI command.

Parameters:

Name Type Description Default
images_data list

A list of dictionaries containing image metadata.

required
operations list

A list of dictionaries detailing the ordered operations.

required
extra_args dict

A dictionary of extra global arguments (like resample filter).

required
Source code in src/image_converter/rich_menu.py
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
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
def render_combined_menu(
    images_data: list[dict[str, Any]],
    operations: list[dict[str, Any]],
    extra_args: dict[str, Any],
) -> None:
    """Render the combined menu mockup layout to the console.

    Displays a summary of selected images and the current sequence of operations
    (the pipeline), along with the equivalent CLI command.

    Args:
        images_data (list): A list of dictionaries containing image metadata.
        operations (list): A list of dictionaries detailing the ordered operations.
        extra_args (dict): A dictionary of extra global arguments (like resample filter).

    """
    console.clear()
    console.print()
    console.print(
        "✨ [bold cyan]Image Converter[/] | [italic white]Interactive Image Processor[/]",
        justify="left",
    )
    console.rule(style="dim")
    console.print()

    # ── Image Table ──
    img_table = Table(
        title="🖼️  Selected Images",
        box=box.MINIMAL_HEAVY_HEAD,
        title_style="bold bright_white",
        border_style="dim white",
        header_style="bold bright_cyan",
        title_justify="left",
        padding=(0, 1),
    )
    img_table.add_column("#", style="dim white", width=3, justify="right")
    img_table.add_column(
        "Filename",
        style="bright_white",
        min_width=25,
        no_wrap=True,
        overflow="ellipsis",
        max_width=30,
    )
    img_table.add_column("Dimensions", style="bright_green", justify="center")
    img_table.add_column("Size", style="bright_yellow", justify="right")
    img_table.add_column("Format", style="bright_magenta")

    for i, img in enumerate(images_data):
        img_table.add_row(
            str(i + 1),
            img["name"],
            img["dims"],
            img["size"],
            img["fmt"],
        )

    # ── Pipeline & CLI Panel ──
    from .menu import _format_operation_display

    pipeline_content = Text()

    cli_args_list = []

    if not operations:
        pipeline_content.append(
            "  (Empty - Select operations below to build your pipeline)\n",
            style="dim italic",
        )
    else:
        for i, op in enumerate(operations):
            # Formats beautifully with numbers
            pretty_op = _format_operation_display(i, op, extra_args)
            pipeline_content.append(f"  {pretty_op}\n", style="bright_white")

            # Build raw CLI equivalent separately
            arg_name = op["dest"].replace("_", "-")
            arg_vals = " ".join(map(str, op.get("values", [])))
            cli_args_list.append(f"--{arg_name} {arg_vals}".strip())

            if op["dest"] == "scale" and "resample" in extra_args:
                cli_args_list.append(f"--resample {extra_args['resample']}")
            if (
                op["dest"] == "edge_detection"
                and op.get("values", [""])[0] == "kovalevsky"
            ):
                cli_args_list.append(f"--threshold {extra_args.get('threshold', 50)}")

    pipeline_content.append("\n")
    pipeline_content.append("  Equivalent CLI Command:\n", style="dim cyan")

    cli_str = " ".join(cli_args_list) if cli_args_list else "None"
    pipeline_content.append(
        rf"  > image-converter \[images] {cli_str}", style="italic bright_cyan"
    )

    pipeline_panel = Panel(
        pipeline_content,
        title="⚙️  Pipeline",
        title_align="left",
        border_style="bright_blue",
        box=box.ROUNDED,
        padding=(1, 2),
    )

    # ── Combined Layout ──
    # Top row: Image Table
    # Bottom row: Pipeline Panel

    console.print(img_table)
    console.print()
    console.print(pipeline_panel)
    console.print()

run_image_selector(image_files, image_dir)

Render a tabular-style selection menu using questionary.

Parameters:

Name Type Description Default
image_files list

A list of image filenames.

required
image_dir str

The directory containing the image files.

required

Returns:

Type Description
list[str] | None

list | None: A list of selected image file paths, or None if cancelled.

Source code in src/image_converter/rich_menu.py
 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
 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
def run_image_selector(image_files: list[str], image_dir: str) -> list[str] | None:
    """Render a tabular-style selection menu using questionary.

    Args:
        image_files (list): A list of image filenames.
        image_dir (str): The directory containing the image files.

    Returns:
        list | None: A list of selected image file paths, or None if cancelled.

    """
    if not image_files:
        return []

    def _fetch_image_data(f: str) -> dict:
        """Fetch metadata for a given image file in the directory."""
        path = os.path.join(image_dir, f)
        dims, size_str, fmt = _get_image_metadata(path)
        return {"name": f, "path": path, "dims": dims, "size": size_str, "fmt": fmt}

    # Pre-fetch metadata in parallel to build nicely aligned strings
    with console.status("[bright_cyan]Loading image metadata...[/]", spinner="dots"):
        with concurrent.futures.ThreadPoolExecutor() as executor:
            images_data = list(executor.map(_fetch_image_data, image_files))

    # Header
    console.print()
    console.print("📁 [bold bright_cyan]Select Images to Process[/]")
    console.rule(style="dim cyan")
    console.print(
        "  [dim white]#[/] │ [bright_white]Filename[/]"
        + " " * 23
        + "│ [bright_green]Dimensions[/]   │ [bright_yellow]Size[/]      │ [bright_magenta]Format[/]"
    )
    console.rule(style="dim cyan")

    # Build choices
    choices = []
    for i, img in enumerate(images_data, 1):
        # Format string to look like table columns
        # name 30, dims 14, size 10, fmt 8

        display_name = img["name"]
        if len(display_name) > 30:
            display_name = display_name[:29] + "…"

        name_col = f"{display_name:<30}"
        dims_col = f"{img['dims']:>12}"
        size_col = f"{img['size']:>9}"
        fmt_col = f"{img['fmt']:>6}"

        display_str = f"{i:>2}{name_col}{dims_col}{size_col}{fmt_col}"
        choices.append(questionary.Choice(display_str, value=img["path"]))

    selected = questionary.checkbox(
        "",
        choices=choices,
        qmark=" ",
        instruction=INSTR_CHECKBOX,
    ).ask()

    return selected