election-game/art/gen-card-grok.sh

50 lines
2.6 KiB
Bash
Executable File
Raw Permalink 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.

#!/bin/zsh
# 用 xAI(grok-imagine-image-2.0)產生一張卡牌插圖:gen-card-grok.sh <id> <題材>
# 金鑰從環境變數 XAI_API_KEY 讀;沒有的話讀 ~/.config/tongsuan/xai.env(XAI_API_KEY=...)。不會印出金鑰。
# 原圖存 art/generated/<id>.png,網頁用的縮圖存 web/public/cards/<id>.webp(和 gen-card.sh 一樣)
set -u
id="$1"; subject="$2"
here="${0:A:h}"
out="$here/generated/$id.png"
web="$here/../web/public/cards/$id.webp"
if [[ -z "${XAI_API_KEY:-}" && -r "$HOME/.config/tongsuan/xai.env" ]]; then
source "$HOME/.config/tongsuan/xai.env"
fi
if [[ -z "${XAI_API_KEY:-}" ]]; then
echo "FAIL $id(沒有 XAI_API_KEY)"
exit 1
fi
style="Style: tabletop board-game card illustration, miniature diorama look with tilt-shift depth of field, soft isometric three-quarter top-down view, warm gouache texture, clean readable shapes, cohesive warm palette with a few saturated accents. Setting: present-day Taiwan. Absolutely no text, no letters, no numbers, no logos, no party symbols or party colors on flags (flags and banners are plain), no real or recognizable people; all figures are small, anonymous and stylized. Square image."
if [[ ! -s "$out" ]]; then
body=$(python3 -c 'import json,sys; print(json.dumps({"model": "grok-imagine-image-2.0", "prompt": sys.argv[1], "n": 1, "response_format": "b64_json"}))' "Subject: $subject. $style")
resp=$(curl -sS --max-time 180 https://api.x.ai/v1/images/generations \
-H "Content-Type: application/json" -H "Authorization: Bearer $XAI_API_KEY" -d "$body")
# 回傳可能是 base64 或網址;兩種都接受(回應先存檔,避免和程式碼搶標準輸入)
print -r -- "$resp" > "$here/generated/$id.json"
python3 - "$out" "$here/generated/$id.json" 2>"$here/generated/$id.log" <<'PY'
import base64, json, sys, urllib.request
out = sys.argv[1]
raw = open(sys.argv[2], encoding="utf-8").read()
try:
d = json.loads(raw)
except json.JSONDecodeError:
sys.exit(f"不是 JSON:{raw[:200]}")
if "error" in d or not d.get("data"):
sys.exit(f"API 錯誤:{json.dumps(d, ensure_ascii=False)[:300]}")
item = d["data"][0]
if item.get("b64_json"):
data = base64.b64decode(item["b64_json"])
else:
data = urllib.request.urlopen(item["url"], timeout=120).read()
open(out, "wb").write(data)
PY
rm -f "$here/generated/$id.json"
fi
if [[ -s "$out" ]]; then
# 原圖可能是 JPEG:先轉 PNG 存檔,網頁用 webp
file "$out" | grep -q PNG || { ffmpeg -loglevel error -y -i "$out" "$out.tmp.png" && mv "$out.tmp.png" "$out"; }
cwebp -quiet -q 80 -resize 640 640 "$out" -o "$web" && echo "ok $id"
else
echo "FAIL $id($(tail -1 "$here/generated/$id.log" 2>/dev/null))"
fi