Skip to content
Back to search

claude-image

SkillWorks with Claude CodeGitHub

教 Claude Code/Codex 真正用好 gpt-image-2 的 skill 包 · Drop-in skill teaching agents to actually use GPT Image 2 — intent-first prompting, surgical edits, parallel batching, visual self-verification

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/jiangmuran--claude-image/badge.svg)](/listings/jiangmuran--claude-image)

HTML

<a href="/listings/jiangmuran--claude-image"><img src="/api/listings/jiangmuran--claude-image/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

Claude Code(一行)

git clone https://github.com/jiangmuran/claude-image.git ~/.claude/skills/gpt-image-2 \
  && bash ~/.claude/skills/gpt-image-2/install.sh

安装脚本会问你要 API key,写到 `~/.zshrc`,可选跑一个冒烟测试。

装完之后下一次有图像请求 Claude 自动发现 skill——不用重启,不用注册。

Codex(或任何扫描 `~/.agents/skills/` 的 agent)

git clone https://github.com/jiangmuran/claude-image.git ~/.agents/skills/gpt-image-2 \
  && bash ~/.agents/skills/gpt-image-2/install.sh

同一个 skill,同一个脚本,同一组环境变量。

手动 / 其他 agent / 直接命令行

git clone https://github.com/jiangmuran/claude-image.git
cd gpt-image-2

echo 'export OPENAI_IMAGE_API_KEY="sk-..."' >> ~/.zshrc
echo 'export OPENAI_IMAGE_BASE_URL="https://jmrai.net/v1"' >> ~/.zshrc
source ~/.zshrc

python3 scripts/gpt_image.py generate \
  -p "a red panda eating bamboo, flat vector illustration, off-white background" \
  -o ./test.png
open test.png

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

