Skip to content

pipeline

load_config

load_config(config_path: Union[str, Path]) -> dict

Load a pipeline config from a JSON or YAML file.

PARAMETER DESCRIPTION
config_path

Path to the config file (.json, .yaml, or .yml).

TYPE: Union[str, Path]

RETURNS DESCRIPTION
dict

Parsed config dict.

RAISES DESCRIPTION
FileNotFoundError

If the config file does not exist.

ValueError

If the config is malformed.

ImportError

If a YAML config is loaded without PyYAML installed.

Source code in geopkgtoolkit/pipeline.py
def load_config(config_path: Union[str, Path]) -> dict:
    """Load a pipeline config from a JSON or YAML file.

    Args:
        config_path: Path to the config file (.json, .yaml, or .yml).

    Returns:
        Parsed config dict.

    Raises:
        FileNotFoundError: If the config file does not exist.
        ValueError: If the config is malformed.
        ImportError: If a YAML config is loaded without PyYAML installed.
    """
    path = Path(config_path)
    if not path.exists():
        raise FileNotFoundError(f"Config file not found: {path}")

    text = path.read_text(encoding="utf-8")
    if path.suffix.lower() in (".yaml", ".yml"):
        try:
            import yaml
        except ImportError:
            raise ImportError(
                "PyYAML is required for YAML pipeline configs. "
                "Install with: pip install geopackage-toolkit[pipeline]"
            )
        config = yaml.safe_load(text)
    else:
        config = json.loads(text)

    _validate_config(config)
    return config

run_pipeline

run_pipeline(config: Union[str, Path, dict], report_path: Optional[Union[str, Path]] = None) -> dict

Run a pipeline and return the run report.

PARAMETER DESCRIPTION
config

Path to a JSON/YAML config file, or an already-parsed config dict.

TYPE: Union[str, Path, dict]

report_path

Optional path to write the run report as JSON. The CLI always writes a report (from the config 'report' key or a default next to the config file).

TYPE: Optional[Union[str, Path]] DEFAULT: None

RETURNS DESCRIPTION
dict

Report dict with per-step status, feature counts, errors, timing::

{ "ok": True, "gpkg": "processed.gpkg", "steps": [ {"step": "import", "status": "ok", "features": 120, ...}, {"step": "clip", "status": "failed", "error": "..."}, ], "elapsed_s": 1.23, }

Notes

With fail_fast: true (default false), execution stops at the first failed step. With the default, all steps run regardless and each failure is recorded in the report.

Source code in geopkgtoolkit/pipeline.py
def run_pipeline(
    config: Union[str, Path, dict],
    report_path: Optional[Union[str, Path]] = None,
) -> dict:
    """Run a pipeline and return the run report.

    Args:
        config: Path to a JSON/YAML config file, or an already-parsed
            config dict.
        report_path: Optional path to write the run report as JSON.
            The CLI always writes a report (from the config 'report' key
            or a default next to the config file).

    Returns:
        Report dict with per-step status, feature counts, errors, timing::

            {
                "ok": True,
                "gpkg": "processed.gpkg",
                "steps": [
                    {"step": "import", "status": "ok", "features": 120, ...},
                    {"step": "clip", "status": "failed", "error": "..."},
                ],
                "elapsed_s": 1.23,
            }

    Notes:
        With ``fail_fast: true`` (default false), execution stops at the
        first failed step. With the default, all steps run regardless and
        each failure is recorded in the report.
    """
    if isinstance(config, (str, Path)):
        config_path = Path(config)
        cfg = load_config(config_path)
        default_report = config_path.with_suffix(".report.json")
    else:
        _validate_config(config)
        cfg = config
        config_path = None
        default_report = Path("pipeline.report.json")

    gpkg_path = Path(cfg["gpkg"])
    fail_fast = cfg.get("fail_fast", False)

    started = time.time()
    steps_report = []
    stopped = False

    for i, step in enumerate(cfg["steps"]):
        entry = {"index": i, "step": step["step"], "status": None}

        if stopped:
            entry["status"] = "skipped"
            steps_report.append(entry)
            continue

        t0 = time.time()
        try:
            result = _run_step(step, gpkg_path)
            entry.update(result)
            entry["status"] = "ok"
        except Exception as e:
            entry["status"] = "failed"
            entry["error"] = str(e)
            if fail_fast:
                stopped = True
        entry["elapsed_s"] = round(time.time() - t0, 3)
        steps_report.append(entry)

    report = {
        "config": str(config_path) if config_path else None,
        "gpkg": str(gpkg_path),
        "fail_fast": fail_fast,
        "ok": all(s["status"] == "ok" for s in steps_report),
        "steps": steps_report,
        "elapsed_s": round(time.time() - started, 3),
    }

    if report_path:
        report_path = Path(report_path)
        report_path.write_text(
            json.dumps(report, indent=2, ensure_ascii=False), encoding="utf-8"
        )
        report["report_file"] = str(report_path)

    return report

summarize_report

summarize_report(report: dict) -> str

Format a run report as a short human-readable summary.

Source code in geopkgtoolkit/pipeline.py
def summarize_report(report: dict) -> str:
    """Format a run report as a short human-readable summary."""
    lines = [f"Pipeline: {report['config'] or '<dict>'} -> {report['gpkg']}"]
    for s in report["steps"]:
        if s["status"] == "ok":
            detail = s.get("features")
            if detail is not None and s.get("output"):
                detail = f"{detail:,} features -> {s['output']}"
            elif detail is not None and s.get("files"):
                detail = f"{detail:,} features ({len(s['files'])} file(s))"
            elif s["step"] == "validate":
                detail = "valid"
            lines.append(f"  {s['index'] + 1}. {s['step']:<10} ok      {detail or ''}")
        elif s["status"] == "failed":
            lines.append(f"  {s['index'] + 1}. {s['step']:<10} FAILED  {s.get('error', '')}")
        else:
            lines.append(f"  {s['index'] + 1}. {s['step']:<10} skipped")
    ok = sum(1 for s in report["steps"] if s["status"] == "ok")
    lines.append(
        f"{ok}/{len(report['steps'])} steps ok ({report['elapsed_s']}s)"
    )
    return "\n".join(lines)