Complete API examples

These are complete executable examples, loaded from the same example files used by the developer portal. Each training example creates a dataset, uploads files, finalizes it, starts training and polls for the result.

These commands submit real work
Use your own API key and capture data. Running the training examples consumes the account’s applicable project and training allowance. Start with a directory containing at least 25 valid JPEG photographs of one static subject. Never put the secret in source control.

The examples require training:write and training:read. They print the result Capture URL; they do not download a binary model. Save each code block using the displayed filename. Environment variables below use shell syntax; substitute your own secret locally.

Resuming after an upload session expires
The Python and Node.js examples resume transfers while their saved upload URLs remain valid. They cache those URLs and do not automatically recover an expired session. If a saved session has expired, follow upload allocation recovery using the original allocation request and Idempotency-Key, then update the saved session URL before resuming. Repeatedly rerunning an expired URL will not renew it.

Python: train.py

Requires Python 3.10 or newer; no third-party packages. Save the following as train.py. Set the environment variable, then run against your image directory.

# macOS / Linux shell
export SPLATWARE_API_KEY="YOUR_API_KEY"
python3 train.py ./images --input-type images --depth fast

# Windows PowerShell
$env:SPLATWARE_API_KEY="YOUR_API_KEY"
python train.py .\images --input-type images --depth fast

The default state file is .splatware-python-state.json. Rerun with the same inputs and state file to resume. For a reconstructed dataset, use --input-type dataset --depth balanced. For an advanced configuration file, use --configuration configuration.json; it overrides the model argument.

One statue, 80 iPhone photos

#!/usr/bin/env python3
"""Train a file or folder with the Splatware API. Set SPLATWARE_API_KEY.
Example: python train.py ./photos --input-type images
Video duration is read locally with ffprobe. Keep the resumable state file private.
"""
import argparse
import concurrent.futures as futures
from contextlib import closing
import hashlib
import http.client
import json
import math
import mimetypes
import os
import pathlib
import re
import shutil
import ssl
import subprocess
import sys
import tempfile
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
import zipfile

BASE = os.environ.get('SPLATWARE_API_BASE', 'https://splatware.com/api/v1').rstrip('/')
KEY = os.environ.get('SPLATWARE_API_KEY')
BLOCK = 256 * 1024
MAX_CHUNK = 8 * 1024 * 1024
MANIFEST_SIZE = 50
DEFAULT_UPLOAD_WORKERS = 8
LABELS = {'payment_pending': 'Confirming payment', 'preparing': 'Preparing training',
          'processing': 'Processing', 'download': 'Downloading source files', 'preprocessing': 'Preprocessing',
          'masking': 'Masking', 'alignment': 'Alignment', 'training': 'Training', 'export': 'Export',
          'completed': 'Completed', 'failed': 'Failed'}
IMAGES = set('png jpg jpeg heic heif tif tiff webp bmp raw dng cr2 cr3 nef arw raf orf rw2 insp exr hdr'.split())
VIDEOS = set('mp4 mov mkv webm avi flv'.split())
NATIVE = {'insv', 'osv', '360'}


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


opener = urllib.request.build_opener(NoRedirect())


def checked_destination(url):
    dest = urllib.parse.urlsplit(url)
    loopback = dest.hostname in ('localhost', '127.0.0.1', '::1')
    if (dest.scheme != 'https' and not (dest.scheme == 'http' and loopback)) or not dest.hostname or dest.username or dest.password:
        raise ValueError('Use HTTPS or a local loopback address.')
    return dest


def request(method, url, data=None, headers=None):
    checked_destination(url)
    req = urllib.request.Request(url, data=data, headers=headers or {}, method=method)
    try:
        with opener.open(req, timeout=120) as response:
            return response.status, response.headers, response.read()
    except urllib.error.HTTPError as error:
        with error:
            return error.code, error.headers, error.read()


class StorageConnections:
    """Reuse one verified TLS connection per worker for direct storage PUTs."""
    def __init__(self):
        self.context = ssl.create_default_context()
        self.by_worker = {}
        self.lock = threading.Lock()
        proxies = urllib.request.getproxies()
        self.use_proxy_handler = bool(proxies.get('https') or proxies.get('all'))

    def send(self, method, url, data, headers):
        dest = checked_destination(url)
        if dest.scheme != 'https' or self.use_proxy_handler:
            return request(method, url, data, headers)
        origin = (dest.hostname, dest.port or 443)
        worker = threading.get_ident()
        with self.lock:
            previous = self.by_worker.get(worker)
            if previous and previous[0] == origin:
                conn = previous[1]
            else:
                if previous:
                    previous[1].close()
                conn = http.client.HTTPSConnection(*origin, timeout=120, context=self.context)
                self.by_worker[worker] = (origin, conn)
        target = urllib.parse.urlunsplit(('', '', dest.path or '/', dest.query, ''))
        try:
            conn.request(method, target, body=data, headers=headers)
            with conn.getresponse() as response:
                return response.status, response.headers, response.read()
        except (OSError, http.client.HTTPException):
            conn.close()
            raise

    def close(self):
        for _, conn in self.by_worker.values():
            conn.close()


class ApiError(RuntimeError):
    def __init__(self, error):
        self.code = error.get('code', 'http_error')
        ref = error.get('request_id')
        super().__init__('{} [{}]{}'.format(error.get('message', 'Request failed.'), self.code,
                                             '  Request ID: ' + ref if ref else ''))


def api(method, path, payload=None, key=None):
    headers = {'Authorization': 'Bearer ' + KEY}
    data = None
    if payload is not None:
        headers['Content-Type'] = 'application/json'
        if key:
            headers['Idempotency-Key'] = key
        data = json.dumps(payload, allow_nan=False).encode()
    for attempt in range(7):
        try:
            status, h, raw = request(method, BASE + path, data, headers)
        except OSError:
            if attempt == 6:
                raise RuntimeError('API connection interrupted. Rerun to resume.')
            time.sleep(min(30, 2 ** attempt))
            continue
        if (status == 429 or status >= 500) and attempt < 6:
            wait = h.get('Retry-After', '')
            delay = min(120, max(1, int(wait))) if wait.isdigit() else min(30, 2 ** attempt)
            print('API temporarily busy. Retrying in {}s.'.format(delay), file=sys.stderr, flush=True)
            time.sleep(delay)
            continue
        try:
            body = json.loads(raw)
        except ValueError:
            raise RuntimeError('API returned HTTP {} without a JSON response.'.format(status))
        if not 200 <= status < 300:
            raise ApiError(body.get('error', {'message': 'HTTP {}'.format(status)}))
        return body['data']


def authenticate():
    session = api('GET', '/session')
    if not (session.get('account_authenticated') and session.get('api_key_verified')):
        raise RuntimeError('The API could not verify the account and key.')
    print('Account authenticated.', flush=True)
    missing = {'training:write', 'training:read'} - set(session.get('scopes', []))
    if missing:
        raise RuntimeError('API key verified. Missing permission: ' + ', '.join(sorted(missing)))
    print('API key verified  |  training:read + training:write', flush=True)


