#!/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)