Metadata-Version: 2.5
Name: dreamsports-mlops-client
Version: 0.1.1
Summary: Track MLOps platform experiments from any self-managed machine: metrics, artifacts, weights, and failure/cancel state reporting.
Project-URL: Homepage, https://gitee.com/rmkj/MLOps
Project-URL: Documentation, https://gitee.com/rmkj/MLOps/blob/master/documentation/docs/experiments/external-runs.md
License: Proprietary
Requires-Python: >=3.9
Description-Content-Type: text/markdown

# dreamsports-mlops-client

Track [MLOps platform](../documentation/docs/experiments/external-runs.md) experiments from any self-managed machine. Python ≥ 3.9, standard-library only.

## Install

```bash
uv pip install dreamsports-mlops-client
# pip also works
pip install dreamsports-mlops-client
```

Offline LAN alternative:

```bash
uv pip install http://<mlops-server>:18081/api/sdk/downloads/dreamsports_mlops_client-0.1.1-py3-none-any.whl
```

Development and verification use uv:

```bash
cd sdk
uv sync
uv run python -m unittest discover -s tests -v
uv build
```

## Quick start

```python
import dreamsports_mlops_client as mlops

mlops.login(server="http://mlops.example:18081", username="you@example.com")
print(mlops.whoami()["display_name"])

run = mlops.create_experiment(
    job="train",  # or mlops.Job.TRAIN; "val" / "export" also accepted
    name="yolo-coco128",  # optional — auto-generated when omitted
    out_dir="./runs/train",
)
run.log_metric({"loss": {"total": 1.2}, "lr": {"lr": 1e-3}}, epoch=0, split="train")
run.log_metric(ap5095={"box": {"mean": 0.42}}, epoch=0, split="val")
run.upload("weights/best.pt")
run.finish()
```

Public API: `login`, `whoami`, `create_experiment`, `Job`, `Run.log_metric`, `Run.upload`, `Run.finish`, read-only `Run.id/url/status`, and `MlopsError/MlopsAuthError/MlopsCancelled/MlopsConflict`.

## Login

`login(username=None, *, password=None, server=None)` resolves server from parameter > `MLOPS_SERVER` > `~/.mlops/config.json` (shared with the CLI) > legacy `~/.cache/mlops/config.json` > shared credentials `api_base` > interactive prompt, and reuses credentials from `MLOPS_TOKEN` > shared CLI credentials (`~/.mlops/credentials`) > legacy `~/.cache/mlops/token`. Passing `username` forces a fresh login and replaces stored credentials.

Password login creates a 30-day PAT named `sdk:<hostname>` and stores only the PAT (mode 0600) in the CLI-shared credentials file; the password never touches disk. With no local credentials in a terminal, `login()` shows a menu: email + password, or browser device authorization (approve on the web `/device` page). Non-interactive stdin without credentials raises `MlopsAuthError`. Any 401 raises `MlopsAuthError`. `whoami()` returns the `/api/auth/me` object, including `display_name`.

## Metrics

`Run.log_metric()` uses the same cleaning/merging helpers as the fixed-runtime `MlopsMetrics`. It supports the positional metrics tree plus `epoch/step/split/hero/loss/lr/ap5095/ap50/ap75/ar/precision/recall/f1/others/per_class`. When both epoch and step are omitted, an internal monotonic counter supplies step. NaN, ±inf and non-numeric leaves are dropped. Hero resolution: `hero` is a slash path to a numeric leaf in the metrics tree (e.g. `loss/total`, `AP50-95/box/mean`). An explicit `hero` that does not resolve warns and falls back to the first leaf under a dict branch (the warning lists every valid path of the row). When omitted, val/export rows first try the default `AP50-95/box/mean`, then the same fallback, so the Telemetry table heroMetric column is never empty. Bare top-level numeric keys (e.g. `{"total": 0.5}`) trigger a nesting-suggestion warning and are skipped by the fallback. Every row carries an RFC3339 `ts` shown in the Telemetry table. Warnings are multi-line: they name the call site (file:line), show `Got:`/`Expected:`, add a `did you mean` hint when a close path exists, and end with an online docs link (`MLOPS_DOCS_URL` overrides the derived `:13081` base); the same issue (same key set / same hero string) warns once per process. Non-numeric leaf values are dropped with the same kind of warning (NaN/None stay silent).

