Skip to content
Docs menu

Script the hub from Python

A small typed Python API for scripts and notebooks. It uploads, downloads, trains and runs sim tests like the CLI.

Prompt for your AI

Read https://mousemouse.ai/docs/python.md first. Write a Python script with the lucen package that downloads a dataset, trains a policy and runs its sim test. Ask me before anything that costs money or moves a robot.
Prompt for your AI
Read https://mousemouse.ai/docs/python.md first. Write a Python script with the lucen package that downloads a dataset, trains a policy and runs its sim test. Ask me before anything that costs money or moves a robot.

Use it from Python. from lucen import Hub is the lucen CLI's own engine behind a small typed API, for a training script or a notebook. It uploads, downloads, trains, follows runs, runs sim tests and handles robots, the way huggingface_hub gives you snapshot_download. Every method is the function the command line calls, with the same arguments. So a script and a terminal always agree on what an upload sends or what a 404 means.

Every Python example on this page is run in order against a real hub by a test. The block under each one is what it printed. … stands for a value that differs per hub, such as an id or a byte count. Where an example names this hub, it is printed with the address of the hub serving this page: https://api.mousemouse.ai for the API, https://mousemouse.ai for the web app.

Install

The module ships inside the lucen-cli distribution, so there is no separate package to install. The PyPI project named lucen is unrelated. Install lucen-cli into the environment your script runs in. The rollout extra adds MuJoCo and onnxruntime, which only sim tests and hub.robots need. Both packages need Python 3.12 or newer. A Mac's own python3 is older, so use a Python that uv installs.

uv pip install "lucen-cli[rollout]"

The generated client underneath is lucen-sdk, a package of its own. Use it when a script wants the API contract itself rather than this module:

pip install lucen-sdk
import lucen

print(lucen.__version__)
0.1.6

Hub()

Hub() resolves the hub and the key exactly as the CLI does: LUCEN_API_URL and LUCEN_API_KEY first, then ~/.config/lucen/credentials. That is the file lucen auth login writes at mode 0600, refused if another user can read it. Nothing is built in: with no address anywhere, Hub() raises and says how to set one rather than sending your key to a guess. Hub(url=…, key=…) overrides either, for a notebook that holds its key in its own secret store; a key is never read from a file the module did not document or an argument you did not pass.

from lucen import Hub

hub = Hub()
me = hub.me()
print(me.username, me.scopes)
you ('read', 'write', 'train')

Scopes nest (read ⊂ write ⊂ train) and the hub enforces them: a call the key may not make raises lucen.Forbidden naming the scope it needed (see Errors). The records every call returns are frozen dataclasses. They carry ids, URLs and counts as attributes, to_dict() for the object lucen … --json would have printed, and raw for the whole SDK object when you need a field the record does not carry.

1 · Download a robot

Every file is hashed while it streams and takes its name only when the sha256 matches the tree's; a second pull into the same directory downloads nothing. A public repo needs no key.

pulled = hub.pull("lucen/laika", "./laika")
print(pulled)
print(pulled.files_downloaded, "downloaded,", pulled.files_skipped, "already local")
Pulled lucen/laika: … file(s), … downloaded (…), 0 already local
… downloaded, 0 already local

2 · Upload a dataset

hub.push creates the repo when it does not exist (kind and public apply only then) and uploads what the hub does not already hold. Files are stored by their content. Download lucen/laika-demo and upload it as your own, and zero bytes move, because the hub already holds those bytes. Change one file and only that file uploads. Stop an upload midway and the next one sends only the parts that never arrived.

hub.pull("lucen/laika-demo", "./laika-demo")
pushed = hub.push("./laika-demo", "you/laika-demo", kind="dataset", public=True)
print(pushed)
print(pushed.url)
again = hub.push("./laika-demo", "you/laika-demo")
print(again.files_uploaded, "uploaded,", again.files_unchanged, "unchanged")
Created and pushed you/laika-demo: … file(s), 0 uploaded (0 B), … deduped, 0 unchanged
https://mousemouse.ai/you/laika-demo
0 uploaded, … unchanged

hub.repos.list(kind="dataset", owner="you"), .get("you/laika-demo"), .create(…) and .delete(…) are the rest of what a script does with repos; hub.datasets.episodes("you/laika-demo") reads the episode index the viewer shows.

3 · Train, and follow it

A run trains on a runner you start. It is free, because the hardware is yours. In a second terminal, with the same credentials:

lucen worker run

