cmvr-visual/docs/API-examples.md

243 lines
10 KiB
Markdown
Raw 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.

# HTTP + SSE 调用示例
以下针对网站业务 API,**不是**直接调用 GPU 上游。示例使用同一登录用户;素材 ID、任务 ID 均由服务器返回,不接受客户端提供的服务器路径。完整字段见 [共享契约](api-contract.md)。
## 登录与会话
Python/httpx 示例通过交互输入取得密码,不写在源码、命令行参数或日志里。使用 SSH 隧道的本地 HTTP 地址;正式 HTTPS 部署改成自己的同源地址。
```python
import getpass
import uuid
from pathlib import Path
import httpx
client = httpx.Client(base_url="http://127.0.0.1:18193/api", timeout=30)
response = client.post("/auth/login", json={
"username": input("账号:"),
"password": getpass.getpass("密码:"),
})
response.raise_for_status()
client.headers["X-CSRF-Token"] = response.json()["csrf_token"]
# client 自动携带 HttpOnly 会话 Cookie;不要打印 response 或 Cookie。
```
管理员创建普通用户使用 `POST /auth/users`,字段为 `username/display_name/password`,密码至少12字符;无公开注册。当前默认管理员配置在本机私有 `.env.server` 中获取,不复制进本示例。初始管理员支持本次指定的六位密码,不改变普通用户12位要求。
## 素材上传、编辑和读取
```python
def upload(path):
path = Path(path)
with path.open("rb") as stream:
response = client.post("/assets", files={"file": (path.name, stream)})
response.raise_for_status()
return response.json()
image = upload("reference.png") # 替换为自己的真实本地文件
image_id = image["id"]
response = client.patch(f"/assets/{image_id}", json={
"name": "产品参考图", "tags": ["产品", "参考"], "favorite": True,
})
response.raise_for_status()
response = client.get("/assets", params={"kind": "image", "tag": "参考", "page": 1, "page_size": 24})
response.raise_for_status()
```
`preview_url`、`thumbnail_url`、`download_url` 都指向受会话保护的 `/api/assets/...` 路由。浏览器同源 `<img>`、`<video>`、`<audio>` 可自动携带 Cookie。下面直接用相对路由测试单段 Range:
```python
response = client.get(f"/assets/{image_id}/content", headers={"Range": "bytes=0-31"})
response.raise_for_status() # 有效范围返回206,Content-Range包含实际长度
response = client.get(f"/assets/{image_id}/content", params={"download": 1})
response.raise_for_status()
Path("reference-copy.png").write_bytes(response.content)
```
不存在、已删除或非本人素材均不可读取。删除使用 `DELETE /assets/{id}`;如果输入仍被任务引用,只从素材库移除,不立即物理删除。生成素材改名、收藏、标签或删除时,来源任务会产生新 version 和 `job.updated` 事件。
## 提交约定
```python
def submit(payload, key=None):
# 网络结果未知时,应保留本次 key 和原 payload 重试,而非重新生成 key。
request_key = key or str(uuid.uuid4())
response = client.post("/jobs", json=payload, headers={"Idempotency-Key": request_key})
response.raise_for_status()
return response.json()["jobs"], request_key
```
HTTP 202 只表示接受任务。相同用户、相同幂等键和相同参数返回同一批业务任务;参数改变返回 409。不要把重新连接当成“再次生成”。下面八个 payload 应按需单独执行,不需要一次运行所有模型。
### 1. 文生图片与批次
```python
payload = {
"task_type": "image.generate", "input": {"prompt": "白色背景上的蓝色陶瓷杯,柔和自然光"},
"parameters": {"width": 1024, "height": 1024, "num_inference_steps": 50, "seed": 42},
"count": 2,
}
jobs, request_key = submit(payload)
job_id = jobs[0]["id"]
```
批量仅适用于 `image.generate`、`defect.generate`,最多 4 项,各项独立排队。此例两个实际种子分别为 42、43。普通 Qwen-Image 不支持参考图编辑。
### 2. 文生或图生视频
```python
payload = {
"task_type": "video.generate",
"input": {"prompt": "镜头缓慢绕产品移动,保持主体结构稳定", "image_asset_id": image_id},
"parameters": {"width": 1280, "height": 704, "num_frames": 121, "fps": 24,
"num_inference_steps": 50, "seed": 42, "upscale": True,
"upscale_width": 1920, "upscale_height": 1080, "tile_size": 128},
}
# 删除 image_asset_id 即为文生视频;保留时必须是本人上传/生成的图片。
```
最多约 5 秒,帧数须为 `4n+1` 且不超过 121,帧率固定 24。当前不是 15 秒任务,结果默认无声。
### 3. Canny 条件样本
```python
payload = {
"task_type": "defect.generate",
"input": {"prompt": "金属零件表面细小划痕,真实工业摄影", "image_asset_id": image_id},
"parameters": {"width": 1024, "height": 1024, "num_inference_steps": 50,
"controlnet_conditioning_scale": 0.8, "canny_low": 100, "canny_high": 200},
}
```
输出包含合成图和边缘控制图,不是带缺陷真值掩膜的训练标注对。
### 4. Whisper 转写
```python
audio = upload("speech.wav")
payload = {
"task_type": "audio.transcribe", "input": {"audio_asset_id": audio["id"]},
"parameters": {"language": "zh", "max_audio_seconds": 1800},
}
```
也可使用本人有声视频的 asset ID;服务先做 CPU 音轨提取。`language="auto"` 为自动识别。成功后 `job.result` 包含 `text`、`segments`,分段为 `start/end/text`,时间按实际分块记录,不是逐词时间轴。
### 5. 数学推演
```python
payload = {"task_type": "math.solve", "input": {"prompt": "解方程 x²-5x+6=0,并验证答案"},
"parameters": {"max_tokens": 2048, "enable_thinking": False}}
```
结果为 `job.result.text` 及文本/JSON 素材;需要业务复核,不把输出当作形式化证明。
### 6. 图片/视频理解
```python
payload = {"task_type": "media.structure", "input": {"asset_id": image_id},
"parameters": {"frame_count": 1}}
# 视频使用视频 asset ID,frame_count 可取1..12。
```
结果含 `subjects/scene/ocr/tags/frames`;视频帧的 `timestamp_seconds` 来自实际解码帧时间。只描述可见画面,不宣称实现完整镜头切分指标。
### 7. CPU 成片合成
```python
video = upload("clip.mp4")
payload = {
"task_type": "video.compose", "input": {"asset_ids": [video["id"]]},
"parameters": {"width": 1280, "height": 720, "fps": 24,
"clips": [{"asset_id": video["id"], "start_seconds": 0, "end_seconds": 3}],
"subtitles": [{"start": 0, "end": 2, "text": "我的产品介绍"}]},
}
# 片段实际时长须至少3秒;可在input加入audio_asset_id引用自己的音频。
```
`asset_ids` 顺序必须与 `clips` 一致;剪辑点、字幕不能越过实际素材/成片时长。帧率限 24、25、30、60,不接受任意 FFmpeg filter、外部 URL 或命令行。外部音轨由用户上传,不自动生成背景音乐。
### 8. Kokoro CPU 中文配音
```python
payload = {"task_type": "audio.speech", "input": {"prompt": "欢迎来到本地创作工作台。"},
"parameters": {"voice": "zf_xiaobei", "speed": 1.0}}
```
另一当前音色为 `zm_yunxi`。须先配置真实 Kokoro 服务;没有可用服务时能力不启用,不返回模拟音频。配音属于 CPU provider,不进入新 GPU 模型队列。
## 定时、查询、取消与重新生成
```python
from datetime import datetime, timedelta, timezone
payload["scheduled_at"] = (datetime.now(timezone.utc) + timedelta(minutes=30)).isoformat()
# 如需提交:jobs, request_key = submit(payload)
response = client.get(f"/jobs/{job_id}")
response.raise_for_status()
job = response.json()
print(job["id"], job["state"], job["attempt_count"], job["preemptions"])
response = client.post(f"/jobs/{job_id}/cancel")
response.raise_for_status()
# 可能仍为cancelling,须继续查询确认最终cancelled。
```
归档 `collecting` 阶段不再接受新的取消;此前已提交的取消会在完成事务中优先处理,不公开 pending 输出。只有 `succeeded/failed/cancelled/timed_out` 终态可调用 `POST /jobs/{id}/retry`;这是用户明确要求的新生成,会取得新业务 ID,不是网络恢复机制。
任务状态包括 `scheduled/submitting/queued/running/collecting/cancelling/succeeded/failed/cancelled/timed_out`。外部用户占用 GPU 时可出现同 ID 的 `running → queued`,`preemptions` 递增;不要为此创建替代任务。`sync_warning` 不是终态失败,`progress=null` 表示没有真实百分比来源。
## SSE 与重连
在已登录网站的浏览器中,先获取任务快照和 cursor,再打开同源 EventSource:
```javascript
const snapshot = await fetch('/api/jobs?page_size=24', {credentials:'include'}).then(r => r.json());
const source = new EventSource(`/api/events?after=${snapshot.cursor}`, {withCredentials:true});
source.addEventListener('job.updated', event => {
const {job} = JSON.parse(event.data);
console.log(event.lastEventId, job.id, job.state, job.version);
// 仅将更高version应用到本地同ID任务。
});
source.addEventListener('reset', () => {
// 重新获取HTTP快照;不要重新生成任务。
});
// 离开工作空间/注销时 source.close();关闭流不取消任务。
```
服务端事件格式:
```text
id: 123
event: job.updated
data: {"job":{"id":"...","version":3,"state":"queued"}}
: heartbeat
```
`Last-Event-ID` header 在重连时优先于最初的 `?after=`;浏览器自动维护该 header。事件持久存于 MySQL,按 owner 过滤。另有 `asset.created/asset.updated/asset.deleted/reset`;心跳不改变游标。注销或会话过期会结束流,前端应恢复登录而不是一直重建任务。
Python 已登录 client 也可重放(会持续读取,按 Ctrl+C 结束):
```python
cursor = client.get("/jobs").json()["cursor"]
with client.stream("GET", "/events", headers={"Last-Event-ID": str(cursor)},
timeout=httpx.Timeout(10, read=None)) as response:
response.raise_for_status()
for line in response.iter_lines():
if line.startswith(("id:", "event:", ":")):
print(line) # 不打印Cookie、密码或推理密钥。
```
调试完注销并清理连接:
```python
client.post("/auth/logout").raise_for_status()
client.close()
```
常见错误:401 登录无效;403 CSRF/权限拒绝;404 非本人或已删资源;409 幂等键冲突或任务状态不允许;400/422 参数不支持;413 上传过大。错误为 `detail.code/message`,验证错误可能附字段位置。不要向用户显示服务器绝对路径或上游认证内容。