SKILL.md · Manifest · 203 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. ---
  2. name: gpt-image-2
  3. description: Use when generating, editing, composing, or iterating on images — illustrations for reports/web, posters with Chinese or English typography, pitch-deck slides, UI mockups, infographics, pixel art, game sprites, character reference sheets, app icons, logo concepts, photoreal product shots, or photo edits with precise local changes. Symptoms include the user asking for "图", "图片", "插图", "海报", "封面", "图标", "ppt素材", "游戏素材", "改图", "修图", "logo", "draw me", "make an image", "生成一张", or attaching an image they want modified. Calls the gpt-image-2 model (April 2026 release; near-perfect text rendering including Chinese, custom resolutions up to 3840px, precise edits with preserve/change pattern) via OpenAI-compatible /images/generations and /images/edits endpoints.
  4. ---
  5. # gpt-image-2
  6. GPT Image 2 — released April 2026 — is the first generation that handles long instructional prompts cleanly, renders text correctly (Chinese / Japanese / Korean too), supports custom resolutions (max side < 3840px, ratio ≤ 3:1), and does precise local edits via the `change ONLY X / keep Y exactly` pattern.
  7. This skill teaches you the prompt grammar, the workflow, and gives you a zero-dep CLI that handles auth, parallel batching, retries, and file IO.
  8. ## The contract
  9. Always go through `scripts/gpt_image.py`. Don't curl the API directly — the script handles auth, retries, b64-vs-URL responses, multipart for edits, parallel single-image calls when batching, and writes files to disk for you. The user can't see images that only exist in the API response.
  10. ## Setup (once per machine)
  11. Two environment variables:
  12. ```bash
  13. export OPENAI_IMAGE_API_KEY="sk-..." # required
  14. export OPENAI_IMAGE_BASE_URL="https://jmrai.net/v1" # default; override only if user has a different host
  15. ```
  16. If `OPENAI_IMAGE_API_KEY` is missing, the script exits with a clear message — ask the user for it, then suggest they add the export to `~/.zshrc`.
  17. ## Calling the script
  18. Use the absolute path so it works from any working directory:
  19. ```bash
  20. SKILL_DIR="$HOME/.claude/skills/gpt-image-2" # adjust if installed elsewhere
  21. GPT_IMG="python3 $SKILL_DIR/scripts/gpt_image.py"
  22. ```
  23. ### Env vars in Claude Code's Bash subshell
  24. Claude Code's Bash tool runs **non-interactive shells that do NOT auto-source `~/.zshrc`**. If the user has the credentials in their shell rc and you get `ERROR: set OPENAI_IMAGE_API_KEY`, prefix every call with a source:
  25. ```bash
  26. source ~/.zshrc 2>/dev/null && python3 $SKILL_DIR/scripts/gpt_image.py generate -p "..." -o ./out.png
  27. ```
  28. Or, if the user provided the key in-conversation, pass it inline (don't write it to disk yourself):
  29. ```bash
  30. OPENAI_IMAGE_API_KEY="sk-..." OPENAI_IMAGE_BASE_URL="https://jmrai.net/v1" \
  31. python3 $SKILL_DIR/scripts/gpt_image.py generate -p "..." -o ./out.png
  32. ```
  33. Test once at the start of a session: `source ~/.zshrc && echo "${OPENAI_IMAGE_API_KEY:0:10}"`. If that prints a key prefix, you can safely use the source-prefix pattern for the rest of the session.
  34. ### Generate
  35. ```bash
  36. $GPT_IMG generate \
  37. -p "<prompt>" \
  38. --size 1536x864 \
  39. -o ./hero.png
  40. ```
  41. Defaults: `--quality high` (cost is identical across tiers on this host), `--size 1024x1024`.
  42. ### Edit (precise local change)
  43. ```bash
  44. $GPT_IMG edit \
  45. -i ./input.png \
  46. -p "Edit the input image: change ONLY <X>. Preserve exactly: <Y>. Do not: <Z>." \
  47. -o ./edited.png
  48. ```
  49. ### Inpaint (mask-based)
  50. White pixels in the mask = region to regenerate; transparent = keep.
  51. ```bash
  52. $GPT_IMG edit -i ./photo.png --mask ./mask.png \
  53. -p "Fill the masked area with continuation of the cobblestone street, matching perspective and lighting." \
  54. -o ./inpainted.png
  55. ```
  56. ### Multiple variants in parallel
  57. `-n N` fires N **parallel** single-image requests. Faster wall-clock than serial, and works regardless of host n>1 support.
  58. ```bash
  59. $GPT_IMG generate -p "..." -n 4 --concurrency 4 -o ./out
  60. # writes out-1.png … out-4.png
  61. ```
  62. ### What the host does NOT support
  63. - **Multi-image input** (composing two source images in one /edits call). For composition, do it in two steps: generate or edit a base, then edit again with the next layer described. The script errors if you pass `-i` more than once.
  64. - **Transparent backgrounds** (`--background transparent` returns HTTP 400). For sprites / icons / cutouts, use a **chroma-key color in the prompt** (`solid magenta #FF00FF background`) and remove it client-side after with `rembg` or ImageMagick (see `references/post-process.md`).
  65. - Aspect ratios above 3:1 or sides ≥ 3840px. The script validates upfront.
  66. Run `python3 $SKILL_DIR/scripts/gpt_image.py --help` (or `<subcommand> --help`) for every flag.
  67. ## Sizes — pick deliberately
  68. | Use case | Size | Aspect |
  69. |----------|------|--------|
  70. | PPT slide / web hero / YouTube thumbnail | `1536x864` (true 16:9) or `1792x1024` | 16:9 / 7:4 |
  71. | Square: app icon, social, logo, character portrait | `1024x1024` | 1:1 |
  72. | High-res square / print poster | `2048x2048` | 1:1 |
  73. | Mobile poster, story, vertical infographic, book cover | `1024x1536` | 2:3 |
  74. | Tall mobile-first hero | `1024x1792` | 9:16ish |
  75. | Wide cinematic banner | `1792x1024` | 16:9ish |
  76. Wrong aspect ratio = wasted generation. Decide BEFORE writing the prompt.
  77. ## The workflow for any image task
  78. 1. **Clarify intent** only if truly ambiguous. Otherwise infer — auto mode means ship.
  79. 2. **Pick the right reference** for the use case (table below).
  80. 3. **Write the prompt** following the structure: *Intent → Scene → Subject → Details → Text → Style → Constraints*. See `references/prompting.md`.
  81. 4. **Pick size** from the table above.
  82. 5. **Call the script.** Save to a sensible path next to the user's project, not `/tmp`.
  83. 6. **VISUALLY VERIFY** — Read the saved PNG yourself. Check: does the text render correctly? Is the composition what you asked for? Did the style land? See § "Visual self-verification" below.
  84. 7. **Iterate** if the verification fails. Change ONE dimension and regenerate.
  85. 8. **Show the user** — Read the final PNG so it appears inline. Tell them the path.
  86. ## Visual self-verification (use your vision)
  87. After every generation, before reporting success to the user, **Read the PNG yourself** and verify against the prompt:
  88. - **Text:** Does each quoted string render exactly? No invented characters? Right font weight?
  89. - **Layout:** Is the negative space where you asked for it? Is the subject on the right side of the frame if you said so?
  90. - **Composition:** Right camera angle? Right framing? Centered if you said centered?
  91. - **Style:** Did the named reference land, or did the model default to generic AI-soup?
  92. - **Negatives obeyed:** No extra hands, no watermarks, no rogue text, no clutter you forbade?
  93. If anything fails, iterate. **Change ONE dimension** (per `references/prompting.md` §6) and regenerate. Don't ship the user a bad result and ask them to verify — your vision is faster than their patience.
  94. If you fired multiple variants (`-n 4`), pick the best one yourself before showing the user. Don't dump four files on them and ask them to choose unless they explicitly want options.
  95. ## When to load deeper references
  96. Read these on demand — don't preload them.
  97. | User wants | Read this |
  98. |------------|-----------|
  99. | Prompt-writing technique, style vocabulary, intent-first framework, anti-patterns to avoid | `references/prompting.md` |
  100. | Concrete templates: pitch decks, UI mockups, posters, character sheets, infographics, logos, photoreal, edits | `references/use-cases.md` |
  101. | Compress, resize, convert, combine, add text post-hoc | `references/post-process.md` |
  102. | Full parameter list, error codes, custom-resolution constraints | `references/api.md` |
  103. ## Core prompt principles (cheat sheet)
  104. The full guide is in `references/prompting.md`; the irreducible minimum:
  105. 1. **Open with intent**, not subject. *"Create a pitch-deck slide titled…"* beats *"A chart and some KPIs"*.
  106. 2. **Quote every character** that should appear, exactly once. For Chinese, name the script flavor (`黑体`, `楷书`, `思源黑体`).
  107. 3. **Use spec language, not praise language.** *"50mm f/2.8, soft north-window light from the left"* beats *"beautiful professional lighting"*.
  108. 4. **For edits: change ONLY X / preserve Y exactly.** Always state both.
  109. 5. **One style anchor**, not five. Name an artist, film, movement, or game.
  110. 6. **Drop the magic words.** *4K, 8K, ultra detailed, masterpiece, trending on artstation* — pre-GPT-Image-2 noise. Useless or harmful now.
  111. 7. **Default `--quality high`** (cost is the same on this host). Use lower tiers only for fast throwaway iteration.
  112. 8. **Iterate, don't stack.** One dimension change per regen.
  113. ## Self-check before calling the API
  114. - [ ] Does the prompt open with intent (slide / poster / mockup / photograph / illustration)?
  115. - [ ] Right aspect ratio for the use case?
  116. - [ ] Did I quote every text string the user wants in the image?
  117. - [ ] If this is an edit, am I describing the change AND what to preserve?
  118. - [ ] Is the output path meaningful and discoverable?
  119. - [ ] Am I about to type any of: `4K, 8K, masterpiece, trending on artstation, ultra detailed`? If yes — delete them.
  120. ## Common mistakes
  121. | Mistake | Fix |
  122. |---------|-----|
  123. | "Make me an image of a cat" | Open with intent, add style, composition, lighting. See prompting.md. |
  124. | Generating in `/tmp` | Save next to user's project so they can find it. |
  125. | Not Reading the result yourself | Visual self-verify EVERY time before showing the user. |
  126. | Showing all `-n 4` variants without picking | Pick the best one yourself unless user asked for options. |
  127. | Asking "what style?" when the user said "a poster" | Make a strong first attempt, then iterate. |
  128. | Curl-ing the API directly | Use the script — handles retries, b64, multipart, parallel. |
  129. | Forgetting Chinese text in quotes | Quote it exactly or model writes nonsense. |
  130. | Stacking magic words | "Ultra detailed 8K masterpiece" makes outputs WORSE on GPT Image 2. |
  131. | Re-describing the whole image in an edit | Describe ONLY the change + what to preserve. |
  132. | Trying to compose two input images in one /edits call | Not supported on this host — chain two edit calls. |
  133. ## Freedom to be creative
  134. These rules guide quality, not creativity. When the user says "surprise me" or leaves room:
  135. - Pick a distinctive style with conviction (don't default to "modern minimalist")
  136. - Push compositions: low angles, dutch tilts, asymmetric layouts, generous negative space
  137. - Fire 3–4 parallel variants when exploring (`-n 4 --concurrency 4`) — same wall-clock as one
  138. - For art briefs, propose a style direction in one sentence before generating, so the user can redirect cheaply
  139. ## Ship-quality bar
  140. A result is ready to show the user when:
  141. - ✅ Read-and-judged by you, not just generated
  142. - ✅ Text (if any) renders exactly the quoted string
  143. - ✅ Composition matches the prompt (subject placement, negative space, camera)
  144. - ✅ Style landed (named reference is recognizable)
  145. - ✅ No obvious AI failures (warped hands, melted text, ghost limbs)
  146. - ✅ Saved at a path the user can find
README.md · README · 402 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. # Claude image
  2. > 教 Claude Code、Codex 等 agent 真正用好 GPT Image 2 的 drop-in skill 包。
  3. > A drop-in skill that teaches Claude Code, Codex, and other agents to actually use GPT Image 2.
  4. [简体中文](#简体中文) · [English](#english)
  5. ---
  6. ## 简体中文
  7. > 把这玩意儿丢进 Claude Code 或 Codex,你的 agent 就能从「这是个 curl 命令,祝你好运」进化成一次到位地产出 pitch deck 幻灯片、中文海报、像素图块、写实产品图、外科手术级修图。
  8. GPT Image 2 是 2026 年 4 月发布的——这一代是分水岭:长指令式 prompt 不再丢细节,文字渲染终于正确(中日韩通吃),自定义分辨率最长 3840px,编辑端点用 `change ONLY X / preserve Y exactly` 模式做精准局部修改。
  9. 但是问题来了:2026 年 4 月之前训练的 agent 一无所知。它们用老办法写 prompt——*"4K, ultra detailed, masterpiece, trending on artstation"*——这些词在 GPT Image 2 上要么被忽略,要么直接帮倒忙。它们粘 curl 命令而不存文件。它们生成完之后问用户"这看着对吗?",根本不自己看一眼。
  10. 这个 skill 把这些全修了。
  11. ### 仓库结构
  12. ```
  13. gpt-image-2/
  14. ├── SKILL.md # 入口。Claude 自动加载。
  15. ├── README.md # 你正在看的这个。
  16. ├── LICENSE # MIT。
  17. ├── install.sh # Claude Code 一键安装。
  18. ├── .env.example # 两个环境变量,就这一点配置。
  19. ├── references/
  20. │ ├── prompting.md # 7 条习惯 + 意图优先框架 + 风格词表
  21. │ ├── use-cases.md # 10+ 复制即用模板:PPT 幻灯片、UI mockup、
  22. │ │ # 中文海报、像素图、角色三视图、信息图、
  23. │ │ # logo、写实摄影、修图……
  24. │ ├── api.md # 完整参数 + 自定义分辨率约束
  25. │ └── post-process.md # 压缩、缩放、转码 (pngquant/cwebp/avifenc)
  26. └── scripts/
  27. └── gpt_image.py # 零依赖 Python CLI (只用 urllib,Python 3.7+)
  28. ```
  29. ### 为什么你的 agent 真的会去调用它
  30. 三个让这玩意儿真正起作用而不是装饰品的设计:
  31. 1. **可发现的 description**。frontmatter 里把所有触发词都列了——"海报"、"图标"、"ppt素材"、"改图"、"draw me"、"make an image"——所以 agent 的 skill 选择器在收到图像请求时真的会触发,而不是退回去自己拼 curl。
  32. 2. **一个 CLI,四种能力**。生成 / 编辑 / 局部重绘 / 并行批处理都是一个脚本的子命令。鉴权、重试、b64 vs URL、multipart、文件 IO、并行批处理——都处理好了。Agent 自己手撸基本上某一项会出错。
  33. 3. **视觉自验证写进了工作流**。Skill 明确告诉 Claude 在把结果给用户之前自己 `Read` 一下生成的 PNG,对照 prompt 检查。再也不会出现"图给你了,你看对不对"。
  34. ### 安装
  35. #### Claude Code(一行)
  36. ```bash
  37. git clone https://github.com/jiangmuran/claude-image.git ~/.claude/skills/gpt-image-2 \
  38. && bash ~/.claude/skills/gpt-image-2/install.sh
  39. ```
  40. 安装脚本会问你要 API key,写到 `~/.zshrc`,可选跑一个冒烟测试。
  41. 装完之后下一次有图像请求 Claude 自动发现 skill——不用重启,不用注册。
  42. #### Codex(或任何扫描 `~/.agents/skills/` 的 agent)
  43. ```bash
  44. git clone https://github.com/jiangmuran/claude-image.git ~/.agents/skills/gpt-image-2 \
  45. && bash ~/.agents/skills/gpt-image-2/install.sh
  46. ```
  47. 同一个 skill,同一个脚本,同一组环境变量。
  48. #### 手动 / 其他 agent / 直接命令行
  49. ```bash
  50. git clone https://github.com/jiangmuran/claude-image.git
  51. cd gpt-image-2
  52. echo 'export OPENAI_IMAGE_API_KEY="sk-..."' >> ~/.zshrc
  53. echo 'export OPENAI_IMAGE_BASE_URL="https://jmrai.net/v1"' >> ~/.zshrc
  54. source ~/.zshrc
  55. python3 scripts/gpt_image.py generate \
  56. -p "a red panda eating bamboo, flat vector illustration, off-white background" \
  57. -o ./test.png
  58. open test.png
  59. ```
  60. ### 凭据
  61. 两个环境变量。配置就这么多。
  62. | 变量 | 必填 | 默认值 |
  63. |------|-----|--------|
  64. | `OPENAI_IMAGE_API_KEY` | 是 | — |
  65. | `OPENAI_IMAGE_BASE_URL` | 否 | `https://agiplan.dev/v1` |
  66. 如果没设置 image 专用的两个,会回退到 `OPENAI_API_KEY` / `OPENAI_BASE_URL`——如果你已经在用同一个 key 跑 chat completions 这就很方便。
  67. 可以前往 https://agiplan.dev 购买划算的token套餐
  68. > **不要把 key commit 进去。** `.gitignore` 已经排除了 `.env`。`.env.example` 只是模板。
  69. ### 它能做什么
  70. 非完整列表(完整模板看 `references/use-cases.md`):
  71. - **Pitch-deck 幻灯片** — 长得像真正的 Series A 董事会幻灯片,而不是"画一张幻灯片的插图"。具体数据、具体字体、具体配色。多页一致性靠 edit endpoint。
  72. - **中文海报和招贴** — 春节海报、产品发布、活动封面。引号里的精确文字 + 字体类型(`楷书 / 黑体 / 思源黑体`)+ "no extra Chinese characters" 收尾。渲染干净。
  73. - **写实 UI mockup** — 桌面 dashboard、移动端,放在真实设备外框里,文案写得像真的。Inter 字体、十六进制配色、合理的任务名。
  74. - **像素图和游戏素材** — 角色 sprite、俯视图块集(用品红色 chroma key)、物品图标、角色三视图、场景概念图。
  75. - **信息图** — GPT Image 2 真正能渲染的密集文字 + 复杂结构。`use-cases.md` 里有"How an Espresso Machine Works"模板。
  76. - **Logo 概念** — 2x2 变体网格,探索不同形状语言。Vector clean、无渐变、无 3D。
  77. - **写实产品图** — 用真正的摄影术语(50mm f/2.8、北窗光、35mm 胶片颗粒)代替"高品质"。
  78. - **外科手术级修图** — `change ONLY X / preserve Y exactly` 模式。物体替换、背景换、风格迁移、mask 局部重绘。
  79. - **报告插图和点缀图** — FT 风格编辑图、水粉章节插图、app 空状态角色。
  80. ### 它怎么教 agent 写 prompt
  81. 完整指南在 `references/prompting.md`。一句话:**抛掉魔法咒语**。
  82. GPT Image 2 之前的 prompt 工程基本上是在和训练数据里的口水话做模式匹配:
  83. ```
  84. beautiful stunning ultra-detailed 4K 8K masterpiece trending on artstation
  85. cinematic lighting professional photography premium quality
  86. ```
  87. GPT Image 2 不奖励这一套。它奖励指令式、具体、意图优先的 prompt:
  88. ```
  89. Create a pitch-deck slide titled "Q3 Revenue Performance" that looks
  90. like a real Series A board-meeting slide. Layout (16:9): title top-left,
  91. 36pt Inter dark gray. Two-column body: left 60% chart, right 40% three
  92. KPI cards. Chart: vertical bars, Q1–Q3 2026, y-axis $0–$8M, three bars
  93. at $3.2M, $4.8M, $6.5M, muted blue palette. KPI cards: "+34% YoY",
  94. "189 new accounts", "$42K ACV". White background, Inter typography,
  95. tight 8px grid, no clip art, no gradients, no stock photography.
  96. ```
  97. 注意里面**没有**:没有夸赞词、没有"ultra detailed"、没有"8K"。每一个词都在做具体的指令性工作。
  98. Skill 教 Claude(或任何 agent)规范结构:
  99. ```
  100. 意图 / 用途 → 场景 / 背景 → 主体 →
  101. 关键细节 → 文字内容 → 风格语言 → 约束条件
  102. ```
  103. 加上 7 条习惯:**意图开头、所有文字加引号、用规格语言不用夸赞语言、修图永远"change ONLY X / preserve Y"、一个风格锚点不要五个、抛掉魔法咒语、迭代不要堆砌**。
  104. ### 视觉自验证为什么重要
  105. 一个细微但巨大的改进:skill 让 Claude **自己 `Read` 生成的 PNG 并对照 prompt 判断**,然后再给用户看。文字渲染对了吗?构图在你说的位置吗?negative 听话了吗?
  106. 如果哪个不对,agent 会**一次只改一个维度**(参考 prompting 指南)然后重新生成。用户看到的是*合格*的结果,而不是"我生成了个东西,你看对不对"。
  107. 这个能 work 是因为 Claude *能*看图。它只是默认不会去看自己生成的东西。Skill 改的就是这个默认。
  108. ### 架构(几个设计选择)
  109. 如果你对实现细节感兴趣:
  110. - **零 Python 依赖**。CLI 只用 `urllib`、`concurrent.futures`、`argparse`。没有 `requests`、没有 `openai`,没有装包步骤。任何 Python 3.7+ 都能跑。
  111. - **客户端并行**。`-n 4` 是发 4 个并行的 n=1 请求,而不是请求 host 一次返回 4 张图。墙钟时间快、不用管 host 是否支持 n>1。
  112. - **合理的默认值**。`--quality high`(这个 host 各档质量同价)。`--size 1024x1024`。`--concurrency 4`。
  113. - **预先验证**。分辨率约束(最长边 <3840px、比例 ≤3:1)在请求 API 之前检查——快速失败、信息明确。
  114. - **多图输入优雅拒绝**。这个 host 的 gpt-image-2 不接受一次 /edits 调用传多张输入图。脚本明确报错并给出工作流建议,而不是默默失败。
  115. 这些都可以改——fork 之后改 `DEFAULT_QUALITY` 或 `DEFAULT_BASE`,或者加个 `--watermark` flag。
  116. ### 不靠 agent 直接用
  117. CLI 本身可以单独跑。批处理、脚本、手动探索都好用。
  118. ```bash
  119. GI="python3 ~/.claude/skills/gpt-image-2/scripts/gpt_image.py"
  120. # 生成
  121. $GI generate -p "a misty mountain temple at dawn, Studio Ghibli watercolor" -o ./temple.png
  122. # 4 张并行变体
  123. $GI generate -p "..." -n 4 --concurrency 4 -o ./out
  124. # 修图 / 局部重绘
  125. $GI edit -i ./photo.png -p "Edit the input: replace ONLY the sky with northern lights. Preserve everything else exactly." -o ./aurora.png
  126. $GI edit -i ./photo.png --mask ./mask.png -p "Fill the masked area with continuation of the road" -o ./fixed.png
  127. # 所有 flag
  128. $GI generate --help
  129. $GI edit --help
  130. ```
  131. ### 更新
  132. ```bash
  133. cd ~/.claude/skills/gpt-image-2 && git pull
  134. ```
  135. Skill 就是文本 + 一个脚本。无构建、无重启、无注册。
  136. ### 给你的团队定制
  137. Fork 一份。设计上可以替换的部分:
  138. - **`references/use-cases.md`** — 加你们自家风格、品牌色卡、常用素材模板(自家的 pitch-deck 模板、自家的品牌 hex、自家的信息图格式)
  139. - **`scripts/gpt_image.py`** — 加 `--watermark` flag、自定义输出命名、S3 上传、Slack 推送、随便加
  140. - **`DEFAULT_BASE`** — 指向你们的私有网关而不是默认值
  141. - **agent 拿到的 system prompt** — 如果你们的 agent 不会自动发现就把 `SKILL.md` 接进 bootstrap
  142. 通用的改动欢迎 PR。团队特定的留在你的 fork 里。
  143. ### License
  144. MIT。看 `LICENSE`。随便用。
  145. ### 致谢
  146. 为 [Claude Code](https://claude.com/claude-code) 而做,但这个模式(markdown skill + 零依赖 CLI + 视觉自验证)适用于任何能读文件 + 调脚本的 agent。
  147. 灵感:OpenAI 官方 GPT Image 2 Cookbook,Anthropic superpowers/writing-skills 关于 agent 可发现 skill 的模式。
  148. ---
  149. ## English
  150. > Drop this into Claude Code or Codex. Your agent will go from "here's a curl command, good luck" to producing pitch-deck slides, Chinese posters, pixel-art tilesets, photoreal product shots, and surgical photo edits — first try, every try.
  151. GPT Image 2 dropped in April 2026. It's a generational leap: long instructional prompts no longer lose detail, text rendering is finally correct (Chinese / Japanese / Korean too), custom resolutions go up to 3840px, and the edit endpoint does precise local edits via a `change ONLY X / preserve Y exactly` pattern.
  152. But here's the catch: agents trained before April 2026 don't know any of this. They write prompts the old way — *"4K, ultra detailed, masterpiece, trending on artstation"* — which on GPT Image 2 is at best ignored and often actively harmful. They paste curl commands instead of saving files. They generate, then ask the user "does this look right?" instead of looking themselves.
  153. This skill fixes all of that.
  154. ### What you get
  155. ```
  156. gpt-image-2/
  157. ├── SKILL.md # The entry point. Loaded automatically by the agent.
  158. ├── README.md # You are here.
  159. ├── LICENSE # MIT.
  160. ├── install.sh # One-command install for Claude Code.
  161. ├── .env.example # Two env vars; that's the entire config.
  162. ├── references/
  163. │ ├── prompting.md # 7 habits + intent-first framework + style vocab
  164. │ ├── use-cases.md # 10+ copy-paste templates: PPT slides, UI mockups,
  165. │ │ # Chinese posters, pixel art, character sheets,
  166. │ │ # infographics, logos, photoreal, photo edits…
  167. │ ├── api.md # Full parameter reference + custom-resolution rules
  168. │ └── post-process.md # Compress, resize, convert (pngquant/cwebp/avifenc)
  169. └── scripts/
  170. └── gpt_image.py # Zero-deps Python CLI (urllib only, Python 3.7+)
  171. ```
  172. ### Why your agent will actually use it
  173. Three design decisions that make this load-bearing instead of decorative:
  174. 1. **Discoverable description.** The frontmatter `description` lists every symptom — "海报", "图标", "ppt素材", "改图", "draw me", "make an image" — so the agent's skill picker actually fires on image requests instead of falling back to ad-hoc curl.
  175. 2. **One CLI, four affordances.** Generate / edit / inpaint / batch-parallel are all the same script with subcommands. Auth, retries, b64-vs-URL, multipart, file IO, parallel batching — handled. Agents that try to roll their own usually get one of those wrong.
  176. 3. **Visual self-verification baked into the workflow.** The skill explicitly tells Claude to `Read` the generated PNG and judge it against the prompt before showing the user. No more "here's an image, hope it's right!"
  177. ### Install
  178. #### Claude Code (one-liner)
  179. ```bash
  180. git clone https://github.com/jiangmuran/claude-image.git ~/.claude/skills/gpt-image-2 \
  181. && bash ~/.claude/skills/gpt-image-2/install.sh
  182. ```
  183. The installer asks for your API key, writes it to `~/.zshrc`, and offers a smoke test.
  184. After install, Claude auto-discovers the skill on the next image request — no restart, no registration.
  185. #### Codex (or any agent that scans `~/.agents/skills/`)
  186. ```bash
  187. git clone https://github.com/jiangmuran/claude-image.git ~/.agents/skills/gpt-image-2 \
  188. && bash ~/.agents/skills/gpt-image-2/install.sh
  189. ```
  190. Same skill, same script, same env vars.
  191. #### Manual / other agents / direct CLI use
  192. ```bash
  193. git clone https://github.com/jiangmuran/claude-image.git
  194. cd gpt-image-2
  195. echo 'export OPENAI_IMAGE_API_KEY="sk-..."' >> ~/.zshrc
  196. echo 'export OPENAI_IMAGE_BASE_URL="https://jmrai.net/v1"' >> ~/.zshrc
  197. source ~/.zshrc
  198. python3 scripts/gpt_image.py generate \
  199. -p "a red panda eating bamboo, flat vector illustration, off-white background" \
  200. -o ./test.png
  201. open test.png
  202. ```
  203. ### Credentials
  204. Two environment variables. That's the entire config surface.
  205. | Var | Required | Default |
  206. |-----|----------|---------|
  207. | `OPENAI_IMAGE_API_KEY` | yes | — |
  208. | `OPENAI_IMAGE_BASE_URL` | no | `https://jmrai.net/v1` |
  209. Falls back to `OPENAI_API_KEY` / `OPENAI_BASE_URL` if the image-specific ones aren't set.
  210. **Buy credits:** https://order.jmrai.net
  211. > **Don't commit your key.** `.gitignore` excludes `.env`. The `.env.example` is a template only.
  212. ### What it can do
  213. A non-exhaustive sample (full catalog in `references/use-cases.md`):
  214. - **Pitch-deck slides** — looks like a real Series A board slide. Specific data, specific fonts, specific palettes. Multi-slide consistency via the edit endpoint.
  215. - **Chinese posters & signage** — quoted text + script flavor (`楷书 / 黑体 / 思源黑体`) + "no extra Chinese characters" tail. Renders crisply.
  216. - **Realistic UI mockups** — desktop dashboards, mobile screens, in real device frames with believable copy.
  217. - **Pixel art & game assets** — character sprites, top-down tilesets (chroma-key magenta backgrounds), item icons, character reference sheets with multiple views.
  218. - **Infographics** — vertical info-dense diagrams that GPT Image 2 actually renders correctly.
  219. - **Logo concepts** — 2x2 grids of variants exploring different shape languages. Vector-clean, no gradients, no 3D.
  220. - **Photoreal product shots** — proper photo language (50mm f/2.8, north-window light, 35mm film grain) instead of "premium quality".
  221. - **Surgical photo edits** — the `change ONLY X / preserve Y exactly` pattern.
  222. - **Report figures & spot illustrations** — FT-style editorial diagrams, gouache section illustrations, app empty-state characters.
  223. ### How it teaches your agent to write prompts
  224. The full guide is in `references/prompting.md`. Headline: **drop the magic words.**
  225. Pre-GPT-Image-2 prompting:
  226. ```
  227. beautiful stunning ultra-detailed 4K 8K masterpiece trending on artstation
  228. cinematic lighting professional photography premium quality
  229. ```
  230. GPT Image 2 doesn't reward this. It rewards instructional, specific, intent-first prompts. The skill teaches the canonical structure:
  231. ```
  232. Intent → Scene → Subject → Details → Text → Style → Constraints
  233. ```
  234. Plus the seven habits: **state intent first, quote every character, use spec-language not praise-language, "change ONLY X / preserve Y" for edits, one style anchor not five, drop the magic words, iterate-don't-stack**.
  235. ### Why visual self-verification matters
  236. The skill tells Claude to **Read the generated PNG and judge it against the prompt** before showing the user. If anything fails, the agent iterates **one dimension at a time** and regenerates. The user sees the *good* result, not "here's what I got, does it look right?"
  237. This works because Claude *can* see images. It just doesn't, by default, look at things it generates. The skill changes that default.
  238. ### Architecture
  239. - **Zero Python deps.** Uses only `urllib`, `concurrent.futures`, `argparse`. Runs on any Python 3.7+.
  240. - **Parallel batching.** `-n 4` fires four parallel single-image requests rather than asking the API for n=4. Faster wall-clock, works regardless of host n>1 support.
  241. - **Sane defaults.** `--quality high` by default (cost is identical across quality tiers on this host). `--size 1024x1024`. `--concurrency 4`.
  242. - **Upfront validation.** Resolution constraints (max side <3840px, ratio ≤3:1) checked before the API round-trip.
  243. - **Multi-image input gracefully refused.** This host's gpt-image-2 doesn't accept multiple input images per /edits call.
  244. ### Manual usage
  245. ```bash
  246. GI="python3 ~/.claude/skills/gpt-image-2/scripts/gpt_image.py"
  247. $GI generate -p "a misty mountain temple at dawn, Studio Ghibli watercolor" -o ./temple.png
  248. $GI generate -p "..." -n 4 --concurrency 4 -o ./out
  249. $GI edit -i ./photo.png -p "Edit the input: replace ONLY the sky with northern lights. Preserve everything else exactly." -o ./aurora.png
  250. $GI generate --help
  251. $GI edit --help
  252. ```
  253. ### Updating
  254. ```bash
  255. cd ~/.claude/skills/gpt-image-2 && git pull
  256. ```
  257. The skill is text + a script. No build step, no restart, no registration.
  258. ### Customizing for your team
  259. Fork it. Pieces designed to be swapped:
  260. - **`references/use-cases.md`** — add your house style, brand palettes, recurring asset templates
  261. - **`scripts/gpt_image.py`** — add a `--watermark` flag, custom output naming, S3 upload, etc.
  262. - **`DEFAULT_BASE`** — point at your private gateway
  263. Pull requests welcome if your additions are general-purpose.
  264. ### License
  265. MIT. See `LICENSE`. Use it however.
  266. ### Credits
  267. Built for [Claude Code](https://claude.com/claude-code) but the pattern (markdown skill + zero-dep CLI + visual self-verification) works with any agent that can read files and call a script.
  268. Inspiration: OpenAI's official GPT Image 2 Cookbook, Anthropic's superpowers/writing-skills patterns for agent-discoverable skills.
scripts/gpt_image.py · Bundled script · 377 lines · 2 findings marked
  1. #!/usr/bin/env python3
  2. """gpt_image.py — call the gpt-image-2 model via the OpenAI-compatible Images API.
  3. Subcommands:
  4. generate POST /images/generations
  5. edit POST /images/edits (single source image; optional mask for inpainting)
  6. Reads OPENAI_IMAGE_API_KEY (required) and OPENAI_IMAGE_BASE_URL (default
  7. https://jmrai.net/v1) from the environment. Falls back to OPENAI_API_KEY /
  8. OPENAI_BASE_URL if the image-specific ones aren't set.
  9. Behavior tuned for this host:
  10. * Quality is the same price across tiers, so default --quality high.
  11. * Multi-image *input* is NOT supported by this host's gpt-image-2.
  12. For composition, do it in two steps (generate base, then edit).
  13. * `-n N` fires N **parallel** single-image requests rather than asking the
  14. API for n=N in one call. Faster wall-clock and works regardless of whether
  15. the host supports n>1.
  16. Outputs are written to disk and the absolute paths are printed, one per line,
  17. on stdout — so callers can capture the paths cleanly.
  18. No third-party dependencies; uses urllib only so it runs on any Python 3.7+.
  19. """
  20. from __future__ import annotations
  21. import argparse
  22. import base64
  23. import json
  24. import mimetypes
  25. import os
  26. import sys
  27. import threading
  28. import time
  29. import urllib.error
  30. import urllib.request
  31. from concurrent.futures import ThreadPoolExecutor, as_completed
  32. from pathlib import Path
  33. DEFAULT_BASE = (
  34. os.environ.get("OPENAI_IMAGE_BASE_URL")
  35. or os.environ.get("OPENAI_BASE_URL")
  36. or "https://jmrai.net/v1"
    • Warning: Default base URL is a third-party relay (jmrai.net). All prompts, uploaded source images, masks and API keys go there unless the user overrides the URL.
    • Line 43 on GitHub
  37. )
  38. DEFAULT_MODEL = os.environ.get("OPENAI_IMAGE_MODEL", "gpt-image-2")
  39. DEFAULT_QUALITY = "high" # this host charges the same across qualities
  40. DEFAULT_CONCURRENCY = 4
  41. # Constraints reported by the host's gpt-image-2.
  42. MAX_SIDE = 3840
  43. MAX_RATIO = 3.0 # long:short side
  44. def _key() -> str:
  45. key = os.environ.get("OPENAI_IMAGE_API_KEY") or os.environ.get("OPENAI_API_KEY")
    • Warning: Falls back to the user's general OPENAI_API_KEY and sends it as a Bearer token to the author's third-party host jmrai.net by default, not OpenAI. A real OpenAI key could be handed to an unrelated relay.
    • Line 55 on GitHub
  46. if not key:
  47. sys.exit(
  48. "ERROR: set OPENAI_IMAGE_API_KEY (or OPENAI_API_KEY).\n"
  49. " export OPENAI_IMAGE_API_KEY='sk-...'\n"
  50. " export OPENAI_IMAGE_BASE_URL='https://jmrai.net/v1' # optional"
  51. )
  52. return key
  53. def _validate_size(size: str) -> None:
  54. try:
  55. w, h = (int(x) for x in size.lower().split("x", 1))
  56. except Exception:
  57. sys.exit(f"ERROR: --size must be WxH (got {size!r})")
  58. if w <= 0 or h <= 0:
  59. sys.exit(f"ERROR: --size dimensions must be positive (got {size!r})")
  60. if max(w, h) >= MAX_SIDE:
  61. sys.exit(
  62. f"ERROR: longest side must be < {MAX_SIDE}px "
  63. f"(got {max(w, h)}px in {size!r})"
  64. )
  65. ratio = max(w, h) / min(w, h)
  66. if ratio > MAX_RATIO:
  67. sys.exit(
  68. f"ERROR: aspect ratio must be ≤ {MAX_RATIO:.0f}:1 "
  69. f"(got {ratio:.2f}:1 in {size!r})"
  70. )
  71. _print_lock = threading.Lock()
  72. def _send(req: urllib.request.Request, retries: int = 4) -> dict:
  73. last_err: str | None = None
  74. for attempt in range(retries):
  75. try:
  76. with urllib.request.urlopen(req, timeout=600) as resp:
  77. return json.loads(resp.read())
  78. except urllib.error.HTTPError as e:
  79. body = e.read().decode("utf-8", "replace")
  80. # Retry on 429 and 5xx, surface 4xx immediately
  81. if (e.code == 429 or 500 <= e.code < 600) and attempt < retries - 1:
  82. wait = 2 ** attempt + (0.1 * attempt)
  83. time.sleep(wait)
  84. last_err = f"HTTP {e.code}: {body}"
  85. continue
  86. sys.exit(f"HTTP {e.code} from {req.full_url}\n{body}")
  87. except urllib.error.URLError as e:
  88. last_err = f"network error: {e}"
  89. if attempt < retries - 1:
  90. time.sleep(2 ** attempt)
  91. continue
  92. sys.exit(last_err)
  93. sys.exit(last_err or "unknown error")
  94. def _post_json(path: str, payload: dict) -> dict:
  95. url = DEFAULT_BASE.rstrip("/") + path
  96. req = urllib.request.Request(
  97. url,
  98. data=json.dumps(payload).encode("utf-8"),
  99. headers={
  100. "Authorization": f"Bearer {_key()}",
  101. "Content-Type": "application/json",
  102. "Accept": "application/json",
  103. },
  104. method="POST",
  105. )
  106. return _send(req)
  107. def _post_multipart(path: str, fields: dict, files: dict[str, list[str]]) -> dict:
  108. url = DEFAULT_BASE.rstrip("/") + path
  109. boundary = f"----gptimage{int(time.time() * 1000)}{threading.get_ident()}"
  110. parts: list[bytes] = []
  111. for k, v in fields.items():
  112. if v is None:
  113. continue
  114. parts.append(
  115. f"--{boundary}\r\n"
  116. f'Content-Disposition: form-data; name="{k}"\r\n\r\n'
  117. f"{v}\r\n".encode("utf-8")
  118. )
  119. for field_name, paths in files.items():
  120. for raw in paths:
  121. fp = Path(raw).expanduser()
  122. if not fp.exists():
  123. sys.exit(f"ERROR: file not found: {fp}")
  124. mime = mimetypes.guess_type(fp.name)[0] or "image/png"
  125. parts.append(
  126. f"--{boundary}\r\n"
  127. f'Content-Disposition: form-data; name="{field_name}"; '
  128. f'filename="{fp.name}"\r\n'
  129. f"Content-Type: {mime}\r\n\r\n".encode("utf-8")
  130. )
  131. parts.append(fp.read_bytes())
  132. parts.append(b"\r\n")
  133. parts.append(f"--{boundary}--\r\n".encode("utf-8"))
  134. body = b"".join(parts)
  135. req = urllib.request.Request(
  136. url,
  137. data=body,
  138. headers={
  139. "Authorization": f"Bearer {_key()}",
  140. "Content-Type": f"multipart/form-data; boundary={boundary}",
  141. "Accept": "application/json",
  142. },
  143. method="POST",
  144. )
  145. return _send(req)
  146. def _download(url: str) -> bytes:
  147. with urllib.request.urlopen(url, timeout=300) as r:
  148. return r.read()
  149. def _output_paths(out_arg: str | None, n: int) -> list[Path]:
  150. if out_arg is None:
  151. base = Path.cwd() / f"gpt-image-{int(time.time())}"
  152. ext = ".png"
  153. else:
  154. p = Path(out_arg).expanduser()
  155. if p.suffix == "" and ((p.exists() and p.is_dir()) or out_arg.endswith("/")):
  156. p.mkdir(parents=True, exist_ok=True)
  157. base = p / "image"
  158. ext = ".png"
  159. else:
  160. base = p.with_suffix("")
  161. ext = p.suffix or ".png"
  162. base.parent.mkdir(parents=True, exist_ok=True)
  163. return [
  164. Path(f"{base}{'' if n == 1 else f'-{i + 1}'}{ext}")
  165. for i in range(n)
  166. ]
  167. def _write_item(item: dict, dest: Path) -> Path:
  168. if "b64_json" in item and item["b64_json"]:
  169. dest.write_bytes(base64.b64decode(item["b64_json"]))
  170. elif "url" in item and item["url"]:
  171. dest.write_bytes(_download(item["url"]))
  172. else:
  173. sys.exit(f"ERROR: response item missing b64_json/url: {item}")
  174. with _print_lock:
  175. print(dest.resolve(), flush=True)
  176. return dest.resolve()
  177. def _run_parallel(
  178. n: int,
  179. concurrency: int,
  180. fn, # callable that returns a dict (single API response)
  181. paths: list[Path],
  182. ) -> list[Path]:
  183. """Fire `n` calls in parallel and write each response to paths[i]."""
  184. results: list[Path | None] = [None] * n
  185. workers = max(1, min(concurrency, n))
  186. with ThreadPoolExecutor(max_workers=workers) as ex:
  187. futures = {ex.submit(fn): i for i in range(n)}
  188. for fut in as_completed(futures):
  189. i = futures[fut]
  190. data = fut.result()
  191. items = data.get("data") or []
  192. if not items:
  193. sys.exit(f"ERROR: empty response: {json.dumps(data)[:500]}")
  194. results[i] = _write_item(items[0], paths[i])
  195. return [r for r in results if r is not None]
  196. def cmd_generate(a: argparse.Namespace) -> None:
  197. _validate_size(a.size)
  198. payload = {
  199. "model": a.model,
  200. "prompt": a.prompt,
  201. "n": 1,
  202. "size": a.size,
  203. }
  204. if a.quality:
  205. payload["quality"] = a.quality
  206. if a.style:
  207. payload["style"] = a.style
  208. if a.background:
  209. payload["background"] = a.background
  210. if a.format:
  211. payload["response_format"] = a.format
  212. if a.user:
  213. payload["user"] = a.user
  214. paths = _output_paths(a.out, a.n)
  215. if a.n == 1:
  216. data = _post_json("/images/generations", payload)
  217. items = data.get("data") or []
  218. if not items:
  219. sys.exit(f"ERROR: empty response: {json.dumps(data)[:500]}")
  220. _write_item(items[0], paths[0])
  221. return
  222. _run_parallel(
  223. n=a.n,
  224. concurrency=a.concurrency,
  225. fn=lambda: _post_json("/images/generations", payload),
  226. paths=paths,
  227. )
  228. def cmd_edit(a: argparse.Namespace) -> None:
  229. _validate_size(a.size)
  230. if len(a.image) > 1:
  231. sys.exit(
  232. "ERROR: this host's gpt-image-2 does not accept multiple input images.\n"
  233. "Workflow for compositions: generate or edit a base, then edit again "
  234. "with the next layer described in the prompt."
  235. )
  236. fields = {
  237. "model": a.model,
  238. "prompt": a.prompt,
  239. "n": "1",
  240. "size": a.size,
  241. }
  242. if a.quality:
  243. fields["quality"] = a.quality
  244. if a.background:
  245. fields["background"] = a.background
  246. if a.format:
  247. fields["response_format"] = a.format
  248. if a.user:
  249. fields["user"] = a.user
  250. files: dict[str, list[str]] = {"image": list(a.image)}
  251. if a.mask:
  252. files["mask"] = [a.mask]
  253. paths = _output_paths(a.out, a.n)
  254. def _call() -> dict:
  255. return _post_multipart("/images/edits", fields, files)
  256. if a.n == 1:
  257. data = _call()
  258. items = data.get("data") or []
  259. if not items:
  260. sys.exit(f"ERROR: empty response: {json.dumps(data)[:500]}")
  261. _write_item(items[0], paths[0])
  262. return
  263. _run_parallel(n=a.n, concurrency=a.concurrency, fn=_call, paths=paths)
  264. def main() -> None:
  265. ap = argparse.ArgumentParser(
  266. description="Call gpt-image-2 over the OpenAI-compatible Images API.",
  267. formatter_class=argparse.RawDescriptionHelpFormatter,
  268. epilog=(
  269. "Notes for this host (jmrai.net default):\n"
  270. " * Quality is the same price across tiers — default is 'high'.\n"
  271. " * `-n N` fires N parallel single-image calls.\n"
  272. " * Multi-image *input* (compose 2 sources in one /edits call) is not supported.\n"
  273. " * Max side < 3840px, aspect ratio ≤ 3:1.\n"
  274. ),
  275. )
  276. sub = ap.add_subparsers(dest="cmd", required=True)
  277. common_quality = dict(
  278. choices=["low", "medium", "high", "standard", "hd"],
  279. default=DEFAULT_QUALITY,
  280. help=f"rendering quality (default {DEFAULT_QUALITY}; "
  281. "all tiers cost the same on this host)",
  282. )
  283. g = sub.add_parser("generate", aliases=["gen"], help="generate from a text prompt")
  284. g.add_argument("-p", "--prompt", required=True, help="text prompt")
  285. g.add_argument("--size", default="1024x1024",
  286. help="WxH; max side <3840, ratio ≤3:1; "
  287. "e.g. 1024x1024, 1536x1024, 1024x1536, 1536x864, 2048x2048")
  288. g.add_argument("-n", type=int, default=1,
  289. help="number of images (fires N parallel calls; default 1)")
  290. g.add_argument("--concurrency", type=int, default=DEFAULT_CONCURRENCY,
  291. help=f"max parallel requests when n>1 (default {DEFAULT_CONCURRENCY})")
  292. g.add_argument("-o", "--out",
  293. help="output file path or directory; auto-suffixed when n>1")
  294. g.add_argument("--model", default=DEFAULT_MODEL)
  295. g.add_argument("--quality", **common_quality)
  296. g.add_argument("--style", choices=["vivid", "natural"],
  297. help="overall style hint if supported")
  298. g.add_argument("--background", choices=["transparent", "opaque", "auto"],
  299. help="transparent for stickers/icons/sprites")
  300. g.add_argument("--format", choices=["url", "b64_json"],
  301. help="response format hint (script handles either)")
  302. g.add_argument("--user", help="optional user identifier passed to the API")
  303. g.set_defaults(fn=cmd_generate)
  304. e = sub.add_parser("edit", help="edit / inpaint an existing image")
  305. e.add_argument("-i", "--image", action="append", required=True,
  306. help="path to source image (host accepts only one — script errors on >1)")
  307. e.add_argument("-p", "--prompt", required=True,
  308. help="describe ONLY the change you want")
  309. e.add_argument("--mask", help="optional PNG mask; white pixels = regenerate")
  310. e.add_argument("--size", default="1024x1024")
  311. e.add_argument("-n", type=int, default=1,
  312. help="number of variants (fires N parallel calls; default 1)")
  313. e.add_argument("--concurrency", type=int, default=DEFAULT_CONCURRENCY,
  314. help=f"max parallel requests when n>1 (default {DEFAULT_CONCURRENCY})")
  315. e.add_argument("-o", "--out")
  316. e.add_argument("--model", default=DEFAULT_MODEL)
  317. e.add_argument("--quality", **common_quality)
  318. e.add_argument("--background", choices=["transparent", "opaque", "auto"])
  319. e.add_argument("--format", choices=["url", "b64_json"])
  320. e.add_argument("--user")
  321. e.set_defaults(fn=cmd_edit)
  322. args = ap.parse_args()
  323. args.fn(args)
  324. if __name__ == "__main__":
  325. main()

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.