> ## Documentation Index
> Fetch the complete documentation index at: https://gccai.heqingsong.uk/llms.txt
> Use this file to discover all available pages before exploring further.

# 完整工作流示例

> imagine → upscale → inpaint → video 等端到端 curl 走查，附 bash / Python / TS 客户端封装

把多接口串起来的端到端示例。所有命令把 `$KEY` 换成你的 API token，`$HOST` 换成实际平台域名。

```bash theme={null}
export KEY="sk-your-api-key"
export HOST="https://gccai.heqingsong.uk"
```

## 流程 A：基础文生图（imagine → upscale）

```bash theme={null}
# 1. imagine 出 4 张图
curl -sS -X POST "$HOST/v1/midjourney/generations/imagine" \
  -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \
  -d '{
    "prompt": "a futuristic city at sunset, photorealistic, cinematic lighting",
    "version": "8.1", "size": "16:9", "speed": "fast", "stylize": 250
  }'
# → {"code":200,"data":[{"task_id":"task_01KQVZAPBW...","status":"submitted"}]}

# 2. 轮询查询直到 SUCCESS（约 30–60s）
curl -sS "$HOST/v1/midjourney/task_01KQVZAPBW..." -H "Authorization: Bearer $KEY"
# → SUCCESS，含 grid_image_url + 4 张 image_urls + buttons(U1-U4 / V1-V4 / 🔄)

# 3. upscale 选第 2 张（本地合成，毫秒级 SUCCESS）
curl -sS -X POST "$HOST/v1/midjourney/generations/upscale" \
  -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \
  -d '{"task_id": "task_01KQVZAPBW...", "index": 2}'
# → 查询拿单图 image_urls[0]
```

## 流程 B：垫图 → 强变体 → 放大

```bash theme={null}
# 1. 垫图 imagine
curl -sS -X POST "$HOST/v1/midjourney/generations/imagine" \
  -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \
  -d '{
    "prompt": "turn this product into a luxury studio photo",
    "image_urls": ["https://your-cdn.example.com/product.png"],
    "iw": 1.5, "size": "1:1"
  }'

# 2. 对结果做强变体
curl -sS -X POST "$HOST/v1/midjourney/generations/high-variation" \
  -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \
  -d '{"task_id": "task_01XXX...", "index": 1, "speed": "fast"}'

# 3. 对变体的某张 upscale
curl -sS -X POST "$HOST/v1/midjourney/generations/upscale" \
  -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \
  -d '{"task_id": "task_02_variant...", "index": 3}'
```

## 流程 C：局部重绘（inpaint + modal 两步）

前提：先 imagine + upscale 拿到单图任务（见流程 A）。

```bash theme={null}
# 1. 提交 inpaint → 进 MODAL
curl -sS -X POST "$HOST/v1/midjourney/generations/inpaint" \
  -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \
  -d '{"task_id": "task_02_upscaled..."}'
# → {"data":[{"task_id":"task_03_inpaint...","status":"modal"}]}
#   注意 status=modal，任务等你补 mask；30 分钟超时自动 CANCEL + 退款

# 2. 前端画 mask（白色=重绘区，透明=保留），上传到自己的 OSS 拿 mask_url（须公网可达）

# 3. 提交 modal 完成
curl -sS -X POST "$HOST/v1/midjourney/generations/modal" \
  -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \
  -d '{
    "task_id": "task_03_inpaint...",
    "prompt": "replace the selected area with a red leather sofa",
    "mask_url": "https://your-oss.example.com/mask-abc.png"
  }'
# → 同 task_id，status 转 submitted；4. 轮询 60–90s 后 SUCCESS，含 4 张局部重绘候选
```

## 流程 D：扩图（Zoom Out）

```bash theme={null}
# 直接出图，无需 mask（Outpaint / CustomZoom 都不进 MODAL）
curl -sS -X POST "$HOST/v1/midjourney/generations/zoom" \
  -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \
  -d '{"task_id": "task_02_upscaled...", "zoom_ratio": 1.5, "speed": "fast"}'
```

## 流程 E：图生视频（i2v）