## Resource sampling

Every run also gets the Summary-page **Utilization / Memory** charts, matching worker experiments: a daemon thread samples whole-machine CPU/memory from `/proc` (Linux) and per-GPU utilization/memory from `nvidia-smi` every 5s. Samples stream live through the events channel while the run is in flight, and `finish()` uploads the full `resource_usage.jsonl` artifact so the charts survive completion. Unavailable sources (no NVIDIA GPU, non-Linux) are simply omitted. Set `MLOPS_SDK_RESOURCE_SAMPLING=0` to disable.

## Uploads

`Run.upload(source, *, recursive=True, include_hidden=False)` accepts a single file or a directory path (bytes and file objects are no longer supported). The artifact path is the file name (directories: `<root dir name>/<relative path>`), and the server classifies every file by extension — `run.upload("best.pt")` is registered as weights and auto-registers a TrainingModel on finish. Directories are walked recursively (disable with `recursive=False`), skip hidden `.`-prefixed entries unless `include_hidden=True`, skip symlinks/special files, and cap at 5000 files. Re-uploading an already-uploaded path is skipped with a warning. When a run has multiple weights artifacts, the server registers the last one whose name starts with `best` as the TrainingModel weights.

Each file follows presign → direct MinIO PUT → confirm. Files stream from disk (constant memory); each retry re-reads and re-hashes the source, so a file modified mid-retry uploads its newer bytes on the next attempt. A failed file retries at most five times with 1/2/5/10/30s backoff, then warns and releases its path for explicit retry. `finish()` waits for all pending artifact uploads to complete (up to `MLOPS_SDK_UPLOAD_TIMEOUT` seconds, default 1800) before posting; artifacts abandoned past that limit — or at the flush hard cap — are named in a warning instead of being silently dropped.

On a TTY with `capture_output=True` (the default), a live status line `[mlops] ↑ N artifact(s) uploading…` shows at the bottom of the terminal while background uploads run and disappears when done; it never reaches the Web Logs. Set `MLOPS_SDK_STATUS_LINE=0` to disable.

## Exit and cancellation semantics

| Event | Platform result |
|---|---|
| `finish()` / clean exit / `sys.exit(0)` | `completed` (`ok`) |
| Uncaught exception / `sys.exit(7)` | `failed` (`user_error`), original exit code retained |
| Ctrl+C / uncaught `MlopsCancelled` | `cancelled` |
| Web Cancel | heartbeat/events observes it; next `log_metric()` raises `MlopsCancelled` |
| Cancel + no finish for 60s | forced `cancelled` |
| `kill -9` / heartbeat lost for 120s | `failed` (`interrupted`) |

`create_experiment()` wraps `sys.excepthook`, `sys.exit` and atexit. Finish harvests `out_dir` before setting the local finished guard, drains the spool, then reports status. Repeated local finish is a no-op; a server 409 raises `MlopsConflict`.

## Terminal and threads

`capture_output=True` tees this process's stdout/stderr to Logs, including existing logging handlers. Carriage-return fragments flush on newline or after two seconds. Subprocess output and the real tty are not captured; blank lines are not uploaded, and writes to `sys.stdout.buffer` bypass the capture.

Three daemon background threads handle uploads/events, the 15-second heartbeat/cancel poll, and resource sampling. Finish waits up to five seconds for delivery. Several active runs in one process share the exit hooks and terminal capture — `create_experiment()` warns when another run is still active; prefer one active run per process.

## Manual release

```bash
./scripts/release-sdk.sh --verify
# Caller supplies the appropriate token; neither mode is run by CI:
TWINE_USERNAME=__token__ TWINE_PASSWORD=... ./scripts/release-sdk.sh --test-pypi
TWINE_USERNAME=__token__ TWINE_PASSWORD=... ./scripts/release-sdk.sh --pypi
```

Only `--verify` runs without upload credentials; besides building and checking `sdk/dist/release/` it also refreshes `sdk/dist/` (the download dir served by the API) with the verified wheel. Uploads are always explicit and require caller-provided tokens.