def duration(seconds):
    if seconds is None:
        return '--'
    seconds = max(0, int(seconds))
    h, rest = divmod(seconds, 3600)
    m, s = divmod(rest, 60)
    return '{:d}:{:02d}:{:02d}'.format(h, m, s) if h else '{:d}:{:02d}'.format(m, s)


def bar(percent):
    if percent is None:
        return '[------------]    --'
    n = int(percent * 12 / 100)
    return '[{}{}] {:5.1f}%'.format('#' * n, '-' * (12 - n), percent)


class Line:
    def __init__(self, final_only_if_piped=False):
        self.tty = sys.stdout.isatty()
        self.final_only_if_piped = final_only_if_piped
        self.width = 0
        self.last = 0
        self.previous = None

    def show(self, text, force=False):
        if not self.tty and self.final_only_if_piped:
            self.previous = text
            return
        now = time.monotonic()
        if text == self.previous or (not force and now - self.last < (0.2 if self.tty else 10)):
            return
        if self.tty:
            limit = max(1, shutil.get_terminal_size().columns - 1)
            text = text[:limit]
            print('\r' + text.ljust(min(self.width, limit)), end='', flush=True)
            self.width = len(text)
        else:
            print(text, flush=True)
        self.last, self.previous = now, text

    def finish(self):
        if self.tty and self.width:
            print(flush=True)
        elif not self.tty and self.final_only_if_piped and self.previous:
            print(self.previous, flush=True)
        self.width = 0
        self.previous = None

    def __enter__(self):
        return self

    def __exit__(self, *_):
        self.finish()


def mime(path):
    overrides = {'.insv': 'application/octet-stream', '.osv': 'application/octet-stream', '.360': 'application/octet-stream',
                 '.bin': 'application/octet-stream', '.ply': 'application/octet-stream', '.heic': 'image/heic',
                 '.heif': 'image/heif', '.mkv': 'video/x-matroska', '.avi': 'video/x-msvideo'}
    return overrides.get(path.suffix.lower()) or mimetypes.guess_type(str(path))[0] or 'application/octet-stream'


def video_facts(path):
    probe = shutil.which('ffprobe')
    if not probe:
        nearby = pathlib.Path.home() / 'ffmpeg' / 'ffprobe.exe'
        probe = str(nearby) if nearby.is_file() else None
    if not probe:
        raise RuntimeError('Install ffprobe or pass --video-seconds with total recording playback time.')
    # Local input only. Probe the primary video stream, independently of longer audio tracks.
    result = subprocess.run([probe, '-v', 'error', '-protocol_whitelist', 'file', '-select_streams', 'v',
                             '-show_entries', 'stream=duration:stream_disposition=attached_pic:format=duration',
                             '-of', 'json', str(path.resolve())], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
                            timeout=60, universal_newlines=True)
    if result.returncode == 0:
        facts = json.loads(result.stdout)
        streams = [s for s in facts.get('streams', []) if not s.get('disposition', {}).get('attached_pic')]
        if streams:
            for value in (streams[0].get('duration'), facts.get('format', {}).get('duration')):
                try:
                    seconds = float(value)
                except (ValueError, TypeError):
                    continue
                if math.isfinite(seconds) and seconds > 0:
                    return seconds, len(streams)
    raise RuntimeError('Could not read video duration for {}. Supply --video-seconds for an estimate.'.format(path.name))


def show_estimate(files, input_type, config, video_seconds=None):
    source = {'file_count': len(files), 'upload_bytes': sum(f.stat().st_size for f in files),
              'image_count': sum(f.suffix[1:].lower() in IMAGES for f in files)}
    videos = [f for f in files if f.suffix[1:].lower() in VIDEOS | NATIVE]
    if video_seconds is not None:
        if not videos or not math.isfinite(video_seconds) or video_seconds <= 0:
            raise ValueError('--video-seconds requires video input and a positive playback duration.')
        if any(f.suffix[1:].lower() in NATIVE for f in videos) and not all(f.suffix[1:].lower() in NATIVE for f in videos):
            raise ValueError('Use either native or exported recordings for 360 video.')
        source['native_360_seconds' if videos[0].suffix[1:].lower() in NATIVE else 'video_seconds'] = video_seconds
    else:
        lenses = {}
        for f in videos:
            seconds, tracks = video_facts(f)
            native = f.suffix[1:].lower() in NATIVE
            pair = re.fullmatch(r'VID_(\d{8}_\d{6})_([01])0_(\d+)\.insv', f.name, re.I) if tracks == 1 else None
            if pair:
                lenses.setdefault((f.parent, pair[1], pair[3]), []).append(seconds)
            else:
                key = 'native_360_seconds' if native else 'video_seconds'
                source[key] = source.get(key, 0) + seconds
        if lenses:
            source['native_360_seconds'] = source.get('native_360_seconds', 0) + sum(min(pair) for pair in lenses.values())
    result = api('POST', '/trainings/estimate', {'input_type': input_type, 'configuration': config, 'source': source})
    print('Estimated cost: {:,.2f} training points  |  estimated processing {} (queue excluded)'.format(
        result['estimated_points'], duration(result['estimated_processing_seconds'])), flush=True)
    return result


class UploadProgress:
    def __init__(self, total):
        self.total = total
        self.completed = 0
        self.sent = 0
        self.started = time.monotonic()
        self.line = Line()

    def update(self, offset, fresh=0):
        self.sent += fresh
        done = self.completed + offset
        remaining = max(0, self.total - done)
        elapsed = time.monotonic() - self.started
        enough_sample = elapsed >= 1 and self.sent >= min(self.total, 2_000_000)
        speed = self.sent / max(0.001, elapsed) if enough_sample or not remaining else 0
        rate = '{:.1f} MB/s'.format(speed / 1e6) if speed else '-- MB/s'
        self.line.show('Upload  {}  {:.1f}/{:.1f} MB  |  {}  |  ETA {}'.format(
            bar(100 * done / self.total), done / 1e6, self.total / 1e6, rate,
            duration(remaining / speed) if speed else ('0:00' if not remaining else '--')), force=not remaining)
        if not remaining:
            self.line.finish()


def acknowledged(headers, size):
    value = headers.get('Range')
    if value is None:
        return 0
    match = re.fullmatch(r'bytes=0-(\d+)', value)
    if not match or int(match[1]) >= size:
        raise RuntimeError('Invalid resumable-upload acknowledgement.')
    return int(match[1]) + 1


