|
|
|
@ -0,0 +1,63 @@
|
|
|
|
|
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, sketch_image_url, model="wanx-sketch-to-image-lite", task="image2image", n=1, size='768*768', style='<watercolor>'):
|
|
|
|
|
"""
|
|
|
|
|
根据提示词和草图生成图片
|
|
|
|
|
:param prompt: 提示词
|
|
|
|
|
:param sketch_image_url: 草图图片 URL
|
|
|
|
|
:param model: 使用的模型,默认为 "wanx-sketch-to-image-lite"
|
|
|
|
|
:param task: 任务类型,默认为 "image2image"
|
|
|
|
|
:param n: 生成图片的数量,默认为 1
|
|
|
|
|
:param size: 图片尺寸,默认为 '768*768'
|
|
|
|
|
:param style: 图片风格,默认为 '<watercolor>'
|
|
|
|
|
:return: (success, message) success 为 True 表示成功,False 表示失败;message 为提示信息
|
|
|
|
|
"""
|
|
|
|
|
try:
|
|
|
|
|
print('----同步调用,请稍等----')
|
|
|
|
|
rsp = ImageSynthesis.call(api_key=MODEL_API_KEY,
|
|
|
|
|
model=model,
|
|
|
|
|
prompt=prompt,
|
|
|
|
|
n=n,
|
|
|
|
|
style=style,
|
|
|
|
|
size=size,
|
|
|
|
|
sketch_image_url=sketch_image_url,
|
|
|
|
|
task=task)
|
|
|
|
|
print('response: %s' % rsp)
|
|
|
|
|
|
|
|
|
|
if rsp.status_code == HTTPStatus.OK:
|
|
|
|
|
if rsp.output.task_status == "SUCCEEDED":
|
|
|
|
|
# 在当前目录下保存图片
|
|
|
|
|
for result in rsp.output.results:
|
|
|
|
|
file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
|
|
|
|
|
#with open('./%s' % file_name, 'wb+') as f:
|
|
|
|
|
# f.write(requests.get(result.url).content)
|
|
|
|
|
#print(f"图片已生成,文件名: {file_name}")
|
|
|
|
|
return True, "图片生成成功"
|
|
|
|
|
else:
|
|
|
|
|
# 生成失败,返回错误信息
|
|
|
|
|
error_message = f"生成失败,错误码: {rsp.output.code}, 错误信息: {rsp.output.message}"
|
|
|
|
|
print(error_message)
|
|
|
|
|
return False, error_message
|
|
|
|
|
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 = "一棵参天大树"
|
|
|
|
|
sketch_image_url = "https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/6609471071/p743851.jpg"
|
|
|
|
|
success, message = generate_image(prompt, sketch_image_url)
|
|
|
|
|
if not success:
|
|
|
|
|
print(f"生成失败: {message}")
|