Files
dsProject/dsLightRag/JiMeng/JmImg2Video.py
2025-08-19 15:40:58 +08:00

129 lines
4.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import json
import time
import logging
from JiMeng.Kit.JmCommon import JmCommon
from JiMeng.Kit.JmErrorCode import JmErrorCode
# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger('JmImg2Video')
class JmImg2Video(JmCommon):
req_key = "jimeng_vgfm_i2v_l20"
action = "CVSync2AsyncSubmitTask"
@staticmethod
def submit_image_to_video_task(image_urls, prompt):
"""
提交图生视频任务使用图片URL
:param image_urls: 图片URL列表
:param prompt: 提示词
:return: 任务结果
:raises Exception: 异常信息
"""
# 创建请求体
req = {
"req_key": JmImg2Video.req_key,
"image_urls": image_urls,
"prompt": prompt
}
response_body = JmCommon.do_request(
method="POST",
query_list={}, # 添加空字典作为query_list参数
body=json.dumps(req).encode('utf-8'),
action=JmImg2Video.action
)
return json.loads(response_body)
def main():
try:
# 玩法参考: https://www.volcengine.com/docs/85621/1544774
image_urls = [
"https://dsideal.obs.myhuaweicloud.com/HuangHai/%E5%A4%87%E4%BB%BD/%E5%B0%8F%E4%B9%94%E5%A4%B4%E5%83%8F.jpg"
]
prompt = ""
mp4_file_name = "image2video.mp4"
# 添加重试逻辑处理API并发限制错误
submit_result = None
submit_retry_count = 0
max_submit_retries = 1000 # 最大重试次数
submit_retry_interval = 3000 # 重试间隔(毫秒)
while submit_retry_count < max_submit_retries:
try:
submit_result = JmImg2Video.submit_image_to_video_task(image_urls, prompt)
logger.info(f"提交结果: {submit_result}")
code = submit_result.get("code")
if code == JmErrorCode.API_CONCURRENT_LIMIT[0]:
logger.warning(f"API并发限制等待{submit_retry_interval}毫秒后重试...")
time.sleep(submit_retry_interval / 1000)
submit_retry_count += 1
continue
elif not JmErrorCode.is_success(code):
logger.error(f"提交任务失败: 错误码={code}, 错误信息={JmErrorCode.get_message_by_code(code)}")
return
# 成功获取结果,跳出循环
break
except Exception as e:
logger.error(f"提交任务异常: {str(e)}", exc_info=True)
submit_retry_count += 1
if submit_retry_count < max_submit_retries:
logger.warning(f"等待{submit_retry_interval}毫秒后重试...")
time.sleep(submit_retry_interval / 1000)
else:
raise # 达到最大重试次数,抛出异常
if submit_retry_count >= max_submit_retries:
logger.error(f"提交任务失败,已达到最大重试次数: {max_submit_retries}")
return
# 获取任务ID
task_id = submit_result.get("data", {}).get("task_id")
logger.info(f"任务ID: {task_id}")
# 检查任务是不是已经结束
query_retry_count = 0
max_query_retries = 10000 # 最大查询次数
query_retry_interval = 3000 # 查询间隔(毫秒)
while query_retry_count < max_query_retries:
result = JmCommon.query_task_result(task_id)
logger.info(f"查询结果: {result}")
code = result.get("code")
if not JmErrorCode.is_success(code):
logger.error(f"查询失败: 错误码={code}, 错误信息={JmErrorCode.get_message_by_code(code)}")
break
data = result.get("data")
if data and data.get("video_url"):
video_url = data.get("video_url")
logger.info(f"视频地址: {video_url}")
# 下载视频
save_video_path = fr"D:\dsWork\dsProject\dsLightRag\JiMeng\{mp4_file_name}"
logger.info("开始下载视频...")
JmCommon.download_file(video_url, save_video_path)
logger.info(f"视频已下载到: {save_video_path}")
break
else:
logger.info(f"任务处理中,等待{query_retry_interval}毫秒后重试...")
time.sleep(query_retry_interval / 1000)
query_retry_count += 1
if query_retry_count >= max_query_retries:
logger.error(f"任务查询超时,已达到最大查询次数: {max_query_retries}")
except Exception as e:
logger.error(f"程序执行异常: {str(e)}", exc_info=True)
if __name__ == "__main__":
main()