Source code for dazpy._client

from __future__ import annotations

import os
import threading
import time
from contextlib import contextmanager
from typing import cast
from collections.abc import Callable, Iterator

import requests as _requests

from .exceptions import DazError
from ._geometry_frames import GeometryFrames, geometry_frames_payload, parse_geometry_frames
from ._result import ExecutionResult
from ._version import (
    VersionCheck,
    server_version_from_status,
    ATOMIC_RENDER_BATCH_VERSION,
    server_at_least,
)
# The response/request helpers live in _client_base (shared with the async
# client); they are re-exported here for existing importers.
from ._client_base import (  # noqa: F401
    _BaseClient,
    _DEFAULT_HOST,
    _DEFAULT_PORT,
    _HTTPResponse,
    _MAX_BACKOFF,
    _TOKEN_FILE,
    _artifact_targets,
    _authentication_error,
    _batch_script,
    _bytes_or_file,
    _cancel_route,
    _events_params,
    _is_artifact_refusal,
    _job_headers,
    _json_ok,
    _json_or_not_found,
    _load_token,
    _map_response,
    _parse_retry_after,
    _raise_for_error,
    _range_header,
    _render_animation_payload,
    _render_batch_payload,
    _render_payload,
    _result_query,
    _retry_delay,
    _safe_artifact_filename,
    _script_payload,
    _submitted_request_id,
    _thumbnail_params,
)


