embodiflow 1.25.0__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.
Files changed (62) hide show
  1. embodiflow/__init__.py +149 -0
  2. embodiflow/_auth.py +68 -0
  3. embodiflow/_batch_wait.py +107 -0
  4. embodiflow/_download.py +556 -0
  5. embodiflow/_generated/__init__.py +28 -0
  6. embodiflow/_generated/api.py +3979 -0
  7. embodiflow/_generated/error_codes.py +1123 -0
  8. embodiflow/_generated/models.py +10743 -0
  9. embodiflow/_generated/operations.json +2250 -0
  10. embodiflow/_generated/operations.py +2274 -0
  11. embodiflow/_poll.py +190 -0
  12. embodiflow/_transfer.py +294 -0
  13. embodiflow/algorithm/__init__.py +18 -0
  14. embodiflow/algorithm/_models/__init__.py +1 -0
  15. embodiflow/algorithm/_models/data_conventions.py +199 -0
  16. embodiflow/algorithm/_models/depth.py +34 -0
  17. embodiflow/algorithm/_models/derived_features.py +90 -0
  18. embodiflow/algorithm/_models/episode_proposals.py +121 -0
  19. embodiflow/algorithm/_models/recording_layout.py +237 -0
  20. embodiflow/algorithm/_schemas/__init__.py +19 -0
  21. embodiflow/algorithm/_schemas/data-conventions.schema.json +398 -0
  22. embodiflow/algorithm/_schemas/depth.schema.json +88 -0
  23. embodiflow/algorithm/_schemas/derived-features.schema.json +160 -0
  24. embodiflow/algorithm/_schemas/episode-proposals.schema.json +315 -0
  25. embodiflow/algorithm/_schemas/recording-layout.schema.json +465 -0
  26. embodiflow/algorithm/lerobot.py +787 -0
  27. embodiflow/algorithm/mp4.py +40 -0
  28. embodiflow/algorithm/procs.py +117 -0
  29. embodiflow/algorithm/sample_run_runner.py +315 -0
  30. embodiflow/algorithm/sample_run_stager.py +885 -0
  31. embodiflow/client.py +279 -0
  32. embodiflow/errors.py +133 -0
  33. embodiflow/flow/__init__.py +73 -0
  34. embodiflow/flow/context.py +169 -0
  35. embodiflow/flow/decorators.py +270 -0
  36. embodiflow/flow/errors.py +335 -0
  37. embodiflow/flow/index.py +183 -0
  38. embodiflow/flow/inputs.py +719 -0
  39. embodiflow/flow/local.py +135 -0
  40. embodiflow/flow/manifest.py +283 -0
  41. embodiflow/flow/passthrough.py +66 -0
  42. embodiflow/flow/preview.py +274 -0
  43. embodiflow/flow/quality_metrics.py +60 -0
  44. embodiflow/flow/recording_writers.py +737 -0
  45. embodiflow/flow/run.py +348 -0
  46. embodiflow/flow/sample.py +261 -0
  47. embodiflow/flow/sample_image.py +379 -0
  48. embodiflow/flow/spec.py +1261 -0
  49. embodiflow/flow/testing.py +126 -0
  50. embodiflow/flow/writers.py +693 -0
  51. embodiflow/helpers.py +19 -0
  52. embodiflow/hf_import.py +146 -0
  53. embodiflow/paginate.py +28 -0
  54. embodiflow/py.typed +1 -0
  55. embodiflow/recordings.py +598 -0
  56. embodiflow/serialize.py +40 -0
  57. embodiflow/standardize.py +314 -0
  58. embodiflow-1.25.0.dist-info/METADATA +176 -0
  59. embodiflow-1.25.0.dist-info/RECORD +62 -0
  60. embodiflow-1.25.0.dist-info/WHEEL +5 -0
  61. embodiflow-1.25.0.dist-info/licenses/LICENSE +201 -0
  62. embodiflow-1.25.0.dist-info/top_level.txt +1 -0
