elabftw-toolkit 0.1.1__py3-none-any.whl
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.
- elabftw_toolkit/__init__.py +62 -0
- elabftw_toolkit/_compat.py +132 -0
- elabftw_toolkit/_http.py +144 -0
- elabftw_toolkit/benten_schema.py +696 -0
- elabftw_toolkit/categories.py +138 -0
- elabftw_toolkit/client.py +1717 -0
- elabftw_toolkit/common.py +1580 -0
- elabftw_toolkit/data/benten_schema.json +1822 -0
- elabftw_toolkit/dataframe.py +119 -0
- elabftw_toolkit/experiments.py +970 -0
- elabftw_toolkit/fields.py +307 -0
- elabftw_toolkit/files.py +1213 -0
- elabftw_toolkit/find.py +351 -0
- elabftw_toolkit/html_tables.py +1413 -0
- elabftw_toolkit/images.py +520 -0
- elabftw_toolkit/items.py +1095 -0
- elabftw_toolkit/links.py +436 -0
- elabftw_toolkit/maiml.py +623 -0
- elabftw_toolkit/mcp_server.py +485 -0
- elabftw_toolkit/metadata_utils.py +770 -0
- elabftw_toolkit/permissions.py +1495 -0
- elabftw_toolkit/plan.py +499 -0
- elabftw_toolkit/record.py +94 -0
- elabftw_toolkit/schema.py +738 -0
- elabftw_toolkit/search.py +559 -0
- elabftw_toolkit/statuses.py +131 -0
- elabftw_toolkit/steps.py +475 -0
- elabftw_toolkit/tags.py +569 -0
- elabftw_toolkit/teams.py +133 -0
- elabftw_toolkit/templates.py +685 -0
- elabftw_toolkit-0.1.1.dist-info/METADATA +191 -0
- elabftw_toolkit-0.1.1.dist-info/RECORD +36 -0
- elabftw_toolkit-0.1.1.dist-info/WHEEL +5 -0
- elabftw_toolkit-0.1.1.dist-info/entry_points.txt +2 -0
- elabftw_toolkit-0.1.1.dist-info/licenses/LICENSE +201 -0
- elabftw_toolkit-0.1.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""elabftw-toolkit: an unofficial toolkit for working with eLabFTW experiments and Resources from Python.
|
|
2
|
+
|
|
3
|
+
Start with ``elab = elabftw_toolkit.client("your-team-name")``.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from importlib.metadata import PackageNotFoundError
|
|
7
|
+
from importlib.metadata import version as _version
|
|
8
|
+
|
|
9
|
+
try:
|
|
10
|
+
__version__ = _version("elabftw-toolkit")
|
|
11
|
+
except PackageNotFoundError: # pragma: no cover
|
|
12
|
+
__version__ = "0+unknown"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
from .client import (
|
|
16
|
+
client,
|
|
17
|
+
)
|
|
18
|
+
from .experiments import (
|
|
19
|
+
make_experiment_title,
|
|
20
|
+
)
|
|
21
|
+
from .fields import (
|
|
22
|
+
extra_field_units,
|
|
23
|
+
extra_fields,
|
|
24
|
+
metadata_of,
|
|
25
|
+
)
|
|
26
|
+
from .find import (
|
|
27
|
+
AmbiguousError,
|
|
28
|
+
DuplicateError,
|
|
29
|
+
LinkResolutionError,
|
|
30
|
+
NotFoundError,
|
|
31
|
+
Ref,
|
|
32
|
+
)
|
|
33
|
+
from .plan import (
|
|
34
|
+
Plan,
|
|
35
|
+
)
|
|
36
|
+
from .record import (
|
|
37
|
+
ChangeRecord,
|
|
38
|
+
)
|
|
39
|
+
from .schema import (
|
|
40
|
+
Schema,
|
|
41
|
+
SchemaError,
|
|
42
|
+
ValidationResult,
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
__all__ = [
|
|
46
|
+
"__version__",
|
|
47
|
+
"client",
|
|
48
|
+
"make_experiment_title",
|
|
49
|
+
"metadata_of",
|
|
50
|
+
"extra_fields",
|
|
51
|
+
"extra_field_units",
|
|
52
|
+
"Schema",
|
|
53
|
+
"SchemaError",
|
|
54
|
+
"ValidationResult",
|
|
55
|
+
"Plan",
|
|
56
|
+
"ChangeRecord",
|
|
57
|
+
"Ref",
|
|
58
|
+
"LinkResolutionError",
|
|
59
|
+
"NotFoundError",
|
|
60
|
+
"AmbiguousError",
|
|
61
|
+
"DuplicateError",
|
|
62
|
+
]
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""Hide naming differences between elabapi_python versions (internal).
|
|
2
|
+
|
|
3
|
+
elabapi_python (the SDK generated from the eLabFTW OpenAPI spec) sometimes renames API
|
|
4
|
+
classes and methods between versions. For example, in 6.0:
|
|
5
|
+
|
|
6
|
+
ExperimentsCategoriesApi → ExperimentCategoriesApi
|
|
7
|
+
ResourcesCategoriesApi → ResourceCategoriesApi
|
|
8
|
+
ExperimentsStatusApi → ExperimentStatusApi
|
|
9
|
+
ResourcesStatusApi → ResourceStatusApi
|
|
10
|
+
|
|
11
|
+
Inside the toolkit, do not write elabapi_python.XxxApi(api_client) directly; write
|
|
12
|
+
|
|
13
|
+
_compat.api_class("ExperimentStatusApi")(api_client)
|
|
14
|
+
_compat.call(links_api, "delete_entity_items_link", "delete_entitiy_items_link", **kw)
|
|
15
|
+
|
|
16
|
+
instead. api_class() tries the aliases registered in ALIASES in order (the lookup happens
|
|
17
|
+
at call time, so tests can replace elabapi_python.ItemsApi with a mock).
|
|
18
|
+
|
|
19
|
+
Use check_sdk() to confirm that the installed elabapi_python has every class and method
|
|
20
|
+
the toolkit uses (tests/test_compat.py relies on it).
|
|
21
|
+
"""
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
from collections.abc import Iterable
|
|
25
|
+
from importlib.metadata import PackageNotFoundError
|
|
26
|
+
from importlib.metadata import version as _version
|
|
27
|
+
from typing import Any
|
|
28
|
+
|
|
29
|
+
import elabapi_python
|
|
30
|
+
|
|
31
|
+
__all__ = ["ALIASES", "REQUIRED", "api_class", "api", "method", "call", "check_sdk", "sdk_version"]
|
|
32
|
+
|
|
33
|
+
# Aliases for the same class (current name first; append older names after it)
|
|
34
|
+
ALIASES: list[tuple[str, ...]] = [
|
|
35
|
+
("ExperimentCategoriesApi", "ExperimentsCategoriesApi"),
|
|
36
|
+
("ResourceCategoriesApi", "ResourcesCategoriesApi"),
|
|
37
|
+
("ExperimentStatusApi", "ExperimentsStatusApi"),
|
|
38
|
+
("ResourceStatusApi", "ResourcesStatusApi"),
|
|
39
|
+
]
|
|
40
|
+
|
|
41
|
+
# Classes and methods the toolkit uses. A tuple means "any one of these is enough".
|
|
42
|
+
REQUIRED: dict[str, list[str | tuple[str, ...]]] = {
|
|
43
|
+
"ExperimentsApi": ["read_experiments", "get_experiment", "patch_experiment", "post_experiment_with_http_info"],
|
|
44
|
+
"ItemsApi": ["read_items", "get_item", "patch_item", "post_item_with_http_info"],
|
|
45
|
+
"ExperimentsTemplatesApi": ["read_experiments_templates", "get_experiment_template"],
|
|
46
|
+
"ExperimentCategoriesApi": ["read_team_experiments_categories"],
|
|
47
|
+
"ResourceCategoriesApi": ["read_team_resources_categories"],
|
|
48
|
+
"ExperimentStatusApi": ["read_team_experiments_status"],
|
|
49
|
+
"ResourceStatusApi": ["read_team_items_status"],
|
|
50
|
+
"StepsApi": ["read_steps", "post_step", "patch_step", "delete_step"],
|
|
51
|
+
"UploadsApi": ["read_uploads", "read_upload", "post_upload", "delete_upload"],
|
|
52
|
+
"LinksToExperimentsApi": [
|
|
53
|
+
"read_entity_experiments_links",
|
|
54
|
+
"post_entity_experiments_links",
|
|
55
|
+
"delete_entity_experiments_link",
|
|
56
|
+
],
|
|
57
|
+
"LinksToItemsApi": [
|
|
58
|
+
"read_entity_items_links",
|
|
59
|
+
"post_entity_items_links",
|
|
60
|
+
("delete_entity_items_link", "delete_entitiy_items_link"),
|
|
61
|
+
],
|
|
62
|
+
"TagsApi": ["post_tag", "delete_tag"],
|
|
63
|
+
"TeamsApi": ["read_teams", "read_team"],
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _names(name: str) -> tuple[str, ...]:
|
|
68
|
+
for group in ALIASES:
|
|
69
|
+
if name in group:
|
|
70
|
+
return group
|
|
71
|
+
return (name,)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def sdk_version() -> str:
|
|
75
|
+
"""Return the installed elabapi_python version ("unknown" if it cannot be determined)."""
|
|
76
|
+
try:
|
|
77
|
+
return _version("elabapi-python")
|
|
78
|
+
except PackageNotFoundError: # pragma: no cover
|
|
79
|
+
return getattr(elabapi_python, "__version__", "unknown")
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def api_class(name: str, module: Any = None):
|
|
83
|
+
"""Return the API class for name (or one of its aliases); raise AttributeError if none exists."""
|
|
84
|
+
module = module or elabapi_python
|
|
85
|
+
names = _names(name)
|
|
86
|
+
for n in names:
|
|
87
|
+
cls = getattr(module, n, None)
|
|
88
|
+
if cls is not None:
|
|
89
|
+
return cls
|
|
90
|
+
raise AttributeError(
|
|
91
|
+
f"elabapi_python {sdk_version()} has no {' / '.join(names)}"
|
|
92
|
+
" (add the new name to _compat.ALIASES)"
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def api(name: str, api_client):
|
|
97
|
+
"""Shorthand for api_class(name)(api_client)."""
|
|
98
|
+
return api_class(name)(api_client)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def method(obj: Any, *names: str):
|
|
102
|
+
"""Return the first method in names that obj has."""
|
|
103
|
+
for n in names:
|
|
104
|
+
m = getattr(obj, n, None)
|
|
105
|
+
if callable(m):
|
|
106
|
+
return m
|
|
107
|
+
raise AttributeError(
|
|
108
|
+
f"{type(obj).__name__} has no {' / '.join(names)} (elabapi_python {sdk_version()})"
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def call(obj: Any, *names: str, **kwargs):
|
|
113
|
+
"""Shorthand for method(obj, *names)(**kwargs)."""
|
|
114
|
+
return method(obj, *names)(**kwargs)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def check_sdk(module: Any = None, required: dict | None = None) -> list[str]:
|
|
118
|
+
"""Return the classes and methods the toolkit uses that are missing ([] if all are present)."""
|
|
119
|
+
module = module or elabapi_python
|
|
120
|
+
missing: list[str] = []
|
|
121
|
+
for cls_name, methods in (required or REQUIRED).items():
|
|
122
|
+
try:
|
|
123
|
+
cls = api_class(cls_name, module)
|
|
124
|
+
except AttributeError:
|
|
125
|
+
missing.append(" / ".join(_names(cls_name)))
|
|
126
|
+
continue
|
|
127
|
+
have = set(dir(cls))
|
|
128
|
+
for m in methods:
|
|
129
|
+
alts: Iterable[str] = (m,) if isinstance(m, str) else m
|
|
130
|
+
if not any(a in have for a in alts):
|
|
131
|
+
missing.append(f"{cls.__name__}.{' / '.join(alts)}")
|
|
132
|
+
return missing
|
elabftw_toolkit/_http.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""Shared helpers for calling the eLabFTW API directly, without the SDK (internal).
|
|
2
|
+
|
|
3
|
+
Calling requests directly ignores the verify_ssl setting from client() and has no timeout,
|
|
4
|
+
so it hangs if the server does not respond. These helpers use the following defaults
|
|
5
|
+
(values passed by the caller take precedence).
|
|
6
|
+
|
|
7
|
+
verify : verify_ssl given to client() (set by configure())
|
|
8
|
+
timeout : DEFAULT_TIMEOUT seconds
|
|
9
|
+
|
|
10
|
+
GET requests only are retried up to GET_RETRIES times, with a pause in between, on
|
|
11
|
+
transient failures (connection error, timeout, 429, 5xx); reads are safe to repeat.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import json
|
|
16
|
+
import time
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
import requests
|
|
20
|
+
|
|
21
|
+
DEFAULT_TIMEOUT = 60
|
|
22
|
+
GET_RETRIES = 4
|
|
23
|
+
RETRY_STATUS = {429, 500, 502, 503, 504}
|
|
24
|
+
_verify: bool | str = True
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def configure(*, verify: bool | str | None = None, timeout: float | None = None) -> None:
|
|
28
|
+
"""Set the defaults for SSL verification and timeout (called from client()).
|
|
29
|
+
|
|
30
|
+
verify is a bool or the path to a CA certificate.
|
|
31
|
+
"""
|
|
32
|
+
global _verify, DEFAULT_TIMEOUT
|
|
33
|
+
if verify is not None:
|
|
34
|
+
_verify = verify
|
|
35
|
+
if timeout is not None:
|
|
36
|
+
DEFAULT_TIMEOUT = timeout
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def request(method: str, url: str, **kwargs) -> requests.Response:
|
|
40
|
+
"""Send an HTTP request with the default verify and timeout.
|
|
41
|
+
|
|
42
|
+
GET requests only are retried up to GET_RETRIES times, with a pause in between, on transient failures.
|
|
43
|
+
"""
|
|
44
|
+
kwargs.setdefault("timeout", DEFAULT_TIMEOUT)
|
|
45
|
+
kwargs.setdefault("verify", _verify)
|
|
46
|
+
if method.upper() != "GET":
|
|
47
|
+
return requests.request(method, url, **kwargs)
|
|
48
|
+
for i in range(GET_RETRIES):
|
|
49
|
+
last = i == GET_RETRIES - 1
|
|
50
|
+
try:
|
|
51
|
+
response = requests.request(method, url, **kwargs)
|
|
52
|
+
except (requests.ConnectionError, requests.Timeout):
|
|
53
|
+
if last:
|
|
54
|
+
raise
|
|
55
|
+
else:
|
|
56
|
+
if response.status_code not in RETRY_STATUS or last:
|
|
57
|
+
return response
|
|
58
|
+
time.sleep(2 ** (i + 1))
|
|
59
|
+
raise AssertionError("unreachable") # pragma: no cover
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def get(url: str, **kwargs) -> requests.Response:
|
|
63
|
+
"""Send a GET request (transient failures are retried)."""
|
|
64
|
+
return request("GET", url, **kwargs)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def post(url: str, **kwargs) -> requests.Response:
|
|
68
|
+
"""Send a POST request."""
|
|
69
|
+
return request("POST", url, **kwargs)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def patch(url: str, **kwargs) -> requests.Response:
|
|
73
|
+
"""Send a PATCH request."""
|
|
74
|
+
return request("PATCH", url, **kwargs)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def delete(url: str, **kwargs) -> requests.Response:
|
|
78
|
+
"""Send a DELETE request."""
|
|
79
|
+
return request("DELETE", url, **kwargs)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
# -- Call API v2 using the host and key of an api_client (elabapi_python.ApiClient)
|
|
83
|
+
|
|
84
|
+
def base_url(api_client) -> str:
|
|
85
|
+
"""Return the api_client's host (the API v2 URL, without a trailing /)."""
|
|
86
|
+
return str(api_client.configuration.host).rstrip("/")
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _headers(api_client) -> dict[str, str]:
|
|
90
|
+
return {
|
|
91
|
+
"Authorization": api_client.configuration.api_key["api_key"],
|
|
92
|
+
"Accept": "application/json",
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _check(response: requests.Response) -> None:
|
|
97
|
+
"""On 4xx / 5xx, raise requests.HTTPError including the server's message."""
|
|
98
|
+
if response.status_code < 400:
|
|
99
|
+
return
|
|
100
|
+
try:
|
|
101
|
+
message = response.json().get("message", response.text)
|
|
102
|
+
except (ValueError, AttributeError):
|
|
103
|
+
message = response.text
|
|
104
|
+
raise requests.HTTPError(
|
|
105
|
+
f"{response.request.method} {response.url} -> {response.status_code}: {str(message)[:300]}",
|
|
106
|
+
response=response,
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def api_get(api_client, path: str, **params) -> Any:
|
|
111
|
+
"""Return the JSON of GET <host>/<path> (e.g. api_get(c, "/items/5"))."""
|
|
112
|
+
response = get(base_url(api_client) + "/" + path.lstrip("/"), headers=_headers(api_client), params=params or None)
|
|
113
|
+
_check(response)
|
|
114
|
+
return response.json()
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def api_patch(api_client, path: str, body: dict) -> Any:
|
|
118
|
+
"""PATCH <host>/<path> and return the response JSON (None if there is no body).
|
|
119
|
+
|
|
120
|
+
If body["metadata"] is a dict, it is sent as a JSON string (eLabFTW expects a string).
|
|
121
|
+
"""
|
|
122
|
+
body = dict(body)
|
|
123
|
+
if isinstance(body.get("metadata"), dict):
|
|
124
|
+
body["metadata"] = json.dumps(body["metadata"], ensure_ascii=False)
|
|
125
|
+
response = patch(base_url(api_client) + "/" + path.lstrip("/"), headers=_headers(api_client), json=body)
|
|
126
|
+
_check(response)
|
|
127
|
+
return response.json() if response.content else None
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def api_post(api_client, path: str, body: dict) -> Any:
|
|
131
|
+
"""POST <host>/<path> (JSON) and return the response JSON (None if there is no body).
|
|
132
|
+
|
|
133
|
+
When creating something, eLabFTW returns no body and puts the new URL in the Location
|
|
134
|
+
header, so without a body this returns {"location": ...} (None if there is no Location either).
|
|
135
|
+
"""
|
|
136
|
+
response = post(base_url(api_client) + "/" + path.lstrip("/"), headers=_headers(api_client), json=body)
|
|
137
|
+
_check(response)
|
|
138
|
+
if response.content:
|
|
139
|
+
try:
|
|
140
|
+
return response.json()
|
|
141
|
+
except ValueError:
|
|
142
|
+
return None
|
|
143
|
+
location = response.headers.get("Location") if response.headers else None
|
|
144
|
+
return {"location": location} if location else None
|