realmetry 0.1.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.
- realmetry/__init__.py +12 -0
- realmetry/cli.py +390 -0
- realmetry/client.py +331 -0
- realmetry/config.py +56 -0
- realmetry-0.1.0.dist-info/METADATA +170 -0
- realmetry-0.1.0.dist-info/RECORD +10 -0
- realmetry-0.1.0.dist-info/WHEEL +5 -0
- realmetry-0.1.0.dist-info/entry_points.txt +2 -0
- realmetry-0.1.0.dist-info/licenses/LICENSE +21 -0
- realmetry-0.1.0.dist-info/top_level.txt +1 -0
realmetry/__init__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""RealMetry SDK: generate sim-ready USD scenes for Isaac Sim / Isaac Lab.
|
|
2
|
+
|
|
3
|
+
import realmetry
|
|
4
|
+
client = realmetry.Client() # API key from `realmetry login`, REALMETRY_API_KEY, or Client(api_key=...)
|
|
5
|
+
scenes = client.generate(10, recipe={"features": {"island": 1}}, out="./scenes")
|
|
6
|
+
scenes[0].usd_path # ./scenes/kitchen_xxxxxxxx_0000/scene.usdc -> load it in Isaac
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from .client import Client, DownloadedScene, RealMetryError, verify_webhook
|
|
10
|
+
|
|
11
|
+
__all__ = ["Client", "DownloadedScene", "RealMetryError", "verify_webhook"]
|
|
12
|
+
__version__ = "0.1.0"
|
realmetry/cli.py
ADDED
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
"""`realmetry` command line.
|
|
2
|
+
|
|
3
|
+
realmetry login # paste your API key once (saved for this user)
|
|
4
|
+
realmetry whoami
|
|
5
|
+
realmetry generate --scenes 10 [--name "Training set v2"] [--folder "Dataset v2"] [--preset pick-and-place]
|
|
6
|
+
[--clutter high --island always] [--random] [--recipe recipe.yaml] [--seed 123] [--out ./scenes]
|
|
7
|
+
realmetry options [--generator kitchen] # starting points and essentials
|
|
8
|
+
realmetry edit <scene> [--recipe changes.yaml] [--reroll decor lighting] # same kitchen, other layers
|
|
9
|
+
realmetry jobs [--search TEXT] [--folder NAME] | realmetry status <job> | realmetry cancel <job>
|
|
10
|
+
realmetry download <job> [--out DIR] | realmetry download --folder "Dataset v2" [--out DIR]
|
|
11
|
+
realmetry rename <job> "New name" # or no name to remove it
|
|
12
|
+
realmetry folders # folders with their jobs and ready scenes
|
|
13
|
+
realmetry move <job> "Dataset v2" # or no folder to take it out
|
|
14
|
+
realmetry schema [--generator kitchen] # adjustable recipe parameters
|
|
15
|
+
realmetry logout
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import argparse
|
|
21
|
+
import getpass
|
|
22
|
+
import json
|
|
23
|
+
import re
|
|
24
|
+
import sys
|
|
25
|
+
import time
|
|
26
|
+
|
|
27
|
+
from . import config
|
|
28
|
+
from .client import Client, RealMetryError, load_recipe
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _progress(j: dict) -> None:
|
|
32
|
+
s = j.get("scenes") or []
|
|
33
|
+
done = sum(1 for x in s if x["status"] == "succeeded")
|
|
34
|
+
failed = sum(1 for x in s if x["status"] == "failed")
|
|
35
|
+
running = sum(1 for x in s if x["status"] == "running")
|
|
36
|
+
print(f"\r [{time.strftime('%H:%M:%S')}] {j['status']:<9} ready {done}/{len(s)}"
|
|
37
|
+
f" generating {running} failed {failed} ", end="", flush=True)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _bytes(done: int, total: int) -> None:
|
|
41
|
+
pct = f"{100 * done / total:5.1f}%" if total else ""
|
|
42
|
+
print(f"\r downloading {done / 1e6:7.1f} MB {pct}", end="", flush=True)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _windows_clipboard() -> str:
|
|
46
|
+
"""Text on the Windows clipboard (no extra packages)."""
|
|
47
|
+
import ctypes
|
|
48
|
+
from ctypes import wintypes
|
|
49
|
+
|
|
50
|
+
user32, kernel32 = ctypes.windll.user32, ctypes.windll.kernel32
|
|
51
|
+
user32.GetClipboardData.restype = wintypes.HANDLE
|
|
52
|
+
kernel32.GlobalLock.argtypes = [wintypes.HGLOBAL]
|
|
53
|
+
kernel32.GlobalLock.restype = wintypes.LPVOID
|
|
54
|
+
kernel32.GlobalUnlock.argtypes = [wintypes.HGLOBAL]
|
|
55
|
+
if not user32.OpenClipboard(None):
|
|
56
|
+
return ""
|
|
57
|
+
try:
|
|
58
|
+
handle = user32.GetClipboardData(13) # CF_UNICODETEXT
|
|
59
|
+
if not handle:
|
|
60
|
+
return ""
|
|
61
|
+
ptr = kernel32.GlobalLock(handle)
|
|
62
|
+
try:
|
|
63
|
+
return ctypes.wstring_at(ptr) if ptr else ""
|
|
64
|
+
finally:
|
|
65
|
+
kernel32.GlobalUnlock(handle)
|
|
66
|
+
finally:
|
|
67
|
+
user32.CloseClipboard()
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _windows_secret_input(prompt: str) -> str:
|
|
71
|
+
"""Like getpass, but each character shows as * (so a paste visibly lands) and Ctrl+V pastes: the classic Windows
|
|
72
|
+
console hands Ctrl+V to the program as a key instead of pasting, so getpass would get nothing."""
|
|
73
|
+
import msvcrt
|
|
74
|
+
|
|
75
|
+
out: list[str] = []
|
|
76
|
+
|
|
77
|
+
def add(text: str) -> None:
|
|
78
|
+
for ch in text:
|
|
79
|
+
if ch.isprintable():
|
|
80
|
+
out.append(ch)
|
|
81
|
+
sys.stdout.write("*")
|
|
82
|
+
sys.stdout.flush()
|
|
83
|
+
|
|
84
|
+
sys.stdout.write(prompt)
|
|
85
|
+
sys.stdout.flush()
|
|
86
|
+
while True:
|
|
87
|
+
ch = msvcrt.getwch()
|
|
88
|
+
if ch in ("\r", "\n"):
|
|
89
|
+
break
|
|
90
|
+
if ch == "\x03":
|
|
91
|
+
raise KeyboardInterrupt
|
|
92
|
+
if ch in ("\x00", "\xe0"): # arrows and other special keys come as two characters: ignore both
|
|
93
|
+
msvcrt.getwch()
|
|
94
|
+
elif ch == "\x16": # Ctrl+V
|
|
95
|
+
add(_windows_clipboard().strip())
|
|
96
|
+
elif ch == "\b":
|
|
97
|
+
if out:
|
|
98
|
+
out.pop()
|
|
99
|
+
sys.stdout.write("\b \b")
|
|
100
|
+
sys.stdout.flush()
|
|
101
|
+
else:
|
|
102
|
+
add(ch)
|
|
103
|
+
sys.stdout.write("\n")
|
|
104
|
+
sys.stdout.flush()
|
|
105
|
+
return "".join(out)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _ask_key() -> str:
|
|
109
|
+
"""Ask for the key without showing it. Confirm what arrived (only its first and last characters)."""
|
|
110
|
+
print("Paste your API key and press Enter.")
|
|
111
|
+
if sys.platform == "win32" and sys.stdin.isatty():
|
|
112
|
+
raw = _windows_secret_input("API key: ")
|
|
113
|
+
else:
|
|
114
|
+
print(" (It stays hidden while you paste or type.)")
|
|
115
|
+
raw = getpass.getpass("API key: ")
|
|
116
|
+
# some terminals wrap a paste in invisible markers; keep only the printable characters
|
|
117
|
+
key = "".join(ch for ch in raw.replace("\x1b[200~", "").replace("\x1b[201~", "") if ch.isprintable()).strip()
|
|
118
|
+
if key:
|
|
119
|
+
print(f"Key received: {key[:3]}...{key[-4:]} ({len(key)} characters)")
|
|
120
|
+
return key
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def cmd_login(a) -> int:
|
|
124
|
+
key = a.key or _ask_key()
|
|
125
|
+
if not key:
|
|
126
|
+
print("No key received. Run 'realmetry login' again and paste the key before pressing Enter.", file=sys.stderr)
|
|
127
|
+
return 1
|
|
128
|
+
if not re.fullmatch(r"(?:rm|sr77)_[0-9a-f]{8}_[A-Za-z0-9_-]{43}", key):
|
|
129
|
+
# said here, before asking the server: what arrived is not a key at all (half a paste, the wrong text copied)
|
|
130
|
+
print(f"That is not an API key: it has {len(key)} characters and a key has 55, starting with rm_. "
|
|
131
|
+
"Copy it again with the Copy button in the web app.", file=sys.stderr)
|
|
132
|
+
return 1
|
|
133
|
+
url = (a.url or config.resolve(None, None)[1]).rstrip("/")
|
|
134
|
+
try:
|
|
135
|
+
me = Client(api_key=key, api_url=url).me()
|
|
136
|
+
except RealMetryError as e:
|
|
137
|
+
print(f"Login failed: {e.detail}", file=sys.stderr)
|
|
138
|
+
return 1
|
|
139
|
+
p = config.save(key, url)
|
|
140
|
+
print(f"Logged in as {me['organization']['name']} ({me['credits']['available']:g} credits). Key saved in {p}")
|
|
141
|
+
return 0
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def cmd_logout(a) -> int:
|
|
145
|
+
print("Key removed." if config.clear() else "No saved key.")
|
|
146
|
+
return 0
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def cmd_whoami(a) -> int:
|
|
150
|
+
me = Client().me()
|
|
151
|
+
print(f"{me['organization']['name']} | {me['credits']['available']:g} credits available")
|
|
152
|
+
return 0
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def cmd_schema(a) -> int:
|
|
156
|
+
s = Client().recipe_schema(a.generator)
|
|
157
|
+
if a.json:
|
|
158
|
+
print(json.dumps(s, indent=1))
|
|
159
|
+
return 0
|
|
160
|
+
print(f"{s['generator_id']} v{s['version']}")
|
|
161
|
+
for g in s["groups"]:
|
|
162
|
+
print(f"\n{g['label']}")
|
|
163
|
+
for p in g["params"]:
|
|
164
|
+
unit = f" {p['unit']}" if p.get("unit") else ""
|
|
165
|
+
print(f" {p['path']:<52} {p['type']:<11} default={json.dumps(p['default'])}{unit}")
|
|
166
|
+
return 0
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
ESSENTIAL_FLAGS = ("layouts", "island", "size", "clutter", "doors", "lighting")
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _val(v: str) -> str:
|
|
173
|
+
return v.strip().replace("-", "_")
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def cmd_options(a) -> int:
|
|
177
|
+
o = Client().options(a.generator)
|
|
178
|
+
if a.json:
|
|
179
|
+
print(json.dumps(o, indent=1))
|
|
180
|
+
return 0
|
|
181
|
+
print("Starting points (--preset):")
|
|
182
|
+
for p in o["presets"]:
|
|
183
|
+
print(f" {p['key'].replace('_', '-'):<20} {p['description']}")
|
|
184
|
+
print('\nEssentials (each also accepts "random"):')
|
|
185
|
+
for e in o["essentials"]:
|
|
186
|
+
vals = " | ".join(x["value"].replace("_", "-") for x in e["options"])
|
|
187
|
+
many = " (comma list)" if e.get("multi") else ""
|
|
188
|
+
print(f" --{e['key']:<10} {vals}{many}")
|
|
189
|
+
return 0
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def cmd_generate(a) -> int:
|
|
193
|
+
c = Client()
|
|
194
|
+
recipe = load_recipe(a.recipe) if a.recipe else {}
|
|
195
|
+
ess = {}
|
|
196
|
+
for k in ESSENTIAL_FLAGS:
|
|
197
|
+
v = getattr(a, k, None)
|
|
198
|
+
if v:
|
|
199
|
+
ess[k] = [_val(x) for x in v.split(",")] if k == "layouts" and v != "random" else _val(v)
|
|
200
|
+
options = {**{k: "random" for k in ESSENTIAL_FLAGS}, **ess} if a.random else (ess or None)
|
|
201
|
+
job = c.create_job(a.scenes, recipe, a.seed, a.generator,
|
|
202
|
+
preset=_val(a.preset) if a.preset else None, options=options, name=a.name, folder=a.folder,
|
|
203
|
+
saved_recipe=a.saved_recipe)
|
|
204
|
+
named = f' "{job["name"]}"' if job.get("name") else ""
|
|
205
|
+
if job.get("folder"):
|
|
206
|
+
named += f' in folder "{job["folder"]["name"]}"'
|
|
207
|
+
print(f"Job {job['id']}{named} created: {a.scenes} scene(s), seed {job['base_seed']}, "
|
|
208
|
+
f"{job['credits_reserved']:g} credits reserved.")
|
|
209
|
+
if job.get("options"):
|
|
210
|
+
print(" " + ", ".join(f"{k}={','.join(v) if isinstance(v, list) else v}" for k, v in job["options"].items()))
|
|
211
|
+
job = c.wait(job["id"], poll=a.poll, on_progress=_progress)
|
|
212
|
+
print()
|
|
213
|
+
return _download(c, job, a.out)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _download(c: Client, job: dict, out: str) -> int:
|
|
217
|
+
ready = [s for s in job["scenes"] if s["status"] == "succeeded"]
|
|
218
|
+
for s in ready:
|
|
219
|
+
print(f" scene {s['scene_index']} (seed {s['seed']})")
|
|
220
|
+
d = c.download_scene(s, out, on_bytes=_bytes)
|
|
221
|
+
print(f"\r -> {d.usd_path}{' ' * 20}")
|
|
222
|
+
bad = [s for s in job["scenes"] if s["status"] == "failed"]
|
|
223
|
+
for s in bad:
|
|
224
|
+
print(f" scene {s['scene_index']} failed: {s.get('public_error')}")
|
|
225
|
+
print(f"Job {job['status']}: {len(ready)} scene(s) in {out}, {job['credits_charged']:g} credits charged.")
|
|
226
|
+
return 0 if ready else 1
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def cmd_edit(a) -> int:
|
|
230
|
+
c = Client()
|
|
231
|
+
recipe = load_recipe(a.recipe) if a.recipe else {}
|
|
232
|
+
job = c.edit(a.scene, recipe, a.reroll)
|
|
233
|
+
s = job["scenes"][0]
|
|
234
|
+
print(f"Edit job {job['id']} created from scene {a.scene} (seed {s['seed']}, same kitchen).")
|
|
235
|
+
job = c.wait(job["id"], poll=a.poll, on_progress=_progress)
|
|
236
|
+
print()
|
|
237
|
+
return _download(c, job, a.out)
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def cmd_download(a) -> int:
|
|
241
|
+
c = Client()
|
|
242
|
+
if a.folder:
|
|
243
|
+
jobs = [j for j in c.folder_jobs(a.folder) if j["scenes"]["succeeded"]]
|
|
244
|
+
print(f'Folder "{c.folder(a.folder)["name"]}": {len(jobs)} job(s) with ready scenes.')
|
|
245
|
+
rc = 1
|
|
246
|
+
for j in jobs:
|
|
247
|
+
print(f"Job {j['id']}{(' ' + repr(j['name'])) if j.get('name') else ''}")
|
|
248
|
+
rc = min(rc, _download(c, c.job(j["id"]), a.out))
|
|
249
|
+
return rc
|
|
250
|
+
if not a.job:
|
|
251
|
+
print("Give one or more job ids, or --folder NAME.", file=sys.stderr)
|
|
252
|
+
return 2
|
|
253
|
+
rc = 0
|
|
254
|
+
for job_id in a.job: # several jobs: each into its own folders under --out
|
|
255
|
+
rc = max(rc, _download(c, c.job(job_id), a.out))
|
|
256
|
+
return rc
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def cmd_recipes(a) -> int:
|
|
260
|
+
rs = Client().recipes(a.generator)
|
|
261
|
+
if not rs:
|
|
262
|
+
print("No saved recipes yet. Save one from New job in the web app (Save as recipe).")
|
|
263
|
+
for r in rs:
|
|
264
|
+
extra = f" - {r['description']}" if r.get("description") else ""
|
|
265
|
+
print(f"{r['name']} (starting point: {r.get('preset') or 'default'}){extra}")
|
|
266
|
+
return 0
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def cmd_folders(a) -> int:
|
|
270
|
+
fs = Client().folders()
|
|
271
|
+
if not fs:
|
|
272
|
+
print('No folders yet. Create one with `realmetry generate ... --folder "Dataset v2"` or in the web app.')
|
|
273
|
+
for f in fs:
|
|
274
|
+
print(f"{f['id']} {f['job_count']:>4} job(s) {f['scenes_ready']:>6} ready {f['name']}")
|
|
275
|
+
return 0
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def cmd_move(a) -> int:
|
|
279
|
+
j = Client().move(a.job, a.folder or None)
|
|
280
|
+
print(f'Job {j["id"]} moved to "{j["folder"]["name"]}".' if j.get("folder") else f"Job {j['id']} has no folder now.")
|
|
281
|
+
return 0
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def cmd_jobs(a) -> int:
|
|
285
|
+
archived = "only" if a.archived else "exclude"
|
|
286
|
+
for j in Client().jobs(a.limit, a.search, a.folder, archived=archived, saved_recipe=a.saved_recipe,
|
|
287
|
+
since=a.since):
|
|
288
|
+
n = j["scenes"]
|
|
289
|
+
print(f"{j['id']} {j['status']:<9} {n['succeeded']}/{j['scene_count']} ready "
|
|
290
|
+
f"seed {j['base_seed']:<10} {j['created_at'][:16]} {j.get('name') or ''}".rstrip())
|
|
291
|
+
return 0
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def cmd_archive(a) -> int:
|
|
295
|
+
c = Client()
|
|
296
|
+
for job_id in a.job:
|
|
297
|
+
j = c.archive(job_id, not a.undo)
|
|
298
|
+
print(f"Job {j['id']} {'archived' if j.get('archived_at') else 'back in the list'}.")
|
|
299
|
+
return 0
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def cmd_rename(a) -> int:
|
|
303
|
+
j = Client().rename(a.job, a.name or None)
|
|
304
|
+
print(f'Job {j["id"]} renamed to "{j["name"]}".' if j.get("name") else f"Job {j['id']} has no name now.")
|
|
305
|
+
return 0
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def cmd_status(a) -> int:
|
|
309
|
+
j = Client().job(a.job)
|
|
310
|
+
named = f' "{j["name"]}"' if j.get("name") else ""
|
|
311
|
+
print(f"{j['id']}{named} {j['status']} ({j['generator_id']} v{j['generator_version']})")
|
|
312
|
+
for s in j["scenes"]:
|
|
313
|
+
print(f" {s['scene_index']:>4} {s['id']} seed {s['seed']:<10} {s['status']:<9} {s.get('public_error') or ''}")
|
|
314
|
+
return 0
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def cmd_cancel(a) -> int:
|
|
318
|
+
r = Client().cancel(a.job)
|
|
319
|
+
print(f"{r['canceled_scenes']} scene(s) canceled; job is {r['status']}.")
|
|
320
|
+
return 0
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def main(argv=None) -> int:
|
|
324
|
+
ap = argparse.ArgumentParser(prog="realmetry", description="RealMetry: sim-ready USD scenes for Isaac Sim / Lab.")
|
|
325
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
326
|
+
s = sub.add_parser("login", help="save your API key (once)"); s.add_argument("--key"); s.add_argument("--url")
|
|
327
|
+
s.set_defaults(f=cmd_login)
|
|
328
|
+
sub.add_parser("logout", help="remove the saved key").set_defaults(f=cmd_logout)
|
|
329
|
+
sub.add_parser("whoami", help="organization and credits").set_defaults(f=cmd_whoami)
|
|
330
|
+
s = sub.add_parser("schema", help="adjustable recipe parameters")
|
|
331
|
+
s.add_argument("--generator", default="kitchen"); s.add_argument("--json", action="store_true")
|
|
332
|
+
s.set_defaults(f=cmd_schema)
|
|
333
|
+
s = sub.add_parser("generate", help="create a job, wait and download the scenes")
|
|
334
|
+
s.add_argument("--scenes", type=int, required=True); s.add_argument("--recipe", help=".json or .yaml overrides")
|
|
335
|
+
s.add_argument("--name", help='optional label to find the job later, e.g. "Training set v2"')
|
|
336
|
+
s.add_argument("--folder", help="folder name or id (a new name is created)")
|
|
337
|
+
s.add_argument("--seed", type=int); s.add_argument("--generator", default="kitchen")
|
|
338
|
+
s.add_argument("--preset", help="starting point, e.g. pick-and-place (see `realmetry options`)")
|
|
339
|
+
s.add_argument("--saved-recipe", dest="saved_recipe",
|
|
340
|
+
help='a recipe your team saved in the web app, by name (see `realmetry recipes`)')
|
|
341
|
+
for k in ESSENTIAL_FLAGS:
|
|
342
|
+
s.add_argument(f"--{k}", help="essential (see `realmetry options`), or random")
|
|
343
|
+
s.add_argument("--random", action="store_true", help="pick the essentials you didn't set at random")
|
|
344
|
+
s.add_argument("--out", default="./rm_scenes"); s.add_argument("--poll", type=float, default=10)
|
|
345
|
+
s.set_defaults(f=cmd_generate)
|
|
346
|
+
s = sub.add_parser("options", help="starting points and essentials of a generator")
|
|
347
|
+
s.add_argument("--generator", default="kitchen"); s.add_argument("--json", action="store_true")
|
|
348
|
+
s.set_defaults(f=cmd_options)
|
|
349
|
+
s = sub.add_parser("edit", help="edit a ready scene by layers (same kitchen) and download it")
|
|
350
|
+
s.add_argument("scene", help="scene id (see `realmetry status <job>`)")
|
|
351
|
+
s.add_argument("--recipe", help=".json/.yaml with changes in editable layers (contents, decor, stools, "
|
|
352
|
+
"lighting, initial_state)")
|
|
353
|
+
s.add_argument("--reroll", nargs="*", default=[], metavar="LAYER", help="re-roll layers, e.g. --reroll decor lighting")
|
|
354
|
+
s.add_argument("--out", default="./rm_scenes"); s.add_argument("--poll", type=float, default=10)
|
|
355
|
+
s.set_defaults(f=cmd_edit)
|
|
356
|
+
s = sub.add_parser("jobs", help="recent jobs"); s.add_argument("--limit", type=int, default=20)
|
|
357
|
+
s.add_argument("--search", help="part of the name, job id prefix or exact seed")
|
|
358
|
+
s.add_argument("--folder", help='folder name or id ("none" = jobs without a folder)')
|
|
359
|
+
s.add_argument("--archived", action="store_true", help="list archived jobs instead")
|
|
360
|
+
s.add_argument("--saved-recipe", dest="saved_recipe", help="only jobs made with this team recipe")
|
|
361
|
+
s.add_argument("--since", help='only jobs created since this date, e.g. 2026-11-01'); s.set_defaults(f=cmd_jobs)
|
|
362
|
+
s = sub.add_parser("archive", help="archive jobs (hidden from lists, nothing is deleted)")
|
|
363
|
+
s.add_argument("job", nargs="+"); s.add_argument("--undo", action="store_true", help="bring them back")
|
|
364
|
+
s.set_defaults(f=cmd_archive)
|
|
365
|
+
sub.add_parser("folders", help="folders with their jobs and ready scenes").set_defaults(f=cmd_folders)
|
|
366
|
+
s = sub.add_parser("recipes", help="recipes your team saved in the web app")
|
|
367
|
+
s.add_argument("--generator"); s.set_defaults(f=cmd_recipes)
|
|
368
|
+
s = sub.add_parser("move", help="move a job to a folder (no folder = take it out)")
|
|
369
|
+
s.add_argument("job"); s.add_argument("folder", nargs="?", default=None); s.set_defaults(f=cmd_move)
|
|
370
|
+
s = sub.add_parser("rename", help="rename a job (no name = remove it)")
|
|
371
|
+
s.add_argument("job"); s.add_argument("name", nargs="?", default=None); s.set_defaults(f=cmd_rename)
|
|
372
|
+
s = sub.add_parser("status", help="scenes of a job"); s.add_argument("job"); s.set_defaults(f=cmd_status)
|
|
373
|
+
s = sub.add_parser("download", help="download ready scenes of one or more jobs, or of every job in a folder")
|
|
374
|
+
s.add_argument("job", nargs="*"); s.add_argument("--folder", help="folder name or id")
|
|
375
|
+
s.add_argument("--out", default="./rm_scenes"); s.set_defaults(f=cmd_download)
|
|
376
|
+
s = sub.add_parser("cancel", help="cancel scenes not started yet"); s.add_argument("job")
|
|
377
|
+
s.set_defaults(f=cmd_cancel)
|
|
378
|
+
a = ap.parse_args(argv)
|
|
379
|
+
try:
|
|
380
|
+
return a.f(a)
|
|
381
|
+
except RealMetryError as e:
|
|
382
|
+
print(f"\nError {e.status}: {e.detail}", file=sys.stderr)
|
|
383
|
+
return 1
|
|
384
|
+
except KeyboardInterrupt:
|
|
385
|
+
print("\nStopped (the job keeps running on the server; resume with `realmetry download <job>`).")
|
|
386
|
+
return 130
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
if __name__ == "__main__":
|
|
390
|
+
sys.exit(main())
|
realmetry/client.py
ADDED
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
"""HTTP client for the RealMetry API. The API key is attached to every request automatically."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import time
|
|
8
|
+
import uuid
|
|
9
|
+
import warnings
|
|
10
|
+
import zipfile
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Callable, Iterable
|
|
14
|
+
|
|
15
|
+
import requests
|
|
16
|
+
|
|
17
|
+
from . import config
|
|
18
|
+
|
|
19
|
+
FINAL = {"succeeded", "partial", "failed", "canceled"}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class RealMetryError(Exception):
|
|
23
|
+
def __init__(self, status: int, detail, payload: dict | None = None):
|
|
24
|
+
self.status, self.detail, self.payload = status, detail, payload or {}
|
|
25
|
+
super().__init__(f"{status}: {detail}")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass
|
|
29
|
+
class DownloadedScene:
|
|
30
|
+
scene_id: str
|
|
31
|
+
scene_index: int
|
|
32
|
+
seed: int
|
|
33
|
+
folder: Path # extracted package folder
|
|
34
|
+
usd_path: Path # <folder>/scene.usdc -> open / reference this in Isaac Sim / Isaac Lab
|
|
35
|
+
manifest_path: Path # <folder>/manifest.json (roles, articulations, masses...)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def load_recipe(path: str | Path) -> dict:
|
|
39
|
+
"""Recipe overrides from a .json or .yaml file (YAML needs `pip install realmetry[yaml]`)."""
|
|
40
|
+
p = Path(path)
|
|
41
|
+
text = p.read_text("utf-8")
|
|
42
|
+
if p.suffix.lower() in (".yaml", ".yml"):
|
|
43
|
+
import yaml
|
|
44
|
+
return yaml.safe_load(text) or {}
|
|
45
|
+
return json.loads(text)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class Client:
|
|
49
|
+
def __init__(self, api_key: str | None = None, api_url: str | None = None, timeout: float = 60):
|
|
50
|
+
self.api_key, self.api_url = config.resolve(api_key, api_url)
|
|
51
|
+
if not self.api_key:
|
|
52
|
+
raise RealMetryError(0, "No API key. Run `realmetry login`, set REALMETRY_API_KEY, or pass Client(api_key=...).")
|
|
53
|
+
self.timeout = timeout
|
|
54
|
+
self.http = requests.Session()
|
|
55
|
+
self.http.headers.update({"Authorization": f"Bearer {self.api_key}", "User-Agent": "realmetry-python/0.1.0"})
|
|
56
|
+
|
|
57
|
+
# ------------------------------------------------------------ low level
|
|
58
|
+
def _req(self, method: str, path: str, **kw):
|
|
59
|
+
r = self.http.request(method, self.api_url + path, timeout=self.timeout, **kw)
|
|
60
|
+
if r.status_code >= 400:
|
|
61
|
+
try:
|
|
62
|
+
body = r.json()
|
|
63
|
+
except ValueError:
|
|
64
|
+
body = {"detail": r.text[:300]}
|
|
65
|
+
raise RealMetryError(r.status_code, body.get("detail", body), body)
|
|
66
|
+
return r.json()
|
|
67
|
+
|
|
68
|
+
# ------------------------------------------------------------ API
|
|
69
|
+
def me(self) -> dict:
|
|
70
|
+
return self._req("GET", "/v1/me")
|
|
71
|
+
|
|
72
|
+
def generators(self) -> list[dict]:
|
|
73
|
+
return self._req("GET", "/v1/generators")["generators"]
|
|
74
|
+
|
|
75
|
+
def recipe_schema(self, generator: str = "kitchen") -> dict:
|
|
76
|
+
return self._req("GET", f"/v1/generators/{generator}/recipe-schema")
|
|
77
|
+
|
|
78
|
+
def options(self, generator: str = "kitchen") -> dict:
|
|
79
|
+
"""Starting points (presets) and essentials of a generator: {"presets": [...], "essentials": [...]}."""
|
|
80
|
+
s = self.recipe_schema(generator)
|
|
81
|
+
return {"presets": s.get("presets", []), "essentials": s.get("essentials", [])}
|
|
82
|
+
|
|
83
|
+
# ------------------------------------------------------------ folders
|
|
84
|
+
def folders(self) -> list[dict]:
|
|
85
|
+
"""Folders of the organization, with job_count and scenes_ready."""
|
|
86
|
+
return self._req("GET", "/v1/folders")["folders"]
|
|
87
|
+
|
|
88
|
+
def recipes(self, generator: str | None = None) -> list[dict]:
|
|
89
|
+
"""Recipes your team saved in the web app (name, preset, options, recipe). Use one with
|
|
90
|
+
create_job(..., saved_recipe="Grasping set v2") or generate(..., saved_recipe=...)."""
|
|
91
|
+
path = "/v1/recipes" + (f"?generator={generator}" if generator else "")
|
|
92
|
+
return self._req("GET", path)["recipes"]
|
|
93
|
+
|
|
94
|
+
def create_folder(self, name: str) -> dict:
|
|
95
|
+
return self._req("POST", "/v1/folders", json={"name": name})
|
|
96
|
+
|
|
97
|
+
def folder(self, folder: str, create: bool = False) -> dict:
|
|
98
|
+
"""A folder by id or by name (any case). With create=True, a missing name is created."""
|
|
99
|
+
try:
|
|
100
|
+
uuid.UUID(str(folder))
|
|
101
|
+
by_id = True
|
|
102
|
+
except ValueError:
|
|
103
|
+
by_id = False
|
|
104
|
+
for f in self.folders():
|
|
105
|
+
if (by_id and f["id"] == str(folder)) or (not by_id and f["name"].lower() == " ".join(folder.split()).lower()):
|
|
106
|
+
return f
|
|
107
|
+
if create and not by_id:
|
|
108
|
+
return self.create_folder(folder)
|
|
109
|
+
raise RealMetryError(404, f"Folder {folder!r} not found. See `realmetry folders`.")
|
|
110
|
+
|
|
111
|
+
def move(self, job_id: str, folder: str | None) -> dict:
|
|
112
|
+
"""Move a job to a folder (id or name, created if missing), or out of its folder with None."""
|
|
113
|
+
folder_id = self.folder(folder, create=True)["id"] if folder else None
|
|
114
|
+
return self._req("PATCH", f"/v1/jobs/{job_id}", json={"folder_id": folder_id})
|
|
115
|
+
|
|
116
|
+
# ------------------------------------------------------------ jobs
|
|
117
|
+
def create_job(self, scene_count: int, recipe: dict | None = None, seed: int | None = None,
|
|
118
|
+
generator: str = "kitchen", preset: str | None = None, options: dict | str | None = None,
|
|
119
|
+
name: str | None = None, folder: str | None = None, saved_recipe: str | None = None,
|
|
120
|
+
**essentials) -> dict:
|
|
121
|
+
"""Recipe in 3 optional levels, each one wins over the previous:
|
|
122
|
+
preset="pick_and_place" starting point (or "random")
|
|
123
|
+
clutter="high", island="always" essentials as keywords (or options={...}, or options="random")
|
|
124
|
+
recipe={...} any of the full parameters
|
|
125
|
+
The returned job shows the resolved `options` (random already resolved) and the final `recipe`.
|
|
126
|
+
`name` is an optional label to find the job later, e.g. "Training set v2".
|
|
127
|
+
`folder` is a folder id or name; a name that doesn't exist yet is created.
|
|
128
|
+
`saved_recipe` (a name or id from recipes()) uses a recipe your team saved, instead of the 3 levels."""
|
|
129
|
+
body: dict = {"generator_id": generator, "scene_count": scene_count, "recipe": recipe or {}}
|
|
130
|
+
if name is not None:
|
|
131
|
+
body["name"] = name
|
|
132
|
+
if folder:
|
|
133
|
+
body["folder_id"] = self.folder(folder, create=True)["id"]
|
|
134
|
+
if seed is not None:
|
|
135
|
+
body["seed"] = seed
|
|
136
|
+
if preset is not None:
|
|
137
|
+
body["preset"] = preset
|
|
138
|
+
if essentials:
|
|
139
|
+
if options == "random":
|
|
140
|
+
raise ValueError('use options="random" alone, or set each essential (e.g. clutter="random")')
|
|
141
|
+
options = {**(options or {}), **essentials}
|
|
142
|
+
if options is not None:
|
|
143
|
+
body["options"] = options
|
|
144
|
+
if saved_recipe:
|
|
145
|
+
body["saved_recipe"] = saved_recipe
|
|
146
|
+
return self._req("POST", "/v1/jobs", json=body)
|
|
147
|
+
|
|
148
|
+
def job(self, job_id: str) -> dict:
|
|
149
|
+
return self._req("GET", f"/v1/jobs/{job_id}")
|
|
150
|
+
|
|
151
|
+
def jobs(self, limit: int = 20, search: str | None = None, folder: str | None = None,
|
|
152
|
+
archived: str = "exclude", saved_recipe: str | None = None, since: str | None = None,
|
|
153
|
+
until: str | None = None) -> list[dict]:
|
|
154
|
+
"""Recent jobs. `search` matches part of the name, a job id prefix or an exact seed.
|
|
155
|
+
`folder` is a folder id or name ("none" = jobs without a folder).
|
|
156
|
+
Archived jobs are left out: archived="only" lists just them, "include" lists both.
|
|
157
|
+
`saved_recipe` (name or id) keeps only jobs made with that team recipe.
|
|
158
|
+
`since` / `until` are ISO dates or times, e.g. "2026-11-01"."""
|
|
159
|
+
params: dict = {"limit": limit}
|
|
160
|
+
if archived != "exclude":
|
|
161
|
+
params["archived"] = archived
|
|
162
|
+
if saved_recipe:
|
|
163
|
+
ref = " ".join(saved_recipe.split()).lower()
|
|
164
|
+
found = [r for r in self.recipes() if r["id"] == saved_recipe or r["name"].lower() == ref]
|
|
165
|
+
if not found:
|
|
166
|
+
raise RealMetryError(404, f"No saved recipe called '{saved_recipe}'.")
|
|
167
|
+
params["recipe"] = found[0]["id"]
|
|
168
|
+
if since:
|
|
169
|
+
params["since"] = since
|
|
170
|
+
if until:
|
|
171
|
+
params["until"] = until
|
|
172
|
+
if search:
|
|
173
|
+
params["q"] = search
|
|
174
|
+
if folder:
|
|
175
|
+
params["folder"] = "none" if folder == "none" else self.folder(folder)["id"]
|
|
176
|
+
return self._req("GET", "/v1/jobs", params=params)["jobs"]
|
|
177
|
+
|
|
178
|
+
def folder_jobs(self, folder: str) -> list[dict]:
|
|
179
|
+
"""Every job in a folder (all pages), newest first."""
|
|
180
|
+
fid = self.folder(folder)["id"]
|
|
181
|
+
out, offset = [], 0
|
|
182
|
+
while True:
|
|
183
|
+
page = self._req("GET", "/v1/jobs", params={"folder": fid, "limit": 200, "offset": offset})
|
|
184
|
+
out += page["jobs"]
|
|
185
|
+
offset += len(page["jobs"])
|
|
186
|
+
if not page["jobs"] or offset >= page["total"]:
|
|
187
|
+
return out
|
|
188
|
+
|
|
189
|
+
def rename(self, job_id: str, name: str | None) -> dict:
|
|
190
|
+
"""Rename a job (None removes the name). Scenes, recipe and credits don't change."""
|
|
191
|
+
return self._req("PATCH", f"/v1/jobs/{job_id}", json={"name": name})
|
|
192
|
+
|
|
193
|
+
def cancel(self, job_id: str) -> dict:
|
|
194
|
+
return self._req("POST", f"/v1/jobs/{job_id}/cancel")
|
|
195
|
+
|
|
196
|
+
def archive(self, job_id: str, archived: bool = True) -> dict:
|
|
197
|
+
"""Archive a job (hidden from jobs() and folders), or bring it back with archived=False.
|
|
198
|
+
Nothing is deleted: scenes and downloads stay."""
|
|
199
|
+
return self._req("PATCH", f"/v1/jobs/{job_id}", json={"archived": archived})
|
|
200
|
+
|
|
201
|
+
def edit(self, scene: dict | str, recipe: dict | None = None, reroll: list[str] | None = None) -> dict:
|
|
202
|
+
"""Edit a ready scene by layers (same seed). Only these layers can change:
|
|
203
|
+
contents, decor, stools, lighting, initial_state. `reroll` re-rolls whole layers ("another decor").
|
|
204
|
+
Returns the new 1-scene job; the original scene is kept.
|
|
205
|
+
|
|
206
|
+
Edits always run on the CURRENT generator version. If the scene was made with an older version, the job's
|
|
207
|
+
`parent_generator_version` differs from `generator_version` and the room itself may come out different
|
|
208
|
+
(a warning is emitted)."""
|
|
209
|
+
scene_id = scene["id"] if isinstance(scene, dict) else scene
|
|
210
|
+
job = self._req("POST", f"/v1/scenes/{scene_id}/edit", json={"recipe": recipe or {}, "reroll": reroll or []})
|
|
211
|
+
old = job.get("parent_generator_version")
|
|
212
|
+
if old and old != job.get("generator_version"):
|
|
213
|
+
warnings.warn(f"scene {scene_id} was made with generator {old}; the edit is remade with "
|
|
214
|
+
f"{job.get('generator_version')}, so the room may differ.", stacklevel=2)
|
|
215
|
+
return job
|
|
216
|
+
|
|
217
|
+
def edit_and_download(self, scene: dict | str, recipe: dict | None = None, reroll: list[str] | None = None,
|
|
218
|
+
out: str | Path = "./rm_scenes", poll: float = 10,
|
|
219
|
+
on_progress: Callable[[dict], None] | None = None) -> DownloadedScene:
|
|
220
|
+
job = self.wait(self.edit(scene, recipe, reroll)["id"], poll=poll, on_progress=on_progress)
|
|
221
|
+
got = self.download_job(job, out)
|
|
222
|
+
if not got:
|
|
223
|
+
raise RealMetryError(0, f"edit job {job['id']} ended {job['status']}")
|
|
224
|
+
return got[0]
|
|
225
|
+
|
|
226
|
+
def download_links(self, scene_id: str) -> list[dict]:
|
|
227
|
+
return self._req("GET", f"/v1/scenes/{scene_id}/download")["files"]
|
|
228
|
+
|
|
229
|
+
# ------------------------------------------------------------ helpers
|
|
230
|
+
def wait(self, job_id: str, poll: float = 10, timeout: float | None = None,
|
|
231
|
+
on_progress: Callable[[dict], None] | None = None) -> dict:
|
|
232
|
+
"""Blocks until the job finishes (succeeded / partial / failed / canceled)."""
|
|
233
|
+
t0 = time.time()
|
|
234
|
+
while True:
|
|
235
|
+
j = self.job(job_id)
|
|
236
|
+
if on_progress:
|
|
237
|
+
on_progress(j)
|
|
238
|
+
if j["status"] in FINAL:
|
|
239
|
+
return j
|
|
240
|
+
if timeout is not None and time.time() - t0 > timeout:
|
|
241
|
+
raise TimeoutError(f"job {job_id} still {j['status']} after {timeout}s")
|
|
242
|
+
time.sleep(poll)
|
|
243
|
+
|
|
244
|
+
def download_scene(self, scene: dict | str, out: str | Path = ".", extract: bool = True,
|
|
245
|
+
on_bytes: Callable[[int, int], None] | None = None) -> DownloadedScene | Path:
|
|
246
|
+
"""Downloads a ready scene package, checks its SHA-256 and (by default) extracts it into `out`."""
|
|
247
|
+
scene_id = scene["id"] if isinstance(scene, dict) else scene
|
|
248
|
+
out = Path(out)
|
|
249
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
250
|
+
links = self.download_links(scene_id)
|
|
251
|
+
pkg = next(f for f in links if f["name"].endswith(".zip"))
|
|
252
|
+
zpath = out / pkg["name"]
|
|
253
|
+
h = hashlib.sha256()
|
|
254
|
+
# the link is already signed for this one file: send it without the RealMetry key (storage rejects a second
|
|
255
|
+
# credential, and the key must never leave for anywhere but the API)
|
|
256
|
+
with requests.get(pkg["url"], stream=True, timeout=self.timeout,
|
|
257
|
+
headers={"User-Agent": self.http.headers.get("User-Agent", "realmetry-python")}) as r:
|
|
258
|
+
if r.status_code >= 400:
|
|
259
|
+
raise RealMetryError(r.status_code, "download failed (link expired? request it again)")
|
|
260
|
+
total, done = int(r.headers.get("content-length") or pkg.get("bytes") or 0), 0
|
|
261
|
+
with open(zpath, "wb") as f:
|
|
262
|
+
for chunk in r.iter_content(1 << 20):
|
|
263
|
+
f.write(chunk)
|
|
264
|
+
h.update(chunk)
|
|
265
|
+
done += len(chunk)
|
|
266
|
+
if on_bytes:
|
|
267
|
+
on_bytes(done, total)
|
|
268
|
+
if pkg.get("sha256") and h.hexdigest() != pkg["sha256"]:
|
|
269
|
+
zpath.unlink(missing_ok=True)
|
|
270
|
+
raise RealMetryError(0, f"checksum mismatch for {pkg['name']}; download again")
|
|
271
|
+
if not extract:
|
|
272
|
+
return zpath
|
|
273
|
+
with zipfile.ZipFile(zpath) as z:
|
|
274
|
+
root = z.namelist()[0].split("/")[0]
|
|
275
|
+
z.extractall(out)
|
|
276
|
+
zpath.unlink()
|
|
277
|
+
folder = out / root
|
|
278
|
+
meta = scene if isinstance(scene, dict) else {}
|
|
279
|
+
return DownloadedScene(scene_id, meta.get("scene_index", -1), meta.get("seed", -1), folder,
|
|
280
|
+
folder / "scene.usdc", folder / "manifest.json")
|
|
281
|
+
|
|
282
|
+
def download_job(self, job: dict | str, out: str | Path = ".", **kw) -> list[DownloadedScene]:
|
|
283
|
+
j = self.job(job) if isinstance(job, str) else job
|
|
284
|
+
if not isinstance(j.get("scenes"), list): # a job from a list has scene counts, not scenes
|
|
285
|
+
j = self.job(j["id"])
|
|
286
|
+
return [self.download_scene(s, out, **kw) for s in j["scenes"] if s["status"] == "succeeded"]
|
|
287
|
+
|
|
288
|
+
def download_folder(self, folder: str, out: str | Path = ".", **kw) -> list[DownloadedScene]:
|
|
289
|
+
"""Downloads every ready scene of every job in a folder (id or name) into `out`."""
|
|
290
|
+
got: list[DownloadedScene] = []
|
|
291
|
+
for j in self.folder_jobs(folder):
|
|
292
|
+
if j["scenes"]["succeeded"]:
|
|
293
|
+
got += self.download_job(j["id"], out, **kw)
|
|
294
|
+
return got
|
|
295
|
+
|
|
296
|
+
def generate(self, scene_count: int, recipe: dict | None = None, seed: int | None = None,
|
|
297
|
+
generator: str = "kitchen", out: str | Path = "./rm_scenes", poll: float = 10,
|
|
298
|
+
on_progress: Callable[[dict], None] | None = None, preset: str | None = None,
|
|
299
|
+
options: dict | str | None = None, name: str | None = None, folder: str | None = None,
|
|
300
|
+
saved_recipe: str | None = None, **essentials) -> list[DownloadedScene]:
|
|
301
|
+
"""Create a job, wait for it and download every ready scene. Returns the local scenes.
|
|
302
|
+
Same recipe levels as create_job: client.generate(12, preset="pick_and_place", clutter="high")."""
|
|
303
|
+
job = self.create_job(scene_count, recipe, seed, generator, preset, options, name=name, folder=folder,
|
|
304
|
+
saved_recipe=saved_recipe, **essentials)
|
|
305
|
+
job = self.wait(job["id"], poll=poll, on_progress=on_progress)
|
|
306
|
+
return self.download_job(job, out)
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def iter_usd_paths(scenes: Iterable[DownloadedScene]) -> list[str]:
|
|
310
|
+
"""Handy for Isaac Lab configs: the list of scene.usdc paths."""
|
|
311
|
+
return [str(s.usd_path.resolve()) for s in scenes]
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def verify_webhook(body: bytes | str, signature_header: str, secret: str, tolerance_s: int = 300) -> dict:
|
|
315
|
+
"""Checks a RealMetry webhook and returns the parsed event. Raises RealMetryError if it is not authentic.
|
|
316
|
+
|
|
317
|
+
In your web server: event = realmetry.verify_webhook(request.body, request.headers["X-RealMetry-Signature"], SECRET)
|
|
318
|
+
The signature is HMAC-SHA256(secret, f"{t}.{body}"); old timestamps are rejected (replay protection)."""
|
|
319
|
+
import hmac as _hmac
|
|
320
|
+
raw = body.decode("utf-8") if isinstance(body, bytes) else body
|
|
321
|
+
try:
|
|
322
|
+
parts = dict(p.split("=", 1) for p in signature_header.split(","))
|
|
323
|
+
ts, sig = int(parts["t"]), parts["v1"]
|
|
324
|
+
except (ValueError, KeyError, AttributeError):
|
|
325
|
+
raise RealMetryError(400, "malformed X-RealMetry-Signature header")
|
|
326
|
+
if abs(time.time() - ts) > tolerance_s:
|
|
327
|
+
raise RealMetryError(400, "webhook timestamp outside tolerance (possible replay)")
|
|
328
|
+
expected = _hmac.new(secret.encode(), f"{ts}.{raw}".encode(), hashlib.sha256).hexdigest()
|
|
329
|
+
if not _hmac.compare_digest(expected, sig):
|
|
330
|
+
raise RealMetryError(400, "invalid webhook signature")
|
|
331
|
+
return json.loads(raw)
|
realmetry/config.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""Where the API key lives, so it is set ONCE (like `aws configure` or `gh auth login`).
|
|
2
|
+
|
|
3
|
+
Priority: explicit argument > environment (REALMETRY_API_KEY / REALMETRY_API_URL) > config file written by `realmetry login`.
|
|
4
|
+
Config file: %APPDATA%\\realmetry\\config.json on Windows, ~/.config/realmetry/config.json elsewhere.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
# the public API; for a local API set REALMETRY_API_URL=http://127.0.0.1:8000
|
|
14
|
+
DEFAULT_API_URL = "https://api.realmetry.co"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def config_path() -> Path:
|
|
18
|
+
if os.environ.get("REALMETRY_CONFIG"):
|
|
19
|
+
return Path(os.environ["REALMETRY_CONFIG"])
|
|
20
|
+
if os.name == "nt" and os.environ.get("APPDATA"):
|
|
21
|
+
return Path(os.environ["APPDATA"]) / "realmetry" / "config.json"
|
|
22
|
+
return Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "realmetry" / "config.json"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def load() -> dict:
|
|
26
|
+
p = config_path()
|
|
27
|
+
try:
|
|
28
|
+
return json.loads(p.read_text("utf-8"))
|
|
29
|
+
except (OSError, ValueError):
|
|
30
|
+
return {}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def save(api_key: str, api_url: str) -> Path:
|
|
34
|
+
p = config_path()
|
|
35
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
36
|
+
p.write_text(json.dumps({"api_key": api_key, "api_url": api_url}, indent=1), "utf-8")
|
|
37
|
+
try:
|
|
38
|
+
os.chmod(p, 0o600) # readable only by the user (no-op on Windows)
|
|
39
|
+
except OSError:
|
|
40
|
+
pass
|
|
41
|
+
return p
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def clear() -> bool:
|
|
45
|
+
p = config_path()
|
|
46
|
+
if p.exists():
|
|
47
|
+
p.unlink()
|
|
48
|
+
return True
|
|
49
|
+
return False
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def resolve(api_key: str | None, api_url: str | None) -> tuple[str | None, str]:
|
|
53
|
+
cfg = load()
|
|
54
|
+
key = api_key or os.environ.get("REALMETRY_API_KEY") or cfg.get("api_key")
|
|
55
|
+
url = api_url or os.environ.get("REALMETRY_API_URL") or cfg.get("api_url") or DEFAULT_API_URL
|
|
56
|
+
return key, url.rstrip("/")
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: realmetry
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python SDK and CLI for RealMetry: generate sim-ready USD scenes for Isaac Sim / Isaac Lab.
|
|
5
|
+
Author-email: RealMetry <hello@realmetry.co>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://realmetry.co
|
|
8
|
+
Project-URL: Documentation, https://app.realmetry.co/docs/sdk
|
|
9
|
+
Project-URL: Dashboard, https://app.realmetry.co
|
|
10
|
+
Project-URL: Terms of service, https://realmetry.co/terms
|
|
11
|
+
Keywords: robotics,simulation,isaac-sim,isaac-lab,openusd,usd,synthetic-data,procedural-generation
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Intended Audience :: Science/Research
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
21
|
+
Requires-Python: >=3.10
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Requires-Dist: requests>=2.31
|
|
25
|
+
Provides-Extra: yaml
|
|
26
|
+
Requires-Dist: pyyaml>=6.0; extra == "yaml"
|
|
27
|
+
Dynamic: license-file
|
|
28
|
+
|
|
29
|
+
# realmetry — RealMetry SDK & CLI
|
|
30
|
+
|
|
31
|
+
Generate sim-ready USD scenes (procedural US kitchens today) for **Isaac Sim / Isaac Lab** and get them on your
|
|
32
|
+
disk, ready to load.
|
|
33
|
+
|
|
34
|
+
[Website](https://realmetry.co) · [Dashboard](https://app.realmetry.co) · [Docs](https://app.realmetry.co/docs/sdk)
|
|
35
|
+
|
|
36
|
+
You need a RealMetry account: [sign up](https://app.realmetry.co/signup), then create an API key in the dashboard.
|
|
37
|
+
|
|
38
|
+
## Install
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
pip install realmetry
|
|
42
|
+
pip install "realmetry[yaml]" # optional: read .yaml recipe files
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Python 3.10 or newer.
|
|
46
|
+
|
|
47
|
+
## 1. Log in once
|
|
48
|
+
|
|
49
|
+
Create an API key in the web dashboard (**API keys → Create key**), then:
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
realmetry login # paste the key; it is saved for your user and sent automatically from now on
|
|
53
|
+
realmetry whoami # organization and credits
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
On servers / CI, set `REALMETRY_API_KEY` instead (it wins over the saved key).
|
|
57
|
+
|
|
58
|
+
## 2. Generate scenes
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
realmetry generate --scenes 10 --out ./scenes
|
|
62
|
+
realmetry generate --scenes 100 --recipe my_recipe.yaml --seed 1234 --out ./scenes
|
|
63
|
+
realmetry generate --scenes 50 --name "Training set v2" --out ./scenes # optional name to find it later
|
|
64
|
+
realmetry generate --scenes 200 --folder "Dataset v2" --out ./scenes # group jobs in a folder (created if new)
|
|
65
|
+
realmetry download --folder "Dataset v2" --out ./dataset # every ready scene of the folder
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
It creates the job, shows progress, then downloads and unzips every ready scene:
|
|
69
|
+
|
|
70
|
+
```
|
|
71
|
+
scenes/
|
|
72
|
+
kitchen_8f3c639d_0000/
|
|
73
|
+
scene.usdc <- open it in Isaac Sim or reference it from Isaac Lab
|
|
74
|
+
manifest.json <- every part: role (door, drawer, handle, graspable...), joint axis/limits, mass, friction
|
|
75
|
+
textures/
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Same seed + same recipe + same generator version = the same scene.
|
|
79
|
+
|
|
80
|
+
## Edit a scene you already have
|
|
81
|
+
|
|
82
|
+
Same kitchen (same seed: room, cabinets, appliances, materials stay identical), different layers:
|
|
83
|
+
|
|
84
|
+
```bash
|
|
85
|
+
realmetry status <job> # scene ids
|
|
86
|
+
realmetry edit <scene> --recipe add_decor.yaml # e.g. props: {deco: {max_sets: 6}}
|
|
87
|
+
realmetry edit <scene> --reroll decor lighting # another decor and other lights, nothing else changes
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Editable layers: `contents`, `decor`, `stools`, `lighting`, `initial_state`. Changing anything else is a new
|
|
91
|
+
scene. In Python: `client.edit(scene_id, recipe={...}, reroll=["decor"])` or `client.edit_and_download(...)`.
|
|
92
|
+
The original scene is kept; the edit is a new scene linked to it.
|
|
93
|
+
|
|
94
|
+
## Recipe in 3 levels
|
|
95
|
+
|
|
96
|
+
Every level is optional and wins over the previous one: **starting point → essentials → any parameter**.
|
|
97
|
+
|
|
98
|
+
```bash
|
|
99
|
+
realmetry options # what this generator offers
|
|
100
|
+
realmetry generate --scenes 12 --preset pick-and-place # 1. starting point
|
|
101
|
+
realmetry generate --scenes 12 --preset pick-and-place --clutter high --island always # 2. essentials
|
|
102
|
+
realmetry generate --scenes 12 --random # the six essentials at random
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
```python
|
|
106
|
+
client.generate(12, preset="pick_and_place")
|
|
107
|
+
client.generate(12, preset="pick_and_place", clutter="high", island="always")
|
|
108
|
+
client.generate(12, options="random") # or clutter="random" for just one
|
|
109
|
+
client.generate(12, preset="pick_and_place", recipe={"props": {"contents": {"fill": [90, 100]}}})
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
The job you get back shows the resolved `options` (random already resolved) and the final `recipe`, so you can
|
|
113
|
+
see exactly what was made and repeat it. Scenes are always made with the latest generator version.
|
|
114
|
+
|
|
115
|
+
### 3. Any parameter
|
|
116
|
+
|
|
117
|
+
Only the parameters you change; everything else keeps the generator defaults (or what the levels above set).
|
|
118
|
+
|
|
119
|
+
```yaml
|
|
120
|
+
features:
|
|
121
|
+
island: 1 # always an island
|
|
122
|
+
layout:
|
|
123
|
+
type: {L: 3, U: 1} # 75 % L-shape, 25 % U-shape
|
|
124
|
+
room:
|
|
125
|
+
ceiling_height: 274 # cm
|
|
126
|
+
initial_state:
|
|
127
|
+
doors_open_probability: 0.5
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
`realmetry schema` lists every adjustable parameter with its type, limits and default.
|
|
131
|
+
|
|
132
|
+
## Python
|
|
133
|
+
|
|
134
|
+
```python
|
|
135
|
+
import realmetry
|
|
136
|
+
|
|
137
|
+
client = realmetry.Client() # uses the saved key
|
|
138
|
+
scenes = client.generate(20, recipe={"features": {"island": 1}}, out="./scenes")
|
|
139
|
+
usd_paths = realmetry.client.iter_usd_paths(scenes) # -> feed your Isaac Lab env / scene config
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
Lower level: `create_job`, `wait`, `job`, `jobs` (with `search=`), `rename`, `cancel`, `download_scene`,
|
|
143
|
+
`download_job`, `recipe_schema`, `folders`, `move`, `download_folder`. Every create/generate call accepts
|
|
144
|
+
`name="..."` and `folder="..."` (name or id).
|
|
145
|
+
|
|
146
|
+
## Other commands
|
|
147
|
+
|
|
148
|
+
```bash
|
|
149
|
+
realmetry jobs # recent jobs
|
|
150
|
+
realmetry jobs --search "training" # by part of the name, id prefix or seed
|
|
151
|
+
realmetry rename <job> "Training set v3" # no name = remove it
|
|
152
|
+
realmetry folders # folders with their jobs and ready scenes
|
|
153
|
+
realmetry recipes # recipes your team saved in the web app
|
|
154
|
+
realmetry jobs --since 2026-11-01 # jobs since a date (--archived: the archived ones)
|
|
155
|
+
realmetry archive JOB [JOB ...] # hide old jobs from lists (--undo brings them back)
|
|
156
|
+
realmetry download JOB1 JOB2 --out ./scenes # several jobs at once
|
|
157
|
+
realmetry generate --scenes 50 --saved-recipe "Grasping set v2" # request one by name
|
|
158
|
+
realmetry move <job> "Dataset v2" # no folder = take it out
|
|
159
|
+
realmetry status <job> # scenes and their state
|
|
160
|
+
realmetry download <job> --out ./scenes
|
|
161
|
+
realmetry cancel <job> # cancels scenes not started yet (their credits are released)
|
|
162
|
+
realmetry logout
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
Errors are explicit: `402` not enough credits (with how many are needed), `422` invalid recipe (which parameter
|
|
166
|
+
and why). Download links expire after 1 hour; `realmetry download <job>` asks for fresh ones any time.
|
|
167
|
+
|
|
168
|
+
## License
|
|
169
|
+
|
|
170
|
+
The SDK is MIT licensed (see `LICENSE`). Generating scenes uses the RealMetry service, under its [Terms of service](https://realmetry.co/terms).
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
realmetry/__init__.py,sha256=eVMKdw28La_Uov4oxl-thy5qexJvobW5tfwHvs7c-30,604
|
|
2
|
+
realmetry/cli.py,sha256=_PnB8858YXnvujoHqiQsbG2lvvdbWg0XMVJl6scC1KQ,17155
|
|
3
|
+
realmetry/client.py,sha256=b3WydV0lXRVKnlQ14QTWOABM92EJOUU30MhLp43ch0I,17167
|
|
4
|
+
realmetry/config.py,sha256=e2DA2BxMZ7ItjDb__E8d-j4Tg1najPQXjkSlB4dexis,1815
|
|
5
|
+
realmetry-0.1.0.dist-info/licenses/LICENSE,sha256=uydDtxv4u79us8tY2YCgGPe6VuCKMgj9WSMhMUr0vrs,1077
|
|
6
|
+
realmetry-0.1.0.dist-info/METADATA,sha256=TGrTN0910wt79I0qiHL54D5II0WQzs--KZJSOo5ibn8,7159
|
|
7
|
+
realmetry-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
8
|
+
realmetry-0.1.0.dist-info/entry_points.txt,sha256=HaCFWOvGSXIB3MEEL2eM4n_Ly6vGqcKQQG1fhocSyR4,49
|
|
9
|
+
realmetry-0.1.0.dist-info/top_level.txt,sha256=koskM6jAxprLWITJhVq4bu0HHsrnB9N9h0AUHzkynq0,10
|
|
10
|
+
realmetry-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 77 Render Studio LLC
|
|
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 @@
|
|
|
1
|
+
realmetry
|