-
Notifications
You must be signed in to change notification settings - Fork 0
feat: parallelized cli batch processing #10
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 7 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
4c849a1
feat: parallelized cli batch processing
404Simon 4d4ee7f
test: detect heavy imports to prevent slow shell completions
404Simon 7efa8d1
fix: move heavy imports after shell completion shortcut
404Simon ae734a0
chore: remove unused import
404Simon 7c5bf99
fix: prefer jobs cli arg over cpu count
404Simon 060910f
chore: collect and print errors after parallel batch processing
404Simon 8383888
test: batching tests
404Simon 7025c09
chore: raise on jobs < 1
404Simon File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,101 @@ | ||
| """Batch I/O helpers and worker function for multiprocessing.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import csv | ||
| from pathlib import Path | ||
| from typing import Iterable | ||
|
|
||
| import numpy as np | ||
| from PIL import Image | ||
|
|
||
| from vesskel.config import PipelineConfig | ||
| from vesskel.pipeline import analyze_binary_image | ||
|
|
||
|
|
||
| def _load_image(path: Path) -> np.ndarray: | ||
| if path.suffix.lower() == ".npy": | ||
| arr = np.load(path) | ||
| else: | ||
| with Image.open(path) as im: | ||
| arr = np.asarray(im) | ||
|
|
||
| if arr.ndim == 0: | ||
| raise ValueError("Scalar input is not supported") | ||
|
|
||
| if arr.ndim == 3 and arr.shape[-1] in (3, 4): | ||
| arr = np.max(arr[..., :3], axis=-1) | ||
|
|
||
| if arr.ndim not in (2, 3): | ||
| raise ValueError(f"Expected 2D or 3D image, got shape={arr.shape}") | ||
|
|
||
| return arr | ||
|
|
||
|
|
||
| def _sanitize_for_csv(value: object) -> object: | ||
| if isinstance(value, (np.generic,)): | ||
| return value.item() | ||
| return value | ||
|
|
||
|
|
||
| def _write_csv(path: Path, rows: Iterable[dict[str, object]]) -> None: | ||
| rows = list(rows) | ||
| if not rows: | ||
| return | ||
|
|
||
| fieldnames = sorted({key for row in rows for key in row.keys()}) | ||
| with path.open("w", newline="") as f: | ||
| writer = csv.DictWriter(f, fieldnames=fieldnames) | ||
| writer.writeheader() | ||
| for row in rows: | ||
| writer.writerow({k: _sanitize_for_csv(v) for k, v in row.items()}) | ||
|
|
||
|
|
||
| def _save_skeleton( | ||
| path: Path, | ||
| skeleton: np.ndarray, | ||
| *, | ||
| npy: bool = True, | ||
| png: bool = False, | ||
| ) -> None: | ||
| if npy: | ||
| np.save(path.with_suffix(".npy"), skeleton.astype(np.uint8)) | ||
| if png: | ||
| if skeleton.ndim != 2: | ||
| raise ValueError("PNG skeleton output is only supported for 2D images") | ||
| img = Image.fromarray((skeleton > 0).astype(np.uint8) * 255) | ||
| img.save(path.with_suffix(".png")) | ||
|
|
||
|
|
||
| def _save_radius(path: Path, radius_matrix: np.ndarray) -> None: | ||
| np.save(path.with_suffix(".npy"), radius_matrix.astype(np.float64)) | ||
|
|
||
|
|
||
| def process_one( | ||
| in_path: Path, | ||
| safe_name: str, | ||
| out_dir: Path, | ||
| config: PipelineConfig, | ||
| ) -> dict[str, object]: | ||
| """Load, analyse, save one image. Returns summary row for agg CSV.""" | ||
| image = _load_image(in_path) | ||
| result = analyze_binary_image(image=image, base_name=in_path.stem, config=config) | ||
|
|
||
| image_out_dir = out_dir / safe_name | ||
| image_out_dir.mkdir(parents=True, exist_ok=True) | ||
|
|
||
| if config.output.write_skeleton_npy or config.output.write_skeleton_png: | ||
| _save_skeleton( | ||
| image_out_dir / f"{safe_name}_skeleton", | ||
| result.skeleton, | ||
| npy=config.output.write_skeleton_npy, | ||
| png=config.output.write_skeleton_png, | ||
| ) | ||
|
|
||
| if config.output.write_radius and result.radius_matrix is not None: | ||
| _save_radius(image_out_dir / f"{safe_name}_radius", result.radius_matrix) | ||
|
|
||
| if config.output.write_branch_csv and result.branch_records: | ||
| _write_csv(image_out_dir / f"{safe_name}_branches.csv", result.branch_records) | ||
|
|
||
| return {"image": in_path.name, **result.summary_features} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.