Zum Inhalt

Image format converter

Overview

The image_format_converter module converts article image assets from TIFF and/or JPEG into PNG or SVG as part of the WDM harvesting workflow.

The module operates on the output of the preceding workflow module. For each eligible article, it copies the previous module's data into a temporary image_format_converter directory, recursively searches supported image folders, converts the selected files, appends processing documentation, and finalizes the article as either a normal module output or a stop-processing-... output.

The implementation is split across:

  • image_format_converter/flow.py — Prefect flow entry point and runtime parameter handling.
  • image_format_converter/tasks.py — article iteration, source discovery, conversion, diagnostics, documentation, and finalization.

Key capabilities

  • Converts .tif, .tiff, .jpg, and .jpeg files.
  • Supports PNG output through Pillow with an ImageMagick fallback.
  • Supports SVG output through an intermediate PNG and VTracer vectorization.
  • Recursively scans images, image, supplementary, and supplement directories.
  • Preserves supported PNG image modes and ICC profiles when Pillow performs the conversion.
  • Restricts ImageMagick and SVG processing with configurable safety limits.
  • Continues checking the remaining images in an article after an individual conversion failure.
  • Records successful conversions in processing/history.csv.
  • Records article conversion errors in the central harvesting error logs.
  • Produces per-article, per-journal, and complete-run image summaries in Prefect logs.
  • Supports isolated testing on a copied journal directory.

Scope and non-goals

This module is intended for format normalization of raster image assets already present in an article package.

It does not:

  • download images;
  • modify links or references in XML, HTML, or metadata files;
  • rename converted files to remove the original extension;
  • convert PNG, GIF, PDF, WebP, or other formats unless they happen to be mislabeled with a selected source extension;
  • combine multiple TIFF pages or image frames;
  • expose VTracer vectorization parameters through the Prefect flow;
  • guarantee that a raster image will produce a small or semantically simple SVG.

Supported conversions

source_format Selected file extensions target_format=png target_format=svg
tif .tif, .tiff Supported Supported
jpg .jpg, .jpeg Supported Supported
tif_and_jpg .tif, .tiff, .jpg, .jpeg Supported Supported

Extension matching is case-insensitive because suffixes are normalized to lowercase before comparison.

Important: SVG output is not a direct TIFF/JPEG-to-SVG transformation. The source is first converted to a temporary PNG. VTracer then vectorizes that PNG.

Module placement and prerequisites

Workflow placement

image_format_converter is a downstream module. It expects a preceding module directory for each article and uses the normal WDM previous-module lifecycle.

The module name must appear in the selected journal's module list in the harvesting configuration. The module immediately before it becomes previous_module.

Minimal configuration fragment:

{
  "Sources": [
    {
      "standard-modules": [
        "mdpi_with_images",
        "image_format_converter"
      ],
      "Journals": [
        {
          "issn-e": "1234-5678"
        }
      ]
    }
  ]
}

The surrounding configuration still needs all fields required by the rest of the WDM workflow. This example only demonstrates module ordering.

Required Python packages

  • Prefect
  • Pillow
  • VTracer (vtracer)

Optional system dependency

ImageMagick is required only when Pillow cannot decode or process a source image. The module searches PATH in this order:

  1. magick — typical ImageMagick 7 command;
  2. convert — supported for older ImageMagick installations.

If neither command is available, a file that needs the fallback cannot be converted and the article is marked to stop processing.

Required WDM structure

The copied previous-module directory is expected to contain:

  • the existing processing/ directory;
  • the existing processing/history.csv file;
  • article and journal metadata required by central error logging;
  • one or more supported source directories when images are present.

The module treats a missing source image directory as a valid no-op. It does not treat a missing processing/history.csv as valid because downstream processing documentation expects that file to have been created earlier in the workflow.

Flow interface

image_format_converter(...)

image_format_converter(
    name_of_config_file="config-test_imgfc_shadman.json",
    test_copy=False,
    source_format="tif",
    target_format="png",
)
Parameter Type Allowed values Default Description
name_of_config_file str Existing WDM configuration filename config-test_imgfc_shadman.json File resolved relative to WDM_DATA_ROOT.
test_copy bool True, False False When enabled, copies each journal directory and processes the copy instead of the original.
source_format literal string tif, jpg, tif_and_jpg tif Chooses the source extensions to discover and convert.
target_format literal string png, svg png Selects the target conversion pipeline.

Example calls

Convert TIFF images to PNG:

from image_format_converter.flow import image_format_converter

image_format_converter(
    name_of_config_file="config.json",
    source_format="tif",
    target_format="png",
)

Convert both TIFF and JPEG images to SVG on a journal copy:

from image_format_converter.flow import image_format_converter

image_format_converter(
    name_of_config_file="config.json",
    test_copy=True,
    source_format="tif_and_jpg",
    target_format="svg",
)

The file can also be executed directly for local testing. Direct execution uses all default parameters.

Environment variables