```bash theme={null}
# 720p 高清 + batch=4（4 倍计费）
curl -sS -X POST "$HOST/v1/midjourney/generations/video" \
  -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \
  -d '{
    "prompt": "city traffic at night, neon reflections, slow camera dolly",
    "image_urls": ["https://your-cdn.example.com/city.jpg"],
    "video_type": "vid_1.1_i2v_720", "batch_size": 4
  }'
# 实扣 = midjourney@video-720p × 4

# 起止帧 transition（end_url 自动升级为 start_end）
curl -sS -X POST "$HOST/v1/midjourney/generations/video" \
  -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \
  -d '{
    "prompt": "transition smoothly from sunrise to sunset",
    "image_urls": ["https://your-cdn.example.com/sunrise.jpg"],
    "end_url": "https://your-cdn.example.com/sunset.jpg",
    "video_type": "vid_1.1_i2v_720"
  }'
```

## 通用工具：Python 客户端封装

```python theme={null}
import time
import httpx

API_KEY = "sk-..."
HOST = "https://gccai.heqingsong.uk"

class MjClient:
    def __init__(self):
        self.client = httpx.Client(
            base_url=HOST,
            headers={"Authorization": f"Bearer {API_KEY}"},
            timeout=30,
        )

    def imagine(self, prompt, **params):
        r = self.client.post("/v1/midjourney/generations/imagine",
                             json={"prompt": prompt, **params})
        return r.json()["data"][0]["task_id"]

    def upscale(self, task_id, index):
        r = self.client.post("/v1/midjourney/generations/upscale",
                             json={"task_id": task_id, "index": index})
        return r.json()["data"][0]["task_id"]

    def query(self, task_id):
        return self.client.get(f"/v1/midjourney/{task_id}").json()

    def wait(self, task_id, timeout=180):
        deadline = time.time() + timeout
        while time.time() < deadline:
            t = self.query(task_id)
            if t["status"] in ("SUCCESS", "FAILURE"):
                return t
            if t["status"] == "MODAL":
                raise RuntimeError(f"task {task_id} 需要调 /modal")
            time.sleep(3)
        raise TimeoutError(task_id)


mj = MjClient()
imagine_id = mj.imagine("a cat", version="8.1", speed="fast", size="16:9")
mj.wait(imagine_id)
upscale_id = mj.upscale(imagine_id, 2)
print(mj.wait(upscale_id)["image_urls"][0])
```

## 通用工具：TypeScript 封装

```ts theme={null}
const API_KEY = "sk-...";
const HOST = "https://gccai.heqingsong.uk";

async function mj(path: string, body: any) {
  const r = await fetch(`${HOST}${path}`, {
    method: "POST",
    headers: { "Authorization": `Bearer ${API_KEY}`, "Content-Type": "application/json" },
    body: JSON.stringify(body),
  });
  return r.json();
}

async function query(id: string) {
  const r = await fetch(`${HOST}/v1/midjourney/${id}`, {
    headers: { "Authorization": `Bearer ${API_KEY}` },
  });
  return r.json();
}

async function waitTask(id: string, timeoutMs = 180_000) {
  const deadline = Date.now() + timeoutMs;
  while (Date.now() < deadline) {
    const t = await query(id);
    if (t.status === "SUCCESS" || t.status === "FAILURE") return t;
    if (t.status === "MODAL") throw new Error(`需要调 /modal: ${id}`);
    await new Promise((r) => setTimeout(r, 3000));
  }
  throw new Error(`超时: ${id}`);
}

const r = await mj("/v1/midjourney/generations/imagine",
                   { prompt: "a cat", version: "8.1", speed: "fast" });
const result = await waitTask(r.data[0].task_id);
console.log(result.image_urls);
```

## 状态机

```text theme={null}
submit → NOT_START(0%) → SUBMITTED(5-30%) → IN_PROGRESS(~99%) → SUCCESS(100%)
                                                              ↘ FAILURE(100%) → 自动退款
inpaint / CustomZoom → MODAL(15%) ──POST /modal {mask_url, prompt}──▶ SUBMITTED → ...
                          └ 30min 超时 → CANCEL + 退款
```
