You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

44 lines
1.8 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
from dashscope import ImageSynthesis
from WxMini.Milvus.Config.MulvusConfig import *
def generate_image(prompt, model="wanx2.1-t2i-turbo", n=1, size='1024*1024'):
"""
根据提示词生成图片
:param prompt: 提示词
:param model: 使用的模型,默认为 "wanx2.1-t2i-turbo"
:param n: 生成图片的数量,默认为 1
:param size: 图片尺寸,默认为 '1024*1024'
:return: (success, message) success 为 True 表示成功False 表示失败message 为提示信息
"""
try:
print('----同步调用,请稍等----')
rsp = ImageSynthesis.call(api_key=MODEL_API_KEY, model=model, prompt=prompt, n=n, size=size)
print('response: %s' % rsp)
if rsp.status_code == HTTPStatus.OK:
# 在当前目录下保存图片
for result in rsp.output.results:
file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
print(f"图片已生成,文件名: {file_name}")
return True, "图片生成成功"
else:
# 生成失败,返回错误信息
error_message = f"同步调用失败,状态码: {rsp.status_code}, 错误码: {rsp.code}, 错误信息: {rsp.message}"
print(error_message)
return False, error_message
except Exception as e:
# 捕获异常,返回错误信息
error_message = f"生成图片时发生异常: {str(e)}"
print(error_message)
return False, error_message
# 示例调用
if __name__ == '__main__':
prompt = "哪吒闹海"
success, message = generate_image(prompt)
if not success:
print(f"生成失败: {message}")