123 lines
3.9 KiB
Python
123 lines
3.9 KiB
Python
import os
|
|
import sys
|
|
import base64
|
|
import mimetypes
|
|
import requests
|
|
from urllib.request import urlretrieve
|
|
|
|
API_KEY = os.getenv("DASHSCOPE_API_KEY", "")
|
|
DEFAULT_API_KEY = "sk-ef591b52e48840c6a63899c8901a9428"
|
|
if not API_KEY:
|
|
API_KEY = DEFAULT_API_KEY
|
|
print(f"使用默认API Key (前8位): {DEFAULT_API_KEY[:8]}...")
|
|
|
|
def encode_image(file_path):
|
|
mime_type, _ = mimetypes.guess_type(file_path)
|
|
if not mime_type:
|
|
mime_type = "image/png"
|
|
with open(file_path, "rb") as f:
|
|
return f"data:{mime_type};base64,{base64.b64encode(f.read()).decode('utf-8')}"
|
|
|
|
def wan_image_edit(
|
|
prompt,
|
|
image_path,
|
|
output_path="wan_output.png",
|
|
size="2K",
|
|
negative_prompt="",
|
|
n=1,
|
|
prompt_extend=True
|
|
):
|
|
"""
|
|
万相2.7图生图 - 基于输入图片和提示词生成新图
|
|
|
|
参数:
|
|
prompt: 提示词,描述想要的效果
|
|
image_path: 输入图片路径
|
|
output_path: 输出图片路径
|
|
size: 输出尺寸 ("2K" 或 "1K")
|
|
negative_prompt: 反向提示词
|
|
n: 生成数量 (1-4)
|
|
prompt_extend: 是否启用提示词扩展
|
|
|
|
示例:
|
|
python wan_image_edit.py "keep the product, white background" "product.png" "output.png"
|
|
"""
|
|
print(f"提示词: {prompt}")
|
|
print(f"输入图片: {image_path}")
|
|
print(f"输出路径: {output_path}")
|
|
print(f"尺寸: {size}")
|
|
|
|
url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation"
|
|
headers = {
|
|
"Content-Type": "application/json",
|
|
"Authorization": f"Bearer {API_KEY}"
|
|
}
|
|
|
|
content = [{"text": prompt}]
|
|
if image_path:
|
|
content.append({"image": encode_image(image_path)})
|
|
|
|
payload = {
|
|
"model": "wan2.7-image-pro",
|
|
"input": {
|
|
"messages": [{
|
|
"role": "user",
|
|
"content": content
|
|
}]
|
|
},
|
|
"parameters": {
|
|
"size": size,
|
|
"n": n,
|
|
"prompt_extend": prompt_extend,
|
|
"watermark": False
|
|
}
|
|
}
|
|
|
|
if negative_prompt:
|
|
payload["parameters"]["negative_prompt"] = negative_prompt
|
|
|
|
try:
|
|
resp = requests.post(url, headers=headers, json=payload, timeout=120)
|
|
result = resp.json()
|
|
|
|
if resp.status_code == 200 and "output" in result:
|
|
choices = result["output"].get("choices", [])
|
|
if choices:
|
|
for idx, choice in enumerate(choices):
|
|
content_list = choice.get("message", {}).get("content", [])
|
|
for item in content_list:
|
|
if item.get("type") == "image":
|
|
image_url = item["image"]
|
|
out_path = output_path if n == 1 else output_path.replace(".png", f"_{idx}.png").replace(".jpg", f"_{idx}.jpg")
|
|
urlretrieve(image_url, out_path)
|
|
print(f"成功: {out_path}")
|
|
return True
|
|
else:
|
|
msg = result.get("message", str(result))
|
|
print(f"失败: {msg}")
|
|
return False
|
|
|
|
except requests.exceptions.Timeout:
|
|
print("请求超时,请重试")
|
|
return False
|
|
except Exception as e:
|
|
print(f"错误: {e}")
|
|
return False
|
|
|
|
if __name__ == "__main__":
|
|
if len(sys.argv) < 3:
|
|
print("用法: python wan_image_edit.py <提示词> <输入图片> [输出路径] [尺寸]")
|
|
print("")
|
|
print("示例:")
|
|
print(' python wan_image_edit.py "keep the product, white background" "product.png" "output.png"')
|
|
print(' python wan_image_edit.py "cyberpunk style" "product.png" "output.png" "2K"')
|
|
print("")
|
|
print("尺寸选项: 1K (1024x1024), 2K (2048x2048)")
|
|
sys.exit(1)
|
|
|
|
prompt = sys.argv[1]
|
|
image_path = sys.argv[2]
|
|
output_path = sys.argv[3] if len(sys.argv) > 3 else "wan_output.png"
|
|
size = sys.argv[4] if len(sys.argv) > 4 else "2K"
|
|
|
|
wan_image_edit(prompt, image_path, output_path, size) |