"""One submission, bounded polling, authenticated download. No POST retries.""" import os from pathlib import Path import time import requests BASE = os.environ.get('VIDEO_BASE_URL', 'https://video.laoma.667734.xyz').rstrip('/') KEY = os.environ.get('VIDEO_API_KEY', '') def json_response(response): response.raise_for_status() return response.json() def main(): if not KEY: raise SystemExit('Set VIDEO_API_KEY before running this billable example.') headers = {'Authorization': 'Bearer ' + KEY} with requests.Session() as session: try: task = json_response(session.post(BASE + '/v1/videos', headers=headers, json={ 'prompt': '秋风落叶', 'model': 'video-2.0-fast', 'duration': 5, 'ratio': '16:9', }, timeout=(10, 60))) except requests.RequestException as exc: raise SystemExit('Submission failed or is uncertain. Check task history; do not resubmit automatically. ' + str(exc)) task_id = task['id'] print('Task ID:', task_id, flush=True) deadline = time.monotonic() + 1800 while True: if time.monotonic() >= deadline: raise SystemExit('Polling stopped. Upstream may still be working; query the same task: ' + task_id) info = json_response(session.get(BASE + '/v1/videos/' + task_id, headers=headers, timeout=(10, 30))) print(info['status'], (info.get('progress') or {}).get('message', ''), flush=True) if info['status'] in ('failed', '风控'): raise SystemExit('Task failed: ' + str(info.get('error'))) if info['status'] == 'completed': break time.sleep(6) partial = Path(task_id + '.mp4.part') final = Path(task_id + '.mp4') try: with session.get(BASE + '/v1/videos/' + task_id + '/content', headers=headers, stream=True, timeout=(10, 120)) as response: response.raise_for_status() with partial.open('wb') as output: for chunk in response.iter_content(1024 * 1024): if chunk: output.write(chunk) partial.replace(final) except Exception: partial.unlink(missing_ok=True) raise print('Downloaded:', final.resolve()) if __name__ == '__main__': main()