Then submit a recipe with follow=True: the call stays until the run ends and returns its final state. Every log line reaches on_log as a LogEvent (event.text is the line as lucen train --follow prints it: | for the trainer's own output, ! for a notice the hub wrote into the log). The built-in ppo_mujoco template trains a reflex policy in MuJoCo on your CPU. Sixty iterations is the train form's Quick test: about a minute and a half on a laptop, enough to stand still, not yet to walk. robot names the robot the policy is for. The runner reads its card, so the published ONNX carries that robot's joint order, which the sim test checks before it runs anything.

run = hub.runs.create(
    {"template": "ppo_mujoco", "robot": "lucen/laika", "hyperparams": {"iterations": 60}},
    follow=True,
    on_log=lambda event: print(event.text) if event.kind == "log" else None,
)
print(run.status, run.output_model_repo)
  | [lucen-ppo-mujoco] lucen/laika: base floating, 12 DoF, task velocity, obs 47 = base_ang_vel + projected_gravity + commands + joint_pos + joint_vel + last_action + gait_phase, fingerprint …
  | [lucen-ppo-mujoco] … envs x 24 steps x 60 iterations on … thread(s); dt 0.002 s x 10 = 50 Hz
  | [lucen-ppo-mujoco] not simulated: actuation.velocity_limit (MuJoCo has no per-joint velocity clamp)
  | [lucen-ppo-mujoco] harness conditions in training: action delay 2 control step(s) = 40 ms (harness); bridge slew on; pushes up to 0.4 m/s every 6-10 s; mirror symmetry off (off by hyperparams.mirror_symmetry)
  | [lucen-ppo-mujoco] terrain curriculum: levels 0-5, the flat floor up to 8 degree slopes and 4 cm steps, 2 m tiles; every robot starts on the floor (level 0)
  | [lucen-ppo-mujoco] initial exploration 0.25 rad per joint (log_std -0.693, init_action_noise_rad)
  | iter    1/60  return …
  | [lucen] published checkpoints/step_0/ to you/ppo-mujoco-… (2 file(s), … B, … B uploaded: policy.npz, ppo_velocity.onnx)
…
  | iter   60/60  return …
  | [lucen-ppo-mujoco] ppo_velocity.onnx stamped; export verified against the trained policy (max abs diff …)
  | [lucen-ppo-mujoco] done: … env steps in … s; episode return …
  | [lucen-ppo-mujoco] terrain: mean level 0.00 of 5; 0 promotion(s), 0 demotion(s)
  | [lucen] published checkpoints/step_60/ to you/ppo-mujoco-… (2 file(s), … B, … B uploaded: policy.npz, ppo_velocity.onnx)
succeeded you/ppo-mujoco-…

Without follow the run is returned queued at once; hub.runs.logs(id, follow=True) streams it later, hub.runs.get(id) reads its state, hub.runs.cancel(id) stops it (a queued run ends now, a running one is stopped by its runner within seconds), and hub.runs.estimate(recipe) / .recommend(recipe) price and plan a recipe before anything is created. The recipe may also be the path of the YAML file lucen train -f reads. Ctrl-C during a follow detaches; the run keeps going.

4 · Test it in sim

A sim test runs the published policy in MuJoCo on the robot's own MJCF and meshes, one command at a time, and the hub scores it. A test passes when every seed stays upright for the whole horizon and tracks its command within 15%. With local=True this machine runs the sim test (the rollout extra). run= attaches the scorecard to the training run. A local sim test that did not succeed raises HubError with the reason, as lucen rollout exits 1.

rollout = hub.rollouts.create(
    run.output_model_repo, "lucen/laika", battery="smoke", local=True, run=run.id
)
print(rollout)
for cell in rollout.cells:
    print(f"{cell.name:<9} {cell.verdict}  {cell.alive}/{cell.seeds} upright")
Sim test rollout_… (succeeded): you/ppo-mujoco-… on lucen/laika, Quick check. 1 of 5 tests pass.
stand     PASS  2/2 upright
vx+0.30   FAIL  2/2 upright
vy+0.10   FAIL  2/2 upright
vy-0.10   FAIL  2/2 upright
yaw+0.50  FAIL  2/2 upright

After sixty iterations the policy stands still and does not yet track a command, and that is what the sim test shows. Train for longer to change it: Long is 1,000 iterations. Measured on this template's current settings, a Long run stands with under 3° of tilt and tracks a sideways command at 12–22%, not yet a walk. Without local=True the sim test waits queued for a lucen rollout worker on any machine with the extra installed. hub.rollouts.get(id) reads it back once that runner reported.

5 · Read the scorecard

rollout.scorecard is the hub's verdict per test. Because the sim test named the run, the run now carries the same count as its gate. The Training Coach keeps every passing test as a constraint on anything it proposes about that run. hub.open(…) is the page's address on the web app (the origin the hub names, remembered the way lucen open remembers it).

print(rollout.scorecard)
print(hub.runs.get(run.id).gate)
print(hub.open(run.id))
{'stand': 'PASS', 'vx+0.30': 'FAIL', 'vy+0.10': 'FAIL', 'vy-0.10': 'FAIL', 'yaw+0.50': 'FAIL'}
1 / 5 PASS
https://mousemouse.ai/runs/run_…

Errors

Every refusal is one exception family, lucen.HubError, carrying the three lines a terminal user reads: message (what happened), detail (what the hub said, when it said anything) and fix (one line that makes the next attempt succeed). The subclass follows the status: NotSignedIn (401, or no key at all), Forbidden (403, and the fix names the scope), NotFound (404: absent, or private and not yours, which look the same), Conflict (409) and HubUnreachable (no answer, or a 502/504/52x from the network in front). A local refusal, such as a directory with no files or a reference that is not owner/slug, is a plain HubError.

from lucen import NotFound

try:
    hub.repos.get("lucen/no-such-robot")
except NotFound as error:
    print(error.status, "-", error.message)
    print("Fix:", error.fix)
404 - Reading lucen/no-such-robot: no such repo, or not yours.
Fix: `hub.repos.list()` shows the ones this credential can see; a private one you are not a member of looks the same as none.

Progress

Silent by default: the record is the whole answer. Hub(progress=True) prints exactly what the CLI prints on stderr: a bar on a terminal, one line per decile in a log. Hub(on_progress=callback) hands every milestone and byte count to a function of yours as a ProgressEvent, for a notebook widget; followed log lines arrive the same way when no on_log is given.

events = []
Hub(on_progress=events.append).pull("lucen/laika", "./laika-again")
print(events[0].kind, "-", events[0].message)
print(events[-1].kind, "-", events[-1].label, f"{events[-1].fraction:.0%}")
step - Downloading … file(s), … (0 already local)
bytes - Downloading 100%

What a script cannot do

The same two things no API key can do: mint a key (/v1/keys is session-only, so a leaked write key cannot promote itself) and approve a policy onto a robot (an agent or a script may request one; a signed-in person decides in the Inbox). The robot's own side is the lucen-device binary. hub.robots.init | validate | publish are Add your robot's three commands as methods, and hub.orgs is lucen org; both need the same scopes the commands do.

The surface

Hub(url=None, key=None, *, progress=False, on_progress=None, timeout=60.0)
  .me() -> Me                       .open(repo_or_id=None) -> str
  .push(path, repo, *, kind="dataset", public=False, rehash=False, description=None,
        jobs=8, dry_run=False, on_progress=None) -> PushResult
  .pull(repo, path=None, *, prefix=None, force=False, jobs=8, on_progress=None) -> PullResult
  .repos.list(*, kind=None, owner=None, q=None, limit=20) -> list[Repo]
        .get(repo) -> Repo · .create(repo, *, kind="dataset", public=False, description=None, tags=()) -> Repo
        .delete(repo) -> None
  .runs.create(recipe, *, executor=None, robot=None, parent=None, owner=None, idempotency_key=None,
               follow=False, on_log=None) -> Run
       .list(*, status=None, executor=None, owner=None, limit=20) -> list[Run] · .get(id) -> Run
       .logs(id, *, follow=False, tail=None) -> Iterator[LogEvent] · .cancel(id) -> Run
       .estimate(recipe) -> RunEstimate · .recommend(recipe) -> RunRecommendation
  .rollouts.create(model, robot, *, battery="smoke", seed=0, seeds=None, horizon_s=None, run=None,
                   conditions=None, checkpoint=None, executor="worker", local=False, name=None,
                   work_dir=None, video=True, keep=False, on_progress=None) -> Rollout
           .get(id) -> Rollout · .list(*, status=None, model=None, run=None, limit=20) · .cancel(id)
  .robots.init(path, *, control_hz, action, base=None, kp=None, kd=None, …) -> RobotDraft
         .validate(directory=".", *, card=None, settle_s=3.0, dynamics=True) -> RobotReport
         .publish(repo, directory=".", *, public=False, description=None, force=False, …) -> RobotPublishResult
         .card(repo) -> dict
  .orgs.list() · .create(slug, *, name=None, description=None) · .members(org)
       .add(org, username, *, role="member") · .remove(org, username) · .leave(org)
  .datasets.episodes(repo) -> list[Episode]

Next