"""Zaomeng server-side API example. Requires Python 3.10+ and requests. Set ZAOMENG_API_KEY in the environment; never publish it in browser code. Uploads do not generate videos. Only the explicit submit command spends credit. Keep job files private: they contain prompts and reference URLs, not API keys. """ import argparse import hashlib import json import os from pathlib import Path import re import time import uuid import requests BASE = 'https://www.xinghecz.com/api/v1' MIMES = {'.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.mp4': 'video/mp4', '.mp3': 'audio/mpeg', '.wav': 'audio/wav'} class Client: def __init__(self, key): self.session = requests.Session() self.session.headers['Authorization'] = 'Bearer ' + key self.last_request = 0.0 def call(self, method, path, *, retry=False, **kwargs): # Upload chunks count towards the account-wide 60 requests/minute limit. for attempt in range(4): time.sleep(max(0, self.last_request + 1.1 - time.monotonic())) self.last_request = time.monotonic() try: response = self.session.request(method, BASE + path, timeout=(15, 180), allow_redirects=False, **kwargs) except requests.RequestException: if not retry or attempt == 3: raise time.sleep(2 ** attempt) continue if retry and response.status_code in (429, 502, 503, 504) and attempt < 3: time.sleep(61 if response.status_code == 429 else 2 ** attempt) continue if not 200 <= response.status_code < 300: raise RuntimeError(f'HTTP {response.status_code}: {response.text[:1000]}') value = response.json() if value.get('ok') is False: raise RuntimeError(str(value.get('error'))) return value def upload(self, filename, upload_id): path = Path(filename) mime = MIMES.get(path.suffix.lower()) if not mime: raise ValueError('Use PNG, JPG, WebP, MP4, MP3 or WAV') size = path.stat().st_size maximum = 50 * 1024 ** 2 if not 0 < size <= maximum: raise ValueError(f'File must be between 1 and {maximum} bytes') digest = hashlib.sha256() with path.open('rb') as stream: while chunk := stream.read(1024 ** 2): digest.update(chunk) prefix = '/video/material-uploads/' + upload_id state = self.call('POST', '/video/material-uploads', retry=True, json={'uploadId': upload_id, 'size': size, 'mimeType': mime}) if state.get('result'): result = state['result'] else: with path.open('rb') as stream: while state['offset'] < size: offset = state['offset'] stream.seek(offset) chunk = stream.read(min(state['chunkBytes'], 1024 ** 2, size - offset)) if not chunk: raise ValueError('File changed during upload; use a new upload ID') state = self.call('POST', prefix + f'/chunk?offset={offset}', retry=True, headers={'Content-Type': 'application/octet-stream'}, data=chunk) if state['offset'] != offset + len(chunk): raise ValueError('Unexpected offset; check upload status before continuing') result = self.call('POST', prefix + '/complete', json={}, retry=True) if result['sha256'] != digest.hexdigest() or result['sizeBytes'] != size: raise ValueError('Uploaded file differs; do not use this reference URL') return result def write_state(path, value, *, new=False): text = json.dumps(value, ensure_ascii=False, indent=2) if new: with path.open('x', encoding='utf-8') as stream: stream.write(text) else: pending = path.with_name(path.name + '.pending') pending.write_text(text, encoding='utf-8') os.replace(pending, path) def main(): parser = argparse.ArgumentParser(description=__doc__) commands = parser.add_subparsers(dest='command', required=True) commands.add_parser('models') upload = commands.add_parser('upload') upload.add_argument('file') upload.add_argument('--upload-id', help='Reuse only for the same unchanged file and account') for action in ('upload-status', 'upload-cancel'): commands.add_parser(action).add_argument('upload_id') quote = commands.add_parser('quote') quote.add_argument('request', type=Path) quote.add_argument('job', type=Path) for action in ('submit', 'status', 'recover'): command = commands.add_parser(action) command.add_argument('job', type=Path) if action == 'submit': command.add_argument('--max-fen', required=True, type=int, help='Explicit maximum acceptable total price, in fen') download = commands.add_parser('download') download.add_argument('url', help='Private /api/video/media/... or referenceUrl') download.add_argument('output', type=Path) args = parser.parse_args() client = Client(os.environ['ZAOMENG_API_KEY']) if args.command == 'models': result = client.call('GET', '/models', retry=True) elif args.command == 'upload': upload_id = args.upload_id or uuid.uuid4().hex print('uploadId:', upload_id, flush=True) result = client.upload(args.file, upload_id) elif args.command.startswith('upload-'): path = '/video/material-uploads/' + args.upload_id result = (client.call('GET', path, retry=True) if args.command == 'upload-status' else client.call('POST', path + '/cancel', json={}, retry=True)) elif args.command == 'download': if not re.fullmatch(r'/api/video/(?:media|references|materials)/[A-Za-z0-9_.-]+', args.url): raise ValueError('Only private site paths are accepted; never send your key to external URLs') with client.session.get(BASE + args.url.removeprefix('/api'), stream=True, timeout=(15, 180), allow_redirects=False) as response: if response.status_code != 200: raise RuntimeError(f'Download failed: HTTP {response.status_code}') with args.output.open('xb') as stream: for chunk in response.iter_content(1024 ** 2): stream.write(chunk) result = {'saved': str(args.output)} else: if args.command == 'quote': job = {'operationId': 'video-' + uuid.uuid4().hex, 'request': json.loads(args.request.read_text(encoding='utf-8-sig'))} write_state(args.job, job, new=True) else: job = json.loads(args.job.read_text(encoding='utf-8')) operation = {'X-Operation-ID': job['operationId']} if args.command in ('quote', 'submit'): if job.get('submitAttempted'): raise ValueError('Submission already attempted. Use status/recover; do not resubmit') result = client.call('POST', '/quote', retry=True, json={ 'endpoint': '/api/video/tasks', 'operationId': job['operationId'], 'request': job['request']}) job['quote'] = result['quote'] write_state(args.job, job) if args.command == 'submit': if result['quote']['amountFen'] > args.max_fen: raise ValueError('Quoted price exceeds --max-fen; no generation submitted') envelope = {k: result[k] for k in ('quote', 'signature')} job['submitAttempted'] = True write_state(args.job, job) # Never automatically retry a paid submission, even on a timeout. result = client.call('POST', '/video/tasks', json=job['request'], headers={**operation, 'X-Studio-Quote': json.dumps(envelope)}) elif args.command == 'status' and job.get('taskId'): result = client.call('POST', '/video/tasks/status', retry=True, headers=operation, json={'request': job['request'], 'taskId': job['taskId']}) else: action = 'recover' if args.command == 'recover' else 'status' result = client.call('POST', '/video/operations/' + action, retry=True, headers=operation, json={'request': job['request']}) task = result.get('task') or result if task.get('taskId'): job['taskId'] = task['taskId'] job['lastResult'] = result write_state(args.job, job) print(json.dumps(result, ensure_ascii=False, indent=2)) if __name__ == '__main__': main()