def upload(path, session, progress, probe_first=True, initial_chunk=BLOCK, transport=None):
    size = path.stat().st_size
    chunk_size = initial_chunk
    send = transport.send if transport is not None else request
    for attempt in range(8):
        try:
            offset = 0
            if probe_first or attempt:
                status, headers, _ = send('PUT', session, b'', {'Content-Length': '0', 'Content-Range': 'bytes */{}'.format(size)})
                if status in (200, 201):
                    progress.update(size)
                    progress.completed += size
                    return
                if status != 308:
                    raise RuntimeError('Upload session returned HTTP {}.'.format(status))
                offset = acknowledged(headers, size)
                progress.update(offset)
            with path.open('rb') as f:
                while offset < size:
                    f.seek(offset)
                    chunk = f.read(min(chunk_size, size - offset))
                    if not chunk:
                        raise ValueError('The source file changed during upload.')
                    started = time.monotonic()
                    status, headers, _ = send('PUT', session, chunk, {'Content-Type': mime(path),
                        'Content-Range': 'bytes {}-{}/{}'.format(offset, offset + len(chunk) - 1, size)})
                    if status in (200, 201) and offset + len(chunk) == size:
                        progress.update(size, size - offset)
                        progress.completed += size
                        return
                    if status != 308:
                        raise RuntimeError('Upload chunk returned HTTP {}.'.format(status))
                    end = acknowledged(headers, size)
                    if not offset < end <= offset + len(chunk):
                        raise RuntimeError('Upload did not acknowledge the expected bytes.')
                    progress.update(end, end - offset)
                    chunk_size = max(BLOCK, min(MAX_CHUNK, int((end - offset) / max(0.01, time.monotonic() - started) / BLOCK) * BLOCK))
                    offset = end
        except (RuntimeError, OSError, http.client.HTTPException):
            if attempt == 7:
                raise
            time.sleep(min(30, 2 ** attempt))
    raise RuntimeError('Upload could not complete. Rerun to resume.')


class FileProgress:
    """Map one resumable transfer to its share of the overall progress bar."""
    def __init__(self, total, lock):
        self.total = total
        self.lock = lock
        self.completed = 0
        self.reported = 0

    def update(self, offset, fresh=0):
        with self.lock:
            delta = max(0, offset - self.reported)
            self.reported += delta
            self.total.completed += delta
            self.total.update(0, min(fresh, delta))


def upload_files(files, manifest, state, dataset_path, save, workers=DEFAULT_UPLOAD_WORKERS,
                 previous_batch_size=MANIFEST_SIZE):
    if not 1 <= workers <= 12:
        raise ValueError('Upload workers must be between 1 and 12.')
    registered = api('GET', dataset_path)['file_count']
    start = state.get('next_file', 0)
    ahead = set(state.get('uploaded_ahead', []))
    if not 0 <= start <= registered <= len(files) or any(i < start or i >= registered for i in ahead):
        raise ValueError('The saved upload progress does not match the dataset.')
    if 'legacy_batch_end' not in state:
        # Reissue existing reservations with their original manifest and idempotency key.
        state['legacy_batch_end'] = registered if previous_batch_size != MANIFEST_SIZE else 0
        save()
    boundary = state['legacy_batch_end']
    if not 0 <= boundary <= registered:
        raise ValueError('The saved upload reservations do not match the dataset.')
    batches = []
    for begin, limit, size in ((0, boundary, previous_batch_size), (boundary, len(files), MANIFEST_SIZE)):
        for first in range(begin, limit, size):
            end = min(first + size, limit)
            if any(i not in ahead for i in range(max(start, first), end)):
                batches.append((first, end))
    if not batches:
        return
    progress = UploadProgress(sum(f['size_bytes'] for f in manifest))
    progress.completed = sum(f['size_bytes'] for f in manifest[:start]) + sum(manifest[i]['size_bytes'] for i in ahead)
    lock = threading.Lock()
    next_checkpoint = 0
    print('Uploading {} remaining files with up to {} parallel transfers...'.format(
        len(files) - start - len(ahead), workers), flush=True)

    def allocate(batch):
        first, end = batch
        suffix = '-fast-uploads-' if previous_batch_size != MANIFEST_SIZE and first >= boundary else '-uploads-'
        rows = manifest[first:end]
        response = api('POST', dataset_path + '/uploads', {'files': rows}, state['run'] + suffix + str(first))
        returned = response['uploads']
        sessions = {s['path']: s['upload_url'] for s in returned}
        if len(returned) != len(rows) or set(sessions) != {r['path'] for r in rows}:
            raise RuntimeError('Storage returned an incomplete or mismatched upload manifest.')
        return sessions

    with closing(StorageConnections()) as storage, futures.ThreadPoolExecutor(max_workers=1) as setup, \
            futures.ThreadPoolExecutor(max_workers=workers) as pool:
        allocation = setup.submit(allocate, batches[0])
        for n, (first, end) in enumerate(batches):
            sessions = allocation.result()
            if n == 0:
                progress.started = time.monotonic()
            if n + 1 < len(batches):
                allocation = setup.submit(allocate, batches[n + 1])
            indices = iter([i for i in range(max(first, start), end) if i not in ahead])
            active = {}
            while True:
                for i in indices:
                    row = manifest[i]
                    first_chunk = MAX_CHUNK if row['size_bytes'] <= MAX_CHUNK else BLOCK
                    future = pool.submit(upload, files[i], sessions[row['path']], FileProgress(progress, lock),
                                         probe_first=i < registered, initial_chunk=first_chunk, transport=storage)
                    active[future] = i
                    if len(active) == workers:
                        break
                if not active:
                    break
                finished, _ = futures.wait(active, return_when=futures.FIRST_COMPLETED)
                for task in finished:
                    task.result()
                    ahead.add(active.pop(task))
                while start in ahead:
                    ahead.remove(start)
                    start += 1
                state['next_file'] = start
                state['uploaded_ahead'] = sorted(ahead)
                if time.monotonic() >= next_checkpoint:
                    save()
                    next_checkpoint = time.monotonic() + 0.5
            save()
    progress.line.finish()


def validate_dataset(path, count, total_bytes, state, save, *, page_key='complete_page', key_prefix=None, unit='files'):
    if state.get('ready'):
        return
    if count < 1:
        raise ValueError('The dataset contains no files to validate.')
    prefix = key_prefix or state['run'] + '-complete-'
    verified = state.get('validated_files')
    if verified is None:
        verified = api('GET', path)['validated_files'] if state.get(page_key) else 0
    with Line(final_only_if_piped=True) as line:
        def show(label):
            line.show('{}  {}  {:,}/{:,} {}'.format(label, bar(100 * verified / count), verified, count, unit), force=True)
        show('Validating')
        while not state.get('ready'):
            page = state.get(page_key, 0)
            result = api('POST', path + '/complete', {}, prefix + str(page))
            ready = result['status'] == 'ready'
            measured = result['validated_files']
            if result['status'] not in ('ready', 'validating') or not 0 <= measured <= count:
                raise RuntimeError('Unexpected dataset validation response.')
            if ready and (measured != count or (total_bytes is not None and result['size_bytes'] != total_bytes)):
                raise RuntimeError('The verified dataset does not match the local files.')
            verified = max(verified, measured)
            state.update({page_key: page + 1, 'validated_files': verified, 'ready': ready})
            save()
            show('Validated' if ready else 'Validating')