Variable Required Purpose
IMAGE_FORMAT_CONVERTER_IMAGEMAGICK_TMPDIR No Parent directory for ImageMagick pixel-cache directories. If unset, the converted image's directory is used.

For large images, IMAGE_FORMAT_CONVERTER_IMAGEMAGICK_TMPDIR should point to a local or dedicated filesystem with sufficient free space. A slow network filesystem can significantly reduce fallback performance.

Source and output layout

Recognized source directories

The module checks these top-level directories inside the current temporary module directory:

images/
image/
supplementary/
supplement/

All existing recognized directories are processed. Search is recursive, so nested image assets are included.

Example:

temp-image_format_converter_2026-07-31/
├── images/
│   ├── figure-01.tif
│   └── nested/
│       └── figure-02.jpeg
├── supplementary/
│   └── supplement-01.tiff
└── processing/
    └── history.csv

Output naming

The output is created beside the source file. The original filename, including its source extension, is retained as part of the output filename.

figure-01.tif
→ figure-01.tif.converted.to.png
figure-02.jpeg
→ figure-02.jpeg.converted.to.svg

This naming scheme avoids ambiguity about the source format and prevents the output from silently colliding with an independently supplied file such as figure-01.png.

Source deletion

A source file is deleted from the copied current-module directory only after its target file has been created successfully.

Consequences:

  • successful conversion: the source is removed and the converted target remains;
  • failed conversion: the source remains for diagnosis;
  • article with mixed results: successful sources may already have been replaced even when another source causes the article to become a stop-processing output.

If a target path already exists, it is deleted before the new conversion starts, and a warning is logged.

Processing lifecycle

  1. The flow records the current UTC date and creates a file logging handler when it is not running as a subflow.
  2. It resolves the module context from the selected configuration file.
  3. It obtains the preceding module and the configured ISSN list.
  4. For each journal, it optionally creates a timestamped test copy.
  5. For every article directory, stale temporary directories from earlier failed runs of this module are removed.
  6. The latest preceding-module directory is located.
  7. The article is skipped when:
  8. no preceding-module directory exists;
  9. the preceding module already contains the processed-by-module-image_format_converter marker;
  10. the preceding-module directory is already a stop-processing directory.
  11. Eligible preceding-module content is copied into a temporary current-module directory.
  12. The module discovers selected source images and logs an article-level source summary.
  13. Each file is converted independently.
  14. Successful input/output pairs are appended to processing/history.csv.
  15. Collected article errors are appended as one central error-log row.
  16. The temporary current-module directory is queued for deferred finalization.
  17. After all journals have been inspected, queued temporary directories are renamed in bulk.
  18. A complete-run discovery summary is logged.

Conversion behavior

PNG conversion pipeline

Primary path: Pillow

Pillow is used first for all PNG conversions.

The module logs:

  • detected image format;
  • image mode;
  • width and height;
  • frame/page count;
  • available image.info keys.

Supported output modes are:

1, L, LA, I, P, RGB, RGBA

When the source mode is not in this set, the image is converted to RGB. The log identifies both the original mode and the conversion purpose.

Examples that normally require conversion include CMYK, YCbCr, and other Pillow modes not supported by the configured PNG path.

When Pillow performs the conversion, an ICC profile present on the prepared output image is passed to the PNG writer.

Multi-frame and multi-page images

Only the first frame or page is converted.

For an image with more than one frame/page, the module:

  1. logs a warning containing the frame count;
  2. seeks back to frame 0 for the real conversion;
  3. copies that frame into memory before saving.

DEBUG_SAVE_SECOND_FRAME is disabled by default. If enabled in the source code, frame 1 is saved for inspection as:

<source-filename>.debug.frame-001.png

This debug option is intended for diagnosis and is not a flow parameter.

Fallback path: ImageMagick

The module falls back to ImageMagick when Pillow raises one of these exceptions:

  • UnidentifiedImageError;
  • Image.DecompressionBombError;
  • OSError.

The fallback explicitly selects the first frame/page by passing [0] with the input path.

ImageMagick is invoked with per-process resource limits and a dedicated temporary pixel cache. Metadata and profiles are stripped from fallback output to avoid invalid profile errors.

Current limits:

Limit Value Meaning
Source file size 100 MiB Maximum source file size accepted by the ImageMagick fallback. This check does not apply when Pillow succeeds.
Memory 4 GiB ImageMagick in-memory pixel cache limit.
Memory map 8 GiB ImageMagick mapped-file cache limit.
Disk 16 GiB ImageMagick disk cache limit.
Area 2 GP Images above the area threshold are forced toward disk-backed cache.
Threads 4 Maximum ImageMagick processing threads.
Time 1800 s Maximum ImageMagick execution time.

These command-line limits cannot exceed stricter global ImageMagick limits defined by the host's policy.xml.

SVG conversion pipeline

