#!/usr/bin/env python3
"""Generate images via APIYI Hunyuan Hy-Image 3.5 Preview (2K/4K). Standard library only."""
import argparse
import base64
import json
import os
import sys
import urllib.error
import urllib.request
from concurrent.futures import ThreadPoolExecutor
MODELS = {
"2k": "hy-image-v3.5-preview-2k",
"4k": "hy-image-v3.5-preview-4k",
}
MAX_COUNT = 5
ENDPOINT = "https://api.apiyi.com/v1/images/generations"
def load_api_key():
"""Prefer the environment; otherwise look for .env next to the script or its parent."""
key = os.environ.get("APIYI_API_KEY")
if key:
return key
here = os.path.dirname(os.path.abspath(__file__))
for d in (here, os.path.dirname(here)):
env_path = os.path.join(d, ".env")
if os.path.exists(env_path):
with open(env_path, encoding="utf-8") as f:
for line in f:
line = line.strip()
if line.startswith("APIYI_API_KEY") and "=" in line:
return line.split("=", 1)[1].strip().strip('"').strip("'")
return None
def project_root():
"""Walk up from the script location to the first .git or .claude directory."""
d = os.path.dirname(os.path.abspath(__file__))
while True:
if os.path.isdir(os.path.join(d, ".git")) or os.path.isdir(os.path.join(d, ".claude")):
return d
parent = os.path.dirname(d)
if parent == d:
return os.getcwd()
d = parent
def mime_of(path):
ext = os.path.splitext(path)[1].lower()
if ext in (".jpg", ".jpeg"):
return "image/jpeg"
if ext == ".webp":
return "image/webp"
return "image/png"
def to_data_uri(path):
with open(path, "rb") as f:
return f"data:{mime_of(path)};base64," + base64.b64encode(f.read()).decode()
def resolve_paths(out, count):
if os.path.dirname(out):
base_path = os.path.abspath(out)
else:
out_dir = os.path.join(project_root(), "hunyuan-output")
os.makedirs(out_dir, exist_ok=True)
base_path = os.path.join(out_dir, out)
if count == 1:
return [base_path]
base, ext = os.path.splitext(base_path)
return [f"{base}-{i}{ext}" for i in range(1, count + 1)]
def generate(api_key, model_id, prompt, image_paths):
payload = {
"model": model_id,
"prompt": prompt,
"response_format": "b64_json",
}
if image_paths:
payload["images"] = [to_data_uri(p) for p in image_paths]
req = urllib.request.Request(
ENDPOINT,
data=json.dumps(payload).encode(),
method="POST",
headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"},
)
try:
with urllib.request.urlopen(req, timeout=360) as r:
resp = json.loads(r.read())
except urllib.error.HTTPError as e:
body = e.read().decode(errors="replace")
raise RuntimeError(f"HTTP {e.code}: {body[:800]}")
except urllib.error.URLError as e:
raise RuntimeError(f"network error: {e}")
data = resp.get("data") or []
if not data:
raise RuntimeError(f"no image returned: {resp}")
item = data[0]
if item.get("b64_json"):
return base64.b64decode(item["b64_json"])
if item.get("url"):
with urllib.request.urlopen(item["url"], timeout=360) as r:
return r.read()
raise RuntimeError(f"unexpected response: {resp}")
def _safe(fn, arg):
try:
return True, fn(arg)
except Exception as e: # noqa: BLE001 - one failed image must not stop the others
return False, str(e)
def main():
api_key = load_api_key()
if not api_key:
sys.exit("未找到 API Key:请在技能目录的 .env 写一行 APIYI_API_KEY=sk-xxx")
parser = argparse.ArgumentParser(description="混元 Hy-Image 3.5 出图")
parser.add_argument("prompt", help="提示词 / 编辑指令")
parser.add_argument("-i", "--image", action="append", default=[], help="参考图路径(可重复)")
parser.add_argument("-m", "--model", choices=sorted(MODELS), default="2k", help="2k 或 4k,默认 2k")
parser.add_argument("-o", "--out", default="output.png", help="输出文件名")
parser.add_argument("-n", "--count", type=int, default=1, help=f"一次出几张,默认 1,最多 {MAX_COUNT}(并发生成)")
args = parser.parse_args()
count = max(1, min(args.count, MAX_COUNT))
if args.count > MAX_COUNT:
print(f"提示:一次最多 {MAX_COUNT} 张,已限制为 {MAX_COUNT}。", file=sys.stderr)
paths = resolve_paths(args.out, count)
model_id = MODELS[args.model]
def task(path):
data = generate(api_key, model_id, args.prompt, args.image)
with open(path, "wb") as f:
f.write(data)
return os.path.abspath(path)
failures = 0
with ThreadPoolExecutor(max_workers=count) as pool:
for path, result in zip(paths, pool.map(lambda p: _safe(task, p), paths)):
ok, value = result
if ok:
print(f"图片已保存至 {value}")
else:
failures += 1
print(f"第 {os.path.basename(path)} 张生成失败:{value}", file=sys.stderr)
if failures == count:
sys.exit("全部生成失败。")
if __name__ == "__main__":
main()