def confirm_quote(payload, ask=False):
    quote = api('POST', '/trainings/quote', payload)
    if not quote['can_submit']:
        raise ApiError(quote.get('error') or {'message': 'The verified quote cannot be submitted.'})
    charge = ('included allowance' if quote['mode'] == 'included'
              else '{:.2f} {}'.format(quote['amount_cents'] / 100, quote['currency'].upper()))
    print('Verified cost: {:,.2f} training points  |  {}'.format(quote['points'], charge), flush=True)
    if ask:
        try:
            approved = input('Start this training at the quoted cost? [y/N] ').strip().lower() == 'y'
        except EOFError:
            approved = False
        if not approved:
            raise ValueError('Training was not submitted. Rerun to review the quote again.')
    return quote['quote_fingerprint']


def stage_percent(progress, start, seconds):
    end = progress.get('stage_end_percent')
    floor = progress.get('stage_start_percent')
    budget = progress.get('estimated_stage_seconds')
    if start is None or end is None or floor is None or not budget or start >= end:
        return start
    return max(start, min(end - 0.1, start + (end - floor) * seconds / budget))


TRAINING_ORDER = ('payment_pending', 'preparing', 'download', 'preprocessing', 'masking', 'alignment', 'training', 'export')


def follow_training(training_id, initial=None, poll_seconds=None, *, state=None, save=None):
    print('Training ID: ' + training_id, flush=True)
    path = '/trainings/' + training_id + '?include=stages'
    job = initial or api('GET', path)
    if initial is None and job.get('billing'):
        bill = job['billing']
        print('Verified cost: {:,.2f} training points  |  {}'.format(bill['points'],
              'included allowance' if bill['mode'] == 'included' else '{:.2f} EUR'.format(bill['amount_cents'] / 100)), flush=True)

    rank, floor, percent = -1, 0, 0.0
    stage, timing, elapsed = 'processing', {}, None
    saved = (state or {}).get('last_training_progress') or {}
    if (saved.get('id') == training_id and saved.get('stage') in TRAINING_ORDER and
            saved.get('created_at') == job.get('created_at') and job['status'] == 'processing'):
        stage, floor, percent = saved['stage'], saved['floor'], saved['percent']
        rank = TRAINING_ORDER.index(stage)
    else:
        saved = {}
    received = time.monotonic()
    with Line(final_only_if_piped=True) as line:
        while True:
            now = time.monotonic()
            delta = max(0, now - received)
            percent = stage_percent(timing, percent, delta)
            received = now
            progress = job.get('progress') or {}
            status = job['status']
            terminal = status in ('completed', 'failed')
            candidate = progress.get('stage') or ('preparing' if status == 'queued' else status)
            next_rank = TRAINING_ORDER.index(candidate) if candidate in TRAINING_ORDER else -1
            next_floor = progress.get('stage_start_percent') or 0
            left = None
            timing = {}
            if terminal:
                stage = status
                percent = 100 if status == 'completed' else max(percent, progress.get('percent') or 0)
            elif next_rank >= 0 and (next_rank > rank or (next_rank == rank and next_floor >= floor)):
                stage, rank, floor = candidate, next_rank, next_floor
                reported = progress.get('percent')
                percent = max(percent, reported or 0, floor)
                timing = progress
                left = progress.get('estimated_remaining_seconds')
                # A recent document write can reset the server's interpolation within a stage.
                span = (progress.get('stage_end_percent') or 0) - floor
                if reported is not None and left is not None and span > 0 and progress.get('estimated_stage_seconds'):
                    left = max(0, left - (percent - reported) * progress['estimated_stage_seconds'] / span)
                if state is not None and save is not None and (saved.get('id') != training_id or saved.get('created_at') != job.get('created_at') or
                        saved.get('stage') != stage or saved.get('floor') != floor or percent - saved.get('percent', 0) >= 5):
                    saved = {'id': training_id, 'created_at': job.get('created_at'), 'stage': stage, 'floor': floor, 'percent': round(percent, 1)}
                    state['last_training_progress'] = saved
                    save()
            # A generic or older worker update holds the last confirmed phase and percentage.
            observed = progress.get('elapsed_seconds')
            if elapsed is None or (terminal and observed is not None):
                elapsed = observed
            else:
                elapsed = max(elapsed + delta, observed or 0)
            label = LABELS.get(stage, 'Processing') if stage != 'processing' else 'confirmed, awaiting worker update'
            interval = poll_seconds if poll_seconds is not None else job.get('poll_after_seconds', 3)
            ticks = 1 if terminal or initial is not None else max(1, min(30, int(interval)))
            for tick in range(ticks):
                age = time.monotonic() - received
                amount = stage_percent(timing, percent, age)
                parts = ['{}  {}'.format(bar(amount), label)]
                if elapsed is not None:
                    approx = '~' if progress.get('elapsed_basis') == 'completion_observed' else ''
                    parts.append('elapsed ' + approx + duration(elapsed + (0 if terminal else age)))
                if not terminal and stage != 'payment_pending':
                    if left is not None and left > age:
                        parts.append('~{} {}'.format(duration(left - age), 'processing' if stage == 'preparing' else 'left'))
                    else:
                        parts.append('ETA updating')
                line.show('  |  '.join(parts), force=terminal or tick == 0)
                if not terminal and initial is None:
                    time.sleep(1)
            if terminal:
                break
            initial = None
            job = api('GET', path)

    if status == 'failed':
        raise ApiError(job.get('error') or {'message': 'Training failed.'})
    print('Capture: ' + urllib.parse.urljoin(BASE + '/', job['capture_url']), flush=True)
    return job


def save_private(path, state):
    fd, name = tempfile.mkstemp(dir=str(path.parent), prefix='.' + path.name + '-')
    try:
        with os.fdopen(fd, 'w', encoding='utf-8') as stream:
            json.dump(state, stream)
        # Windows can briefly deny replacement while a scanner has the file open.
        for attempt in range(8):
            try:
                os.replace(name, str(path))
                break
            except PermissionError as error:
                if getattr(error, 'winerror', None) not in (5, 32, 33) or attempt == 7:
                    raise
                time.sleep(0.025 * 2 ** attempt)
    finally:
        if os.path.exists(name):
            os.unlink(name)


SAMPLE_SHA256 = '9d676fa25682c7306c01e8bb4882e3281713b769acb4067351caeb0b73b3fb78'
SAMPLE_BYTES = 33_303_588


