sunfield 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.
- sunfield-0.1.0/.gitignore +11 -0
- sunfield-0.1.0/PKG-INFO +59 -0
- sunfield-0.1.0/README.md +31 -0
- sunfield-0.1.0/pyproject.toml +66 -0
- sunfield-0.1.0/sunfield/__init__.py +19 -0
- sunfield-0.1.0/sunfield/client.py +481 -0
- sunfield-0.1.0/sunfield/models.py +160 -0
sunfield-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: sunfield
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Official Python SDK for Sunfield — stateful headless Blender sandboxes and elastic Cycles OptiX GPU burst for AI agents
|
|
5
|
+
Project-URL: Homepage, https://sunfield.dev
|
|
6
|
+
Project-URL: Repository, https://github.com/Strange-Metal/sunfield-sdk
|
|
7
|
+
Project-URL: Documentation, https://sunfield.dev/skill.md
|
|
8
|
+
Project-URL: API Reference, https://sunfield.dev/docs
|
|
9
|
+
Project-URL: Remote MCP, https://sunfield.dev/mcp-server
|
|
10
|
+
Author-email: "Strange Metal, Inc." <contact@strangemetal.org>
|
|
11
|
+
License: MIT
|
|
12
|
+
Keywords: 3d-sandbox,ai-agents,blender,bpy,cycles,headless-blender,mcp,optix,rendering-api,synthetic-data
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Topic :: Multimedia :: Graphics :: 3D Rendering
|
|
19
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
20
|
+
Requires-Python: >=3.11
|
|
21
|
+
Requires-Dist: httpx>=0.27.0
|
|
22
|
+
Requires-Dist: pydantic>=2.9.0
|
|
23
|
+
Provides-Extra: dev
|
|
24
|
+
Requires-Dist: pytest-asyncio>=0.24.0; extra == 'dev'
|
|
25
|
+
Requires-Dist: pytest>=8.3.0; extra == 'dev'
|
|
26
|
+
Requires-Dist: ruff>=0.7.0; extra == 'dev'
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
|
|
29
|
+
# `sunfield` — Python SDK for Sunfield Headless Blender GPU Sandboxes
|
|
30
|
+
|
|
31
|
+
Official Python SDK for [Sunfield](https://sunfield.dev) — warm, isolated headless Blender 4.5 GPU sandboxes (`--network=none`), sub-second multi-view visual & `BVHTree` spatial inspection, 149 CC0 Poly Haven assets, `tmpfs` scene forking, and elastic Cycles OptiX burst rendering behind hard `max_cost_usd` caps.
|
|
32
|
+
|
|
33
|
+
## Quickstart
|
|
34
|
+
|
|
35
|
+
Claim **$1.00 in free GPU credits** (no credit card required) at [sunfield.dev/start](https://sunfield.dev/start).
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pip install sunfield
|
|
39
|
+
export SUNFIELD_API_KEY="sunfield_sk_..."
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
import os
|
|
44
|
+
from sunfield import Sunfield
|
|
45
|
+
|
|
46
|
+
with Sunfield(api_key=os.environ["SUNFIELD_API_KEY"]) as sf:
|
|
47
|
+
with sf.sessions.create(preset="studio") as s:
|
|
48
|
+
s.stage_assets(["hdri.brown_photostudio_01"])
|
|
49
|
+
s.exec("load_hdri('assets/hdri.brown_photostudio_01/brown_photostudio_01_2k.hdr', strength=1.2)")
|
|
50
|
+
check = s.inspect(views=["camera", "iso_3q"], passes=["rgb", "depth", "normals"])
|
|
51
|
+
render = s.render(engine="cycles", samples=64, resolution=(1920, 1080), max_cost_usd=0.05)
|
|
52
|
+
render.save_all(sf, "./outputs/hero")
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Links
|
|
56
|
+
- Documentation & Agent Skill: [sunfield.dev/skill.md](https://sunfield.dev/skill.md)
|
|
57
|
+
- Hosted Remote MCP (`https://sunfield.dev/mcp`): [sunfield.dev/mcp-server](https://sunfield.dev/mcp-server)
|
|
58
|
+
- Pricing & Estimator: [sunfield.dev/pricing](https://sunfield.dev/pricing)
|
|
59
|
+
- Examples & SunfieldBench: [github.com/Strange-Metal/sunfield-sdk](https://github.com/Strange-Metal/sunfield-sdk)
|
sunfield-0.1.0/README.md
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# `sunfield` — Python SDK for Sunfield Headless Blender GPU Sandboxes
|
|
2
|
+
|
|
3
|
+
Official Python SDK for [Sunfield](https://sunfield.dev) — warm, isolated headless Blender 4.5 GPU sandboxes (`--network=none`), sub-second multi-view visual & `BVHTree` spatial inspection, 149 CC0 Poly Haven assets, `tmpfs` scene forking, and elastic Cycles OptiX burst rendering behind hard `max_cost_usd` caps.
|
|
4
|
+
|
|
5
|
+
## Quickstart
|
|
6
|
+
|
|
7
|
+
Claim **$1.00 in free GPU credits** (no credit card required) at [sunfield.dev/start](https://sunfield.dev/start).
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pip install sunfield
|
|
11
|
+
export SUNFIELD_API_KEY="sunfield_sk_..."
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
```python
|
|
15
|
+
import os
|
|
16
|
+
from sunfield import Sunfield
|
|
17
|
+
|
|
18
|
+
with Sunfield(api_key=os.environ["SUNFIELD_API_KEY"]) as sf:
|
|
19
|
+
with sf.sessions.create(preset="studio") as s:
|
|
20
|
+
s.stage_assets(["hdri.brown_photostudio_01"])
|
|
21
|
+
s.exec("load_hdri('assets/hdri.brown_photostudio_01/brown_photostudio_01_2k.hdr', strength=1.2)")
|
|
22
|
+
check = s.inspect(views=["camera", "iso_3q"], passes=["rgb", "depth", "normals"])
|
|
23
|
+
render = s.render(engine="cycles", samples=64, resolution=(1920, 1080), max_cost_usd=0.05)
|
|
24
|
+
render.save_all(sf, "./outputs/hero")
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Links
|
|
28
|
+
- Documentation & Agent Skill: [sunfield.dev/skill.md](https://sunfield.dev/skill.md)
|
|
29
|
+
- Hosted Remote MCP (`https://sunfield.dev/mcp`): [sunfield.dev/mcp-server](https://sunfield.dev/mcp-server)
|
|
30
|
+
- Pricing & Estimator: [sunfield.dev/pricing](https://sunfield.dev/pricing)
|
|
31
|
+
- Examples & SunfieldBench: [github.com/Strange-Metal/sunfield-sdk](https://github.com/Strange-Metal/sunfield-sdk)
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "sunfield"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Official Python SDK for Sunfield — stateful headless Blender sandboxes and elastic Cycles OptiX GPU burst for AI agents"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.11"
|
|
11
|
+
license = {text = "MIT"}
|
|
12
|
+
authors = [{name = "Strange Metal, Inc.", email = "contact@strangemetal.org"}]
|
|
13
|
+
keywords = [
|
|
14
|
+
"blender",
|
|
15
|
+
"bpy",
|
|
16
|
+
"headless-blender",
|
|
17
|
+
"cycles",
|
|
18
|
+
"optix",
|
|
19
|
+
"ai-agents",
|
|
20
|
+
"3d-sandbox",
|
|
21
|
+
"synthetic-data",
|
|
22
|
+
"rendering-api",
|
|
23
|
+
"mcp",
|
|
24
|
+
]
|
|
25
|
+
classifiers = [
|
|
26
|
+
"Development Status :: 4 - Beta",
|
|
27
|
+
"Intended Audience :: Developers",
|
|
28
|
+
"Programming Language :: Python :: 3.11",
|
|
29
|
+
"Programming Language :: Python :: 3.12",
|
|
30
|
+
"Programming Language :: Python :: 3.13",
|
|
31
|
+
"Topic :: Multimedia :: Graphics :: 3D Rendering",
|
|
32
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
33
|
+
]
|
|
34
|
+
dependencies = [
|
|
35
|
+
"httpx>=0.27.0",
|
|
36
|
+
"pydantic>=2.9.0",
|
|
37
|
+
]
|
|
38
|
+
|
|
39
|
+
[project.urls]
|
|
40
|
+
Homepage = "https://sunfield.dev"
|
|
41
|
+
Repository = "https://github.com/Strange-Metal/sunfield-sdk"
|
|
42
|
+
Documentation = "https://sunfield.dev/skill.md"
|
|
43
|
+
"API Reference" = "https://sunfield.dev/docs"
|
|
44
|
+
"Remote MCP" = "https://sunfield.dev/mcp-server"
|
|
45
|
+
|
|
46
|
+
[project.optional-dependencies]
|
|
47
|
+
dev = [
|
|
48
|
+
"pytest>=8.3.0",
|
|
49
|
+
"pytest-asyncio>=0.24.0",
|
|
50
|
+
"ruff>=0.7.0",
|
|
51
|
+
]
|
|
52
|
+
|
|
53
|
+
[tool.hatch.build.targets.wheel]
|
|
54
|
+
packages = ["sunfield"]
|
|
55
|
+
|
|
56
|
+
[tool.pytest.ini_options]
|
|
57
|
+
testpaths = ["tests"]
|
|
58
|
+
addopts = "-v"
|
|
59
|
+
asyncio_default_fixture_loop_scope = "function"
|
|
60
|
+
|
|
61
|
+
[tool.ruff]
|
|
62
|
+
line-length = 120
|
|
63
|
+
target-version = "py311"
|
|
64
|
+
|
|
65
|
+
[tool.ruff.lint]
|
|
66
|
+
select = ["E4", "E7", "E9", "F", "I", "UP"]
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""Sunfield Python SDK — E2B / Browserbase for Blender."""
|
|
2
|
+
|
|
3
|
+
from .client import InsufficientCreditsError, Session, Sunfield, SunfieldError
|
|
4
|
+
from .models import Artifact, Balance, ExecResult, InspectResult, RenderResult, SessionFile, StashItem
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
"Artifact",
|
|
8
|
+
"Balance",
|
|
9
|
+
"Sunfield",
|
|
10
|
+
"SunfieldError",
|
|
11
|
+
"ExecResult",
|
|
12
|
+
"InspectResult",
|
|
13
|
+
"InsufficientCreditsError",
|
|
14
|
+
"RenderResult",
|
|
15
|
+
"Session",
|
|
16
|
+
"SessionFile",
|
|
17
|
+
"StashItem",
|
|
18
|
+
]
|
|
19
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,481 @@
|
|
|
1
|
+
"""Ergonomic Python client for the Sunfield Control Plane API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import time
|
|
8
|
+
from collections.abc import Callable
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any
|
|
11
|
+
from urllib.parse import quote
|
|
12
|
+
|
|
13
|
+
import httpx
|
|
14
|
+
|
|
15
|
+
from .models import Balance, ExecResult, InspectResult, RenderResult, SessionFile, StashItem
|
|
16
|
+
|
|
17
|
+
_SAFE_ID_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _safe_id(raw: str, label: str) -> str:
|
|
21
|
+
val = str(raw or "").strip()
|
|
22
|
+
if not _SAFE_ID_RE.match(val):
|
|
23
|
+
raise ValueError(f"Invalid {label}: {raw!r}")
|
|
24
|
+
return quote(val, safe="")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _safe_rel_path(raw: str, label: str) -> str:
|
|
28
|
+
val = str(raw or "").strip().lstrip("/")
|
|
29
|
+
if not val or ".." in val.split("/") or "\\" in val:
|
|
30
|
+
raise ValueError(f"Invalid {label}: {raw!r}")
|
|
31
|
+
return quote(val, safe="/")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class SunfieldError(RuntimeError):
|
|
35
|
+
def __init__(self, status_code: int, detail: str) -> None:
|
|
36
|
+
self.status_code = status_code
|
|
37
|
+
self.detail = detail
|
|
38
|
+
super().__init__(f"Sunfield API error ({status_code}): {detail}")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class InsufficientCreditsError(SunfieldError):
|
|
42
|
+
"""Raised when the account balance cannot cover the requested pre-auth hold (HTTP 402)."""
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class Session:
|
|
46
|
+
"""Handle to a warm, stateful headless Blender sandbox session."""
|
|
47
|
+
|
|
48
|
+
def __init__(self, client: Sunfield, session_id: str, worker_id: str = "", preset: str = "studio") -> None:
|
|
49
|
+
self._client = client
|
|
50
|
+
self.session_id = _safe_id(session_id, "session_id")
|
|
51
|
+
self.worker_id = worker_id
|
|
52
|
+
self.preset = preset
|
|
53
|
+
self._closed = False
|
|
54
|
+
|
|
55
|
+
def __enter__(self) -> Session:
|
|
56
|
+
return self
|
|
57
|
+
|
|
58
|
+
def __exit__(self, *args: object) -> None:
|
|
59
|
+
if not self._closed:
|
|
60
|
+
self.close()
|
|
61
|
+
|
|
62
|
+
def exec(self, code: str, *, timeout_s: float = 30.0, checkpoint: bool = True) -> ExecResult:
|
|
63
|
+
data = self._client._request(
|
|
64
|
+
"POST",
|
|
65
|
+
f"/v1/sessions/{self.session_id}/exec",
|
|
66
|
+
json={"code": code, "timeout_s": timeout_s, "checkpoint": checkpoint},
|
|
67
|
+
timeout=timeout_s + 25.0,
|
|
68
|
+
)
|
|
69
|
+
return ExecResult.model_validate(data)
|
|
70
|
+
|
|
71
|
+
def inspect(
|
|
72
|
+
self,
|
|
73
|
+
*,
|
|
74
|
+
views: list[str] | None = None,
|
|
75
|
+
passes: list[str] | None = None,
|
|
76
|
+
resolution: tuple[int, int] = (512, 512),
|
|
77
|
+
checks: list[str] | None = None,
|
|
78
|
+
engine: str = "eevee",
|
|
79
|
+
cycles_samples: int = 16,
|
|
80
|
+
summary_only: bool = False,
|
|
81
|
+
max_objects: int = 50,
|
|
82
|
+
timeout_s: float = 60.0,
|
|
83
|
+
) -> InspectResult:
|
|
84
|
+
payload: dict[str, Any] = {
|
|
85
|
+
"views": views or ["camera", "iso_3q"],
|
|
86
|
+
"passes": passes or ["rgb"],
|
|
87
|
+
"resolution": list(resolution),
|
|
88
|
+
"checks": checks or ["bounds", "framing", "collisions", "floating"],
|
|
89
|
+
"engine": engine,
|
|
90
|
+
"cycles_samples": cycles_samples,
|
|
91
|
+
"summary_only": summary_only,
|
|
92
|
+
"max_objects": max_objects,
|
|
93
|
+
"timeout_s": timeout_s,
|
|
94
|
+
}
|
|
95
|
+
data = self._client._request(
|
|
96
|
+
"POST",
|
|
97
|
+
f"/v1/sessions/{self.session_id}/inspect",
|
|
98
|
+
json=payload,
|
|
99
|
+
timeout=timeout_s + 25.0,
|
|
100
|
+
)
|
|
101
|
+
return InspectResult.model_validate(data)
|
|
102
|
+
|
|
103
|
+
def upload_file(self, local_path: str | Path, filename: str | None = None) -> SessionFile:
|
|
104
|
+
path = Path(local_path)
|
|
105
|
+
fname = filename or path.name
|
|
106
|
+
with path.open("rb") as fh:
|
|
107
|
+
resp = self._client._http.post(
|
|
108
|
+
f"/v1/sessions/{self.session_id}/files",
|
|
109
|
+
headers={"Authorization": f"Bearer {self._client.api_key}"},
|
|
110
|
+
files={"file": (fname, fh, "application/octet-stream")},
|
|
111
|
+
data={"filename": fname},
|
|
112
|
+
timeout=180.0,
|
|
113
|
+
)
|
|
114
|
+
if resp.status_code >= 400:
|
|
115
|
+
raise SunfieldError(resp.status_code, resp.text)
|
|
116
|
+
return SessionFile.model_validate(resp.json())
|
|
117
|
+
|
|
118
|
+
def list_files(self) -> list[SessionFile]:
|
|
119
|
+
rows = self._client._request("GET", f"/v1/sessions/{self.session_id}/files")
|
|
120
|
+
return [SessionFile.model_validate(r) for r in rows]
|
|
121
|
+
|
|
122
|
+
def delete_file(self, filename: str) -> dict[str, Any]:
|
|
123
|
+
safe_name = _safe_rel_path(filename, "filename")
|
|
124
|
+
return self._client._request("DELETE", f"/v1/sessions/{self.session_id}/files/{safe_name}")
|
|
125
|
+
|
|
126
|
+
def export(self, dest: str | Path | None = None, *, format: str = "blend", timeout_s: float = 120.0) -> bytes | Path:
|
|
127
|
+
if format not in {"blend", "glb"}:
|
|
128
|
+
raise ValueError(f"Unsupported export format: {format!r}")
|
|
129
|
+
resp = self._client._http.get(
|
|
130
|
+
f"/v1/sessions/{self.session_id}/export",
|
|
131
|
+
params={"format": format},
|
|
132
|
+
headers={"Authorization": f"Bearer {self._client.api_key}"},
|
|
133
|
+
timeout=timeout_s,
|
|
134
|
+
)
|
|
135
|
+
if resp.status_code >= 400:
|
|
136
|
+
raise SunfieldError(resp.status_code, resp.text)
|
|
137
|
+
if dest is not None:
|
|
138
|
+
out = Path(dest)
|
|
139
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
140
|
+
out.write_bytes(resp.content)
|
|
141
|
+
return out
|
|
142
|
+
return resp.content
|
|
143
|
+
|
|
144
|
+
def save_checkpoint(self, name: str) -> dict[str, Any]:
|
|
145
|
+
return self._client._request(
|
|
146
|
+
"POST",
|
|
147
|
+
f"/v1/sessions/{self.session_id}/checkpoints",
|
|
148
|
+
json={"name": name},
|
|
149
|
+
timeout=45.0,
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
def list_checkpoints(self) -> list[dict[str, Any]]:
|
|
153
|
+
res = self._client._request("GET", f"/v1/sessions/{self.session_id}/checkpoints")
|
|
154
|
+
return list(res.get("checkpoints", [])) if isinstance(res, dict) else list(res)
|
|
155
|
+
|
|
156
|
+
def restore_checkpoint(self, name: str) -> dict[str, Any]:
|
|
157
|
+
safe_name = _safe_id(name, "checkpoint name")
|
|
158
|
+
return self._client._request(
|
|
159
|
+
"POST",
|
|
160
|
+
f"/v1/sessions/{self.session_id}/checkpoints/{safe_name}/restore",
|
|
161
|
+
timeout=45.0,
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
def stage_assets(self, asset_ids: list[str]) -> dict[str, Any]:
|
|
165
|
+
return self._client._request(
|
|
166
|
+
"POST",
|
|
167
|
+
f"/v1/sessions/{self.session_id}/assets",
|
|
168
|
+
json={"asset_ids": list(asset_ids)},
|
|
169
|
+
timeout=120.0,
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
def stash(self, name: str, *, format: str = "blend", timeout_s: float = 120.0) -> StashItem:
|
|
173
|
+
data = self._client._request(
|
|
174
|
+
"POST",
|
|
175
|
+
f"/v1/sessions/{self.session_id}/stash",
|
|
176
|
+
json={"name": name, "format": format},
|
|
177
|
+
timeout=timeout_s,
|
|
178
|
+
)
|
|
179
|
+
return StashItem.model_validate(data)
|
|
180
|
+
|
|
181
|
+
def mount_stash(self, names: list[str], *, timeout_s: float = 180.0) -> list[SessionFile]:
|
|
182
|
+
data = self._client._request(
|
|
183
|
+
"POST",
|
|
184
|
+
f"/v1/sessions/{self.session_id}/stash/mount",
|
|
185
|
+
json={"names": list(names)},
|
|
186
|
+
timeout=timeout_s,
|
|
187
|
+
)
|
|
188
|
+
return [SessionFile.model_validate(f) for f in data.get("files", [])]
|
|
189
|
+
|
|
190
|
+
def fork(self, count: int = 1) -> list[Session]:
|
|
191
|
+
data = self._client._request(
|
|
192
|
+
"POST",
|
|
193
|
+
f"/v1/sessions/{self.session_id}/fork",
|
|
194
|
+
json={"count": count},
|
|
195
|
+
timeout=65.0,
|
|
196
|
+
)
|
|
197
|
+
return [
|
|
198
|
+
Session(self._client, sid, worker_id=self.worker_id, preset=self.preset)
|
|
199
|
+
for sid in data.get("session_ids", [])
|
|
200
|
+
]
|
|
201
|
+
|
|
202
|
+
def estimate_render(
|
|
203
|
+
self,
|
|
204
|
+
*,
|
|
205
|
+
engine: str = "cycles",
|
|
206
|
+
samples: int = 64,
|
|
207
|
+
resolution: tuple[int, int] = (1024, 1024),
|
|
208
|
+
frames: list[int] | None = None,
|
|
209
|
+
probe_samples: int = 8,
|
|
210
|
+
max_cost_usd: float = 1.0,
|
|
211
|
+
timeout_s: float = 120.0,
|
|
212
|
+
) -> dict[str, Any]:
|
|
213
|
+
return self._client._request(
|
|
214
|
+
"POST",
|
|
215
|
+
f"/v1/sessions/{self.session_id}/render/estimate",
|
|
216
|
+
json={
|
|
217
|
+
"engine": engine,
|
|
218
|
+
"samples": samples,
|
|
219
|
+
"resolution": list(resolution),
|
|
220
|
+
"frames": frames or [1],
|
|
221
|
+
"probe_samples": probe_samples,
|
|
222
|
+
"max_cost_usd": max_cost_usd,
|
|
223
|
+
"timeout_s": timeout_s,
|
|
224
|
+
},
|
|
225
|
+
timeout=timeout_s + 25.0,
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
def render(
|
|
229
|
+
self,
|
|
230
|
+
*,
|
|
231
|
+
engine: str = "cycles",
|
|
232
|
+
samples: int = 64,
|
|
233
|
+
resolution: tuple[int, int] = (1024, 1024),
|
|
234
|
+
frames: list[int] | None = None,
|
|
235
|
+
aov_passes: list[str] | None = None,
|
|
236
|
+
use_denoising: bool = True,
|
|
237
|
+
max_cost_usd: float = 1.0,
|
|
238
|
+
probe_samples: int = 8,
|
|
239
|
+
timeout_s: float = 300.0,
|
|
240
|
+
async_mode: bool = False,
|
|
241
|
+
) -> RenderResult:
|
|
242
|
+
payload = {
|
|
243
|
+
"engine": engine,
|
|
244
|
+
"samples": samples,
|
|
245
|
+
"resolution": list(resolution),
|
|
246
|
+
"frames": frames or [1],
|
|
247
|
+
"aov_passes": aov_passes or ["rgb"],
|
|
248
|
+
"use_denoising": use_denoising,
|
|
249
|
+
"max_cost_usd": max_cost_usd,
|
|
250
|
+
"probe_samples": probe_samples,
|
|
251
|
+
"timeout_s": timeout_s,
|
|
252
|
+
"async": async_mode,
|
|
253
|
+
}
|
|
254
|
+
req_timeout = 60.0 if async_mode else (timeout_s + 35.0)
|
|
255
|
+
data = self._client._request(
|
|
256
|
+
"POST",
|
|
257
|
+
f"/v1/sessions/{self.session_id}/render",
|
|
258
|
+
json=payload,
|
|
259
|
+
timeout=req_timeout,
|
|
260
|
+
)
|
|
261
|
+
return RenderResult.model_validate(data)
|
|
262
|
+
|
|
263
|
+
def close(self) -> dict[str, Any]:
|
|
264
|
+
if self._closed:
|
|
265
|
+
return {"ok": True, "session_id": self.session_id}
|
|
266
|
+
self._closed = True
|
|
267
|
+
return self._client._request("DELETE", f"/v1/sessions/{self.session_id}")
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
class _SessionsResource:
|
|
271
|
+
def __init__(self, client: Sunfield) -> None:
|
|
272
|
+
self._client = client
|
|
273
|
+
|
|
274
|
+
def create(self, *, preset: str = "studio", pool: str = "interactive") -> Session:
|
|
275
|
+
data = self._client._request(
|
|
276
|
+
"POST",
|
|
277
|
+
"/v1/sessions",
|
|
278
|
+
json={"preset": preset, "pool": pool},
|
|
279
|
+
timeout=60.0,
|
|
280
|
+
)
|
|
281
|
+
return Session(
|
|
282
|
+
self._client,
|
|
283
|
+
session_id=data["session_id"],
|
|
284
|
+
worker_id=data.get("worker_id", ""),
|
|
285
|
+
preset=data.get("preset", preset),
|
|
286
|
+
)
|
|
287
|
+
|
|
288
|
+
def list(self) -> list[dict[str, Any]]:
|
|
289
|
+
return self._client._request("GET", "/v1/sessions")
|
|
290
|
+
|
|
291
|
+
def get(self, session_id: str) -> Session:
|
|
292
|
+
return Session(self._client, session_id=session_id)
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
class Sunfield:
|
|
296
|
+
"""Main Sunfield SDK client."""
|
|
297
|
+
|
|
298
|
+
def __init__(
|
|
299
|
+
self,
|
|
300
|
+
api_key: str | None = None,
|
|
301
|
+
base_url: str | None = None,
|
|
302
|
+
timeout: float = 60.0,
|
|
303
|
+
http_client: httpx.Client | None = None,
|
|
304
|
+
) -> None:
|
|
305
|
+
self.api_key = api_key or os.environ.get("SUNFIELD_API_KEY", "")
|
|
306
|
+
self.base_url = (base_url or os.environ.get("SUNFIELD_BASE_URL", "https://sunfield.dev")).rstrip("/")
|
|
307
|
+
if not self.api_key:
|
|
308
|
+
raise ValueError("Missing Sunfield API key. Pass api_key=... or set SUNFIELD_API_KEY.")
|
|
309
|
+
|
|
310
|
+
self._owns_client = http_client is None
|
|
311
|
+
self._http = http_client or httpx.Client(
|
|
312
|
+
base_url=self.base_url,
|
|
313
|
+
headers={"Authorization": f"Bearer {self.api_key}"},
|
|
314
|
+
timeout=timeout,
|
|
315
|
+
)
|
|
316
|
+
self.sessions = _SessionsResource(self)
|
|
317
|
+
|
|
318
|
+
def __enter__(self) -> Sunfield:
|
|
319
|
+
return self
|
|
320
|
+
|
|
321
|
+
def __exit__(self, *args: object) -> None:
|
|
322
|
+
self.close()
|
|
323
|
+
|
|
324
|
+
def close(self) -> None:
|
|
325
|
+
if self._owns_client:
|
|
326
|
+
self._http.close()
|
|
327
|
+
|
|
328
|
+
def _request(self, method: str, path: str, **kwargs: Any) -> Any:
|
|
329
|
+
headers = dict(kwargs.pop("headers", {}))
|
|
330
|
+
headers.setdefault("Authorization", f"Bearer {self.api_key}")
|
|
331
|
+
resp = self._http.request(method, path, headers=headers, **kwargs)
|
|
332
|
+
if resp.status_code >= 400:
|
|
333
|
+
try:
|
|
334
|
+
detail = resp.json().get("detail", resp.text)
|
|
335
|
+
except Exception:
|
|
336
|
+
detail = resp.text
|
|
337
|
+
if resp.status_code == 402:
|
|
338
|
+
raise InsufficientCreditsError(resp.status_code, str(detail))
|
|
339
|
+
raise SunfieldError(resp.status_code, str(detail))
|
|
340
|
+
return resp.json()
|
|
341
|
+
|
|
342
|
+
def health(self) -> dict[str, Any]:
|
|
343
|
+
resp = self._http.get("/health")
|
|
344
|
+
resp.raise_for_status()
|
|
345
|
+
return resp.json()
|
|
346
|
+
|
|
347
|
+
def balance(self) -> Balance:
|
|
348
|
+
return Balance.model_validate(self._request("GET", "/v1/account/balance"))
|
|
349
|
+
|
|
350
|
+
def search_assets(
|
|
351
|
+
self,
|
|
352
|
+
q: str | None = None,
|
|
353
|
+
*,
|
|
354
|
+
kind: str | None = None,
|
|
355
|
+
category: str | None = None,
|
|
356
|
+
limit: int = 12,
|
|
357
|
+
) -> dict[str, Any]:
|
|
358
|
+
params: dict[str, Any] = {"limit": limit}
|
|
359
|
+
if q:
|
|
360
|
+
params["q"] = q
|
|
361
|
+
if kind:
|
|
362
|
+
params["kind"] = kind
|
|
363
|
+
if category:
|
|
364
|
+
params["category"] = category
|
|
365
|
+
return self._request("GET", "/v1/assets/search", params=params)
|
|
366
|
+
|
|
367
|
+
def list_stash(self) -> list[StashItem]:
|
|
368
|
+
rows = self._request("GET", "/v1/stash")
|
|
369
|
+
return [StashItem.model_validate(r) for r in rows]
|
|
370
|
+
|
|
371
|
+
def delete_stash(self, name: str) -> dict[str, Any]:
|
|
372
|
+
safe_name = _safe_rel_path(name, "stash name")
|
|
373
|
+
return self._request("DELETE", f"/v1/stash/{safe_name}")
|
|
374
|
+
|
|
375
|
+
def get_job(self, job_id: str) -> RenderResult:
|
|
376
|
+
safe_jid = _safe_id(job_id, "job_id")
|
|
377
|
+
return RenderResult.model_validate(self._request("GET", f"/v1/jobs/{safe_jid}"))
|
|
378
|
+
|
|
379
|
+
def cancel_job(self, job_id: str) -> dict[str, Any]:
|
|
380
|
+
safe_jid = _safe_id(job_id, "job_id")
|
|
381
|
+
return self._request("DELETE", f"/v1/jobs/{safe_jid}")
|
|
382
|
+
|
|
383
|
+
def wait_for_job(
|
|
384
|
+
self,
|
|
385
|
+
job_id: str,
|
|
386
|
+
*,
|
|
387
|
+
poll_interval_s: float = 2.0,
|
|
388
|
+
timeout_s: float = 3600.0,
|
|
389
|
+
max_transient_errors: int = 8,
|
|
390
|
+
on_progress: Callable[[RenderResult], None] | None = None,
|
|
391
|
+
) -> RenderResult:
|
|
392
|
+
deadline = time.monotonic() + timeout_s
|
|
393
|
+
consecutive_errors = 0
|
|
394
|
+
while True:
|
|
395
|
+
try:
|
|
396
|
+
res = self.get_job(job_id)
|
|
397
|
+
consecutive_errors = 0
|
|
398
|
+
except (httpx.TimeoutException, httpx.TransportError) as exc:
|
|
399
|
+
consecutive_errors += 1
|
|
400
|
+
if consecutive_errors > max_transient_errors or time.monotonic() >= deadline:
|
|
401
|
+
raise exc
|
|
402
|
+
time.sleep(min(poll_interval_s * (2 ** min(consecutive_errors - 1, 3)), 15.0))
|
|
403
|
+
continue
|
|
404
|
+
except SunfieldError as exc:
|
|
405
|
+
if exc.status_code not in (429, 502, 503, 504):
|
|
406
|
+
raise
|
|
407
|
+
consecutive_errors += 1
|
|
408
|
+
if consecutive_errors > max_transient_errors or time.monotonic() >= deadline:
|
|
409
|
+
raise
|
|
410
|
+
time.sleep(min(poll_interval_s * (2 ** min(consecutive_errors - 1, 3)), 15.0))
|
|
411
|
+
continue
|
|
412
|
+
|
|
413
|
+
if on_progress is not None:
|
|
414
|
+
on_progress(res)
|
|
415
|
+
if res.status not in {"running", "queued", "pending"}:
|
|
416
|
+
return res
|
|
417
|
+
if time.monotonic() >= deadline:
|
|
418
|
+
raise TimeoutError(f"Render job {job_id} still {res.status} after {timeout_s:.1f}s")
|
|
419
|
+
time.sleep(poll_interval_s)
|
|
420
|
+
|
|
421
|
+
def download_artifact(self, artifact_id: str) -> bytes:
|
|
422
|
+
safe_aid = _safe_id(artifact_id, "artifact_id")
|
|
423
|
+
resp = self._http.get(
|
|
424
|
+
f"/v1/artifacts/{safe_aid}",
|
|
425
|
+
headers={"Authorization": f"Bearer {self.api_key}"},
|
|
426
|
+
)
|
|
427
|
+
if resp.status_code >= 400:
|
|
428
|
+
raise SunfieldError(resp.status_code, resp.text)
|
|
429
|
+
return resp.content
|
|
430
|
+
|
|
431
|
+
def save_artifact(self, artifact_id: str, dest: str | Path) -> Path:
|
|
432
|
+
path = Path(dest)
|
|
433
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
434
|
+
path.write_bytes(self.download_artifact(artifact_id))
|
|
435
|
+
return path
|
|
436
|
+
|
|
437
|
+
def download_job_archive(
|
|
438
|
+
self,
|
|
439
|
+
job_id: str,
|
|
440
|
+
dest: str | Path,
|
|
441
|
+
*,
|
|
442
|
+
pass_name: str | None = None,
|
|
443
|
+
timeout_s: float = 300.0,
|
|
444
|
+
) -> Path:
|
|
445
|
+
safe_jid = _safe_id(job_id, "job_id")
|
|
446
|
+
params = {"pass_name": pass_name} if pass_name else None
|
|
447
|
+
resp = self._http.get(
|
|
448
|
+
f"/v1/jobs/{safe_jid}/archive.zip",
|
|
449
|
+
params=params,
|
|
450
|
+
headers={"Authorization": f"Bearer {self.api_key}"},
|
|
451
|
+
timeout=timeout_s,
|
|
452
|
+
)
|
|
453
|
+
if resp.status_code >= 400:
|
|
454
|
+
raise SunfieldError(resp.status_code, resp.text)
|
|
455
|
+
out = Path(dest)
|
|
456
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
457
|
+
out.write_bytes(resp.content)
|
|
458
|
+
return out
|
|
459
|
+
|
|
460
|
+
def download_job_video(
|
|
461
|
+
self,
|
|
462
|
+
job_id: str,
|
|
463
|
+
dest: str | Path,
|
|
464
|
+
*,
|
|
465
|
+
fps: int = 24,
|
|
466
|
+
crf: int = 18,
|
|
467
|
+
timeout_s: float = 300.0,
|
|
468
|
+
) -> Path:
|
|
469
|
+
safe_jid = _safe_id(job_id, "job_id")
|
|
470
|
+
resp = self._http.get(
|
|
471
|
+
f"/v1/jobs/{safe_jid}/video.mp4",
|
|
472
|
+
params={"fps": fps, "crf": crf},
|
|
473
|
+
headers={"Authorization": f"Bearer {self.api_key}"},
|
|
474
|
+
timeout=timeout_s,
|
|
475
|
+
)
|
|
476
|
+
if resp.status_code >= 400:
|
|
477
|
+
raise SunfieldError(resp.status_code, resp.text)
|
|
478
|
+
out = Path(dest)
|
|
479
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
480
|
+
out.write_bytes(resp.content)
|
|
481
|
+
return out
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
"""Typed response models for the Sunfield Python SDK."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import TYPE_CHECKING, Any
|
|
9
|
+
|
|
10
|
+
from pydantic import BaseModel, Field
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from .client import Sunfield
|
|
14
|
+
|
|
15
|
+
_SAFE_FNAME_RE = re.compile(r"[^A-Za-z0-9._-]+")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _safe_artifact_dest(out_dir: Path, view_or_frame: str, pass_name: str) -> Path:
|
|
19
|
+
base = out_dir.resolve()
|
|
20
|
+
v = _SAFE_FNAME_RE.sub("_", str(view_or_frame or "frame")).strip("._-") or "frame"
|
|
21
|
+
p = _SAFE_FNAME_RE.sub("_", str(pass_name or "rgb")).strip("._-") or "rgb"
|
|
22
|
+
if ".." in v or ".." in p:
|
|
23
|
+
raise ValueError(f"Unsafe artifact filename components: {view_or_frame!r}, {pass_name!r}")
|
|
24
|
+
dest = (base / f"{v}_{p}.png").resolve()
|
|
25
|
+
if not dest.is_relative_to(base):
|
|
26
|
+
raise ValueError(f"Resolved artifact path escapes output directory: {dest}")
|
|
27
|
+
return dest
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class Balance(BaseModel):
|
|
31
|
+
account_id: str
|
|
32
|
+
balance_usd: float
|
|
33
|
+
balance_microusd: int
|
|
34
|
+
recent_entries: list[dict[str, Any]] = Field(default_factory=list)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class SceneDiff(BaseModel):
|
|
38
|
+
added: list[str] = Field(default_factory=list)
|
|
39
|
+
removed: list[str] = Field(default_factory=list)
|
|
40
|
+
modified: list[str] = Field(default_factory=list)
|
|
41
|
+
object_count: int = 0
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class ExecResult(BaseModel):
|
|
45
|
+
ok: bool
|
|
46
|
+
status: str
|
|
47
|
+
stdout: str = ""
|
|
48
|
+
stderr: str = ""
|
|
49
|
+
traceback: str | None = None
|
|
50
|
+
signal: str | None = None
|
|
51
|
+
hint: str | None = None
|
|
52
|
+
scene_diff: SceneDiff | None = None
|
|
53
|
+
duration_ms: float = 0.0
|
|
54
|
+
checkpoint_ms: float = 0.0
|
|
55
|
+
recovery_ms: float | None = None
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class Artifact(BaseModel):
|
|
59
|
+
artifact_id: str
|
|
60
|
+
view_or_frame: str
|
|
61
|
+
pass_name: str
|
|
62
|
+
url: str
|
|
63
|
+
size_bytes: int
|
|
64
|
+
kind: str = "render"
|
|
65
|
+
session_id: str | None = None
|
|
66
|
+
job_id: str | None = None
|
|
67
|
+
created_at: float | None = None
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def view(self) -> str:
|
|
71
|
+
return self.view_or_frame
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class SessionFile(BaseModel):
|
|
75
|
+
file_id: str
|
|
76
|
+
session_id: str
|
|
77
|
+
filename: str
|
|
78
|
+
worker_path: str
|
|
79
|
+
content_type: str = "application/octet-stream"
|
|
80
|
+
size_bytes: int = 0
|
|
81
|
+
sha256: str = ""
|
|
82
|
+
created_at: float = 0.0
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class StashItem(BaseModel):
|
|
86
|
+
stash_id: str
|
|
87
|
+
name: str
|
|
88
|
+
content_type: str = "application/octet-stream"
|
|
89
|
+
size_bytes: int = 0
|
|
90
|
+
sha256: str = ""
|
|
91
|
+
created_at: float = 0.0
|
|
92
|
+
updated_at: float = 0.0
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class InspectResult(BaseModel):
|
|
96
|
+
ok: bool
|
|
97
|
+
artifacts: list[Artifact] = Field(default_factory=list)
|
|
98
|
+
telemetry: dict[str, Any] | None = None
|
|
99
|
+
duration_ms: float = 0.0
|
|
100
|
+
error: str | None = None
|
|
101
|
+
|
|
102
|
+
def save_all(self, client: Sunfield, output_dir: str | Path) -> list[Path]:
|
|
103
|
+
out = Path(output_dir)
|
|
104
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
105
|
+
if not self.artifacts:
|
|
106
|
+
return []
|
|
107
|
+
targets = [(art, _safe_artifact_dest(out, art.view_or_frame, art.pass_name)) for art in self.artifacts]
|
|
108
|
+
|
|
109
|
+
def _fetch(item: tuple[Artifact, Path]) -> Path:
|
|
110
|
+
art, dest = item
|
|
111
|
+
dest.write_bytes(client.download_artifact(art.artifact_id))
|
|
112
|
+
return dest
|
|
113
|
+
|
|
114
|
+
if len(targets) == 1:
|
|
115
|
+
return [_fetch(targets[0])]
|
|
116
|
+
with ThreadPoolExecutor(max_workers=min(8, len(targets))) as pool:
|
|
117
|
+
return list(pool.map(_fetch, targets))
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class RenderResult(BaseModel):
|
|
121
|
+
job_id: str
|
|
122
|
+
ok: bool
|
|
123
|
+
status: str
|
|
124
|
+
engine: str
|
|
125
|
+
device: str = ""
|
|
126
|
+
frames_rendered: int = 0
|
|
127
|
+
probe: dict[str, Any] | None = None
|
|
128
|
+
progress: dict[str, Any] | None = None
|
|
129
|
+
artifacts: list[Artifact] = Field(default_factory=list)
|
|
130
|
+
actual_gpu_s: float = 0.0
|
|
131
|
+
actual_cost_usd: float = 0.0
|
|
132
|
+
poll_url: str | None = None
|
|
133
|
+
archive_url: str | None = None
|
|
134
|
+
video_url: str | None = None
|
|
135
|
+
error: str | None = None
|
|
136
|
+
|
|
137
|
+
@property
|
|
138
|
+
def cost_usd(self) -> float:
|
|
139
|
+
return self.actual_cost_usd
|
|
140
|
+
|
|
141
|
+
@property
|
|
142
|
+
def gpu_seconds(self) -> float:
|
|
143
|
+
return self.actual_gpu_s
|
|
144
|
+
|
|
145
|
+
def save_all(self, client: Sunfield, output_dir: str | Path) -> list[Path]:
|
|
146
|
+
out = Path(output_dir)
|
|
147
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
148
|
+
if not self.artifacts:
|
|
149
|
+
return []
|
|
150
|
+
targets = [(art, _safe_artifact_dest(out, art.view_or_frame, art.pass_name)) for art in self.artifacts]
|
|
151
|
+
|
|
152
|
+
def _fetch(item: tuple[Artifact, Path]) -> Path:
|
|
153
|
+
art, dest = item
|
|
154
|
+
dest.write_bytes(client.download_artifact(art.artifact_id))
|
|
155
|
+
return dest
|
|
156
|
+
|
|
157
|
+
if len(targets) == 1:
|
|
158
|
+
return [_fetch(targets[0])]
|
|
159
|
+
with ThreadPoolExecutor(max_workers=min(8, len(targets))) as pool:
|
|
160
|
+
return list(pool.map(_fetch, targets))
|