SVG conversion has three stages:

  1. Convert the TIFF/JPEG source to a temporary PNG using the complete PNG pipeline, including the ImageMagick fallback.
  2. Validate the temporary PNG's dimensions and pixel count.
  3. Vectorize the temporary PNG with vtracer.convert_image_to_svg_py(...).

The temporary PNG is named:

<source-filename>.tmp-for-svg.png

It is deleted in a finally block whether vectorization succeeds or fails.

SVG safety limits

Limit Current value Failure condition
MAX_SVG_SOURCE_PIXELS 660,000,000 pixels width × height exceeds the limit.
MAX_SVG_SOURCE_DIMENSION 72,000 pixels Width or height exceeds the limit.

Pillow's global decompression-bomb pixel check is temporarily disabled only while reading the dimensions of the module-generated temporary PNG. The module's own SVG limits are then applied immediately, and Pillow's original setting is restored.

The limits exist because VTracer may require substantial memory and CPU for very large rasters. Increasing them without increasing or measuring host capacity can result in the worker being terminated by the operating system, for example with SIGKILL.

Vectorization characteristics

VTracer's Python default settings are currently used. No parameters for color precision, path simplification, segmentation, or curve fitting are exposed through the flow.

SVG is therefore best suited to diagrams, line art, icons, charts, and illustrations with relatively simple color regions. Photographic JPEGs may create large, complex SVG files and are usually better normalized to PNG.

Error handling and stop-processing semantics

Parameter validation

Unsupported flow values are rejected before journal processing.

Examples:

Unsupported source_format 'png'. Supported values are: ['tif', 'jpg', 'tif_and_jpg']
Unsupported target_format 'pdf'. Supported values are: ['png', 'svg']

At the top-level conversion function, invalid values raise ValueError. The per-article Prefect task also validates its values and returns a stop condition if invoked directly with invalid input.

Per-file failures

A conversion failure does not immediately terminate the article loop. Instead, the module:

  1. marks the article with mark_stop=True;
  2. records the error message;
  3. logs the error;
  4. continues with the next selected source file.

All error messages from the article are joined into one error-log value after file iteration.

When Pillow cannot identify a selected file, the module inspects its first bytes and reports a best-effort type such as JPEG, PNG, GIF, TIFF, PDF, ZIP-like, HTML, XML/text-like, empty, or unknown.

Article outcome

Condition mark_stop Final module directory
No recognized source directories False Normal output directory
Recognized directories but no selected files False Normal output directory
All selected files convert successfully False Normal output directory
A configured source path exists but is not a directory True stop-processing-image_format_converter_<suffix>
One or more files fail True stop-processing-image_format_converter_<suffix>

The module still writes successful history rows for files converted before or after another file's failure.

Finalization failures

Finalization is performed after all journal/article iteration. Each queued rename job is handled independently. If a temp directory is missing or a rename/cleanup operation fails, the module logs the error and continues with the remaining jobs.

A finalization error may therefore leave a temporary directory behind even when the Prefect flow itself reaches its end. Operators should inspect finalization errors rather than relying only on the overall flow state.

Processing documentation

Per-article processing history

Each successful conversion appends one input/output pair to:

processing/history.csv

The recorded description follows this format:

Convert TIF image to PNG
Convert JPG image to SVG

Input and output paths are relative to the current module directory.

Example conceptual rows:

Input Output Description
images/figure.tif images/figure.tif.converted.to.png Convert TIF image to PNG
supplement/plot.jpg supplement/plot.jpg.converted.to.svg Convert JPG image to SVG

Central error log

When an article has one or more conversion errors, the module calls the shared error logging interface in automatic mode. The central CSV is written below:

<WDM_DATA_ROOT>/logs/error_logs/<publisher>/image_format_converter/
<ISSN>_<publisher>_image_format_converter.csv

Default columns include:

  • date;
  • Prefect flow-run ID;
  • Prefect flow-run name;
  • module;
  • ISSN;
  • DOI;
  • article directory;
  • error message.

The article directory refers to the expected final stop-processing directory.

Logging and observability

The flow uses Prefect logging and, when run as a top-level flow, adds a rotating file handler below the WDM data root.

Important log categories include:

Flow context

  • log file path;
  • module name;
  • data root and temporary data root;
  • selected source format;
  • resolved module context;
  • preceding module;
  • ISSN list.

Article discovery

  • journal path;
  • current preceding-module path;
  • missing recognized source folders;
  • number of selected images;
  • selected image counts grouped by source folder and actual format.

Conversion diagnostics

  • image format, mode, dimensions, frame count, and metadata keys;
  • mode conversion decisions;
  • first-frame-only warnings;
  • fallback activation;
  • ImageMagick standard output and standard error on failure;
  • source header guess when conversion fails.

Completion summaries

The module logs:

  • attempted/skipped/prohibited article counts per journal;
  • a run-level image discovery summary grouped by ISSN, folder, and format;
  • a grand total of selected source images.

