veo_client.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import requests
  2. import time
  3. from typing import Dict, Any
  4. class VEOClient:
  5. """VEO 3.1 异步调用客户端"""
  6. def __init__(self, api_key: str, base_url: str = "https://api.apiyi.com"):
  7. self.base_url = base_url
  8. self.headers = {
  9. "Content-Type": "application/json",
  10. "Authorization": f"Bearer {api_key}"
  11. }
  12. def create_video(self, prompt: str, model: str = "veo-3.1-fast") -> str:
  13. """创建视频任务,返回 video_id"""
  14. response = requests.post(
  15. f"{self.base_url}/v1/videos",
  16. headers=self.headers,
  17. json={"prompt": prompt, "model": model}
  18. )
  19. response.raise_for_status()
  20. return response.json()["id"]
  21. def get_status(self, video_id: str) -> Dict[str, Any]:
  22. """查询任务状态,completed 时响应中直接含 video_url"""
  23. response = requests.get(
  24. f"{self.base_url}/v1/videos/{video_id}",
  25. headers=self.headers
  26. )
  27. response.raise_for_status()
  28. return response.json()
  29. def wait_for_completion(
  30. self,
  31. video_id: str,
  32. timeout: int = 600,
  33. interval: int = 5
  34. ) -> Dict[str, Any]:
  35. """轮询直到完成,返回包含 video_url 的状态数据"""
  36. start_time = time.time()
  37. while time.time() - start_time < timeout:
  38. data = self.get_status(video_id)
  39. status = data.get("status")
  40. if status == "completed":
  41. return data
  42. elif status == "failed":
  43. raise Exception(f"视频生成失败: {data}")
  44. time.sleep(interval)
  45. raise TimeoutError("等待超时")