#!/usr/bin/env python3 """Image API example client (Python 3.10+ standard library only). Submits one image job, polls it to a final state and saves the results. POST spends API credits; polling and downloads do not. python3 image_job.py background-removal IMAGE OUT_DIR [model=bria] [output_format=webp] python3 image_job.py upscale IMAGE OUT_DIR [model=print] [scale=4] [content=text] [output_format=png] python3 image_job.py generation PROMPT_FILE OUT_DIR [width=1280] [height=768] [num_images=2] [seed=7] Environment: ARTWORK_API_KEY (the same ip_art_ key as artwork checks), ARTWORK_API_BASE_URL (HTTPS origin, no path) and ARTWORK_IDEMPOTENCY_KEY (persist it before running; reuse the same value and inputs after a timeout). Bounded: at most 5 attempts per request, a shared 15-minute budget, waits capped at 10 seconds unless Retry-After asks for longer, no redirects. Exit codes: 0 completed, 2 job failed, 1 request or usage error. Prints only the job ID, status, credits, error codes, request IDs and saved file paths. """ import email.utils import json import os from pathlib import Path import re import sys import time import urllib.error import urllib.parse import urllib.request import uuid ROUTES = {'background-removal': ('background-removals', 'background_removal'), 'upscale': ('upscales', 'upscale'), 'generation': ('generations', 'image_generation')} INTEGER_FIELDS = {'width', 'height', 'num_images', 'seed'} EXTENSIONS = {'image/png': 'png', 'image/webp': 'webp', 'image/jpeg': 'jpg'} BUDGET_SECONDS = 15 * 60 MAX_DOWNLOAD = 64 * 1024 * 1024 class Stop(Exception): pass class NoRedirect(urllib.request.HTTPRedirectHandler): def redirect_request(self, *args, **kwargs): return None OPENER = urllib.request.build_opener(NoRedirect) def settings(): key = os.environ.get('ARTWORK_API_KEY', '') base = os.environ.get('ARTWORK_API_BASE_URL', '') idem = os.environ.get('ARTWORK_IDEMPOTENCY_KEY', '') if not re.fullmatch(r'ip_art_[A-Za-z0-9_-]{8,}', key): raise Stop('Set ARTWORK_API_KEY to your ip_art_ API key') parsed = urllib.parse.urlsplit(base) loopback = parsed.hostname in ('127.0.0.1', 'localhost', '::1') if parsed.scheme not in ('https', 'http') or (parsed.scheme == 'http' and not loopback) or \ parsed.path not in ('', '/') or parsed.query or parsed.fragment or parsed.username: raise Stop('ARTWORK_API_BASE_URL must be an https:// origin with no path') if not re.fullmatch(r'[\x21-\x7e]{1,200}', idem): raise Stop('Set ARTWORK_IDEMPOTENCY_KEY to 1-200 visible ASCII characters and keep it for retries') return key, base.rstrip('/'), idem def multipart(raw, fields): boundary = uuid.uuid4().hex parts = [] for name, value in fields.items(): parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"\r\n\r\n{value}\r\n'.encode()) parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="image"\r\n' 'Content-Type: application/octet-stream\r\n\r\n'.encode() + raw + b'\r\n') parts.append(f'--{boundary}--\r\n'.encode()) return b''.join(parts), f'multipart/form-data; boundary={boundary}' def retry_after(headers, attempt): value = headers.get('Retry-After') if headers else None if value: if value.isdigit(): return int(value) try: return max(0, email.utils.parsedate_to_datetime(value).timestamp() - time.time()) except (TypeError, ValueError): pass return min(10, 2 ** attempt) def request(method, url, deadline, *, key=None, body=None, headers=None, raw=False): """One logical request with bounded retries on connection loss, 429 and 5xx.""" for attempt in range(5): wait = None try: req = urllib.request.Request(url, data=body, method=method, headers=dict(headers or {})) if key: req.add_header('Authorization', 'Bearer ' + key) with OPENER.open(req, timeout=20) as response: data = response.read(MAX_DOWNLOAD + 1) if len(data) > MAX_DOWNLOAD: raise Stop('Response too large') return (data, response.headers.get('Content-Type', '')) if raw else json.loads(data) except urllib.error.HTTPError as error: if 300 <= error.code < 400: raise Stop('Redirect refused') from None if error.code != 429 and error.code < 500: code, request_id = 'http_%d' % error.code, None try: payload = json.loads(error.read(65536)) code = payload['error']['code'] if re.fullmatch(r'[a-z_]{1,64}', payload['error']['code']) else code request_id = payload.get('request_id') if re.fullmatch(r'[0-9a-f-]{36}', payload.get('request_id', '')) else None except Exception: pass raise Stop(f'HTTP {error.code} {code}' + (f' request_id={request_id}' if request_id else '')) from None wait = retry_after(error.headers, attempt) except (urllib.error.URLError, TimeoutError, ConnectionError, json.JSONDecodeError): wait = min(10, 2 ** attempt) # response lost: retry with the SAME idempotency key if attempt == 4 or time.monotonic() + wait > deadline: raise Stop('Gave up retrying; rerun later with the same ARTWORK_IDEMPOTENCY_KEY') time.sleep(wait) def main(argv): if len(argv) < 3 or argv[0] not in ROUTES or any('=' not in extra for extra in argv[3:]): raise Stop(__doc__.split('\n\n')[1]) command, source, out_dir = argv[0], Path(argv[1]), Path(argv[2]) key, base, idem = settings() path, _ = ROUTES[command] fields = dict(extra.split('=', 1) for extra in argv[3:]) out_dir.mkdir(parents=True, exist_ok=True) deadline = time.monotonic() + BUDGET_SECONDS headers = {'Idempotency-Key': idem} if command == 'generation': body = {name: int(value) if name in INTEGER_FIELDS else value for name, value in fields.items()} body['prompt'] = source.read_text(encoding='utf-8').strip() data, headers['Content-Type'] = json.dumps(body).encode(), 'application/json' else: data, headers['Content-Type'] = multipart(source.read_bytes(), fields) job = request('POST', f'{base}/api/v1/images/{path}', deadline, key=key, body=data, headers=headers) job_id = job['id'] if not re.fullmatch(r'[0-9a-f-]{36}', job_id): raise Stop('Unexpected response') print(json.dumps({'id': job_id, 'reserved_credits': job.get('reserved_credits')}), flush=True) delay = 2 while True: detail = request('GET', f'{base}/api/v1/images/jobs/{job_id}', deadline, key=key) status = detail.get('processing_status') if status in ('completed', 'failed'): break if time.monotonic() + delay > deadline: raise Stop(f'Still {status}; resume polling job {job_id} later') time.sleep(delay) delay = min(10, delay * 2) if status == 'failed': print(json.dumps({'id': job_id, 'processing_status': 'failed', 'error_code': detail.get('error_code')})) return 2 saved = [] for output in detail.get('outputs', [])[:8]: url = output.get('url', '') if not url.startswith('/api/v1/images/outputs/'): raise Stop('Unexpected output link') content, content_type = request('GET', base + url, deadline, raw=True) # signed link: no API key sent extension = EXTENSIONS.get(content_type.split(';')[0].strip()) if extension is None or type(output.get('index')) is not int: raise Stop('Unexpected output type') target = out_dir / f'{job_id}-{output["index"]}.{extension}' target.write_bytes(content) saved.append(str(target)) print(json.dumps({'id': job_id, 'processing_status': 'completed', 'charged_credits': detail.get('charged_credits'), 'saved': saved})) return 0 if __name__ == '__main__': try: sys.exit(main(sys.argv[1:])) except Stop as stop: print(str(stop), file=sys.stderr) sys.exit(1) except (OSError, ValueError, KeyError) as error: print(f'Error: {type(error).__name__}', file=sys.stderr) sys.exit(1)