def sample_photos(directory):
    """Resolve just this published, checksum-pinned dataset. Never send the API key to the download."""
    directory = pathlib.Path(directory)
    directory.mkdir(parents=True, exist_ok=True)
    archive = directory / 'photos.zip'
    if not archive.exists() or archive.stat().st_size != SAMPLE_BYTES or hashlib.sha256(archive.read_bytes()).hexdigest() != SAMPLE_SHA256:
        origin = urllib.parse.urlsplit(BASE)
        url = urllib.parse.urlunsplit((origin.scheme, origin.netloc, '/samples/mehringdamm/photos.zip', '', ''))
        print('Downloading the 80 original photos (33.3 MB)…', flush=True)
        with urllib.request.urlopen(url, timeout=90) as response:
            data = response.read(SAMPLE_BYTES + 1)
        if len(data) != SAMPLE_BYTES or hashlib.sha256(data).hexdigest() != SAMPLE_SHA256:
            raise ValueError('The sample download failed its checksum. Please retry.')
        with tempfile.NamedTemporaryFile(dir=directory, delete=False) as temp:
            temp.write(data)
        pathlib.Path(temp.name).replace(archive)
    photos = directory / 'photos'
    photos.mkdir(exist_ok=True)
    with zipfile.ZipFile(archive) as files:
        entries = sorted(name for name in files.namelist() if re.fullmatch(r'photos/[0-9]{4}\.jpg', name))
        if len(set(entries)) != 80 or sum(files.getinfo(name).file_size for name in entries) != 33_294_553:
            raise ValueError('The sample does not contain the expected 80 JPEGs.')
        expected = {pathlib.PurePosixPath(name).name for name in entries}
        if photos.is_symlink() or any(f.is_symlink() or f.name not in expected or not f.is_file() for f in photos.iterdir()):
            raise ValueError('The sample folder contains other files. Use a clean working directory.')
        for name in entries:
            dest = photos / pathlib.PurePosixPath(name).name
            data = files.read(name)
            if not dest.is_file() or dest.read_bytes() != data:
                dest.write_bytes(data)
        (directory / 'LICENSE.txt').write_bytes(files.read('LICENSE.txt'))
    return photos


def main():
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('source', type=pathlib.Path, nargs='?')
    p.add_argument('--sample', choices=['mehringdamm'], help='Train the licensed 80-photo iPhone example at Fast depth.')
    p.add_argument('--input-type', choices=['images', 'videos', 'mixed', '360-image', '360-video', 'dataset'], default='images')
    p.add_argument('--depth', choices=['fast', 'balanced', 'high', 'higher', 'highest'], default='fast')
    p.add_argument('--model', help=argparse.SUPPRESS)
    p.add_argument('--configuration', type=pathlib.Path, help='JSON training configuration; overrides --depth')
    p.add_argument('--billing-mode', choices=['auto', 'included', 'pay_as_you_go'], default='auto')
    p.add_argument('--video-seconds', type=float, help='Total playback seconds for an estimate without ffprobe; count paired lenses once.')
    p.add_argument('--state', type=pathlib.Path)
    p.add_argument('--workers', type=int, choices=range(1, 13), default=DEFAULT_UPLOAD_WORKERS,
                   help='Maximum simultaneous file transfers (default: 8).')
    args = p.parse_args()
    if args.sample:
        if args.source or args.configuration or args.model or args.depth != 'fast' or args.input_type != 'images' or args.video_seconds is not None:
            p.error('The sample provides its own input, depth and settings.')
        if not KEY:
            p.error('Set SPLATWARE_API_KEY to a key with training:read and training:write.')
        directory = pathlib.Path('.splatware-samples') / 'mehringdamm'
        return train(sample_photos(directory), title='Mehringdamm Statue',
                     configuration={'trainingDepth': 'fast', 'modelSHDegree': 3},
                     state_path=args.state or directory / 'training-state.json', billing_mode=args.billing_mode,
                     workers=args.workers, ask_before_training=True)
    if not args.source:
        p.error('Provide a source file or folder, or use --sample mehringdamm.')
    return train(args.source, model=args.model, depth=args.depth, input_type=args.input_type, configuration=args.configuration,
                 billing_mode=args.billing_mode, video_seconds=args.video_seconds,
                 state_path=args.state or pathlib.Path('.splatware-python-state.json'), workers=args.workers)


def source_digest(files):
    """Bind a resumable upload to the actual, ordered file contents with bounded memory."""
    identity = hashlib.sha256()
    for file in files:
        digest = hashlib.sha256()
        with file.open('rb') as stream:
            for chunk in iter(lambda: stream.read(1024 * 1024), b''):
                digest.update(chunk)
        identity.update(digest.digest())
    return identity.hexdigest()