embodiflow/__init__.py ADDED
@@ -0,0 +1,149 @@
1
+ """EmbodiFlow Python SDK: the algorithm runtime, and the public REST client when it is installed.
2
+
3
+ Two distributions carry the ``embodiflow`` import package (S11 11d):
4
+
5
+ - ``embodiflow`` (PyPI; ``pip install embodiflow``) is the public one: the generated REST client
6
+ (``embodiflow.client``, ``embodiflow._generated``) with this runtime vendored in at build time,
7
+ byte for byte, so a local install has the same ``embodiflow.flow`` and ``embodiflow.algorithm``
8
+ as an algorithm image.
9
+ - ``embodiflow-runtime`` (internal, never on PyPI) holds only the step runtime (``embodiflow.flow``),
10
+ the job document, the IO helpers and the manifest spec (``embodiflow.algorithm``). Algorithm
11
+ images and the SDK base images install only this distribution, so a public API change, which
12
+ regenerates the REST client, does not change their bytes.
13
+
14
+ The client names below are imported lazily, on first use. In an environment with only the
15
+ runtime (an algorithm image), using one fails with ``ModuleNotFoundError`` naming the missing
16
+ distribution instead of a bare import error.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import importlib
22
+ import importlib.util
23
+ from pkgutil import extend_path
24
+ from typing import Any
25
+
26
+ # The client modules live in packages/sdk-python. Installed, the `embodiflow` wheel holds both;
27
+ # from the source tree (packages/sdk-python-runtime and
28
+ # packages/sdk-python both on sys.path) this joins the two directories into one package.
29
+ __path__ = extend_path(__path__, __name__)
30
+
31
+ # `embodiflow.paginate` is both a client module and its function. Importing the module (the client does)
32
+ # sets the package attribute to the module, which would shadow the lazy name below; binding the function
33
+ # first keeps it, as the eager import did. The module is plain stdlib and absent in an algorithm image.
34
+ try:
35
+ from embodiflow.paginate import paginate
36
+ except ModuleNotFoundError as exc:
37
+ if exc.name != "embodiflow.paginate":
38
+ raise
39
+
40
+ from embodiflow.flow import ( # noqa: E402
41
+ ArtifactWriter,
42
+ Camera,
43
+ Check,
44
+ CheckWriter,
45
+ Constraint,
46
+ Context,
47
+ DatasetVersion,
48
+ Episode,
49
+ EpisodeWriter,
50
+ Feature,
51
+ FeatureWriter,
52
+ Features,
53
+ Frame,
54
+ Input,
55
+ McapReader,
56
+ Member,
57
+ OutputError,
58
+ RawFile,
59
+ RawFiles,
60
+ Recording,
61
+ RecordingBuilder,
62
+ RecordingEditor,
63
+ SelectionWriter,
64
+ SetupContext,
65
+ TransientError,
66
+ param,
67
+ )
68
+
69
+ RUNTIME_NAMES = (
70
+ "ArtifactWriter",
71
+ "Camera",
72
+ "Check",
73
+ "CheckWriter",
74
+ "Constraint",
75
+ "Context",
76
+ "DatasetVersion",
77
+ "Episode",
78
+ "EpisodeWriter",
79
+ "Feature",
80
+ "FeatureWriter",
81
+ "Features",
82
+ "Frame",
83
+ "Input",
84
+ "McapReader",
85
+ "Member",
86
+ "OutputError",
87
+ "RawFile",
88
+ "RawFiles",
89
+ "Recording",
90
+ "RecordingBuilder",
91
+ "RecordingEditor",
92
+ "SelectionWriter",
93
+ "SetupContext",
94
+ "TransientError",
95
+ "param",
96
+ )
97
+
98
+ # Public client names -> (module, attribute). Resolved on first access by __getattr__.
99
+ CLIENT_NAMES: dict[str, tuple[str, str]] = {
100
+ "GENERATED_OPERATION_COUNT": ("embodiflow._generated", "GENERATED_OPERATION_COUNT"),
101
+ "OPERATIONS": ("embodiflow._generated", "OPERATIONS"),
102
+ "GeneratedApi": ("embodiflow._generated.api", "GeneratedApi"),
103
+ "ErrorCode": ("embodiflow._generated.error_codes", "ErrorCode"),
104
+ "SdkErrorCode": ("embodiflow._generated.error_codes", "SdkErrorCode"),
105
+ "EmbodiFlowApiError": ("embodiflow.client", "EmbodiFlowApiError"),
106
+ "EmbodiFlowClient": ("embodiflow.client", "EmbodiFlowClient"),
107
+ "format_auth_error_message": ("embodiflow.errors", "format_auth_error_message"),
108
+ "paginate": ("embodiflow.paginate", "paginate"),
109
+ "upload_folder": ("embodiflow.recordings", "upload_folder"),
110
+ "download": ("embodiflow._download", "download"),
111
+ "DownloadError": ("embodiflow._download", "DownloadError"),
112
+ "import_hf": ("embodiflow.hf_import", "import_hf"),
113
+ }
114
+
115
+ CLIENT_DISTRIBUTION = "embodiflow"
116
+
117
+
118
+ def __getattr__(name: str) -> Any:
119
+ target = CLIENT_NAMES.get(name)
120
+ if target is None:
121
+ # AttributeError (never ImportError) so `from embodiflow import <submodule>` still imports it.
122
+ raise AttributeError(f"module 'embodiflow' has no attribute {name!r}")
123
+ module_name, attribute = target
124
+ try:
125
+ module = importlib.import_module(module_name)
126
+ except ModuleNotFoundError as exc:
127
+ if exc.name is not None and (exc.name == module_name or module_name.startswith(exc.name + ".")):
128
+ raise ModuleNotFoundError(
129
+ f"embodiflow.{name} is part of the public REST client, which is not installed here: this "
130
+ f"environment has only the algorithm runtime (embodiflow-runtime). Install {CLIENT_DISTRIBUTION} "
131
+ "to call the API; an algorithm step never needs it.",
132
+ name=module_name,
133
+ ) from exc
134
+ raise
135
+ value = getattr(module, attribute)
136
+ globals()[name] = value
137
+ return value
138
+
139
+
140
+ # `from embodiflow import *`, dir() and completion list the client names only where the client is installed,
141
+ # so they never trip the error above in an algorithm image; an explicit use still raises it.
142
+ CLIENT_INSTALLED = importlib.util.find_spec("embodiflow.client") is not None
143
+
144
+
145
+ def __dir__() -> list[str]:
146
+ return sorted(set(globals()) | (set(CLIENT_NAMES) if CLIENT_INSTALLED else set()))
147
+
148
+
149
+ __all__ = [*RUNTIME_NAMES, *(CLIENT_NAMES if CLIENT_INSTALLED else ())]
embodiflow/_auth.py ADDED
@@ -0,0 +1,68 @@
1
+ """Credentials for the module-level helpers (``embodiflow.download``, ``embodiflow.upload_folder``).
2
+
3
+ The same sources as the CLI, in the same order: ``EMBODIFLOW_API_KEY`` and ``EMBODIFLOW_API_URL``,
4
+ else the profile ``ef login`` wrote (``$EMBODIFLOW_CONFIG_DIR`` or ``~/.embodiflow``; ``config.json`` for
5
+ the default profile, ``profiles/<name>.json`` for ``EMBODIFLOW_PROFILE``). The key is never printed.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import os
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from embodiflow.client import EmbodiFlowClient
16
+
17
+
18
+
19
+ class CredentialsMissing(ValueError):
20
+ """No API key in the environment or in a CLI profile."""
21
+
22
+
23
+ def config_dir() -> Path:
24
+ raw = os.environ.get("EMBODIFLOW_CONFIG_DIR", "").strip()
25
+ return Path(raw).expanduser() if raw else Path.home() / ".embodiflow"
26
+
27
+
28
+ def profile_path(profile: str | None = None) -> Path:
29
+ name = (profile or os.environ.get("EMBODIFLOW_PROFILE", "")).strip() or "default"
30
+ if name == "default":
31
+ return config_dir() / "config.json"
32
+ return config_dir() / "profiles" / f"{name}.json"
33
+
34
+
35
+ def _read_profile(profile: str | None) -> dict[str, Any]:
36
+ path = profile_path(profile)
37
+ try:
38
+ data = json.loads(path.read_text(encoding="utf-8"))
39
+ except (OSError, ValueError):
40
+ return {}
41
+ return data if isinstance(data, dict) else {}
42
+
43
+
44
+ def resolve_credentials(profile: str | None = None) -> tuple[str, str]:
45
+ """``(base_url, api_key)``: the environment first, then the CLI profile."""
46
+ stored = _read_profile(profile)
47
+ api_key = os.environ.get("EMBODIFLOW_API_KEY", "").strip() or str(stored.get("apiKey") or "").strip()
48
+ if not api_key:
49
+ raise CredentialsMissing(
50
+ "No EmbodiFlow credentials: set EMBODIFLOW_API_KEY, or run `ef login` once "
51
+ f"(profile file {profile_path(profile)})"
52
+ )
53
+ base_url = (
54
+ os.environ.get("EMBODIFLOW_API_URL", "").strip()
55
+ or str(stored.get("baseUrl") or "").strip()
56
+ )
57
+ if not base_url:
58
+ # No built-in host: a token is never sent to a deployment nobody named.
59
+ raise CredentialsMissing(
60
+ "No EmbodiFlow API is set: run `ef login --api-url https://<your-api>` once, "
61
+ "or set EMBODIFLOW_API_URL"
62
+ )
63
+ return base_url.rstrip("/"), api_key
64
+
65
+
66
+ def default_client(profile: str | None = None) -> EmbodiFlowClient:
67
+ base_url, api_key = resolve_credentials(profile)
68
+ return EmbodiFlowClient(base_url=base_url, api_key=api_key)
@@ -0,0 +1,107 @@
1
+ """Waiting on an upload batch until its processing ends.
2
+
3
+ One meaning of ``wait`` for :func:`embodiflow.upload_folder` and
4
+ :func:`embodiflow.import_hf`, the same as ``ef recordings upload --wait``: the
5
+ outcome the API states (``processingOutcome``), a named failure or refusal, or
6
+ a batch kept without processing. Only ``succeeded`` is a success;
7
+ ``partially_succeeded`` returns with the outcome so the caller can look.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import time
13
+ from collections.abc import Callable
14
+ from typing import Any, cast
15
+
16
+ from embodiflow._generated.error_codes import SdkErrorCode
17
+ from embodiflow._poll import poll_until
18
+ from embodiflow.client import EmbodiFlowApiError, EmbodiFlowClient
19
+
20
+ BATCH_WAIT_TIMEOUT_SECONDS = 7200.0
21
+
22
+
23
+ def _done(batch: dict[str, Any]) -> bool:
24
+ # A retry may be running on a batch that holds an earlier failure: only the outcome ends that wait.
25
+ run_live = (batch.get("latestRun") or {}).get("status") in ("queued", "running")
26
+ return (
27
+ batch.get("processingOutcome") is not None
28
+ or (batch.get("failure") is not None and not run_live)
29
+ or bool(batch.get("processingRefused"))
30
+ or bool(batch.get("withoutProcessing"))
31
+ )
32
+
33
+
34
+ def _failed(batch: dict[str, Any]) -> bool:
35
+ return bool(batch.get("failure") or batch.get("processingRefused") or batch.get("processingOutcome") in ("failed", "cancelled"))
36
+
37
+
38
+ def wait_for_batch(
39
+ client: EmbodiFlowClient,
40
+ batch_id: str,
41
+ *,
42
+ project: str,
43
+ timeout: float = BATCH_WAIT_TIMEOUT_SECONDS,
44
+ poll_seconds: float = 5.0,
45
+ sleep: Callable[[float], None] = time.sleep,
46
+ on_progress: Callable[[dict[str, Any]], None] | None = None,
47
+ on_note: Callable[[str], None] | None = None,
48
+ started_at: float | None = None,
49
+ clock: Callable[[], float] | None = None,
50
+ ) -> dict[str, Any]:
51
+ """Poll ``batch_id`` of ``project`` until its processing ended; return how it ended.
52
+
53
+ Raises :class:`EmbodiFlowApiError` ``UPLOAD_PROCESSING_FAILED`` when processing
54
+ failed, was refused or was cancelled, and :class:`embodiflow._poll.WaitTimeoutError`
55
+ (a :class:`TimeoutError`) after ``timeout`` seconds (the platform keeps processing).
56
+ A dropped connection or a 408 / 429 / 5xx answer never ends the wait.
57
+ ``started_at`` (a ``clock`` reading) says when the wait the caller asked for
58
+ began, when part of it went before this one: ``timeout`` counts from there.
59
+ """
60
+
61
+ def result_of(batch: dict[str, Any]) -> dict[str, Any]:
62
+ return {
63
+ "batchId": batch_id,
64
+ "status": batch.get("status"),
65
+ "processedAt": batch.get("processedAt"),
66
+ "processingOutcome": batch.get("processingOutcome"),
67
+ "failure": batch.get("failure"),
68
+ "processingRefused": batch.get("processingRefused"),
69
+ }
70
+
71
+ def failure(batch: dict[str, Any]) -> EmbodiFlowApiError:
72
+ refused = batch.get("processingRefused")
73
+ if refused:
74
+ ending = f"was refused ({refused.get('code')})"
75
+ elif batch.get("processingOutcome") == "cancelled":
76
+ ending = "was cancelled"
77
+ else:
78
+ ending = f"failed ({(batch.get('failure') or {}).get('code') or 'unknown'})"
79
+ return EmbodiFlowApiError(
80
+ 422,
81
+ cast(SdkErrorCode, "UPLOAD_PROCESSING_FAILED"),
82
+ f"Batch {batch_id} was uploaded but processing {ending}",
83
+ details=result_of(batch),
84
+ )
85
+
86
+ def progress(batch: dict[str, Any]) -> None:
87
+ if on_progress is not None and not _done(batch):
88
+ on_progress(batch)
89
+
90
+ batch = poll_until(
91
+ what=f"batch {batch_id}",
92
+ resume=f"embodiflow.recordings.follow_batch({project!r}, {batch_id!r})",
93
+ describe=lambda _b: "processing",
94
+ continues="the upload itself is complete and processing goes on without this call",
95
+ probe=lambda: client._request("GET", f"/v1/upload-batches/{batch_id}")["data"],
96
+ is_success=lambda b: _done(b) and not _failed(b),
97
+ is_failure=lambda b: _done(b) and _failed(b),
98
+ failure=failure,
99
+ on_progress=progress,
100
+ on_note=on_note,
101
+ timeout=timeout,
102
+ started_at=started_at,
103
+ interval=poll_seconds,
104
+ sleep=sleep,
105
+ clock=clock,
106
+ )
107
+ return result_of(batch)