Interpretation note: the image summaries describe files discovered before conversion. They are not success/failure statistics. Similarly, the journal's “processed” article count represents articles attempted by the module, including articles that become stop-processing outputs.

Test-copy mode

When test_copy=True, the shared WDM copy helper creates a sibling copy of the journal directory with a name similar to:

<journal-path>-image_format_converter-<YYYY-MM-DD>-<unix-timestamp>

The module processes that copy and leaves the original journal directory untouched.

Operational implications:

  • copying a large journal may require substantial time and free disk space;
  • the copied journal remains after the run and must be removed manually when no longer needed;
  • logs and central error files still use the normal module name and global log locations;
  • test-copy mode is appropriate for validating new limits or ImageMagick behavior on representative articles.

Configuration constants

The following constants are currently code-level settings in tasks.py, not Prefect flow parameters.

Constant Current value Operational effect
SOURCE_FOLDER_NAMES images, image, supplementary, supplement Top-level directories searched recursively.
PNG_SUPPORTED_MODES 1, L, LA, I, P, RGB, RGBA Modes saved without forced RGB conversion.
DEBUG_SAVE_SECOND_FRAME False Enables/disables diagnostic export of frame 1.
MIN_FRAMES_FOR_SECOND_FRAME 2 Minimum frame count for the diagnostic export.
MAX_SUPPORTED_SOURCE_FILE_SIZE_BYTES 104,857,600 Maximum source size for ImageMagick fallback.
IMAGEMAGICK_MEMORY_LIMIT 4GiB ImageMagick memory limit.
IMAGEMAGICK_MAP_LIMIT 8GiB ImageMagick map limit.
IMAGEMAGICK_DISK_LIMIT 16GiB ImageMagick disk limit.
IMAGEMAGICK_AREA_LIMIT 2GP Pixel-cache area threshold.
IMAGEMAGICK_THREAD_LIMIT 4 ImageMagick thread limit.
IMAGEMAGICK_TIME_LIMIT 1800 ImageMagick processing time limit in seconds.
MAX_SVG_SOURCE_PIXELS 660,000,000 VTracer input pixel-count guard.
MAX_SVG_SOURCE_DIMENSION 72,000 VTracer input width/height guard.

Changing these values changes the supported workload and risk profile. Changes should be tested against real large-image samples and the worker's RAM, swap, temporary storage, and ImageMagick policy.

Troubleshooting

Symptom or log message Likely cause Recommended action
Previous module ... not found Article has no directory matching the configured preceding module. Verify module ordering, article contents, and the configuration used for the run.
No source folders found None of the four recognized folder names exists. Treat as a valid no-op or rename/configure the upstream folder to a recognized name.
No TIF/JPG images found Recognized directories exist but contain no selected extensions. Check source_format, file extensions, and nested directory contents.
Expected source path to be a directory A file or other object uses a reserved source-folder name. Rename/remove the conflicting path and rerun the article.
Pillow could not decode/process image. Trying ImageMagick fallback Unusual TIFF encoding, very large image, decompression-bomb protection, or another Pillow I/O failure. Confirm ImageMagick is installed and inspect the later fallback result. This warning alone is not a final failure.
neither 'magick' nor 'convert' was found in PATH ImageMagick is unavailable inside the worker environment. Install ImageMagick or correct the worker/container PATH.
Source file is larger than ... supported limit Pillow failed and the source exceeds the 100 MiB fallback file-size guard. Validate the file, then adjust the limit only after capacity testing.
ImageMagick cache resources exhausted or policy error Per-process limits, free temporary storage, or global policy.xml limits are too restrictive. Check free disk space, IMAGE_FORMAT_CONVERTER_IMAGEMAGICK_TMPDIR, and magick -list resource; coordinate policy changes with infrastructure maintainers.
Skipping SVG conversion because temporary PNG is too large Pixel count exceeds MAX_SVG_SOURCE_PIXELS. Keep the article stopped, use PNG instead, downsample upstream, or raise the guard only after memory testing.
dimensions are too large for safe vectorization Width or height exceeds MAX_SVG_SOURCE_DIMENSION. Use PNG, resize upstream, or change the guard after testing.
Worker exits with SIGKILL and no Python exception Operating system/container killed the process, commonly due to memory pressure. Reduce SVG limits, use PNG, increase worker memory, reduce concurrency, and place ImageMagick cache on adequate storage.
File matched selected extension ... but Pillow could not identify it Incorrect extension, corruption, truncated file, or unsupported encoding. Use the logged header guess, inspect the original file, and replace or correct it upstream.
History documentation fails processing/ or processing/history.csv is missing from the previous module copy. Repair the preceding workflow output; the image converter expects existing processing history.
Temp module folder remains after the run Bulk finalization failed or the worker stopped before finalization. Inspect finalization logs, verify filesystem permissions, and rerun after correcting the underlying issue.

Capacity and safety guidance

File size is not memory usage

