init: AI 文生图调用脚本与文档
- gpt-image-t2i / grok-image-t2i:OpenAI 兼容接口文生图脚本 - SKILLS.md:输出规范(统一输出到 output/,按「模型名-时间戳」命名) - 接口与参数说明文档
This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
# GPT 图像生成 API 文档
|
||||
|
||||
## 调用示例
|
||||
|
||||
### gpt-image-2-1K
|
||||
|
||||
```bash
|
||||
curl https://api.slomerex.xyz/v1/chat/completions \
|
||||
-H "Authorization: Bearer $NEW_API_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"model": "gpt-image-2-1K",
|
||||
"messages": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": "Explain quantum entanglement in one paragraph."
|
||||
}
|
||||
],
|
||||
"temperature": 0.7
|
||||
}'
|
||||
```
|
||||
|
||||
### gpt-image-2-2K
|
||||
|
||||
```bash
|
||||
curl https://api.slomerex.xyz/v1/chat/completions \
|
||||
-H "Authorization: Bearer $NEW_API_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"model": "gpt-image-2-2K",
|
||||
"messages": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": "Explain quantum entanglement in one paragraph."
|
||||
}
|
||||
],
|
||||
"temperature": 0.7
|
||||
}'
|
||||
```
|
||||
|
||||
### gpt-image-2-4K
|
||||
|
||||
```bash
|
||||
curl https://api.slomerex.xyz/v1/chat/completions \
|
||||
-H "Authorization: Bearer $NEW_API_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"model": "gpt-image-2-4K",
|
||||
"messages": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": "Explain quantum entanglement in one paragraph."
|
||||
}
|
||||
],
|
||||
"temperature": 0.7
|
||||
}'
|
||||
```
|
||||
|
||||
> 将 `<YOUR_API_KEY>` 替换为令牌设置中的 API Key。
|
||||
|
||||
## 身份验证
|
||||
|
||||
所有请求必须携带 `Authorization: Bearer <TOKEN>` 请求头。Anthropic 格式的端点也接受 `x-api-key` 请求头。
|
||||
|
||||
在「令牌」页面生成 API Key,可以按模型、分组、IP、速率等维度精细化授权。
|
||||
|
||||
## 支持的参数
|
||||
|
||||
| 参数 | 类型 | 默认值 / 范围 | 说明信息 |
|
||||
|------|------|--------------|----------|
|
||||
| prompt | string(必填) | — | 想要生成图像的文字描述 |
|
||||
| size | enum | 1024x1024 | 输出图像尺寸 |
|
||||
| quality | enum | standard | 生成质量预设 |
|
||||
| style | enum | vivid | 画风 |
|
||||
| n | integer | 1(范围 1 ~ 10) | 生成的图像数量 |
|
||||
| response_format | enum | url | 图像结果的返回方式 |
|
||||
@@ -0,0 +1,84 @@
|
||||
#!/usr/bin/env python3
|
||||
"""调用 gpt-image-2-2K 生成图片的示例脚本"""
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import datetime
|
||||
import json
|
||||
import sys
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
from pathlib import Path
|
||||
|
||||
API_URL = "https://api.slomerex.xyz/v1/images/generations"
|
||||
API_KEY = "sk-zkaPOvLoj1VRFxStvCQkpBXjcDELrgEK0F8Z2Vt9d8SZo8CV"
|
||||
MODEL = "gpt-image-2-2K"
|
||||
|
||||
# 图片描述提示词,直接改这里即可
|
||||
PROMPT = """An ancient steampunk city floating above stormy clouds, with a massive bronze clock tower at its center, the clock face made of glowing blue crystal. Golden "god rays" of sunset pierce through the gaps in the cloud layers, illuminating the intricate gears and pipes on the tower's surface. In the foreground, a small airship is passing through an arch beside the tower, trailing long warm-colored exhaust smoke. Tiny pedestrians holding umbrellas are faintly visible on the streets. Overall color palette features a strong contrast between teal-blue and amber-gold. Cinematic lighting, photorealistic textures, 8K, extremely detailed, with an epic sense of impending storm."""
|
||||
|
||||
|
||||
def generate_image(prompt: str, size: str = "1024x1024", output: str = "output.png"):
|
||||
payload = {
|
||||
"model": MODEL,
|
||||
"prompt": prompt,
|
||||
"size": size,
|
||||
"n": 1,
|
||||
}
|
||||
|
||||
req = urllib.request.Request(
|
||||
API_URL,
|
||||
data=json.dumps(payload).encode("utf-8"),
|
||||
headers={
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": f"Bearer {API_KEY}",
|
||||
},
|
||||
method="POST",
|
||||
)
|
||||
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=120) as resp:
|
||||
data = json.loads(resp.read().decode("utf-8"))
|
||||
except urllib.error.HTTPError as e:
|
||||
body = e.read().decode("utf-8", errors="replace")
|
||||
print(f"HTTP {e.code} 错误: {body}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
except urllib.error.URLError as e:
|
||||
print(f"网络错误: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
if "data" not in data:
|
||||
print(f"响应中没有 data 字段: {json.dumps(data, ensure_ascii=False)}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
out_path = Path(output)
|
||||
for i, item in enumerate(data["data"]):
|
||||
# 优先取 b64_json,否则取 url
|
||||
if item.get("b64_json"):
|
||||
raw = base64.b64decode(item["b64_json"])
|
||||
elif item.get("url"):
|
||||
with urllib.request.urlopen(item["url"], timeout=120) as img_resp:
|
||||
raw = img_resp.read()
|
||||
else:
|
||||
print(f"第 {i} 张图片没有 b64_json / url 字段", file=sys.stderr)
|
||||
continue
|
||||
|
||||
path = out_path if len(data["data"]) == 1 else out_path.with_name(f"{out_path.stem}_{i}{out_path.suffix}")
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(raw)
|
||||
print(f"已保存: {path} ({len(raw)} bytes)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description="使用 gpt-image-2-2K 生成图片")
|
||||
parser.add_argument("prompt", nargs="?", default=None, help="图片提示词(不传则使用脚本内硬编码的 PROMPT)")
|
||||
parser.add_argument("--size", default="1024x1024", help="图片尺寸,如 1024x1024 / 1536x1024")
|
||||
# 默认输出到项目根目录的 output/ 文件夹,按「模型名-时间戳.后缀名」命名
|
||||
parser.add_argument(
|
||||
"--output", "-o",
|
||||
default=f"output/{MODEL}-{datetime.datetime.now():%Y%m%d_%H%M%S}.png",
|
||||
help="输出文件路径(默认 output/ 目录下「模型名-时间戳.png」)",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
generate_image(args.prompt or PROMPT, args.size, args.output)
|
||||
Reference in New Issue
Block a user