[docs] class DazClient(_BaseClient): """HTTP client for the DAZ Studio Script Server. Handles authentication, request serialisation, and response mapping for all server endpoints. The token is loaded automatically from ``~/.daz3d/dazscriptserver_token.txt`` when *token* is ``None``. Args: host: Hostname or IP address of the Script Server. port: Listening port of the Script Server. token: API token. Pass an empty string to disable authentication or ``None`` to auto-load from the default token file. timeout: Per-request HTTP timeout in seconds. check_version: Before the first request, and again after a connection failure or when the plugin's ``X-Server-Instance-Id`` changes (Studio restarted), read the plugin version from ``GET /status`` and emit a :class:`~dazpy.exceptions.ServerVersionWarning` if it is older than :data:`dazpy.MIN_SERVER_VERSION`. Failures of the check itself are ignored. on_version_check: Optional callable receiving a :class:`~dazpy.VersionCheck` after every completed check (compatible or not), on the thread that ran it. Exceptions it raises are swallowed. The latest result is also :attr:`version_check`. Requests are issued through a pooled ``requests.Session`` for connection reuse. Call :meth:`close` when done, or use as a context manager:: client = DazClient() # default 127.0.0.1:18811 client = DazClient(token="my-secret-token") # explicit token with DazClient() as client: result = client.execute("1 + 1;") """ _CONNECT_ERRORS = (_requests.exceptions.ConnectionError,) _TIMEOUT_ERRORS = (_requests.exceptions.Timeout,) _TRANSPORT_ERRORS = (_requests.exceptions.RequestException,) def __init__( self, host: str = _DEFAULT_HOST, port: int = _DEFAULT_PORT, token: str | None = None, timeout: float = 30.0, check_version: bool = True, on_version_check: Callable[[VersionCheck], object] | None = None, ): super().__init__(host, port, token, timeout, check_version, on_version_check) self._session = _requests.Session() def __enter__(self) -> DazClient: return self def __exit__(self, *exc_info) -> None: self.close()
[docs] def close(self) -> None: """Close the underlying ``requests.Session``'s pooled connections.""" self._session.close()
def _send(self, method: str, path: str, headers: dict | None, timeout: float | None, **kwargs) -> _requests.Response: """Issue one request through the session (``_post``/``_get``/``_delete``).""" self._check_server_version() try: return self._observe(getattr(self._session, method)( f"{self._base}{path}", headers=self._merged_headers(headers), timeout=self._http_timeout(timeout), **kwargs, )) except self._TRANSPORT_ERRORS as e: raise self._transport_error(e, timeout) from e def _check_server_version(self) -> None: """Best-effort plugin version check (see ``check_version``).""" if not self._versions.claim_check(): return check = None try: check = self._version_check_from_status(self._session.get( f"{self._base}/status", headers=self._headers, timeout=self._timeout )) except Exception: check = None # unreachable/odd server: let the real request report it finally: self._versions.finish_check(check) @property def server_version(self) -> str | None: """The connected server's version string, or ``None`` if unknown.""" known = self._known_server_version() if known is None: try: known = self._server_version = server_version_from_status(self.status()) except Exception: return None return known
[docs] @contextmanager def waiting_out_busy(self, max_wait: float) -> Iterator[DazClient]: """Within the block, this client's script execution and submission calls on this thread (``execute``, ``execute_file``, registered-script and async submits, render submits) retry a busy Studio for up to *max_wait* seconds, as if passed ``retry_on_busy=True`` -- including those made for you by :class:`~dazpy.DazNode`, :class:`~dazpy.DazScene` and the other proxies. Other threads are unaffected. A call's own ``retry_on_busy=True, max_wait=...`` takes precedence; nested blocks keep the longer wait. Use it around a multi-call operation that must not fail halfway because Studio briefly reports busy (Studio 6 does after a load or clear, while it streams in background content). """ local = self.__dict__.setdefault("_busy_wait", threading.local()) prev = getattr(local, "max_wait", None) local.max_wait = float(max_wait) if prev is None else max(prev, float(max_wait)) try: yield self finally: local.max_wait = prev
def _scoped_busy_wait(self) -> float | None: return getattr(self.__dict__.get("_busy_wait"), "max_wait", None) def _with_busy_retry(self, fn, retry_on_busy: bool, max_wait: float, *, retry_server_errors: bool | Callable[[], bool] = True): """Run *fn* (a zero-arg callable), retrying busy and server-marked ``retryable`` errors while *retry_on_busy* is true (or inside :meth:`waiting_out_busy`), up to *max_wait* seconds total. Each wait is at least the server's ``Retry-After``. *retry_server_errors* False (or a callable returning False, evaluated at each failure) limits retries to busy errors, for routes where a ``retryable`` server error can follow a partial success. """ deadline = self._busy_deadline(retry_on_busy, max_wait) if deadline is None: return fn() backoff = 1.0 while True: try: return fn() except DazError as exc: pause = self._retry_pause(exc, deadline, backoff, retry_server_errors) if pause is None: raise time.sleep(pause) backoff = min(backoff + 1.0, _MAX_BACKOFF)
[docs] def execute( self, script: str, args: object = None, *, retry_on_busy: bool = False, max_wait: float = 30.0, timeout: float | None = None, ) -> ExecutionResult: """Execute a DazScript string synchronously. Args: script: DazScript source code to execute. args: Optional value passed into the script as ``getArguments()[0]``. Must be JSON-serialisable. retry_on_busy: If ``True``, transparently retry with backoff when the server reports ``StudioBusyError``/``ConcurrencyLimitError`` or another error marked ``retryable`` (rate limited, queue full), waiting at least its ``Retry-After``, instead of raising immediately. max_wait: Maximum total seconds to retry when *retry_on_busy* is ``True``, before re-raising the busy error. timeout: HTTP timeout in seconds for this call only (default: the client's *timeout*). Give slow scripts, such as the first content load after Studio starts, more time. Returns: The execution result containing the script return value and any console output. Raises: ConnectionError: If the server cannot be reached. AuthenticationError: If the token is invalid or the IP is blocked. ScriptSyntaxError: If the script contains a parse error. ScriptRuntimeError: If the script raises a runtime exception. StudioBusyError: If DAZ Studio's main thread is busy and *retry_on_busy* is ``False`` or *max_wait* is exceeded. ConcurrencyLimitError: If too many concurrent requests are in flight and *retry_on_busy* is ``False`` or *max_wait* is exceeded. TimeoutError: If the request exceeds *timeout* seconds. """ payload = _script_payload({"script": script}, args) def _do(): return _map_response(self._post("/execute", payload, timeout=timeout), script=script) return self._with_busy_retry(_do, retry_on_busy, max_wait)
[docs] def execute_file( self, script_file: str, args: object = None, *, retry_on_busy: bool = False, max_wait: float = 30.0 ) -> ExecutionResult: """Execute a ``.dsa`` script file that resides on the DAZ Studio host. Args: script_file: Absolute path to the ``.dsa`` file on the server host. args: Optional argument passed to the script. retry_on_busy: If ``True``, transparently retry with backoff when the server reports ``StudioBusyError``/``ConcurrencyLimitError`` or another error marked ``retryable`` (rate limited, queue full), waiting at least its ``Retry-After``, instead of raising immediately. max_wait: Maximum total seconds to retry when *retry_on_busy* is ``True``, before re-raising the busy error. Returns: The execution result. Raises: ConnectionError: If the server cannot be reached. AuthenticationError: On auth failure. ScriptSyntaxError: On parse error. ScriptRuntimeError: On runtime error. StudioBusyError: If DAZ Studio's main thread is busy and *retry_on_busy* is ``False`` or *max_wait* is exceeded. ConcurrencyLimitError: If too many concurrent requests are in flight and *retry_on_busy* is ``False`` or *max_wait* is exceeded. TimeoutError: On HTTP timeout. """ payload = _script_payload({"scriptFile": script_file}, args) def _do(): return _map_response(self._post("/execute", payload)) return self._with_busy_retry(_do, retry_on_busy, max_wait)
[docs] def execute_async_submit( self, script: str, args: object = None, *, report_file: str | None = None, retry_on_busy: bool = False, max_wait: float = 30.0, idempotency_key: str | None = None, correlation_id: str | None = None, ) -> str: """Submit a script for asynchronous execution and return immediately. Args: script: DazScript source code. args: Optional argument for the script. report_file: Optional host-side JSONL file used by the script to report structured progress, logs, and output artefacts. retry_on_busy: If ``True``, transparently retry with backoff when the server reports ``StudioBusyError``/``ConcurrencyLimitError`` or another error marked ``retryable`` (rate limited, queue full), waiting at least its ``Retry-After``, instead of raising immediately. max_wait: Maximum total seconds to retry when *retry_on_busy* is ``True``, before re-raising the busy error. idempotency_key: Optional ``Idempotency-Key``. Resubmitting the same body with the same key returns the original ``request_id`` instead of queueing a second job, which makes retries after a timeout safe. Accepted by every ``*_submit`` method. correlation_id: Optional ``X-Correlation-Id`` stored on the job and echoed in its status/result records. Returns: The server-assigned ``request_id`` string. Use it with :meth:`get_request_status` or :meth:`get_request_result` to poll for the outcome. Raises: ConnectionError: If the server cannot be reached. AuthenticationError: On auth failure. StudioBusyError: If DAZ Studio's main thread is busy and *retry_on_busy* is ``False`` or *max_wait* is exceeded. ConcurrencyLimitError: If too many concurrent requests are in flight and *retry_on_busy* is ``False`` or *max_wait* is exceeded. """ payload = _script_payload({"script": script}, args, report_file) def _do(): return _submitted_request_id(self._post( "/execute/async", payload, _job_headers(idempotency_key, correlation_id))) return self._with_busy_retry(_do, retry_on_busy, max_wait)
[docs] def execute_file_async_submit( self, script_file: str, args: object = None, *, report_file: str | None = None, retry_on_busy: bool = False, max_wait: float = 30.0, idempotency_key: str | None = None, correlation_id: str | None = None, ) -> str: """Submit a host-side ``.dsa`` file for asynchronous execution. The file is loaded by DAZ Studio when the queued job starts, preserving its filename for ``getScriptFileName()`` and relative ``include()`` calls. Returns the server-assigned request id immediately; use the request status/result/cancel methods to manage its lifecycle. """ payload = _script_payload({"scriptFile": script_file}, args, report_file) def _do(): return _submitted_request_id(self._post( "/execute/async", payload, _job_headers(idempotency_key, correlation_id))) return self._with_busy_retry(_do, retry_on_busy, max_wait)
[docs] def execute_batch_async( self, operations: list[dict], args: object = None, *, report_file: str | None = None ) -> str: """Submit multiple operations as one async request (one queue slot, one script). Args: operations: List of ``{"body_lines": [...], "result_expression": "..."}`` dicts — same shape as :meth:`~dazpy.Batch.add_operation`'s arguments. args: Optional argument passed to the combined script. report_file: Optional host-side JSONL file used for structured job observation, as in :meth:`execute_async_submit`. Returns: The server-assigned ``request_id``. Poll it like any other async request; the result's ``result`` field is a dict keyed ``"_r0"``, ``"_r1"``, ... in submission order. """ return self.execute_async_submit( _batch_script(operations), args=args, report_file=report_file)
[docs] def register_script(self, name: str, script: str, description: str = "") -> dict: """Register or replace a named DazScript on the server.""" return _json_ok(self._post( "/scripts/register", {"name": name, "description": description, "script": script}, ))
[docs] def list_scripts(self) -> list[dict]: """Return the registered scripts. Returns: One dict per script with ``"name"``, ``"registered_at"`` and, when given at registration, ``"description"``. The registry is in-memory, so it is empty after a server restart. """ return _json_ok(self._get("/scripts")).get("scripts", [])
[docs] def delete_script(self, name: str, *, missing_ok: bool = False) -> bool: """Remove a registered script. Args: name: The script's registered name. missing_ok: Return ``False`` instead of raising when no script has that name. Returns: ``True`` if the script was removed, ``False`` if it was not registered and *missing_ok* is true. Raises: ServerResponseError: ``error_code == "SCRIPT_NOT_FOUND"`` when the name is unknown and *missing_ok* is false. """ resp = self._delete(f"/scripts/{name}") if resp.status_code == 404 and missing_ok: return False _raise_for_error(resp) return True
[docs] def export_geometry_frames( self, frames, *, node: str | None = None, indices=None, surfaces=None, bones=None, resolution: str = "base", scene_update: bool = True, channels=None, values=None, vertices: bool = True, timeout: float | None = None, ) -> GeometryFrames: """Export the deformed figure mesh and bone origins for several frames. One native call (``POST /geometry/frames``), about 25x faster than a DazScript loop. Only the figure is re-evaluated per frame; the original frame and resolution level are restored afterwards. Args: frames: Frame numbers to evaluate (at least one). node: Figure name or label. Default: the first figure. indices: Vertex subset to return. surfaces: Surface names whose vertices are added to the subset. bones: Bones whose world-space origins are returned per frame. resolution: ``"base"`` (base cage, default) or ``"current"``. scene_update: ``False`` skips the final Scene update (about 130 ms). For back-to-back calls, let only the last update. channels: Override channels, each ``{"bone": b, "property": p}``, ``{"node": n, "property": p}``, ``{"morph": m}`` or ``{"property": p}`` (on the figure). Requires *values*. values: Override sets, one row per set with one number per channel. Each frame is evaluated once per set and every channel is restored afterwards; the result is then per set (``result.sets[i]``), and ``result.restore_mismatches`` should be 0. vertices: ``False`` returns bone origins only and skips the mesh deformation, for pure bone IK. Requires *bones*; not with *indices*/*surfaces*. ``result.vertices`` holds an empty list per frame. timeout: HTTP timeout for this call; defaults to the client's. Raise it for long frame lists on heavy figures. Returns: A :class:`~dazpy.GeometryFrames`. """ payload = geometry_frames_payload( frames, node, indices, surfaces, bones, resolution, scene_update, channels, values, vertices) resp = self._post("/geometry/frames", payload, timeout=timeout) _raise_for_error(resp) return parse_geometry_frames(resp.content, payload.get("bones", []))
[docs] def execute_registered( self, name: str, args: object = None, *, retry_on_busy: bool = False, max_wait: float = 30.0, ) -> ExecutionResult: """Execute a registered script by name.""" payload = _script_payload({}, args) def _do(): return _map_response(self._post(f"/scripts/{name}/execute", payload)) return self._with_busy_retry(_do, retry_on_busy, max_wait)
[docs] def execute_registered_async_submit( self, name: str, args: object = None, *, report_file: str | None = None, retry_on_busy: bool = False, max_wait: float = 30.0, idempotency_key: str | None = None, correlation_id: str | None = None, ) -> str: """Submit a registered script and return its async request id.""" payload = _script_payload({}, args, report_file) def _do(): return _submitted_request_id(self._post( f"/scripts/{name}/async", payload, _job_headers(idempotency_key, correlation_id))) return self._with_busy_retry(_do, retry_on_busy, max_wait)
[docs] def get_request_status(self, request_id: str) -> dict: """Return the current status of an async request. Args: request_id: The ID returned by :meth:`execute_async_submit`. Returns: A dict with at least ``"status"`` and ``"observation"`` keys. Observation contains structured progress, the bounded log tail, and the output manifest. Possible status values: ``"queued"``, ``"running"``, ``"cancel_requested"``, ``"stale"``, ``"completed"``, ``"failed"``, ``"cancelled"``, ``"completed_after_cancel_request"``, ``"completed_after_stale"``, or ``"not_found"``. ``cancel_requested`` and ``stale`` are not final: a running script can't be interrupted, so once it returns the status changes to its real outcome. ``cancelled`` means the work really stopped (it never started, or a render was aborted). """ return _json_or_not_found(self._get(f"/requests/{request_id}/status"))
[docs] def get_request_result(self, request_id: str, wait: bool = False, wait_timeout: int = 30) -> dict: """Fetch the result of a completed async request. Args: request_id: The ID returned by :meth:`execute_async_submit`. wait: If ``True``, the server will long-poll until the request completes or *wait_timeout* is reached. wait_timeout: Maximum number of seconds the server should wait before returning (only relevant when *wait* is ``True``). Returns: A dict containing ``success``, ``result``, ``output``, ``error``, ``duration_ms``, ``status``, and ``observation`` keys. """ params, request_timeout = _result_query(wait, wait_timeout) return _json_or_not_found(self._get( f"/requests/{request_id}/result", params=params, timeout=request_timeout))
[docs] def list_requests(self, status: str | None = None) -> dict: """List all tracked async requests (script and render) with their status. Args: status: Optional filter: any status value listed in :meth:`get_request_status` (e.g. ``"running"``, ``"cancel_requested"``, ``"completed"``). Omit to list requests in every status. Returns: A dict with a ``"requests"`` list (each item has ``request_id``, ``status``, ``progress``, ``submitted_at``) plus ``total`` and a per-status count for every status value. """ return _json_ok(self._get("/requests", params={"status": status} if status else None))
[docs] def cancel_request_detail(self, request_id: str) -> dict: """Cancel a script or render request and return the server response.""" method, path = _cancel_route(request_id) return _json_ok(self._post(path, {}) if method == "post" else self._delete(path))
[docs] def cancel_request(self, request_id: str) -> bool: """Cancel a queued or running async request. Args: request_id: The ID returned by :meth:`execute_async_submit`. Returns: ``True`` if the server accepted the cancel, ``False`` otherwise. A queued request is cancelled at once; a running one only becomes ``cancel_requested`` (scripts can't be interrupted), so poll the request for its real outcome. """ try: self.cancel_request_detail(request_id) return True except DazError: return False
# ── Artifacts ─────────────────────────────────────────────────────────────
[docs] def list_artifacts(self, request_id: str) -> dict: """List the files an async job declared (GET /artifacts/{request_id}). A job's artifacts are its output manifest: outputs declared in its ``reportFile`` (``output``/``manifest`` events), plus the image(s) a render job wrote. Use them to fetch results from a DAZ Studio host whose filesystem the client can't see. Returns: A dict with ``request_id``, ``status``, ``count`` and an ``artifacts`` list. Each entry has ``artifact_id``, ``url``, ``path``, ``filename``, ``content_type``, ``size`` (``None`` when unavailable), ``available`` and any ``kind``/``label``/``metadata`` the job declared. Raises: ServerResponseError: ``REQUEST_NOT_FOUND`` for an unknown or expired job. """ return _json_ok(self._get(f"/artifacts/{request_id}"))
[docs] def download_artifact( self, request_id: str, artifact_id: str | int, dest: str | os.PathLike[str] | None = None, *, byte_range: tuple[int, int | None] | None = None, chunk_size: int = 1 << 20, timeout: float | None = None, ) -> bytes | str: """Download one declared artifact (GET /artifacts/{request_id}/{artifact_id}). Args: request_id: The async job's id. artifact_id: The manifest entry's ``artifact_id``. dest: Local file to stream the content into. When omitted the content is returned as ``bytes``. byte_range: ``(start, end)`` inclusive byte offsets, or ``(start, None)`` for "from *start* to the end". Sent as an HTTP ``Range`` header; the server answers 206. chunk_size: Streaming chunk size when writing to *dest*. timeout: Socket timeout; defaults to the client's timeout. Returns: The content as ``bytes``, or the path written when *dest* is given. Raises: ServerResponseError: ``ARTIFACT_NOT_FOUND`` (404) when the job declared no such artifact, ``ARTIFACT_UNAVAILABLE`` (410) when the declared file is gone, ``ARTIFACT_OUTSIDE_ROOTS`` (403) when its real path is outside the server's allowed artifact folders, ``REQUEST_NOT_FOUND`` for an unknown job, or HTTP 416 for a range outside the file. """ resp = self._send("get", f"/artifacts/{request_id}/{artifact_id}", _range_header(byte_range), timeout, stream=True) try: _raise_for_error(resp) if dest is None: return resp.content path = os.fspath(dest) with open(path, "wb") as f: for chunk in resp.iter_content(chunk_size=chunk_size): if chunk: f.write(chunk) return path finally: resp.close()
[docs] def get_artifact_thumbnail( self, request_id: str, artifact_id: str | int, size: int = 256, *, format: str = "png", dest: str | os.PathLike[str] | None = None, timeout: float | None = None, ) -> bytes | str: """Fetch a scaled preview of an image artifact (GET /artifacts/{request_id}/{artifact_id}?thumbnail=<size>). The longest edge fits in *size* pixels, the aspect ratio is kept and the image is never upscaled. Check ``thumbnail_supported`` on :meth:`list_artifacts` entries first; ``/capabilities`` lists the decodable types under ``thumbnail_source_formats``. Args: request_id: The async job's id. artifact_id: The manifest entry's ``artifact_id``. size: Longest edge in pixels, 16-1024. format: ``"png"`` (keeps alpha) or ``"jpeg"`` (alpha flattened onto white). dest: Local file to write the thumbnail to. When omitted the encoded image is returned as ``bytes``. timeout: Socket timeout; defaults to the client's timeout. Returns: The encoded image as ``bytes``, or the path written when *dest* is given. Raises: ServerResponseError: ``THUMBNAIL_UNSUPPORTED`` (422) when the artifact isn't a decodable image or is too large, ``INVALID_FIELD`` (400) for a bad *size*/*format*, plus the :meth:`download_artifact` errors. StudioBusyError: Studio's main thread is busy (rendering, loading a scene, running a long job); retry after ``retry_after``. Cached thumbnails are still served while busy. """ resp = self._get(f"/artifacts/{request_id}/{artifact_id}", params=_thumbnail_params(size, format), timeout=timeout) _raise_for_error(resp) return _bytes_or_file(resp.content, dest)
[docs] def download_artifacts( self, request_id: str, dest_dir: str | os.PathLike[str] ) -> list[str]: """Download every available artifact of a job into *dest_dir*. Files are named ``<artifact_id>_<filename>`` so two outputs with the same base name can't overwrite each other. Unavailable entries are skipped. Returns the paths written, in manifest order. """ # With a dest, download_artifact returns the written path (str). return [cast(str, self.download_artifact(request_id, aid, path)) for aid, path in _artifact_targets(self.list_artifacts(request_id), dest_dir)]
# ── Render ────────────────────────────────────────────────────────────────
[docs] def render_submit( self, output_path: str, *, figure: str | None = None, morphs: dict | None = None, figures: list | None = None, width: int = 0, height: int = 0, camera: str = "", engine: str = "", iray_samples: int = 0, reset_morphs: bool = False, retry_on_busy: bool = False, max_wait: float = 30.0, idempotency_key: str | None = None, correlation_id: str | None = None, ) -> dict: """Submit a render job and return immediately. Args: output_path: Absolute path on the DAZ Studio host to write the image. figure: Label of the figure to configure morphs on. morphs: Morph values to apply ``{label: value}``. figures: List of ``{"name": ..., "morphs": {...}}`` dicts for multi-figure scenes. width: Image width in pixels (must be paired with *height*). height: Image height in pixels (must be paired with *width*). camera: Camera label to render from. engine: Render engine (``"iray"``, ``"viewport"``, ``"filament"``). iray_samples: iRay sample count (0 = use scene default). reset_morphs: If ``True``, reset all morphs to defaults before applying. retry_on_busy: If ``True``, transparently retry with backoff when the server reports ``StudioBusyError``/``ConcurrencyLimitError`` or another error marked ``retryable`` (rate limited, queue full), waiting at least its ``Retry-After``, instead of raising immediately. max_wait: Maximum total seconds to retry when *retry_on_busy* is ``True``, before re-raising the busy error. Returns: A dict with ``request_id``, ``status`` (``"queued"``), and ``submitted_at`` keys. Raises: ConnectionError: If the server cannot be reached. AuthenticationError: On HTTP 401/403. StudioBusyError: If DAZ Studio's main thread is busy and *retry_on_busy* is ``False`` or *max_wait* is exceeded. ConcurrencyLimitError: If too many concurrent requests are in flight and *retry_on_busy* is ``False`` or *max_wait* is exceeded. """ payload = _render_payload( output_path, figure=figure, morphs=morphs, figures=figures, width=width, height=height, camera=camera, engine=engine, iray_samples=iray_samples, reset_morphs=reset_morphs) def _do(): return _json_ok(self._post("/render", payload, _job_headers(idempotency_key, correlation_id))) return self._with_busy_retry(_do, retry_on_busy, max_wait)
[docs] def render_batch_submit( self, variants: list, base: dict | None = None, *, retry_on_busy: bool = False, max_wait: float = 30.0, idempotency_key: str | None = None, correlation_id: str | None = None, ) -> dict: """Submit a batch render job and return immediately. Args: variants: List of variant dicts, each with at least ``output_path``. Supported keys mirror :meth:`render_submit` optional fields. base: Optional shared defaults applied to all variants. retry_on_busy: If ``True``, transparently retry with backoff when the server reports ``StudioBusyError``/``ConcurrencyLimitError`` or another error marked ``retryable`` (rate limited, queue full), waiting at least its ``Retry-After``, instead of raising immediately. Other ``retryable`` errors are retried only on plugin 2.17+, where a rejected batch queued nothing; older plugins could partially accept it. max_wait: Maximum total seconds to retry when *retry_on_busy* is ``True``, before re-raising the busy error. Returns: A dict with ``batch_id``, ``request_ids`` (list), and ``total`` keys. Raises: ConnectionError: If the server cannot be reached. AuthenticationError: On HTTP 401/403. StudioBusyError: If DAZ Studio's main thread is busy and *retry_on_busy* is ``False`` or *max_wait* is exceeded. ConcurrencyLimitError: If too many concurrent requests are in flight and *retry_on_busy* is ``False`` or *max_wait* is exceeded. """ payload = _render_batch_payload(variants, base) def _do(): return _json_ok(self._post("/render/batch", payload, _job_headers(idempotency_key, correlation_id))) # Before plugin 2.17 a queue-full 503 here could follow a partial # accept, and resubmitting would duplicate the queued variants. return self._with_busy_retry( _do, retry_on_busy, max_wait, retry_server_errors=lambda: server_at_least(self.version_check, ATOMIC_RENDER_BATCH_VERSION))
[docs] def render_animation_submit( self, output_path: str, start_frame: int, end_frame: int, *, frame_padding: int = 4, width: int = 0, height: int = 0, camera: str = "", engine: str = "", retry_on_busy: bool = False, max_wait: float = 30.0, idempotency_key: str | None = None, correlation_id: str | None = None, ) -> dict: """Submit an animation render job spanning a frame range and return immediately. Renders each frame in ``[start_frame, end_frame]`` to a separate file, as a single trackable async request (mirrors :meth:`render_submit`'s request-tracking shape, not :meth:`render_batch_submit`'s fan-out). Args: output_path: Output path pattern containing the literal token ``"{frame}"``, e.g. ``r"C:\\tmp\\anim\\frame_{frame}.png"``. The token is replaced with the frame number, zero-padded to *frame_padding* digits. start_frame: First frame to render (inclusive). end_frame: Last frame to render (inclusive). frame_padding: Zero-padding width for the frame number (default ``4``). width: Image width in pixels (must be paired with *height*). height: Image height in pixels (must be paired with *width*). camera: Camera label to render from. engine: Render engine (``"iray"``, ``"viewport"``, ``"filament"``). retry_on_busy: If ``True``, transparently retry with backoff when the server reports ``StudioBusyError``/``ConcurrencyLimitError`` or another error marked ``retryable`` (rate limited, queue full), waiting at least its ``Retry-After``, instead of raising immediately. max_wait: Maximum total seconds to retry when *retry_on_busy* is ``True``, before re-raising the busy error. Returns: A dict with ``request_id``, ``status`` (``"queued"``), and ``submitted_at`` keys. Raises: ConnectionError: If the server cannot be reached. AuthenticationError: On HTTP 401/403. StudioBusyError: If DAZ Studio's main thread is busy and *retry_on_busy* is ``False`` or *max_wait* is exceeded. ConcurrencyLimitError: If too many concurrent requests are in flight and *retry_on_busy* is ``False`` or *max_wait* is exceeded. """ payload = _render_animation_payload( output_path, start_frame, end_frame, frame_padding=frame_padding, width=width, height=height, camera=camera, engine=engine) def _do(): return _json_ok(self._post("/render/animation", payload, _job_headers(idempotency_key, correlation_id))) return self._with_busy_retry(_do, retry_on_busy, max_wait)
[docs] def cancel_render(self, request_id: str) -> bool: """Cancel a queued or running render job. Args: request_id: The ``request_id`` from :meth:`render_submit` or a :class:`~dazpy._render_api.RenderResult` with ``wait=False``. Returns: ``True`` if the server accepted the cancel, ``False`` otherwise (already finished, not found, or connection error). A running render is aborted via ``killRender()``; poll for the final status. """ if not request_id.startswith("rnd-"): return False return self.cancel_request(request_id)
[docs] def stream_render_progress(self, request_id: str, stream_timeout: float = 305.0) -> _requests.Response | None: """Open the SSE progress stream for a render request. Returns a streaming :class:`requests.Response` on success, or ``None`` if the endpoint is unavailable. Callers must close the response when done. """ try: resp = self._session.get( f"{self._base}/render/{request_id}/progress", headers=self._headers, stream=True, timeout=stream_timeout, ) except _requests.exceptions.RequestException: return None if resp.status_code != 200: resp.close() return None return resp
[docs] def stream_scene_events( self, categories: list[str] | None = None, stream_timeout: float | None = None, ) -> _requests.Response | None: """Open the SSE stream for general scene-change events (GET /scene/events). Args: categories: Optional subset of event categories to subscribe to (``"node"``, ``"skeleton"``, ``"light"``, ``"camera"``, ``"selection"``, ``"scene"``, ``"time"``, ``"render"``). ``None`` (default) subscribes to all categories. stream_timeout: Socket timeout in seconds. ``None`` (default) waits indefinitely — the server sends a keepalive comment every 15 seconds, so the connection never idles out. Returns: A streaming :class:`requests.Response` on success, or ``None`` if the endpoint is unavailable. Callers must close the response when done (e.g. via a ``with`` statement). """ try: resp = self._session.get( f"{self._base}/scene/events", headers=self._headers, params=_events_params(categories), stream=True, timeout=stream_timeout, ) except _requests.exceptions.RequestException: return None if resp.status_code != 200: resp.close() return None return resp
# ── Server health ─────────────────────────────────────────────────────────
[docs] def status(self) -> dict: """Return the server status dict from ``GET /status``. Raises: AuthenticationError: On HTTP 401/403. """ return _json_ok(self._get("/status"))
[docs] def health(self) -> dict: """Return the health check dict from ``GET /health``. Raises: AuthenticationError: On HTTP 401/403. """ return _json_ok(self._get("/health"))
[docs] def metrics(self) -> dict: """Return the metrics dict from ``GET /metrics``. Raises: AuthenticationError: On HTTP 401/403. """ return _json_ok(self._get("/metrics"))
[docs] def capabilities(self) -> dict: """Return the server's capabilities document from ``GET /capabilities``. Describes the server/DAZ Studio/SDK versions, routes (including companion-plugin routes), feature flags, current limits, and the render engines registered right now (``render_engines.selectable`` lists the values ``render(engine=...)`` accepts). While DAZ Studio is busy the server returns its last snapshot, marked ``render_engines.source == "snapshot"``. ``compatibility_hash`` changes only when routes, feature flags or the schema change. Servers that predate this endpoint answer 404. Raises: AuthenticationError: On HTTP 401/403. ServerResponseError: On HTTP 404 from a server without ``/capabilities`` (``status_code == 404``). StudioBusyError: On HTTP 503 before the server has a snapshot. """ return _json_ok(self._get("/capabilities"))