Compressed TIFF or JPEG file size is not a reliable predictor of conversion memory. Decoding expands the image into pixels. A rough lower-bound estimate for one uncompressed raster buffer is:

width × height × channels × bytes_per_channel

Real conversion may require several simultaneous buffers, library overhead, caches, and vectorization structures. SVG conversion can require much more memory than the source raster buffer alone.

  1. Test on a copied journal with test_copy=True.
  2. Record image dimensions, pixel count, source file size, and peak worker memory.
  3. Ensure the temporary filesystem has space for ImageMagick cache and intermediate PNG data.
  4. Increase one limit at a time.
  5. Avoid concurrent large SVG conversions until single-image peak usage is understood.
  6. Keep enough headroom for Prefect, Python, filesystem cache, and other processes.
  7. Prefer PNG when vector output is not an explicit preservation or delivery requirement.

Decompression-bomb protection

Pillow's decompression-bomb exception is a safety mechanism triggered by unusually large decoded pixel counts. It does not prove that a file is malicious. The module treats it as a reason to attempt conversion through the resource-limited ImageMagick fallback.

Operators should still validate the integrity of unusually large inputs before relaxing any guard.

API reference

Names beginning with an underscore are implementation details and are not considered a stable public API. External callers should normally invoke the Prefect flow or convert_image_formats(...) rather than calling internal helpers directly.

Flow entry point

image_format_converter.flow.image_format_converter(name_of_config_file='config-test_imgfc_shadman.json', test_copy=False, source_format='tif', target_format='png')

Prefect flow entry point for the module. It initializes run logging, resolves the WDM data roots and module context, determines the previous module and configured journals, constructs ConversionOptions, and delegates processing to convert_image_formats(...).

Parameters

  • name_of_config_file (str) – Name of the harvesting configuration file located under WDM_DATA_ROOT.
  • test_copy (bool) – When True, process a timestamped copy of each journal directory instead of the original directory.
  • source_format (Literal["tif", "jpg", "tif_and_jpg"]) – Select which source image extensions are discovered and converted.
  • target_format (Literal["png", "svg"]) – Select the target conversion pipeline.

Returns

  • None

Raises

  • FileNotFoundError – If the selected configuration file cannot be opened.
  • KeyError, IndexError, or configuration-related exceptions – If the configuration does not provide the structure required by the shared configuration helpers.
  • ValueError – Propagated from convert_image_formats(...) when a source or target format is unsupported.
  • Filesystem, logging, Prefect, and conversion exceptions may propagate from downstream helpers when a run cannot be initialized or processed.

Processing steps

  1. Record the current UTC date and timestamp.
  2. Attach the shared rotating file logger when the flow is not running as a subflow.
  3. Resolve the flow name and configured WDM data roots.
  4. Load the module context from the selected configuration file.
  5. Determine the preceding workflow module and the configured ISSN list.
  6. Build a ConversionOptions instance from the flow parameters.
  7. Call convert_image_formats(...) to execute journal- and article-level processing.

Notes

  • The @flow decorator exposes this function as the public Prefect flow named image_format_converter.
  • Running flow.py directly invokes this function with its default arguments and is intended only for local testing.
  • Parameter type restrictions are expressed with Literal, but runtime validation is also performed in tasks.py.

Data models

image_format_converter.tasks.ConversionOptions

@dataclass(frozen=True)
class ConversionOptions:
    test_copy: bool
    source_format: SourceFormat
    target_format: TargetFormat

Immutable runtime options passed from the Prefect flow to journal-level processing.

Parameters

  • test_copy (bool) – Process a timestamped copy of each journal directory when True.
  • source_format (Literal["tif", "jpg", "tif_and_jpg"]) – Select the source extensions to discover.
  • target_format (Literal["png", "svg"]) – Select the target conversion pipeline.

image_format_converter.tasks.ArticleConversionContext

@dataclass(frozen=True)
class ArticleConversionContext:
    journal_issn: str
    article_id: str
    run_image_summary: list[dict]

Carries article identity and the shared run-summary collection into the article conversion task.

Parameters

  • journal_issn (str) – ISSN of the journal currently being processed.
  • article_id (str) – Article directory name used in log messages.
  • run_image_summary (list[dict]) – Mutable run-level aggregation list shared across article calls.

Notes

Although the dataclass is frozen, run_image_summary is a mutable list. Internal summary helpers append records to that list.

Main processing functions

image_format_converter.tasks.convert_image_formats(module_name, previous_module, issns, current_datetime, options)

Coordinate journal discovery, article eligibility checks, conversion, documentation, and deferred finalization for one flow run.

Parameters

  • module_name (str) – Current Prefect flow/module name.
  • previous_module (str | None) – Name of the module whose latest article output is used as input.
  • issns (Iterable[str]) – Journal ISSNs selected from the harvesting configuration.
  • current_datetime (dict) – Run timestamp dictionary. The date-str value is written to processing history.
  • options (ConversionOptions) – Source, target, and test-copy settings.

Returns

  • None