def train(source, model=None, *, depth='fast', input_type='images', title=None, max_gaussians=None, configuration=None,
          billing_mode='auto', video_seconds=None, state_path='.splatware-python-state.json', workers=DEFAULT_UPLOAD_WORKERS,
          ask_before_training=False):
    """Upload local files, validate, train and return the completed job. Reuse state_path to resume."""
    if not KEY:
        raise ValueError('Set SPLATWARE_API_KEY.')
    source, state_path = pathlib.Path(source), pathlib.Path(state_path)
    title = source.name if title is None else title
    excluded = {state_path.resolve()}
    if isinstance(configuration, (str, pathlib.Path)):
        config_file = pathlib.Path(configuration)
        excluded.add(config_file.resolve())
        configuration = json.loads(config_file.read_text(encoding='utf-8'))
    config = dict(configuration) if configuration is not None else ({'selectedModel': model} if model is not None else {'trainingDepth': depth})
    if max_gaussians is not None:
        config['maxGaussiansCount'] = max_gaussians
    authenticate()
    if source.is_dir():
        files = sorted(f for f in source.rglob('*') if f.is_file() and not f.is_symlink()
                       and f.resolve() not in excluded and not any(x.startswith('.') for x in f.relative_to(source).parts))
    else:
        files = [source]
    if not files:
        raise ValueError('The input folder contains no files.')
    manifest = [{'path': f.relative_to(source).as_posix() if source.is_dir() else f.name,
                 'content_type': mime(f), 'size_bytes': f.stat().st_size} for f in files]
    if input_type != 'dataset' and any('/' in f['path'] for f in manifest):
        raise ValueError('Only dataset input permits nested paths.')
    fingerprint = json.dumps({'base': BASE, 'source': str(source.resolve()), 'manifest': manifest,
                              'configuration': config, 'type': input_type}, sort_keys=True)
    state = json.loads(state_path.read_text()) if state_path.exists() else {
        'run': str(uuid.uuid4()), 'fingerprint': fingerprint, 'title': title, 'complete_page': 0}
    if state['fingerprint'] != fingerprint or state.get('billing_mode', billing_mode) != billing_mode or state.get('title', source.name) != title:
        raise ValueError('Inputs, title or billing mode changed. Choose another state file.')
    state['billing_mode'] = billing_mode
    def save():
        save_private(state_path, state)
    if state.get('training'):
        return follow_training(state['training'], state=state, save=save)
    if not state.get('uploads_complete') and not state.get('ready'):
        if state.get('dataset') and not state.get('source_sha256'):
            raise ValueError('This older partial upload has no file checksums. Use a new state file to restart safely.')
        if state.get('sources_changed_during_upload'):
            raise ValueError('A source changed during an earlier transfer. Restart with a new state file.')
        file_stamps = [(f.stat().st_size, f.stat().st_mtime_ns) for f in files]
        digest = source_digest(files)
        if state.get('source_sha256', digest) != digest:
            raise ValueError('The source file contents changed. Restore the original files or choose a new state file.')
        state['source_sha256'] = digest
    save()
    if not state.get('uploads_complete') and not state.get('ready'):
        show_estimate(files, input_type, config, video_seconds)
    if 'dataset' not in state:
        print('Creating dataset...', flush=True)
        state['dataset'] = api('POST', '/datasets', {'name': title, 'input_type': input_type}, state['run'] + '-dataset')['id']
        save()
    path = '/datasets/' + state['dataset']
    if not state.get('uploads_complete') and not state.get('ready'):
        try:
            upload_files(files, manifest, state, path, save, workers)
        finally:
            try:
                changed = any((f.stat().st_size, f.stat().st_mtime_ns) != stamp for f, stamp in zip(files, file_stamps))
            except OSError:
                changed = True
            if changed:
                state['sources_changed_during_upload'] = True
                save()
                raise ValueError('A source changed during transfer. Restart with a new state file.')
        state.pop('uploads', None)
        state['uploads_complete'] = True
        save()
    validate_dataset(path, len(manifest), sum(row['size_bytes'] for row in manifest), state, save)
    payload = {'dataset_id': state['dataset'], 'configuration': config, 'billing_mode': billing_mode}
    needs_approval = ask_before_training and state.get('approved_quote') != state.get('quote_fingerprint')
    if not state.get('quote_fingerprint') or needs_approval:
        state['quote_fingerprint'] = confirm_quote(payload, ask=ask_before_training)
        if ask_before_training:
            state['approved_quote'] = state['quote_fingerprint']
        save()
    payload['quote_fingerprint'] = state['quote_fingerprint']
    print('Submitting training...', flush=True)
    try:
        job = api('POST', '/trainings', payload, state['run'] + '-training')
    except ApiError as error:
        if error.code == 'quote_changed':
            state.pop('quote_fingerprint', None)
            state.pop('approved_quote', None)
            save()
        raise
    state['training'] = job['id']
    save()
    return follow_training(job['id'], job, state=state, save=save)


if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print('\nStopped locally. Rerun with the same state file to resume.')
        sys.exit(130)
    except (OSError, RuntimeError, ValueError, subprocess.TimeoutExpired) as error:
        print('Error:', error, file=sys.stderr)
        sys.exit(1)

Node.js: train.mjs

Requires Node.js 20 or newer and uses built-in modules. Save as train.mjs. Set SPLATWARE_API_KEY as shown above, then run:

node train.mjs ./images images fast

# Advanced configuration, explicit state file
node train.mjs ./dataset dataset balanced run-state.json configuration.json

The default state file is .splatware-node-state.json. Keep it private and reuse it for retries. If the input manifest or configuration changes, start a deliberately new run with a new state file rather than overwriting an unfinished run.

#!/usr/bin/env node
// Node 20+. Usage: node train.mjs ./images images fast [state.json] [configuration.json]
// SPLATWARE_API_KEY is required; SPLATWARE_API_BASE defaults to https://splatware.com/api/v1.
import { createReadStream } from "node:fs";
import { open, readFile, writeFile, readdir, stat } from "node:fs/promises";
import path from "node:path";
import { createHash, randomUUID } from "node:crypto";
const [
  sourceArg,
  inputType = "images",
  depth = "fast",
  statePath = ".splatware-node-state.json",
  configurationFile,
] = process.argv.slice(2);
if (!sourceArg || !process.env.SPLATWARE_API_KEY)
  throw new Error(
    "Usage: SPLATWARE_API_KEY=… node train.mjs SOURCE [INPUT_TYPE] [MODEL] [STATE] [CONFIGURATION_JSON]",
  );
const source = path.resolve(sourceArg),
  base = (
    process.env.SPLATWARE_API_BASE || "https://splatware.com/api/v1"
  ).replace(/\/$/, "");
const origin = new URL(base);
if (origin.protocol !== "https:" && !(origin.protocol === "http:" && ["127.0.0.1", "localhost", "[::1]"].includes(origin.hostname)))
  throw new Error("The API requires HTTPS outside localhost.");
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
let lineWidth = 0;
function liveLine(text, finished = false) {
  if (process.stdout.isTTY) {
    const width = Math.max(1, (process.stdout.columns || 80) - 1);
    const visible = text.slice(0, width);
    process.stdout.write("\r" + visible.padEnd(Math.min(width, lineWidth)) + (finished ? "\n" : ""));
    lineWidth = finished ? 0 : visible.length;
  } else if (finished) {
    console.log(text);
  }
}
async function api(method, route, payload, key = randomUUID()) {
  const headers = {
    Authorization: `Bearer ${process.env.SPLATWARE_API_KEY}`,
    ...(payload
      ? { "Content-Type": "application/json", "Idempotency-Key": key }
      : {}),
  };
  for (let attempt = 0; attempt < 7; attempt++) {
    let response;
    try {
      response = await fetch(base + route, {
        method,
        headers,
        body: payload ? JSON.stringify(payload) : undefined,
        redirect: "error", signal: AbortSignal.timeout(120000),
      });
    } catch (e) {
      if (attempt === 6) throw e;
      await wait(1000 * 2 ** attempt);
      continue;
    }
    if (response.status === 429 || response.status >= 500) {
      await wait(
        Math.min(
          60,
          Number(response.headers.get("Retry-After") || 2 ** attempt),
        ) * 1000,
      );
      continue;
    }
    const result = await response.json();
    if (!response.ok) throw new Error(JSON.stringify(result.error));
    return result.data;
  }
  throw new Error("API retries exhausted; rerun with the same state file.");
}
const mimes = {
  jpg: "image/jpeg",
  jpeg: "image/jpeg",
  png: "image/png",
  webp: "image/webp",
  tif: "image/tiff",
  heic: "image/heic",
  heif: "image/heif",
  tiff: "image/tiff",
  bmp: "image/bmp",
  mp4: "video/mp4",
  mov: "video/quicktime",
  mkv: "video/x-matroska",
  avi: "video/x-msvideo",
  mpeg: "video/mpeg",
  flv: "video/x-flv",
  glb: "model/gltf-binary",
  json: "application/json",
  txt: "text/plain",
};
const mime = (file) =>
  mimes[path.extname(file).slice(1).toLowerCase()] ||
  "application/octet-stream";
