cmvr-visual/docs/API-examples.md

341 lines
18 KiB
Markdown
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.

# HTTP + SSE 调用示例
2026-11-13导航调整只移除独立工作流、批量和成片页面;本文所述共享后端API、历史数据、幂等与权限合同继续保留。当前网页创作从“故事”进入,在故事内“03 成片”处理时间线,在“任务”查看进度。
以下针对网站业务 API,**不是**直接调用 GPU 上游。示例使用同一登录用户;素材 ID、任务 ID 均由服务器返回,不接受客户端提供的服务器路径。完整字段见 [共享契约](api-contract.md)。
2026-11-26补充:下文故事候选的批准接口属于人工路径,不是自动成片的必经步骤。普通网页自动路径见[自动长视频与音轨操作指南](自动长视频与音轨操作指南_20261126.md)。生产与本地的时段由可信后端环境`GPU_WINDOW_ENABLED`决定,两类队列均受控;浏览器不能在请求中加入该开关来豁免。H3静音视频须在成片阶段选择实际音频,不能通过视频提示词生成配乐。
## 登录与会话
Python/httpx 示例通过交互输入取得密码,不写在源码、命令行参数或日志里。当前业务API在本机通过HTTP直接访问,不需要SSH隧道;正式HTTPS部署时改成自己的同源地址。
```python
import getpass
import uuid
from pathlib import Path
import httpx
client = httpx.Client(base_url="http://127.0.0.1:8000/api", timeout=30, trust_env=False)
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`,初始密码至少6字符(允许6位数字);无公开注册。当前本地默认管理员配置保存在私有 `.env.local`,不复制进本示例;已有账号密码不会被重启重置。用户主动修改密码仍须至少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}`;仍被任务、草稿或冻结运行引用时返回409,需要先处理相关引用。删除成功会移除对应文件及数据库文件记录。生成素材改名、收藏、标签或删除时,来源任务会产生新 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"]
```
这里的`count`是单次任务命令的数量:`image.generate`、`defect.generate`等支持最多4项,各项独立排队;不同任务类型的限制以能力接口为准。通用生产批次另外使用`POST /batches`,最多100个清单项,不是把这里的`count`改成100。此例两个实际种子分别为42、43。参考图编辑使用独立的`image.reference.generate`任务类型。
### 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 即为文生视频;保留时必须是本人上传/生成的图片。
```
单镜头默认121帧、约5秒,现支持最多361帧、约15秒;帧数须为`4n+1`,帧率固定24。例如10秒/15秒生成源分别使用241/361帧,成片再裁到选用的精确帧数。模型生成结果默认无声。
### 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`,验证错误可能附字段位置。不要向用户显示服务器绝对路径或上游认证内容。
## 故事工作室 v3
以下沿用前文已登录且设置CSRF的 `client`(base_url以 `/api` 结尾)。先读取 `/stories/capabilities`;模型不可用时接口明确拒绝参考生成,不会替换为文字生成。`reference_mode="text"` 是调用者显式选择,参考图仅作人工比对。
```python
import uuid
shot_id = uuid.uuid4().hex
story = client.post("/stories", json={
"name": "我的故事",
"spec": {"schema_version": 3, "shots": [{
"id": shot_id, "name": "镜头一", "visual_prompt": "海边站台的清晨",
"motion_prompt": "镜头缓慢推进,海风吹动衣角",
"video_parameters": {"source_seconds": 15},
"edit": {"start_frame": 0, "duration_frames": 360}
}], "render": {"fps": 24, "total_frames": 360}}
}).json()
path = "/stories/" + story["id"]
preview = client.get(path + "/preview").json()
# 此镜头没有绑定参考图,因此明确使用文字生成。
command = {"expected_version": story["version"], "shot_id": shot_id,
"kind": "frame", "source_kind": "generated", "count": 1,
"reference_mode": "text", "execution_mode": "interactive"}
key = uuid.uuid4().hex # 发请求前保存key与精确body;超时只原样重放。
created = client.post(path + "/candidates", json=command,
headers={"Idempotency-Key": key}).json()
candidate_id = created["candidates"][0]["id"]
# 轮询 /candidates?shot_id=...&kind=frame 或接收owner SSE;ready后人工预览。
story = client.get(path).json()
approved = client.post(path + "/selections", json={
"expected_version": story["version"], "shot_id": shot_id,
"kind": "frame", "candidate_id": candidate_id
}, headers={"Idempotency-Key": uuid.uuid4().hex})
approved.raise_for_status()
```
批准首帧后,以 `kind="video"`、`source_kind="generated"` 创建视频候选,预览后再用相同选择接口确认选片。人工首帧或视频以 `source_kind="manual",asset_id="本人素材ID"` 导入;人工视频不要求无用的首帧或提示词。调用 `/readiness` 为ready后,POST `/renders`,body为 `{expected_version,execution_mode}`,同样保存幂等键;返回原有RunSnapshot,后续通过 `/workflow-runs/{id}` 查询。冻结后的 `run.frozen_spec` 和 `run.render_inputs` 用于历史复查。
PATCH 故事使用 `If-Match: 当前version`。批准信息通过对应的选择端点写入,清除批准使用 POST `/selections/clear`。单独删除候选也需要 `If-Match`,当前选择和其他记录的引用会受保护。机器令牌使用 `workflows` 权限。账号事件包括 `story.updated`、`candidate.updated`、`selection.updated`。断流或 reset 后应重新读取快照。
DELETE `/stories/{id}` 携带故事当前版本的 `If-Match`。一次请求会删除故事、关联工作流和子任务,以及仅用于该故事的未收藏素材。已收藏或被其他作品引用的素材会保留。HTTP 200 表示清理完成,HTTP 202 及 `pending: true` 表示故事已从列表移除,服务端正在取消任务并继续清理。
## H3 原生对白自动成片(本地实现)
此流程需要升级并实测认证后的上游推理服务。当前本地代码改造不会自动升级服务器,不能根据旧 H3 或 MuseTalk 可用状态判断原生功能可用。以下沿用已登录、已配置CSRF的 `client` 及本人故事 `draft_id`。
```python
import uuid
editor_path = f"/editors/{draft_id}"
editor = client.get(editor_path).json()
# 该命令也用于显式升级旧V5草稿;不会修改已冻结历史任务。
response = client.post(editor_path + "/dialogue/enable", json={
"expected_version": editor["version"]
}, headers={"Idempotency-Key": uuid.uuid4().hex})
response.raise_for_status()
editor = response.json()
manifest = editor["manifest"]
assert manifest["spec"]["dialogue"]["generation"] == "native_av"
# 在manifest中完善speakers / utterances / sequences及每镜performance。
# speaker.native_voice例:“年轻男性,清亮中音,语速平稳,咬字清楚”。
# utterance.text保存完整台词;native_utterance_ids按原顺序分配整句,[]表示无对白。
# 文本台词沿用source='tts'标签;在native_av模式它由H3直接生成,不创建TTS步骤。
# 每镜最多一名可见人物;旧参考录音/录音台词须由用户明确解除或转换。
# 背景乐放audio.layers,不再创建独立TTS旁白或MuseTalk步骤。
saved = client.post(editor_path + "/save", json={
"expected_version": editor["version"], "manifest": manifest
}, headers={"Idempotency-Key": uuid.uuid4().hex})
saved.raise_for_status()
editor = saved.json()
caps = client.get("/capabilities").json()
native = caps.get("dialogue", {}).get("native_av", {})
if not native.get("available"):
raise RuntimeError(native.get("reason") or "上游尚未完成原生音视频和逐词识别认证")
command = {"expected_version": editor["version"], "output_goal": "film",
"targets": [], "force": [], "execution_mode": "interactive"}
planned = client.post(editor_path + "/plan", json=command)
planned.raise_for_status()
plan = planned.json()
if plan["issues"]:
raise RuntimeError(plan["issues"])
body = {**command, "expected_plan_hash": plan["plan_hash"]}
key = uuid.uuid4().hex # 持久保存精确body和key;超时原样重放。
created = client.post(editor_path + "/runs", json=body,
headers={"Idempotency-Key": key})
created.raise_for_status()
```
通过 `/workflow-runs/{id}` 查询完成及应用结果,勿因HTTP超时新建重复任务。仅改字幕或配乐后再次保存并计划film,可复用有效H3素材;修改角色声线或台词则重生成受影响镜头的完整音视频。局部目标可选 `video:<shot_id>`;重新测时使用 `native_alignment:<shot_id>` 的force,重新识别而不重生成视频。`captions`支持字幕重编译。计划存在遗漏、重复分配、超过整镜容量、锁定冲突或能力缺失时先处理问题,不伪造质检报告或时间戳。字幕以实际生成音轨为准,人工文案与时间保护仍保留。