Raises

  • ValueError – If source_format or target_format is unsupported.
  • Filesystem and documentation exceptions may propagate when journal preparation, module copying, or history writing fails.

Processing steps

  1. Validate conversion options.
  2. Resolve and optionally copy each journal directory.
  3. Skip ineligible articles.
  4. Copy the latest previous-module output into a temporary current-module directory.
  5. Call convert_images(...) for the article.
  6. Append processing history and central error-log records.
  7. Queue article directories for bulk finalization.
  8. Finalize queued directories and log the complete-run source summary.

image_format_converter.tasks.convert_images(temp_current_module_dir, source_format, target_format, logger, article_context)

Discover and convert all selected source images in one article's temporary module directory.

Parameters

  • temp_current_module_dir (Path) – Temporary current-module directory containing the copied article package.
  • source_format (SourceFormat) – Source selection: tif, jpg, or tif_and_jpg.
  • target_format (TargetFormat) – Output format: png or svg.
  • logger – Prefect-compatible logger used for diagnostics.
  • article_context (ArticleConversionContext) – Article identity and run-summary state.

Returns

  • tuple[list[str], list[str], list[str], bool, str | None] – A five-item result:
  • successful relative input paths;
  • successful relative output paths;
  • one description for each successful conversion;
  • mark_stop, indicating whether the article must become a stop-processing output;
  • combined article error text, or None when no conversion failed.

Notes

Per-file exceptions are converted into article error messages. The function continues processing later files and therefore normally does not raise for an individual image failure.

Validation and source discovery

image_format_converter.tasks._get_format_validation_error(source_format, target_format)

_get_format_validation_error(
    source_format: SourceFormat,
    target_format: TargetFormat,
) -> str | None

Validate a source/target option pair without raising an exception.

Parameters

  • source_format (SourceFormat) – Proposed source selection.
  • target_format (TargetFormat) – Proposed output format.

Returns

  • str | None – A human-readable validation error, or None when both values are supported.

image_format_converter.tasks._get_existing_source_dirs(source_dirs, logger)

Filter candidate source paths to directories that currently exist.

Parameters

  • source_dirs (list[Path]) – Candidate images, image, supplementary, and supplement paths.
  • logger – Logger used to report absent paths.

Returns

  • tuple[list[Path], str | None] – Existing directories and an optional error message.

Behavior

Missing paths are valid and are skipped. A path that exists but is not a directory causes an error result.


image_format_converter.tasks._find_source_files(source_dirs, source_suffixes)

Recursively find files whose lower-case suffix matches the selected source extensions.

Parameters

  • source_dirs (list[Path]) – Existing source directories to search.
  • source_suffixes (set[str]) – Accepted suffixes, including the leading dot.

Returns

  • list[Path] – Deterministically sorted matching paths.

Conversion dispatch

image_format_converter.tasks._convert_source_file(source_path, temp_current_module_dir, target_format, logger)

Convert one source file, delete the source after success, and construct processing-history values.

Parameters

  • source_path (Path) – TIFF or JPEG source file.
  • temp_current_module_dir (Path) – Root used to create relative history paths.
  • target_format (TargetFormat) – png or svg.
  • logger – Logger used for overwrite and success messages.

Returns

  • tuple[str, str, str] – Relative input path, relative output path, and conversion description.

Raises

  • ValueError – If an unsupported target format reaches the dispatcher.
  • Conversion and filesystem exceptions from the selected output pipeline may propagate to convert_images(...).

Notes

The target is named <source-name>.converted.to.<target-format>. An existing target is removed before conversion. The source is unlinked only after the selected converter returns successfully.

PNG conversion helpers

image_format_converter.tasks._convert_to_png(source_path, target_path, logger, conversion_purpose='PNG output')

Convert one raster image to PNG with Pillow and activate ImageMagick for selected Pillow failures.

Parameters

  • source_path (Path) – Source raster path.
  • target_path (Path) – PNG output path.
  • logger – Logger used for image diagnostics and fallback messages.
  • conversion_purpose (str) – Human-readable reason included in mode-conversion logs.

Returns

  • None

Raises

  • Exceptions from Pillow operations that are not part of the fallback set.
  • RuntimeError and other exceptions raised by _convert_to_png_with_imagemagick(...) when fallback conversion fails.

Fallback conditions

ImageMagick is attempted when Pillow raises UnidentifiedImageError, Image.DecompressionBombError, or OSError.


image_format_converter.tasks._prepare_first_frame_for_output(image, source_path, logger)

Select frame/page 0 and copy it into an independent Pillow image for output.

Parameters

  • image (PIL.Image.Image) – Open Pillow image.
  • source_path (Path) – Source path used in warnings.
  • logger – Logger used for multi-frame and debug messages.

Returns

  • PIL.Image.Image – Copy of the first frame/page.

Notes

When DEBUG_SAVE_SECOND_FRAME is enabled and a second frame exists, frame 1 is written as a diagnostic PNG. Failures in that optional diagnostic export are logged and ignored.