async function walk(dir) {
  const files = [];
  for (const entry of await readdir(dir, { withFileTypes: true })) {
    if (entry.name.startsWith(".")) continue;
    const full = path.join(dir, entry.name);
    if (entry.isDirectory()) files.push(...(await walk(full)));
    else if (entry.isFile()) files.push(full);
  }
  return files.sort();
}
const directory = (await stat(source)).isDirectory();
const excluded = new Set([statePath, configurationFile].filter(Boolean).map(file => path.resolve(file)));
const files = directory ? (await walk(source)).filter(file => !excluded.has(file)) : [source];
const manifest = await Promise.all(
  files.map(async (f) => ({
    path: directory
      ? path.relative(source, f).split(path.sep).join("/")
      : path.basename(f),
    content_type: mime(f),
    size_bytes: (await stat(f)).size,
  })),
);
if (inputType !== "dataset" && manifest.some((f) => f.path.includes("/")))
  throw new Error("Only dataset input permits nested paths.");
const configuration = configurationFile
  ? JSON.parse(await readFile(configurationFile, "utf8"))
  : ["fast", "balanced", "high", "higher", "highest"].includes(depth) ? { trainingDepth: depth } : { selectedModel: depth };
const fingerprint = JSON.stringify({
  source,
  base,
  inputType,
  manifest,
  configuration,
});
let state;
try {
  state = JSON.parse(await readFile(statePath, "utf8"));
} catch (e) {
  if (e.code !== "ENOENT") throw e;
  state = { run: randomUUID(), fingerprint, uploads: {}, completePage: 0 };
}
if (state.fingerprint !== fingerprint)
  throw new Error("Inputs changed. Use a new state file.");
const save = () => writeFile(statePath, JSON.stringify(state), { mode: 0o600 });
if (!state.training && !state.ready && !state.uploadsComplete) {
  if (state.dataset && !state.sourceSha256) throw new Error("Older partial upload. Restart with a new state file.");
  const identity = createHash("sha256");
  for (const file of files) {
    const digest = createHash("sha256");
    for await (const chunk of createReadStream(file)) digest.update(chunk);
    identity.update(digest.digest());
  }
  const checksum = identity.digest("hex");
  if (state.sourceSha256 && state.sourceSha256 !== checksum) throw new Error("File contents changed. Use a new state file.");
  state.sourceSha256 = checksum;
}
await save();
async function upload(file, session) {
  const size = (await stat(file)).size;
  const handle = await open(file, "r");
  try {
    for (let attempt = 0; attempt < 8; attempt++) {
      try {
        let response = await fetch(session, {
          method: "PUT",
          headers: {
            "Content-Length": "0",
            "Content-Range": `bytes */${size}`,
          },
          body: Buffer.alloc(0),
          signal: AbortSignal.timeout(120000),
        });
        if (response.ok) return;
        if (response.status !== 308)
          throw new Error(`Upload session returned HTTP ${response.status}.`);
        let offset = response.headers.get("Range")
          ? Number(response.headers.get("Range").split("-")[1]) + 1
          : 0;
        while (offset < size) {
          const chunk = Buffer.alloc(Math.min(8 * 1024 * 1024, size - offset));
          const { bytesRead } = await handle.read(
            chunk,
            0,
            chunk.length,
            offset,
          );
          if (!bytesRead) throw new Error("Input file changed during upload.");
          response = await fetch(session, {
            method: "PUT",
            headers: {
              "Content-Type": mime(file),
              "Content-Length": String(bytesRead),
              "Content-Range": `bytes ${offset}-${
                offset + bytesRead - 1
              }/${size}`,
            },
            body: chunk.subarray(0, bytesRead),
            signal: AbortSignal.timeout(120000),
          });
          if (response.ok) return;
          if (response.status !== 308)
            throw new Error(`Upload returned HTTP ${response.status}.`);
          offset = response.headers.get("Range")
            ? Number(response.headers.get("Range").split("-")[1]) + 1
            : 0;
        }
      } catch (e) {
        if (attempt === 7) throw e;
        await wait(Math.min(30, 2 ** attempt) * 1000);
      }
    }
    throw new Error("Upload retries exhausted.");
  } finally {
    await handle.close();
  }
}
if (!state.dataset) {
  state.dataset = (
    await api(
      "POST",
      "/datasets",
      { name: path.basename(source), input_type: inputType },
      state.run + "-dataset",
    )
  ).id;
  await save();
}
for (
  let start = 0;
  !state.uploadsComplete && !state.ready && start < files.length;
  start += 50
) {
  if (!state.uploads[start]) {
    state.uploads[start] = (
      await api(
        "POST",
        `/datasets/${state.dataset}/uploads`,
        { files: manifest.slice(start, start + 50) },
        state.run + "-uploads-" + start,
      )
    ).uploads;
    await save();
  }
  for (let i = 0; i < state.uploads[start].length; i++)
    await upload(files[start + i], state.uploads[start][i].upload_url);
}
state.uploads = {};
state.uploadsComplete = true;
await save();
if (!state.ready) liveLine(`Validating files · ${state.validatedFiles || 0}/${files.length}`);
while (!state.ready) {
  const result = await api(
    "POST",
    `/datasets/${state.dataset}/complete`,
    {},
    state.run + "-complete-" + state.completePage,
  );
  state.completePage++;
  state.validatedFiles = result.validated_files;
  state.ready = result.status === "ready";
  if (state.ready && result.validated_files !== files.length) throw new Error("Validated file count does not match the input.");
  await save();
  liveLine(`${state.ready ? "Validated" : "Validating"} files · ${result.validated_files}/${files.length}`, state.ready);
}
if (!state.training) {
  state.training = (
    await api(
      "POST",
      "/trainings",
      { dataset_id: state.dataset, configuration },
      state.run + "-training",
    )
  ).id;
  await save();
}
const stages = ["payment_pending", "preparing", "download", "preprocessing", "masking", "alignment", "training", "export"];
let rank = -1, percent = 0;
console.log("Training ID:", state.training);
for (;;) {
  const job = await api("GET", "/trainings/" + state.training);
  const progress = job.progress;
  const stage = progress?.stage || (job.status === "queued" ? "preparing" : job.status);
  const next = stages.indexOf(stage);
  if (next >= 0 && next >= rank) {
    rank = next;
    percent = Math.max(percent, progress?.percent ?? 0);
  }
  const terminal = job.status === "completed" || job.status === "failed";
  const current = stages[rank];
  const label = terminal ? job.status : current === "preparing" ? "Preparing training" : current || "Awaiting worker update";
  liveLine(`${label} · ${job.status === "completed" ? 100 : percent}%`, terminal);
  if (job.status === "completed") {
    console.log(new URL(job.capture_url, base).href);
    break;
  }
  if (job.status === "failed") throw new Error(job.error.message);
  await wait(1000 * Math.max(1, Math.min(30, Number(job.poll_after_seconds) || 10)));
}

cURL and Bash: train.sh

