volkcell 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
volkcell-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 VolkCell Technologies Ltd
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,2 @@
1
+ # Tests stay in the repository; they are not part of the published source package.
2
+ prune tests
@@ -0,0 +1,126 @@
1
+ Metadata-Version: 2.4
2
+ Name: volkcell
3
+ Version: 0.1.0
4
+ Summary: Python client and command line for the VolkCell cell image analysis API
5
+ License: MIT
6
+ Project-URL: Homepage, https://www.volkcell.com
7
+ Classifier: License :: OSI Approved :: MIT License
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
10
+ Classifier: Topic :: Scientific/Engineering :: Image Processing
11
+ Requires-Python: >=3.9
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: numpy>=1.22
15
+ Requires-Dist: Pillow>=9.0
16
+ Requires-Dist: requests>=2.28
17
+ Provides-Extra: pandas
18
+ Requires-Dist: pandas>=1.4; extra == "pandas"
19
+ Provides-Extra: test
20
+ Requires-Dist: pytest>=7; extra == "test"
21
+ Dynamic: license-file
22
+
23
+ # volkcell
24
+
25
+ Python client and command line for the [VolkCell](https://www.volkcell.com) cell image analysis API.
26
+ Images are uploaded to VolkCell and analysed there.
27
+
28
+ ## Install
29
+
30
+ Python 3.9 or later:
31
+
32
+ ```
33
+ pip install volkcell
34
+ pip install "volkcell[pandas]" # for result.objects_dataframe()
35
+ ```
36
+
37
+ ## API key
38
+
39
+ You need a VolkCell team workspace. Its owner or an admin creates a key at
40
+ `https://www.volkcell.com/w/<workspace>/api-keys`. The key starts with `vcw_` and is shown once.
41
+
42
+ ```
43
+ export VOLKCELL_API_KEY="your key"
44
+ ```
45
+
46
+ Keep the key out of scripts and notebooks you share. Runs made with it are billed to the workspace.
47
+
48
+ ## Command line
49
+
50
+ ```
51
+ volkcell count image.tif
52
+ volkcell count image.tif --analysis adherent --objects cells.csv
53
+ volkcell count image.tif --json
54
+ volkcell result JOB_ID
55
+ ```
56
+
57
+ `--analysis` is `auto` (default), `suspension` or `adherent`. Warnings are printed to standard error.
58
+ The exit status is 0 when there is a result (with or without warnings) and 1 on an error.
59
+
60
+ Each `count` starts a new analysis and uses your allowance. If waiting stops early, use
61
+ `volkcell result JOB_ID` to read the same run. If the upload itself fails with a connection or server error,
62
+ check your runs in VolkCell before sending the image again: it may have been accepted.
63
+
64
+ ## Python
65
+
66
+ ```python
67
+ import volkcell
68
+
69
+ result = volkcell.count("image.tif", analysis="auto")
70
+ print(result.count)
71
+ for warning in result.warnings:
72
+ print("WARNING:", warning)
73
+
74
+ table = result.objects_dataframe() # or result.objects, a list of dicts
75
+ ```
76
+
77
+ `count` also takes a numpy array: `uint8` greyscale or colour, or `uint16` greyscale. It is sent as a
78
+ lossless PNG with the pixel values unchanged. For a stack or multichannel array, pass one 2-D plane.
79
+
80
+ | Field | Meaning |
81
+ |-------|---------|
82
+ | `count` | Cell count. `None` if there is none, or if one file produced several images |
83
+ | `warnings` | Everything VolkCell and the client flagged. **Read these before using a number** |
84
+ | `objects` | One row per outlined object: area, equivalent diameter, centroid and bounding box, in pixels |
85
+ | `labels` | Label image as a numpy array (0 is background), for single-image results |
86
+ | `outlines_match_input` | `False` if the label image is a different size from your image; `None` if not compared |
87
+ | `confluency_percent` | Confluency, when the analysis reports it |
88
+ | `images` | Count and confluency per image |
89
+ | `job_id` | Use with `volkcell.get_result(job_id)` |
90
+ | `raw` | The API's results response |
91
+
92
+ Object measurements are calculated by this client from the label image. They are in pixels.
93
+
94
+ ## Errors
95
+
96
+ All errors are subclasses of `volkcell.VolkCellError` and carry `job_id` once a job exists.
97
+
98
+ | Error | When |
99
+ |-------|------|
100
+ | `AuthenticationError` | No key, or the key was refused |
101
+ | `InputError` | The file or array cannot be sent |
102
+ | `RequestRejected` | The server refused the request, for example because Auto could not tell what the image is. Choose `suspension` or `adherent` |
103
+ | `LimitError` | Rate, running-job or image allowance limit |
104
+ | `AnalysisFailed` | The run produced no result; see `warnings` |
105
+ | `AnalysisTimeout` | Waiting stopped (default 900 s); the run may still finish |
106
+ | `ServiceError` | VolkCell could not be reached or had a temporary problem |
107
+
108
+ Limits: one image per call, up to 100 MB. TIFF, PNG, JPEG, BMP, CZI, ND2, LIF, OIB, OIF.
109
+
110
+ ## Settings
111
+
112
+ `VOLKCELL_BASE_URL` or `Client(base_url=...)` selects another VolkCell server. The key is sent only to that
113
+ address, over HTTPS (plain HTTP is accepted for localhost), and redirects are not followed.
114
+
115
+ ## Tests
116
+
117
+ ```
118
+ pip install ".[test]"
119
+ pytest
120
+ ```
121
+
122
+ The tests use a local mock server.
123
+
124
+ ## Licence
125
+
126
+ MIT. See `LICENSE`.
@@ -0,0 +1,104 @@
1
+ # volkcell
2
+
3
+ Python client and command line for the [VolkCell](https://www.volkcell.com) cell image analysis API.
4
+ Images are uploaded to VolkCell and analysed there.
5
+
6
+ ## Install
7
+
8
+ Python 3.9 or later:
9
+
10
+ ```
11
+ pip install volkcell
12
+ pip install "volkcell[pandas]" # for result.objects_dataframe()
13
+ ```
14
+
15
+ ## API key
16
+
17
+ You need a VolkCell team workspace. Its owner or an admin creates a key at
18
+ `https://www.volkcell.com/w/<workspace>/api-keys`. The key starts with `vcw_` and is shown once.
19
+
20
+ ```
21
+ export VOLKCELL_API_KEY="your key"
22
+ ```
23
+
24
+ Keep the key out of scripts and notebooks you share. Runs made with it are billed to the workspace.
25
+
26
+ ## Command line
27
+
28
+ ```
29
+ volkcell count image.tif
30
+ volkcell count image.tif --analysis adherent --objects cells.csv
31
+ volkcell count image.tif --json
32
+ volkcell result JOB_ID
33
+ ```
34
+
35
+ `--analysis` is `auto` (default), `suspension` or `adherent`. Warnings are printed to standard error.
36
+ The exit status is 0 when there is a result (with or without warnings) and 1 on an error.
37
+
38
+ Each `count` starts a new analysis and uses your allowance. If waiting stops early, use
39
+ `volkcell result JOB_ID` to read the same run. If the upload itself fails with a connection or server error,
40
+ check your runs in VolkCell before sending the image again: it may have been accepted.
41
+
42
+ ## Python
43
+
44
+ ```python
45
+ import volkcell
46
+
47
+ result = volkcell.count("image.tif", analysis="auto")
48
+ print(result.count)
49
+ for warning in result.warnings:
50
+ print("WARNING:", warning)
51
+
52
+ table = result.objects_dataframe() # or result.objects, a list of dicts
53
+ ```
54
+
55
+ `count` also takes a numpy array: `uint8` greyscale or colour, or `uint16` greyscale. It is sent as a
56
+ lossless PNG with the pixel values unchanged. For a stack or multichannel array, pass one 2-D plane.
57
+
58
+ | Field | Meaning |
59
+ |-------|---------|
60
+ | `count` | Cell count. `None` if there is none, or if one file produced several images |
61
+ | `warnings` | Everything VolkCell and the client flagged. **Read these before using a number** |
62
+ | `objects` | One row per outlined object: area, equivalent diameter, centroid and bounding box, in pixels |
63
+ | `labels` | Label image as a numpy array (0 is background), for single-image results |
64
+ | `outlines_match_input` | `False` if the label image is a different size from your image; `None` if not compared |
65
+ | `confluency_percent` | Confluency, when the analysis reports it |
66
+ | `images` | Count and confluency per image |
67
+ | `job_id` | Use with `volkcell.get_result(job_id)` |
68
+ | `raw` | The API's results response |
69
+
70
+ Object measurements are calculated by this client from the label image. They are in pixels.
71
+
72
+ ## Errors
73
+
74
+ All errors are subclasses of `volkcell.VolkCellError` and carry `job_id` once a job exists.
75
+
76
+ | Error | When |
77
+ |-------|------|
78
+ | `AuthenticationError` | No key, or the key was refused |
79
+ | `InputError` | The file or array cannot be sent |
80
+ | `RequestRejected` | The server refused the request, for example because Auto could not tell what the image is. Choose `suspension` or `adherent` |
81
+ | `LimitError` | Rate, running-job or image allowance limit |
82
+ | `AnalysisFailed` | The run produced no result; see `warnings` |
83
+ | `AnalysisTimeout` | Waiting stopped (default 900 s); the run may still finish |
84
+ | `ServiceError` | VolkCell could not be reached or had a temporary problem |
85
+
86
+ Limits: one image per call, up to 100 MB. TIFF, PNG, JPEG, BMP, CZI, ND2, LIF, OIB, OIF.
87
+
88
+ ## Settings
89
+
90
+ `VOLKCELL_BASE_URL` or `Client(base_url=...)` selects another VolkCell server. The key is sent only to that
91
+ address, over HTTPS (plain HTTP is accepted for localhost), and redirects are not followed.
92
+
93
+ ## Tests
94
+
95
+ ```
96
+ pip install ".[test]"
97
+ pytest
98
+ ```
99
+
100
+ The tests use a local mock server.
101
+
102
+ ## Licence
103
+
104
+ MIT. See `LICENSE`.
@@ -0,0 +1,39 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "volkcell"
7
+ version = "0.1.0"
8
+ description = "Python client and command line for the VolkCell cell image analysis API"
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ dependencies = [
12
+ "numpy>=1.22",
13
+ "Pillow>=9.0",
14
+ "requests>=2.28",
15
+ ]
16
+ license = {text = "MIT"}
17
+ classifiers = [
18
+ "License :: OSI Approved :: MIT License",
19
+ "Programming Language :: Python :: 3",
20
+ "Topic :: Scientific/Engineering :: Bio-Informatics",
21
+ "Topic :: Scientific/Engineering :: Image Processing",
22
+ ]
23
+
24
+ [project.optional-dependencies]
25
+ pandas = ["pandas>=1.4"]
26
+ test = ["pytest>=7"]
27
+
28
+ [project.urls]
29
+ Homepage = "https://www.volkcell.com"
30
+
31
+ [project.scripts]
32
+ volkcell = "volkcell.cli:main"
33
+
34
+ [tool.setuptools.packages.find]
35
+ where = ["src"]
36
+
37
+ [tool.pytest.ini_options]
38
+ testpaths = ["tests"]
39
+ markers = ["live: runs one real analysis (skipped unless set up)"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,30 @@
1
+ """Client for the VolkCell cell image analysis API (https://www.volkcell.com)."""
2
+ __version__ = "0.1.0"
3
+
4
+ from .client import Client, count, get_result # noqa: E402
5
+ from .errors import ( # noqa: E402
6
+ AnalysisFailed,
7
+ AnalysisTimeout,
8
+ AuthenticationError,
9
+ InputError,
10
+ LimitError,
11
+ RequestRejected,
12
+ ServiceError,
13
+ VolkCellError,
14
+ )
15
+ from .result import CountResult # noqa: E402
16
+
17
+ __all__ = [
18
+ "AnalysisFailed",
19
+ "AnalysisTimeout",
20
+ "AuthenticationError",
21
+ "Client",
22
+ "CountResult",
23
+ "InputError",
24
+ "LimitError",
25
+ "RequestRejected",
26
+ "ServiceError",
27
+ "VolkCellError",
28
+ "count",
29
+ "get_result",
30
+ ]
@@ -0,0 +1,99 @@
1
+ """``volkcell count image.tif``"""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import csv
6
+ import json
7
+ import sys
8
+
9
+ from . import __version__
10
+ from .client import ANALYSES, Client
11
+ from .errors import VolkCellError
12
+ from .result import OBJECT_COLUMNS
13
+
14
+
15
+ def _parser() -> argparse.ArgumentParser:
16
+ parser = argparse.ArgumentParser(prog="volkcell", description="Count cells with VolkCell.",
17
+ epilog="The API key is read from VOLKCELL_API_KEY. https://www.volkcell.com")
18
+ parser.add_argument("--version", action="version", version=f"volkcell {__version__}")
19
+ commands = parser.add_subparsers(dest="command", required=True)
20
+ count = commands.add_parser("count", help="analyse one image (uses your allowance)")
21
+ count.add_argument("image")
22
+ count.add_argument("--analysis", choices=list(ANALYSES), default="auto", help="default: auto")
23
+ result = commands.add_parser("result", help="read an earlier job without analysing it again")
24
+ result.add_argument("job_id")
25
+ for command in (count, result):
26
+ command.add_argument("--json", action="store_true", help="print the result as JSON")
27
+ command.add_argument("--objects", metavar="FILE.csv", help="write the per-object table")
28
+ command.add_argument("--timeout", type=float, default=900.0, help="seconds to wait (default 900)")
29
+ command.add_argument("--base-url", help="server address (default: VOLKCELL_BASE_URL or www.volkcell.com)")
30
+ return parser
31
+
32
+
33
+ def _print_warnings(warnings, stream) -> None:
34
+ for warning in warnings:
35
+ print(f"WARNING: {warning}", file=stream)
36
+
37
+
38
+ def main(argv=None) -> int:
39
+ args = _parser().parse_args(argv)
40
+ try:
41
+ client = Client(base_url=args.base_url)
42
+ if args.command == "count":
43
+ result = client.count(
44
+ args.image, args.analysis, timeout=args.timeout,
45
+ on_submit=lambda job: print(f"Submitted as job {job}. Waiting...", file=sys.stderr))
46
+ else:
47
+ result = client.get_result(args.job_id, timeout=args.timeout)
48
+ except VolkCellError as exc:
49
+ _print_warnings(exc.warnings, sys.stderr)
50
+ print(f"Error: {exc}", file=sys.stderr)
51
+ if exc.job_id:
52
+ print(f"Job id: {exc.job_id} (volkcell result {exc.job_id} reads it without a new analysis)",
53
+ file=sys.stderr)
54
+ return 1
55
+ except KeyboardInterrupt:
56
+ print("Stopped waiting. A submitted job keeps running.", file=sys.stderr)
57
+ return 130
58
+
59
+ # Warnings go first to stderr in both formats, so they are seen even if writing the table fails.
60
+ _print_warnings(result.warnings, sys.stderr)
61
+ if args.json:
62
+ print(json.dumps(result.to_dict(), indent=2))
63
+ else:
64
+ print(f"File: {result.filename}")
65
+ if len(result.images) > 1:
66
+ for image in result.images:
67
+ print(f"Count ({image['filename']}): {_shown(image['count'])}")
68
+ else:
69
+ print(f"Count: {_shown(result.count)}")
70
+ if result.confluency_percent is not None:
71
+ print(f"Confluency: {result.confluency_percent}%")
72
+ print(f"Outlined objects: {len(result.objects)}")
73
+ print(f"Warnings: {len(result.warnings)}")
74
+ print(f"Job id: {result.job_id}")
75
+ if args.objects:
76
+ try:
77
+ with open(args.objects, "w", newline="", encoding="utf-8") as handle:
78
+ writer = csv.DictWriter(handle, fieldnames=OBJECT_COLUMNS)
79
+ writer.writeheader()
80
+ writer.writerows({k: _csv_safe(v) for k, v in row.items()} for row in result.objects)
81
+ except OSError as exc:
82
+ print(f"Error: could not write {args.objects}: {exc.strerror}", file=sys.stderr)
83
+ return 1
84
+ return 0
85
+
86
+
87
+ def _shown(value) -> str:
88
+ return "not available" if value is None else str(value)
89
+
90
+
91
+ def _csv_safe(value):
92
+ """Keep a file name such as "=cmd.tif" from running as a spreadsheet formula."""
93
+ if isinstance(value, str) and value[:1] in ("=", "+", "-", "@", "\t", "\r"):
94
+ return "'" + value
95
+ return value
96
+
97
+
98
+ if __name__ == "__main__":
99
+ sys.exit(main())
@@ -0,0 +1,339 @@
1
+ """Calls to the VolkCell API: submit one image, wait, read counts, outlines and warnings."""
2
+ from __future__ import annotations
3
+
4
+ import io
5
+ import os
6
+ import time
7
+ from pathlib import Path, PurePath
8
+ from typing import Any, Callable, Dict, List, Optional, Tuple
9
+ from urllib.parse import quote, urlsplit
10
+
11
+ import numpy as np
12
+ import requests
13
+ from PIL import Image
14
+
15
+ from . import __version__
16
+ from .errors import (
17
+ AnalysisFailed, AnalysisTimeout, AuthenticationError, InputError, LimitError, RequestRejected, ServiceError,
18
+ VolkCellError,
19
+ )
20
+ from .result import CountResult, measure_objects, read_label_png
21
+
22
+ DEFAULT_BASE_URL = "https://www.volkcell.com"
23
+ KEY_PREFIX = "vcw_"
24
+ ANALYSES = {
25
+ "auto": {"analysis_type": "auto"},
26
+ "suspension": {"analysis_type": "count_confluency", "analysis_mode": "suspension"},
27
+ "adherent": {"analysis_type": "count_confluency", "analysis_mode": "adherent"},
28
+ }
29
+ EXTENSIONS = (".tif", ".tiff", ".png", ".jpg", ".jpeg", ".bmp", ".czi", ".nd2", ".lif", ".oib", ".oif")
30
+ MAX_FILE_BYTES = 100 * 1024 * 1024
31
+ _LOCAL_HOSTS = {"localhost", "127.0.0.1", "::1"}
32
+ _MAX_CONSECUTIVE_POLL_ERRORS = 5
33
+
34
+ # The upload answers only after the server has read and converted the file, so it is given longer than other calls.
35
+ SUBMIT_TIMEOUT_SECONDS = 600.0
36
+ MAY_BE_ACCEPTED = (" VolkCell may already have accepted the image and started a billed analysis. "
37
+ "Check your runs in VolkCell before sending it again.")
38
+
39
+ REVIEW_WARNING = "VolkCell asked for this result to be reviewed. Check the outlines before using it."
40
+ NO_WARNINGS_WARNING = ("VolkCell's per-image warnings could not be read, so this list may be incomplete. "
41
+ "Check the run in VolkCell before using the result.")
42
+
43
+
44
+ class Client:
45
+ """A connection to VolkCell.
46
+
47
+ ``api_key`` defaults to the ``VOLKCELL_API_KEY`` environment variable and
48
+ ``base_url`` to ``VOLKCELL_BASE_URL`` or https://www.volkcell.com.
49
+ """
50
+
51
+ def __init__(self, api_key: Optional[str] = None, base_url: Optional[str] = None, *,
52
+ request_timeout: float = 120.0, poll_interval: float = 3.0,
53
+ extra_headers: Optional[Dict[str, str]] = None):
54
+ key = (api_key if api_key is not None else os.environ.get("VOLKCELL_API_KEY", "")).strip()
55
+ if not key:
56
+ raise AuthenticationError(
57
+ "No API key. Set VOLKCELL_API_KEY or pass api_key=. A workspace owner or admin creates keys in "
58
+ "VolkCell at https://www.volkcell.com/w/<workspace>/api-keys")
59
+ # Checked before anything is sent, so some other secret kept in this variable never leaves the machine.
60
+ if not key.startswith(KEY_PREFIX) or not key.isascii() or any(c.isspace() for c in key):
61
+ raise AuthenticationError(f"That is not a VolkCell API key: a key starts with {KEY_PREFIX}. "
62
+ "Nothing was sent.")
63
+ base = (base_url or os.environ.get("VOLKCELL_BASE_URL", "") or DEFAULT_BASE_URL).strip().rstrip("/")
64
+ parts = urlsplit(base)
65
+ if not parts.hostname or not (parts.scheme == "https"
66
+ or (parts.scheme == "http" and parts.hostname in _LOCAL_HOSTS)):
67
+ raise InputError("The server address must start with https://")
68
+ self.base_url = base
69
+ self.request_timeout = request_timeout
70
+ self.poll_interval = poll_interval
71
+ self._session = requests.Session()
72
+ self._session.headers.update({"User-Agent": f"volkcell-python/{__version__}"})
73
+ self._session.headers.update(extra_headers or {})
74
+ self._session.headers["X-API-Key"] = key
75
+
76
+ # -- HTTP -----------------------------------------------------------------------------------------------------
77
+
78
+ def _request(self, method: str, path: str, **kwargs) -> requests.Response:
79
+ if not path.startswith("/") or path.startswith("//"):
80
+ raise ServiceError("The server returned an address outside VolkCell, so it was not opened.")
81
+ try:
82
+ # Redirects are refused: the key header would follow them to another host.
83
+ kwargs.setdefault("timeout", self.request_timeout)
84
+ response = self._session.request(method, self.base_url + path, allow_redirects=False, **kwargs)
85
+ except requests.RequestException as exc:
86
+ raise ServiceError(f"Could not reach VolkCell at {self.base_url} ({type(exc).__name__}).") from None
87
+ if 200 <= response.status_code < 300:
88
+ return response
89
+ raise _http_error(response)
90
+
91
+ def _json(self, method: str, path: str, **kwargs) -> Any:
92
+ response = self._request(method, path, **kwargs)
93
+ try:
94
+ value = response.json()
95
+ except ValueError:
96
+ value = None
97
+ if not isinstance(value, dict):
98
+ raise ServiceError("VolkCell sent an answer that could not be read.", status=response.status_code)
99
+ return value
100
+
101
+ # -- API ------------------------------------------------------------------------------------------------------
102
+
103
+ def count(self, path_or_array, analysis: str = "auto", *, timeout: float = 900.0, name: Optional[str] = None,
104
+ on_submit: Optional[Callable[[str], None]] = None) -> CountResult:
105
+ """Analyse one image file or array and wait for the result.
106
+
107
+ Each call starts a new analysis and uses your allowance. It is never retried automatically.
108
+ ``on_submit`` is called with the job id as soon as the server accepts the image.
109
+ """
110
+ params = ANALYSES.get(analysis)
111
+ if params is None:
112
+ raise InputError(f"analysis must be one of: {', '.join(ANALYSES)}")
113
+ filename, content, size = _prepare(path_or_array, name)
114
+ try:
115
+ answer = self._json("POST", "/api/v1/analyze", params=params,
116
+ timeout=max(self.request_timeout, SUBMIT_TIMEOUT_SECONDS),
117
+ files=[("files", (filename, content, "application/octet-stream"))])
118
+ job_id = str(answer.get("job_id") or "")
119
+ if not job_id:
120
+ raise ServiceError("VolkCell returned no job id.")
121
+ except ServiceError as exc:
122
+ if exc.status is not None and 300 <= exc.status < 500: # refused: nothing was started
123
+ raise
124
+ raise ServiceError(str(exc) + MAY_BE_ACCEPTED, status=exc.status) from None
125
+ if on_submit:
126
+ on_submit(job_id)
127
+ return self.get_result(job_id, timeout=timeout, input_size=size, filename=filename)
128
+
129
+ def get_result(self, job_id: str, *, timeout: float = 900.0, input_size: Optional[Tuple[int, int]] = None,
130
+ filename: str = "") -> CountResult:
131
+ """Wait for a job already submitted and read its result. Starts nothing new."""
132
+ job = quote(str(job_id), safe="")
133
+ try:
134
+ self._wait(job, timeout)
135
+ return self._read(job_id, job, input_size, filename)
136
+ except VolkCellError as exc:
137
+ exc.job_id = exc.job_id or job_id
138
+ raise
139
+
140
+ def _wait(self, job: str, timeout: float) -> None:
141
+ deadline = time.monotonic() + timeout
142
+ errors = 0
143
+ while True:
144
+ pause = self.poll_interval
145
+ try:
146
+ status = self._json("GET", f"/api/v1/job/{job}/status")
147
+ except (ServiceError, LimitError) as exc:
148
+ errors += 1
149
+ if errors >= _MAX_CONSECUTIVE_POLL_ERRORS and not isinstance(exc, LimitError):
150
+ raise
151
+ pause = max(pause, getattr(exc, "retry_after", 0.0))
152
+ else:
153
+ errors = 0
154
+ if status.get("status") in ("completed", "failed"):
155
+ return
156
+ if time.monotonic() + pause > deadline:
157
+ raise AnalysisTimeout(f"The analysis did not finish within {timeout:g} seconds. It may still "
158
+ "finish: fetch it later with get_result(job_id).")
159
+ time.sleep(pause)
160
+
161
+ def _read(self, job_id: str, job: str, input_size, filename: str) -> CountResult:
162
+ data = self._json("GET", f"/api/v1/job/{job}/results")
163
+ rows = data.get("results") or []
164
+ warnings: List[str] = []
165
+ _add(warnings, *(data.get("review_reasons") or []))
166
+ failed = data.get("failed_files") or []
167
+ for item in failed:
168
+ reason = item.get("reason") or item.get("error") or "This image was not analysed."
169
+ label = item.get("filename") or item.get("file") or ""
170
+ _add(warnings, f"{label}: {reason}" if label else reason)
171
+ if data.get("error"):
172
+ _add(warnings, data["error"])
173
+ if data.get("status") == "failed" or not rows:
174
+ message = data.get("error") or (warnings[-1] if warnings else "VolkCell produced no result.")
175
+ raise AnalysisFailed(str(message), job_id=job_id, warnings=warnings)
176
+
177
+ confluency: Dict[str, Optional[float]] = {}
178
+ try:
179
+ wells = self._json("GET", f"/api/v1/job/{job}/wells")
180
+ for well in wells.get("wells") or []:
181
+ _add(warnings, *(well.get("warnings") or []))
182
+ if len(well.get("filenames") or []) == 1:
183
+ confluency[well["filenames"][0]] = well.get("confluency_percent_mean")
184
+ except VolkCellError:
185
+ _add(warnings, NO_WARNINGS_WARNING, *(row.get("count_reliability_reason") for row in rows))
186
+ if data.get("review_required") and not data.get("review_reasons"):
187
+ _add(warnings, REVIEW_WARNING)
188
+
189
+ images = [{"filename": r.get("filename", ""), "count": r.get("cell_count"),
190
+ "confluency_percent": confluency.get(r.get("filename", ""))} for r in rows]
191
+ single = len(rows) == 1
192
+ count = images[0]["count"] if single else None
193
+ if failed:
194
+ _add(warnings, "Part of this upload was not analysed, so the result does not cover all of it.")
195
+ if len(rows) > 1:
196
+ _add(warnings, f"This file was analysed as {len(rows)} images, so there is no single count. "
197
+ "The count of each image is listed separately.")
198
+ if any(image["count"] is None for image in images):
199
+ _add(warnings, "VolkCell published no cell count for at least one image.")
200
+
201
+ objects: List[Dict[str, Any]] = []
202
+ labels = None
203
+ mask_size = None
204
+ matches = None
205
+ for row in rows:
206
+ image_name = row.get("filename", "")
207
+ url = ((data.get("images") or {}).get(image_name) or {}).get("mask")
208
+ try:
209
+ if not url:
210
+ raise ServiceError("no outlines")
211
+ mask = read_label_png(self._request("GET", _encoded_image_path(url)).content)
212
+ except (VolkCellError, OSError, ValueError, Image.DecompressionBombError):
213
+ _add(warnings, f"Outlines are not available for {image_name}, so it has no per-object table.")
214
+ continue
215
+ found = measure_objects(mask, image_name)
216
+ objects.extend(found)
217
+ if row.get("cell_count") is not None and row["cell_count"] != len(found):
218
+ _add(warnings, f"The count for {image_name} is {row['cell_count']} but {len(found)} objects are "
219
+ "outlined. Check the run in VolkCell before using the per-object table.")
220
+ if len(rows) == 1:
221
+ labels = mask
222
+ mask_size = (int(mask.shape[1]), int(mask.shape[0]))
223
+ if input_size is not None:
224
+ matches = mask_size == tuple(input_size)
225
+ if not matches:
226
+ _add(warnings, f"The outlines are {mask_size[0]} x {mask_size[1]} pixels and the image is "
227
+ f"{input_size[0]} x {input_size[1]}, so object positions do not line up with "
228
+ "the image.")
229
+
230
+ return CountResult(
231
+ filename=filename or rows[0].get("filename", ""), count=count, warnings=warnings, objects=objects,
232
+ images=images, job_id=job_id, confluency_percent=images[0]["confluency_percent"] if single else None,
233
+ mask_size=mask_size, outlines_match_input=matches, labels=labels, raw=data,
234
+ )
235
+
236
+
237
+ def count(path_or_array, analysis: str = "auto", *, api_key: Optional[str] = None, base_url: Optional[str] = None,
238
+ timeout: float = 900.0, name: Optional[str] = None,
239
+ on_submit: Optional[Callable[[str], None]] = None) -> CountResult:
240
+ """Count cells in one image file or numpy array. See ``Client.count``."""
241
+ return Client(api_key, base_url).count(path_or_array, analysis, timeout=timeout, name=name, on_submit=on_submit)
242
+
243
+
244
+ def get_result(job_id: str, *, api_key: Optional[str] = None, base_url: Optional[str] = None,
245
+ timeout: float = 900.0) -> CountResult:
246
+ """Read an earlier job without analysing (or paying for) the image again."""
247
+ return Client(api_key, base_url).get_result(job_id, timeout=timeout)
248
+
249
+
250
+ def _encoded_image_path(url: str) -> str:
251
+ """The server puts the file name into the address as it is, so "#", "?" and "%" in it need encoding."""
252
+ head, marker, name = str(url).partition("/image/")
253
+ return head + marker + quote(name, safe="") if marker else head
254
+
255
+
256
+ def _add(warnings: List[str], *items) -> None:
257
+ for item in items:
258
+ text = str(item or "").strip()
259
+ if text and text not in warnings:
260
+ warnings.append(text)
261
+
262
+
263
+ def _http_error(response: requests.Response) -> VolkCellError:
264
+ status = response.status_code
265
+ # Only the API's own message is shown. Other bodies (proxy or error pages) are not repeated to the user.
266
+ detail = ""
267
+ try:
268
+ value = response.json().get("detail")
269
+ if isinstance(value, str):
270
+ detail = value.strip()
271
+ elif isinstance(value, list):
272
+ detail = "; ".join(str(v.get("msg", "")) for v in value if isinstance(v, dict)).strip("; ")
273
+ except (ValueError, AttributeError):
274
+ pass
275
+ if 300 <= status < 400:
276
+ return ServiceError("The server answered with a redirect, which is not followed. Check the server address.",
277
+ status=status)
278
+ if status >= 500:
279
+ return ServiceError(f"VolkCell is having a temporary problem (HTTP {status}). Please try again later.",
280
+ status=status)
281
+ if status in (401, 403):
282
+ return AuthenticationError(detail or f"VolkCell refused the request (HTTP {status}).", status=status)
283
+ if status == 429:
284
+ error = LimitError(detail or "A VolkCell limit was reached. Please try again later.", status=status)
285
+ try:
286
+ error.retry_after = min(300.0, max(0.0, float(response.headers.get("Retry-After", 0))))
287
+ except ValueError:
288
+ error.retry_after = 0.0
289
+ return error
290
+ if status == 413:
291
+ return RequestRejected(detail or "The upload is too large.", status=status)
292
+ return RequestRejected(detail or f"VolkCell could not accept the request (HTTP {status}).", status=status)
293
+
294
+
295
+ def _prepare(source, name: Optional[str]) -> Tuple[str, bytes, Optional[Tuple[int, int]]]:
296
+ """(upload name, file bytes, (width, height) or None when the size cannot be read here)."""
297
+ if isinstance(source, np.ndarray):
298
+ content, size = _encode_array(source)
299
+ filename = PurePath(name or "image").stem + ".png"
300
+ elif isinstance(source, (str, os.PathLike)):
301
+ path = Path(source)
302
+ if not path.is_file():
303
+ raise InputError(f"File not found: {path}")
304
+ filename = PurePath(name).name if name else path.name
305
+ if PurePath(filename).suffix.lower() not in EXTENSIONS:
306
+ raise InputError(f"Unsupported file type. Supported: {', '.join(EXTENSIONS)}")
307
+ if path.stat().st_size > MAX_FILE_BYTES:
308
+ raise InputError("The file is larger than 100 MB, the limit for one image.")
309
+ content = path.read_bytes()
310
+ size = _image_size(content)
311
+ else:
312
+ raise InputError("Pass a file path or a numpy array.")
313
+ if len(content) > MAX_FILE_BYTES:
314
+ raise InputError("The image is larger than 100 MB, the limit for one image.")
315
+ return filename, content, size
316
+
317
+
318
+ def _image_size(content: bytes) -> Optional[Tuple[int, int]]:
319
+ try:
320
+ with Image.open(io.BytesIO(content)) as picture:
321
+ return picture.size
322
+ except Exception: # microscope formats, or a TIFF layout Pillow cannot open: the server reads those
323
+ return None
324
+
325
+
326
+ def _encode_array(array: np.ndarray) -> Tuple[bytes, Tuple[int, int]]:
327
+ """Lossless PNG with the pixel values unchanged. Nothing is rescaled."""
328
+ shape_ok = array.ndim == 2 or (array.ndim == 3 and array.shape[2] in (3, 4))
329
+ if not shape_ok or 0 in array.shape:
330
+ raise InputError("An array must be a 2-D greyscale image or height x width x 3 or 4 colour image. "
331
+ "Pick one plane of a stack or one channel first.")
332
+ if array.dtype == np.bool_:
333
+ array = array.astype(np.uint8) * 255
334
+ if not (array.dtype == np.uint8 or (array.dtype.kind == "u" and array.dtype.itemsize == 2 and array.ndim == 2)):
335
+ raise InputError(f"Unsupported array type {array.dtype}. Use uint8 (grey or colour) or uint16 (grey). "
336
+ "Values are not rescaled for you.")
337
+ buffer = io.BytesIO()
338
+ Image.fromarray(np.ascontiguousarray(array.astype(array.dtype.newbyteorder("=")))).save(buffer, format="PNG")
339
+ return buffer.getvalue(), (int(array.shape[1]), int(array.shape[0]))
@@ -0,0 +1,37 @@
1
+ """Errors raised by the client. ``job_id`` is set once the server has accepted the image."""
2
+
3
+
4
+ class VolkCellError(Exception):
5
+ def __init__(self, message, *, status=None, job_id=None, warnings=None):
6
+ super().__init__(message)
7
+ self.status = status
8
+ self.job_id = job_id
9
+ self.warnings = list(warnings or [])
10
+
11
+
12
+ class InputError(VolkCellError):
13
+ """The image or an argument cannot be sent."""
14
+
15
+
16
+ class AuthenticationError(VolkCellError):
17
+ """No API key, or the key was refused."""
18
+
19
+
20
+ class RequestRejected(VolkCellError):
21
+ """The server refused the request; the message says why."""
22
+
23
+
24
+ class LimitError(VolkCellError):
25
+ """A rate, job or image allowance limit was reached."""
26
+
27
+
28
+ class ServiceError(VolkCellError):
29
+ """VolkCell could not be reached or answered unexpectedly."""
30
+
31
+
32
+ class AnalysisFailed(VolkCellError):
33
+ """The analysis ran and did not produce a result."""
34
+
35
+
36
+ class AnalysisTimeout(VolkCellError):
37
+ """Stopped waiting. The analysis may still finish: use ``get_result(job_id)``."""
@@ -0,0 +1,99 @@
1
+ """What a count returns, and the per-object table made from the label image."""
2
+ from __future__ import annotations
3
+
4
+ import io
5
+ from dataclasses import dataclass, field
6
+ from typing import Any, Dict, List, Optional, Tuple
7
+
8
+ import numpy as np
9
+ from PIL import Image
10
+
11
+ OBJECT_COLUMNS = (
12
+ "image", "label", "area_px", "equivalent_diameter_px", "centroid_x", "centroid_y",
13
+ "bbox_x", "bbox_y", "bbox_width", "bbox_height",
14
+ )
15
+
16
+
17
+ @dataclass
18
+ class CountResult:
19
+ """One analysed file.
20
+
21
+ ``count`` is None when VolkCell published no count, or when one file produced
22
+ several images (then see ``images``). Always read ``warnings``.
23
+ """
24
+ filename: str
25
+ count: Optional[int]
26
+ warnings: List[str]
27
+ objects: List[Dict[str, Any]]
28
+ images: List[Dict[str, Any]]
29
+ job_id: str
30
+ confluency_percent: Optional[float] = None
31
+ #: (width, height) of the label image the objects were measured on.
32
+ mask_size: Optional[Tuple[int, int]] = None
33
+ #: True / False when the input size is known, None when it could not be compared.
34
+ outlines_match_input: Optional[bool] = None
35
+ #: 2-D label image (0 = background), or None when the server gave none.
36
+ labels: Optional[np.ndarray] = field(default=None, repr=False)
37
+ #: The server's results response, unchanged.
38
+ raw: Dict[str, Any] = field(default_factory=dict, repr=False)
39
+
40
+ def objects_dataframe(self):
41
+ """The per-object table as a pandas DataFrame (``pip install "volkcell[pandas]"``)."""
42
+ try:
43
+ import pandas
44
+ except ImportError:
45
+ raise ImportError('pandas is not installed. Install it with: pip install "volkcell[pandas]"') from None
46
+ return pandas.DataFrame(self.objects, columns=list(OBJECT_COLUMNS))
47
+
48
+ def to_dict(self) -> Dict[str, Any]:
49
+ return {
50
+ "filename": self.filename,
51
+ "job_id": self.job_id,
52
+ "count": self.count,
53
+ "confluency_percent": self.confluency_percent,
54
+ "warnings": list(self.warnings),
55
+ "images": list(self.images),
56
+ "objects": list(self.objects),
57
+ }
58
+
59
+
60
+ def read_label_png(data: bytes) -> np.ndarray:
61
+ with Image.open(io.BytesIO(data)) as picture:
62
+ labels = np.array(picture)
63
+ if labels.ndim != 2 or not (np.issubdtype(labels.dtype, np.integer) or labels.dtype == bool):
64
+ raise ValueError("not a label image")
65
+ return labels.astype(np.int64)
66
+
67
+
68
+ def measure_objects(labels: np.ndarray, image: str) -> List[Dict[str, Any]]:
69
+ """One row per label, in pixels. x is the column and y the row, from the top left."""
70
+ ys, xs = np.nonzero(labels)
71
+ if ys.size == 0:
72
+ return []
73
+ ids, index = np.unique(labels[ys, xs], return_inverse=True)
74
+ index = index.reshape(-1)
75
+ n = ids.size
76
+ area = np.bincount(index, minlength=n)
77
+ cx = np.bincount(index, weights=xs, minlength=n) / area
78
+ cy = np.bincount(index, weights=ys, minlength=n) / area
79
+ low_x, low_y = np.full(n, labels.shape[1]), np.full(n, labels.shape[0])
80
+ high_x, high_y = np.zeros(n, dtype=np.int64), np.zeros(n, dtype=np.int64)
81
+ np.minimum.at(low_x, index, xs)
82
+ np.minimum.at(low_y, index, ys)
83
+ np.maximum.at(high_x, index, xs)
84
+ np.maximum.at(high_y, index, ys)
85
+ return [
86
+ {
87
+ "image": image,
88
+ "label": int(ids[i]),
89
+ "area_px": int(area[i]),
90
+ "equivalent_diameter_px": round(float(2.0 * np.sqrt(area[i] / np.pi)), 2),
91
+ "centroid_x": round(float(cx[i]), 2),
92
+ "centroid_y": round(float(cy[i]), 2),
93
+ "bbox_x": int(low_x[i]),
94
+ "bbox_y": int(low_y[i]),
95
+ "bbox_width": int(high_x[i] - low_x[i] + 1),
96
+ "bbox_height": int(high_y[i] - low_y[i] + 1),
97
+ }
98
+ for i in range(n)
99
+ ]
@@ -0,0 +1,126 @@
1
+ Metadata-Version: 2.4
2
+ Name: volkcell
3
+ Version: 0.1.0
4
+ Summary: Python client and command line for the VolkCell cell image analysis API
5
+ License: MIT
6
+ Project-URL: Homepage, https://www.volkcell.com
7
+ Classifier: License :: OSI Approved :: MIT License
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
10
+ Classifier: Topic :: Scientific/Engineering :: Image Processing
11
+ Requires-Python: >=3.9
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: numpy>=1.22
15
+ Requires-Dist: Pillow>=9.0
16
+ Requires-Dist: requests>=2.28
17
+ Provides-Extra: pandas
18
+ Requires-Dist: pandas>=1.4; extra == "pandas"
19
+ Provides-Extra: test
20
+ Requires-Dist: pytest>=7; extra == "test"
21
+ Dynamic: license-file
22
+
23
+ # volkcell
24
+
25
+ Python client and command line for the [VolkCell](https://www.volkcell.com) cell image analysis API.
26
+ Images are uploaded to VolkCell and analysed there.
27
+
28
+ ## Install
29
+
30
+ Python 3.9 or later:
31
+
32
+ ```
33
+ pip install volkcell
34
+ pip install "volkcell[pandas]" # for result.objects_dataframe()
35
+ ```
36
+
37
+ ## API key
38
+
39
+ You need a VolkCell team workspace. Its owner or an admin creates a key at
40
+ `https://www.volkcell.com/w/<workspace>/api-keys`. The key starts with `vcw_` and is shown once.
41
+
42
+ ```
43
+ export VOLKCELL_API_KEY="your key"
44
+ ```
45
+
46
+ Keep the key out of scripts and notebooks you share. Runs made with it are billed to the workspace.
47
+
48
+ ## Command line
49
+
50
+ ```
51
+ volkcell count image.tif
52
+ volkcell count image.tif --analysis adherent --objects cells.csv
53
+ volkcell count image.tif --json
54
+ volkcell result JOB_ID
55
+ ```
56
+
57
+ `--analysis` is `auto` (default), `suspension` or `adherent`. Warnings are printed to standard error.
58
+ The exit status is 0 when there is a result (with or without warnings) and 1 on an error.
59
+
60
+ Each `count` starts a new analysis and uses your allowance. If waiting stops early, use
61
+ `volkcell result JOB_ID` to read the same run. If the upload itself fails with a connection or server error,
62
+ check your runs in VolkCell before sending the image again: it may have been accepted.
63
+
64
+ ## Python
65
+
66
+ ```python
67
+ import volkcell
68
+
69
+ result = volkcell.count("image.tif", analysis="auto")
70
+ print(result.count)
71
+ for warning in result.warnings:
72
+ print("WARNING:", warning)
73
+
74
+ table = result.objects_dataframe() # or result.objects, a list of dicts
75
+ ```
76
+
77
+ `count` also takes a numpy array: `uint8` greyscale or colour, or `uint16` greyscale. It is sent as a
78
+ lossless PNG with the pixel values unchanged. For a stack or multichannel array, pass one 2-D plane.
79
+
80
+ | Field | Meaning |
81
+ |-------|---------|
82
+ | `count` | Cell count. `None` if there is none, or if one file produced several images |
83
+ | `warnings` | Everything VolkCell and the client flagged. **Read these before using a number** |
84
+ | `objects` | One row per outlined object: area, equivalent diameter, centroid and bounding box, in pixels |
85
+ | `labels` | Label image as a numpy array (0 is background), for single-image results |
86
+ | `outlines_match_input` | `False` if the label image is a different size from your image; `None` if not compared |
87
+ | `confluency_percent` | Confluency, when the analysis reports it |
88
+ | `images` | Count and confluency per image |
89
+ | `job_id` | Use with `volkcell.get_result(job_id)` |
90
+ | `raw` | The API's results response |
91
+
92
+ Object measurements are calculated by this client from the label image. They are in pixels.
93
+
94
+ ## Errors
95
+
96
+ All errors are subclasses of `volkcell.VolkCellError` and carry `job_id` once a job exists.
97
+
98
+ | Error | When |
99
+ |-------|------|
100
+ | `AuthenticationError` | No key, or the key was refused |
101
+ | `InputError` | The file or array cannot be sent |
102
+ | `RequestRejected` | The server refused the request, for example because Auto could not tell what the image is. Choose `suspension` or `adherent` |
103
+ | `LimitError` | Rate, running-job or image allowance limit |
104
+ | `AnalysisFailed` | The run produced no result; see `warnings` |
105
+ | `AnalysisTimeout` | Waiting stopped (default 900 s); the run may still finish |
106
+ | `ServiceError` | VolkCell could not be reached or had a temporary problem |
107
+
108
+ Limits: one image per call, up to 100 MB. TIFF, PNG, JPEG, BMP, CZI, ND2, LIF, OIB, OIF.
109
+
110
+ ## Settings
111
+
112
+ `VOLKCELL_BASE_URL` or `Client(base_url=...)` selects another VolkCell server. The key is sent only to that
113
+ address, over HTTPS (plain HTTP is accepted for localhost), and redirects are not followed.
114
+
115
+ ## Tests
116
+
117
+ ```
118
+ pip install ".[test]"
119
+ pytest
120
+ ```
121
+
122
+ The tests use a local mock server.
123
+
124
+ ## Licence
125
+
126
+ MIT. See `LICENSE`.
@@ -0,0 +1,15 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ README.md
4
+ pyproject.toml
5
+ src/volkcell/__init__.py
6
+ src/volkcell/cli.py
7
+ src/volkcell/client.py
8
+ src/volkcell/errors.py
9
+ src/volkcell/result.py
10
+ src/volkcell.egg-info/PKG-INFO
11
+ src/volkcell.egg-info/SOURCES.txt
12
+ src/volkcell.egg-info/dependency_links.txt
13
+ src/volkcell.egg-info/entry_points.txt
14
+ src/volkcell.egg-info/requires.txt
15
+ src/volkcell.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ volkcell = volkcell.cli:main
@@ -0,0 +1,9 @@
1
+ numpy>=1.22
2
+ Pillow>=9.0
3
+ requests>=2.28
4
+
5
+ [pandas]
6
+ pandas>=1.4
7
+
8
+ [test]
9
+ pytest>=7
@@ -0,0 +1 @@
1
+ volkcell