image_format_converter.tasks._convert_image_mode_to_rgb(image, source_path, logger, conversion_purpose)

Convert a Pillow image to RGB and log the original mode and purpose.

Parameters

  • image (PIL.Image.Image) – Image requiring mode conversion.
  • source_path (Path) – Source path included in logs.
  • logger – Logger used for success and failure messages.
  • conversion_purpose (str) – Context such as PNG output or SVG conversion intermediate PNG.

Returns

  • PIL.Image.Image – RGB-converted image.

Raises

  • Re-raises the Pillow exception when mode conversion fails.

image_format_converter.tasks._convert_to_png_with_imagemagick(source_path, target_path, logger)

Run ImageMagick with explicit memory, map, disk, area, thread, and time limits.

Parameters

  • source_path (Path) – Source image. The command explicitly selects frame/page [0].
  • target_path (Path) – PNG output path.
  • logger – Logger used for successful fallback conversion.

Returns

  • None

Raises

  • RuntimeError – If the source exceeds the configured fallback file-size limit.
  • RuntimeError – If neither magick nor convert is available.
  • RuntimeError – If ImageMagick exits with a non-zero status.
  • RuntimeError – If ImageMagick reports success but no target file is created.

Notes

A dedicated temporary pixel-cache directory is created for the subprocess. The command applies -strip, so fallback output does not preserve source profiles or metadata.


image_format_converter.tasks._get_imagemagick_command()

Resolve the ImageMagick executable available on PATH.

Returns

  • str | None – "magick", otherwise "convert", otherwise None.

image_format_converter.tasks._get_imagemagick_temp_parent_dir(target_path)

Resolve the parent location for ImageMagick temporary pixel-cache directories.

Parameters

  • target_path (Path) – Output path used as the fallback location.

Returns

  • Path – IMAGE_FORMAT_CONVERTER_IMAGEMAGICK_TMPDIR when configured; otherwise target_path.parent.

SVG conversion helpers

image_format_converter.tasks._convert_to_svg(source_path, target_path, logger)

Convert a TIFF/JPEG source into a temporary PNG, validate it, and vectorize it with VTracer.

Parameters

  • source_path (Path) – Source raster path.
  • target_path (Path) – SVG output path.
  • logger – Logger forwarded to the PNG conversion pipeline.

Returns

  • None

Raises

  • Exceptions from PNG conversion, SVG safety validation, or VTracer vectorization.

Notes

The temporary <source-name>.tmp-for-svg.png file is removed in a finally block, regardless of success or failure.


image_format_converter.tasks._validate_png_for_svg(png_path, original_source_path)

Enforce the configured pixel-count and per-dimension limits before VTracer starts.

Parameters

  • png_path (Path) – Temporary PNG created by the module.
  • original_source_path (Path) – Original TIFF/JPEG path included in error messages.

Returns

  • None

Raises

  • RuntimeError – If width × height exceeds MAX_SVG_SOURCE_PIXELS.
  • RuntimeError – If width or height exceeds MAX_SVG_SOURCE_DIMENSION.

Notes

Image.MAX_IMAGE_PIXELS is temporarily set to None only while reading dimensions. Its previous value is restored before this function returns or raises.

Diagnostics and labels

image_format_converter.tasks._guess_file_type_from_header(path)

Inspect up to 32 leading bytes and return a best-effort diagnostic file type.

Parameters

  • path (Path) – File that could not be decoded or converted.

Returns

  • str – A label such as JPEG, PNG, GIF, TIFF, PDF, ZIP-like file, HTML, XML/text-like file, empty file, or an unknown-header description.

Notes

Inspection failures are returned as text instead of being raised.


image_format_converter.tasks._get_source_format_selection_label(source_format)

Return a readable label for the selected source option.

Parameters

  • source_format (SourceFormat) – Selected source-format option: tif, jpg, or tif_and_jpg.

Returns

  • str – TIF/JPG for tif_and_jpg; otherwise the upper-case option value.

image_format_converter.tasks._get_source_file_format_label(source_path)

Return a readable format label based on the actual source suffix.

Parameters

  • source_path (Path) – Source file whose suffix is converted into a display label.

Returns

  • str – TIF, JPG, or the upper-case suffix without its leading dot.

image_format_converter.tasks._log_image_details(image, source_path, logger)

Log Pillow-detected format, image mode, dimensions, frame count, and available metadata keys.

Parameters

  • image (PIL.Image.Image) – Open Pillow image whose detected properties are logged.
  • source_path (Path) – Source file path included in the diagnostic log entry.
  • logger – Prefect-compatible logger that receives the image-details message.

Returns

  • None

Summary helpers

image_format_converter.tasks._build_source_file_summary(source_files, temp_current_module_dir)

Count discovered source files by top-level source folder and actual source format.