Requires Bash, curl and jq, and a directory of at least 25 .jpg/.jpeg files. Save as train.sh and run after setting SPLATWARE_API_KEY:

bash train.sh ./images
Recovery behavior differs
This concise example uploads each file in one request and does not persist run state. Rerunning it starts a new dataset and can create a new job. Use Python or Node.js for chunk recovery and resumable runs.
#!/usr/bin/env bash
# Bash, curl and jq. Upload at least 25 JPEGs; Node/Python add resumable chunk recovery.
set -euo pipefail
: "${SPLATWARE_API_KEY:?Set SPLATWARE_API_KEY}"
BASE="${SPLATWARE_API_BASE:-https://splatware.com/api/v1}"
if [[ "$BASE" != https://* && ! "$BASE" =~ ^http://(127\.0\.0\.1|localhost|\[::1\])(:[0-9]+)?/ ]]; then
  printf 'The API requires HTTPS outside localhost.\n' >&2; exit 1
fi
DIRECTORY="${1:?Usage: train.sh DIRECTORY_WITH_25_OR_MORE_JPEGS}"
shopt -s nullglob
FILES=("$DIRECTORY"/*.jpg "$DIRECTORY"/*.jpeg)
if (( ${#FILES[@]} < 25 )); then printf 'Training requires at least 25 JPEG images.\n' >&2; exit 1; fi
RUN="$(date +%s)-${RANDOM}"
api() { curl --fail-with-body --silent --show-error -H "Authorization: Bearer $SPLATWARE_API_KEY" -H 'Content-Type: application/json' "$@"; }
live_line() {
  if [[ -t 1 ]]; then
    local width=$(( ${COLUMNS:-80} - 1 ))
    printf '\r%-*.*s' "$width" "$width" "$1"
    if [[ ${2:-} == done ]]; then printf '\n'; fi
  elif [[ ${2:-} == done ]]; then
    printf '%s\n' "$1"
  fi
}
DATASET=$(api "$BASE/datasets" -H "Idempotency-Key: $RUN-dataset" -d '{"name":"API example","input_type":"images"}' | jq -er '.data.id')
INDEX=0
for FILE in "${FILES[@]}"; do
  SIZE=$(wc -c < "$FILE" | tr -d ' ')
  MANIFEST=$(jq -nc --arg name "input-$INDEX.jpg" --argjson size "$SIZE" '{files:[{path:$name,content_type:"image/jpeg",size_bytes:$size}]}')
  UPLOAD=$(api "$BASE/datasets/$DATASET/uploads" -H "Idempotency-Key: $RUN-upload-$INDEX" -d "$MANIFEST" | jq -er '.data.uploads[0].upload_url')
  curl --fail-with-body --silent --show-error -X PUT "$UPLOAD" -H 'Content-Type: image/jpeg' -H "Content-Range: bytes 0-$((SIZE-1))/$SIZE" --data-binary "@$FILE" > /dev/null
  INDEX=$((INDEX+1))
done
PAGE=0
while true; do
  RESULT=$(api "$BASE/datasets/$DATASET/complete" -H "Idempotency-Key: $RUN-complete-$PAGE" -d '{}')
  COUNT=$(jq -er '.data.validated_files' <<< "$RESULT")
  if [[ $(jq -er '.data.status' <<< "$RESULT") == ready ]]; then
    live_line "Validated $COUNT/${#FILES[@]} photos" done
    break
  fi
  live_line "Validating $COUNT/${#FILES[@]} photos"
  PAGE=$((PAGE+1))
done
TRAINING=$(api "$BASE/trainings" -H "Idempotency-Key: $RUN-training" -d "$(jq -nc --arg id "$DATASET" '{dataset_id:$id,configuration:{trainingDepth:"fast"}}')" | jq -er '.data.id')
printf 'Training ID: %s\n' "$TRAINING"
RANK=-1
PERCENT=0
STAGES=(payment_pending preparing download preprocessing masking alignment training export)
LABEL='Awaiting worker update'
while true; do
  JOB=$(api "$BASE/trainings/$TRAINING")
  STATUS=$(jq -r '.data.status' <<< "$JOB")
  if [[ "$STATUS" == completed ]]; then live_line 'Completed 100%' done; jq -r '.data.capture_url' <<< "$JOB"; break; fi
  if [[ "$STATUS" == failed ]]; then live_line "Failed $PERCENT%" done; jq -r '.data.error.message' <<< "$JOB" >&2; exit 1; fi
  STAGE=$(jq -r '.data.progress.stage // .data.status' <<< "$JOB")
  for i in "${!STAGES[@]}"; do
    if [[ "$STAGE" == "${STAGES[i]}" ]] && (( i >= RANK )); then
      RANK=$i
      LABEL=$STAGE
      if [[ "$STAGE" == preparing ]]; then LABEL='Preparing training'; fi
      PERCENT=$(jq -r --argjson previous "$PERCENT" '[$previous, (.data.progress.percent // 0)] | max' <<< "$JOB")
      break
    fi
  done
  live_line "$LABEL $PERCENT%"
  sleep "$(jq -r '[1, ([30, (.data.poll_after_seconds // 10)] | min)] | max' <<< "$JOB")"
done

Webhook signature verification

Pass the raw body, Splatware-Signature header and stored signing secret to the helper before parsing JSON. Persist accepted event ids separately; these helpers do not implement a web server or a deduplication database.

Python: verify_webhook.py

"""Verify before parsing JSON. Persist event IDs to deduplicate delivery retries."""
import hashlib, hmac, time

def verify_webhook(raw_body: bytes, signature: str, signing_secret: str) -> bool:
    try:
        fields = dict(part.split('=', 1) for part in signature.split(','))
        timestamp = fields['t']
        if abs(time.time() - int(timestamp)) > 300:
            return False
        expected = hmac.new(signing_secret.encode(), timestamp.encode() + b'.' + raw_body, hashlib.sha256).hexdigest()
        return hmac.compare_digest(expected, fields['v1'])
    except (KeyError, ValueError):
        return False

Node.js: verify-webhook.mjs

import { createHmac, timingSafeEqual } from "node:crypto";
// Verify raw bytes before JSON.parse. Persist Splatware-Event-Id to deduplicate retries.
export function verifyWebhook(rawBody, signature, signingSecret) {
  const fields = Object.fromEntries(
    String(signature)
      .split(",")
      .map((v) => v.split("=")),
  );
  if (
    !/^\d+$/.test(fields.t || "") ||
    Math.abs(Date.now() / 1000 - Number(fields.t)) > 300 ||
    !/^[a-f0-9]{64}$/.test(fields.v1 || "")
  )
    return false;
  const expected = createHmac("sha256", signingSecret)
    .update(fields.t + ".")
    .update(rawBody)
    .digest();
  return timingSafeEqual(expected, Buffer.from(fields.v1, "hex"));
}

See webhook setup, retries and the current OpenAPI document.