Parameters

  • source_files (list[Path]) – Discovered source-image paths to summarize.
  • temp_current_module_dir (Path) – Article module root used to identify each file's top-level source folder.

Returns

  • dict[str, dict[str, int]] – Nested mapping such as {"images": {"TIF": 10, "JPG": 2}}.

image_format_converter.tasks._log_source_file_summary(article_summary, logger, journal_issn, article_id)

Write one structured, multi-line discovery summary for an article.

Parameters

  • article_summary (dict[str, dict[str, int]]) – Per-folder and per-format counts produced by _build_source_file_summary(...).
  • logger – Prefect-compatible logger that receives the summary as one log entry.
  • journal_issn (str) – Journal ISSN displayed in the summary header and total line.
  • article_id (str) – Article directory identifier displayed in the summary.

Returns

  • None

image_format_converter.tasks._add_article_summary_to_run_summary(run_image_summary, article_summary, journal_issn, article_id)

Flatten article summary counts into the shared run-level summary list.

Parameters

  • run_image_summary (list[dict]) – Mutable run-level collection to which flattened count records are appended.
  • article_summary (dict[str, dict[str, int]]) – Per-folder and per-format counts for the current article.
  • journal_issn (str) – Journal ISSN stored in each appended record.
  • article_id (str) – Article identifier stored in each appended record.

Returns

  • None

Side effects

Appends one record per journal/article/folder/format combination to run_image_summary.


image_format_converter.tasks._log_final_source_image_summary(run_image_summary, logger)

Aggregate and log source discovery totals across the complete run.

Parameters

  • run_image_summary (list[dict]) – Flattened article summary records collected during the run.
  • logger – Prefect-compatible logger that receives the complete-run summary.

Returns

  • None

Notes

The summary represents files discovered before conversion. It is not a success/failure report.

Finalization

image_format_converter.tasks._bulk_finalize_module_dirs(rename_jobs, module_name, logger)

Finalize queued article outputs after journal iteration has completed.

Parameters

  • rename_jobs (list[dict]) – Jobs containing temp_current_module_dir, latest_previous_module, and mark_stop.
  • module_name (str) – Current module name.
  • logger – Logger used for success and failure messages.

Returns

  • None

Processing steps

  1. Verify that the temporary directory still exists.
  2. Rename it to the normal or stop-processing-... current-module directory.
  3. Delete the previous module's content directory.
  4. Create the previous module's processed-by marker.

Notes

Each job is wrapped in its own try/except. Errors are logged and processing continues with later jobs; finalization exceptions are not re-raised.

Operational validation checklist

Before deploying a change:

  • [ ] The module is placed after an image-producing module in the configuration.
  • [ ] processing/history.csv exists in representative preceding-module outputs.
  • [ ] Pillow and VTracer import successfully in the worker environment.
  • [ ] ImageMagick is available when fallback support is required.
  • [ ] IMAGE_FORMAT_CONVERTER_IMAGEMAGICK_TMPDIR points to suitable storage for large images.
  • [ ] TIFF-to-PNG succeeds for a normal single-frame image.
  • [ ] JPEG-to-PNG succeeds.
  • [ ] TIFF/JPEG-to-SVG succeeds for a small diagram.
  • [ ] A multi-page TIFF logs first-frame-only behavior.
  • [ ] An invalid image produces a central error row and a stop-processing folder.
  • [ ] A no-image article finishes as a normal no-op.
  • [ ] Test-copy mode leaves the original journal unchanged.
  • [ ] Final history rows contain correct relative input/output paths.
  • [ ] Complete-run summary totals match the discovered test files.
  • [ ] Large-image tests remain inside the worker's RAM and temporary-disk capacity.

Maintenance notes

  • Treat the constants in tasks.py as operational policy, not arbitrary tuning values.
  • Keep source-folder aliases synchronized with the conventions used by upstream harvesting modules.
  • When adding a source format, update validation, suffix selection, readable labels, conversion tests, and documentation together.
  • When adding a target format, implement a dedicated conversion path and ensure source deletion still occurs only after successful output creation.
  • Preserve the one-to-one lengths of inputs, outputs, and descriptions; the shared history writer uses strict pairing.
  • Keep error messages self-contained because multiple per-file messages are combined into one article-level CSV cell.
  • Review whether run summaries should continue to represent discovered sources or be expanded with separate success/failure counts before changing their semantics.

Current implementation limitations

  1. The preceding module is read from the first resolved module-context entry, so all journals in one flow run should use a compatible module ordering.
  2. Only the first image frame/page is converted.
  3. ImageMagick fallback strips profiles and metadata.
  4. VTracer defaults are fixed in code.
  5. The module does not update article XML references to the new filenames.
  6. Successful files are converted even when another file in the same article fails.
  7. Finalization failures are logged but not re-raised by the bulk finalizer.
  8. Run summaries report discovered inputs, not conversion outcomes.
  9. Test copies are not automatically removed.
  10. The ImageMagick source-size guard applies only after Pillow has failed.