chore: checkpoint verified visual studio baseline
11
.dockerignore
Normal file
@ -0,0 +1,11 @@
|
||||
.git
|
||||
**/.env*
|
||||
!**/.env.example
|
||||
**/.venv
|
||||
**/node_modules
|
||||
**/data
|
||||
**/__pycache__
|
||||
**/.pytest_cache
|
||||
**/*.log
|
||||
**/.inference-key
|
||||
qa
|
||||
15
.env.example
Normal file
@ -0,0 +1,15 @@
|
||||
# Copy to .env on the server. This file contains no working credentials.
|
||||
CMVR_MODE=production
|
||||
MYSQL_HOST=192.168.28.10
|
||||
MYSQL_PORT=3306
|
||||
MYSQL_DATABASE=cmvr-visual
|
||||
MYSQL_USER=
|
||||
MYSQL_PASSWORD=
|
||||
ADMIN_USERNAME=admin
|
||||
ADMIN_DISPLAY_NAME=管理员
|
||||
ADMIN_PASSWORD=
|
||||
# Set true behind public HTTPS. False is only for loopback HTTP/SSH preview.
|
||||
COOKIE_SECURE=false
|
||||
TTS_API_KEY=
|
||||
WORKSPACE_HOST=/data/llmusers/llmuser/workspace
|
||||
WEB_PORT=18193
|
||||
20
.gitignore
vendored
Normal file
@ -0,0 +1,20 @@
|
||||
**/.env
|
||||
**/.env.*
|
||||
!**/.env.example
|
||||
!**/.env.test.example
|
||||
**/.venv/
|
||||
**/__pycache__/
|
||||
**/.pytest_cache/
|
||||
**/node_modules/
|
||||
**/dist/
|
||||
**/data/
|
||||
**/.coverage
|
||||
**/coverage/
|
||||
**/test-results/
|
||||
**/playwright-report/
|
||||
**/*.log
|
||||
**/.inference-key
|
||||
**/*credentials*.json
|
||||
/.deploy/
|
||||
/.cache-models/
|
||||
/.local/
|
||||
220
README.md
Normal file
@ -0,0 +1,220 @@
|
||||
# CMVR Visual
|
||||
|
||||
面向本地模型的创作工作台:Vue 3、Element Plus、Pinia 前端,FastAPI、SQLAlchemy async、MySQL 后端,通过 HTTP 和 SSE 提供登录、素材管理、异步任务与实时状态。
|
||||
|
||||
## 当前交付状态
|
||||
|
||||
- 工程目录:`E:\workspace\hybrid\cmvr-visual`;服务器源码目录:`/workspace/projects/cmvr-visual`。
|
||||
- 已连接用户指定的正式数据库 `192.168.28.10:3306/cmvr-visual`,按本次要求暂用 root;创建六张本应用 `visual_*` 表和默认网站管理员。`/api/system/status` 返回 `environment=production`、`database_backend=mysql`。
|
||||
- 默认管理员为 `admin`,初始密码按用户指定的本次私有配置设置;初始管理员支持六位密码,普通用户创建仍要求12位以上。重启不会重置已有密码。后续补账号维护、改密与专用数据库账号,详见复核方案。
|
||||
- 本机私有 `.env.server` 保存当前服务器配置,`.env.preview` 仅保留旧验收库配置。原独立 MySQL 与样例数据没有自动迁入正式库;秘密不提交Git、不打印到日志、不复制进文档。`.env.example` 不含可用密码。
|
||||
- 网站仅发布服务器 `127.0.0.1:18193`,当前通过受信 SSH 隧道本地访问;不直接向局域网或互联网公开。
|
||||
|
||||
执行结果以实际验收记录及接口状态为准。单元测试、模拟上游边界和构建成功分别验证各自范围,不等同于真实模型生成或正式数据库验收。
|
||||
|
||||
历史功能基线见 [验收报告](docs/验收报告.md):75项自动化测试、八类真实服务调用及桌面/手机验证。正式库接入后新增初始账号回归,后端52项通过;[实际接入记录](qa/mysql-integration-20261110.json)验证正式库登录、读写与SSE。
|
||||
|
||||
最新 [需求复核与落地方案](docs/需求复核与落地方案_20261110.md) 已纳入用户确认的“三分镜合成15秒”和“交互全天/批量夜间”。这两项与审计修复仍为待实施计划;当前视频生成单任务仍约5秒,调度仍只有单次预约。
|
||||
|
||||
二次可实施性复审见 [实施方案V2](docs/实施方案V2_20261110.md) 和 [12项执行计划](docs/superpowers/plans/2026-11-10-cmvr-visual-v2.md):补齐上游协议、执行代次、分镜依赖、夜间停止确认、批次/资源阶段、时间轴、迁移与恢复。V2尚未实施,Qwen批量须先验证单请求停止能力。
|
||||
|
||||
## 八项能力与实际限制
|
||||
|
||||
| 任务类型 | 后端 | 实际能力与边界 |
|
||||
| --- | --- | --- |
|
||||
| `image.generate` | 既有 Qwen-Image GPU 队列 | 文本生成图片;默认 1024²、50 步。不提供图像编辑或 LoRA 管理。 |
|
||||
| `video.generate` | 既有 Wan2.2-TI2V-5B,可接 Real-ESRGAN | 文生视频或参考首帧;最多 121 帧、24 fps,约 **5 秒**,可选 1080p 增强。不是 15 秒生成,也不附带声音。 |
|
||||
| `defect.generate` | SDXL + Canny ControlNet | 根据参考图片边缘约束生成条件样本,输出合成图和控制图;**控制图不是缺陷真值 mask**。 |
|
||||
| `audio.transcribe` | 既有 Whisper large-v3-turbo | 音频或有声视频转写;视频先在 CPU 提取音轨,最长 1800 秒。时间戳是约 30 秒分块边界,不是逐词对齐。 |
|
||||
| `math.solve` | 既有 Qwen 文本 HTTP 服务 | 数学解答文本;没有形式化证明或专业正确率验收承诺。 |
|
||||
| `media.structure` | Qwen 视觉 HTTP + CPU 抽帧 | 图片理解、视频实际抽帧后的主体/场景/OCR/标签。均匀抽帧不等同于完整镜头切分。 |
|
||||
| `video.compose` | CPU FFmpeg | 片段排序、裁切、直切拼接、上传音轨和人工字幕;最多 24 段、总长 30 分钟,帧率 24/25/30/60。没有热度预测。 |
|
||||
| `audio.speech` | 独立 Kokoro-82M **CPU** 服务 | 中文配音 WAV,当前音色 `zf_xiaobei`、`zm_yunxi`;语速 0.5–2。仅在配置真实服务后启用,不提供音乐生成。 |
|
||||
|
||||
参数约束以登录后的 `/api/capabilities` 为准。生成步数字段为 `num_inference_steps`。只有图片和条件样本支持 `count=1..4`,批次拆成独立任务,种子按序递增。没有真实生成进度来源时 `progress=null`,界面不编造百分比。
|
||||
|
||||
## 项目分层与通信
|
||||
|
||||
```text
|
||||
浏览器 Vue / Pinia
|
||||
│ 同源 HTTP:登录、上传、查询、取消、下载
|
||||
│ SSE:持久任务/素材事件与断线重放
|
||||
Nginx → FastAPI 业务 API → MySQL visual_* 表
|
||||
│
|
||||
├─ 持久协调器 → 既有 GPU jobs API
|
||||
├─ Qwen 文本/视觉 HTTP
|
||||
└─ CPU FFmpeg / 独立 CPU Kokoro
|
||||
```
|
||||
|
||||
`frontend/` 为界面;`backend/app/` 为账号、素材、任务、事件和协调器;`providers.py`、`media.py` 为数据库无关的模型与媒体适配;`tts/` 为 CPU 配音服务;`deploy/`、`compose.yaml` 为部署文件;[API 示例](docs/API-examples.md) 和 [共享契约](docs/api-contract.md) 说明调用方式。
|
||||
|
||||
任务提交是短 HTTP 请求,长任务通过 SSE 单向通知浏览器,不需要双向 WebSocket。事件先和数据库状态一起提交;`Last-Event-ID` 用于重连重放,Cookie 使原生 EventSource 无需把令牌放进 URL。SSE 断开不会取消生成,重连后还会重新获取 HTTP 状态快照。[SSE 标准](https://html.spec.whatwg.org/multipage/server-sent-events.html)
|
||||
|
||||
后端只使用 CPU,不持有 GPU。新模型始终由已部署的 `llmuser` 队列/守护执行:一次只选择一张空闲 GPU 执行一个任务,其他用户优先;运行中发现外部占卡,会清理自己的模型进程并用**同一上游 ID**重新排队。网站保留 `running → queued`、尝试次数和让卡记录,不创建替代生成。
|
||||
|
||||
上游提交前持久化完整请求和固定幂等键;响应丢失时只原样重试同一请求、同一键取回 ID。ID 已知后只查询或取消。最终输出下载失败只重试导入;多文件结果全部导入成功后才一起公开。取消先于归档事务提交时,取消优先;明确点击“再次生成”则创建新的业务任务。
|
||||
|
||||
## 路径与隔离
|
||||
|
||||
| 用途 | 路径 / 设置 |
|
||||
| --- | --- |
|
||||
| 宿主工作区 | `/data/llmusers/llmuser/workspace` |
|
||||
| 容器共享工作区 | `/workspace` |
|
||||
| 服务器网站源码 | `/workspace/projects/cmvr-visual` |
|
||||
| 素材 | `/workspace/cmvr-visual/assets` |
|
||||
| CPU 工作目录与导入暂存 | `/workspace/cmvr-visual/jobs` |
|
||||
| 协调器锁 | `/workspace/cmvr-visual/state/coordinator.lock` |
|
||||
| 容器 UID:GID | `1013:1014` |
|
||||
| 专用 Docker 网络 | `cmvr-visual-net` |
|
||||
| 模型 API | Docker 网络内 `http://llmuser-workspace:18190` |
|
||||
| 模型认证文件 | `/workspace/projects/llm-services/config/api_key`,仅后端读取 |
|
||||
|
||||
用户只提交素材 ID;服务器校验 owner 后解析共享工作区路径。素材内容、缩略图、Range 请求、任务和 SSE 都经过登录与归属校验,不将素材目录直接挂成公开静态目录。被任务引用的已删除输入仍保留物理文件。账号密码用加盐 scrypt,Cookie 为 HttpOnly;所有写操作除登录外均要求 CSRF 头。
|
||||
|
||||
API 和 TTS 容器不挂 GPU、宿主 `/proc`、Docker socket,不使用 privileged;根文件系统只读,工作数据只写入配置的工作区。现有 GPU 权重、模型队列、守护与其他用户服务**不由此工程重新部署**。
|
||||
|
||||
## 本地开发
|
||||
|
||||
需要 Python 3.11+、Node/pnpm;媒体探测和合成需 `ffmpeg`、`ffprobe` 在 PATH。本地 SQLite 仅是显式开发预览,不是 MySQL 故障后的自动回退。
|
||||
|
||||
PowerShell,在项目根目录执行:
|
||||
|
||||
```powershell
|
||||
python -m venv backend/.venv
|
||||
& ./backend/.venv/Scripts/python.exe -m pip install -r backend/requirements.txt
|
||||
New-Item -ItemType Directory -Force .local/workspace | Out-Null
|
||||
$env:CMVR_MODE = 'preview'
|
||||
$env:WORKSPACE_ROOT = (Resolve-Path .local/workspace).Path
|
||||
$dbPath = Join-Path (Resolve-Path .local).Path 'preview.sqlite3'
|
||||
$env:DATABASE_URL = 'sqlite+aiosqlite:///' + $dbPath.Replace('\', '/')
|
||||
$env:COOKIE_SECURE = 'false'
|
||||
$env:INFERENCE_BASE_URL = ''
|
||||
$env:ADMIN_USERNAME = Read-Host '初始管理员账号'
|
||||
$adminSecret = Read-Host '初始管理员密码(至少12字符)' -AsSecureString
|
||||
$env:ADMIN_PASSWORD = [Net.NetworkCredential]::new('', $adminSecret).Password
|
||||
& ./backend/.venv/Scripts/python.exe -m uvicorn app.main:app --app-dir backend --host 127.0.0.1 --port 8000 --workers 1
|
||||
```
|
||||
|
||||
另开终端:
|
||||
|
||||
```powershell
|
||||
cd frontend
|
||||
pnpm install --frozen-lockfile
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
访问 `http://127.0.0.1:5173`。Vite 将 `/api` 同源代理到 `127.0.0.1:8000`。开发进程不会自动加载 `.env`;须显式设置环境或使用受控的环境文件加载方式。首次启动仅在账号不存在时创建管理员,重复启动不会用环境变量重置已有密码。无默认密码、无公开注册。
|
||||
|
||||
上例主动禁用 GPU 入口:Windows 本地文件路径不能作为远端模型的 `/workspace` 路径。真实生成使用下述同机 Docker 部署。数学/视觉、FFmpeg、配音是否可用取决于实际服务和本地程序配置;不会在缺失时生成假结果。
|
||||
|
||||
测试与前端构建:
|
||||
|
||||
```powershell
|
||||
cd backend
|
||||
& ./.venv/Scripts/python.exe -m pytest -q
|
||||
cd ../frontend
|
||||
pnpm test
|
||||
pnpm build
|
||||
```
|
||||
|
||||
缺少 FFmpeg 时相关媒体集成测试会跳过,Linux 的实际媒体测试应单独执行。不要据 SQLite 测试推断正式 MySQL 已连接。
|
||||
|
||||
## 正式 MySQL 配置
|
||||
|
||||
目标库 `192.168.28.10:3306/cmvr-visual` 已实际接入,当前按用户要求暂用 root,之后再创建独立数据库业务账号。DBA 可参考 [最小权限 SQL 示例](deploy/production.sql.example),仅授权本库并限制账号来源;不读取或复用其他项目的秘密。
|
||||
|
||||
私有 `.env` 至少配置 `CMVR_MODE=production`、`MYSQL_HOST`、`MYSQL_PORT`、`MYSQL_DATABASE`、`MYSQL_USER`、`MYSQL_PASSWORD` 及管理员初始化信息。推荐这些分离字段,后端用 `URL.create` 处理数据库名与密码特殊字符;不要手工拼接连接串。正式库不可达时启动失败,不会切换 SQLite。
|
||||
|
||||
应用仅创建以下表:`visual_users`、`visual_sessions`、`visual_assets`、`visual_jobs`、`visual_job_assets`、`visual_job_events`。当前启动使用 `create_all`,**没有自动迁移工具**:它不会删除现有数据,也不会替已有表添加新字段。升级前备份并审查 schema 差异,在独立库演练迁移;不能靠删表、删库或清队列解决字段不一致。
|
||||
|
||||
## Docker Compose 启动
|
||||
|
||||
运维在宿主源码目录 `/data/llmusers/llmuser/workspace/projects/cmvr-visual` 操作。先将前端构建为 `frontend/dist`,因为前端镜像直接复制该目录:
|
||||
|
||||
也可在本机 `E:\workspace\hybrid\cmvr-visual\frontend` 执行 `pnpm install --frozen-lockfile`、`pnpm build`,再将生成的 `dist` 同步到服务器 `frontend/dist`。本次验收采用这一方式;服务器镜像构建不依赖宿主 Node/pnpm。
|
||||
|
||||
```bash
|
||||
cd /data/llmusers/llmuser/workspace/projects/cmvr-visual
|
||||
cp .env.example .env
|
||||
chmod 600 .env
|
||||
# 用本机安全编辑器填写专用数据库与管理员秘密;不把秘密写进命令历史。
|
||||
cd frontend
|
||||
pnpm install --frozen-lockfile
|
||||
pnpm build
|
||||
cd ..
|
||||
```
|
||||
|
||||
已有配置时不要重新覆盖 `.env`。预览环境的 `.env.preview` 是独立秘密记录,不能原样当成正式账号配置。本 Compose 的 API 使用 `env_file: .env`;仅加 `--env-file .env.preview` 不会替换这条容器环境文件设置。检查时使用 `docker compose config --quiet`,不要打印会展开秘密的完整配置。[Compose 环境插值说明](https://docs.docker.com/compose/how-tos/environment-variables/variable-interpolation/)
|
||||
|
||||
首次确认专用网络存在,并确认既有模型容器已接入;只在尚未创建/连接时执行对应命令:
|
||||
|
||||
```bash
|
||||
docker network inspect cmvr-visual-net
|
||||
# 网络不存在时:
|
||||
docker network create cmvr-visual-net
|
||||
# llmuser-workspace 尚未接入此网络时:
|
||||
docker network connect cmvr-visual-net llmuser-workspace
|
||||
```
|
||||
|
||||
确认共享目录可由 `1013:1014` 写入;不要递归修改其他模型或其他业务目录的所有权。Kokoro 所需的清单权重需预先放入 `/workspace/models/kokoro-82m`。首次缺失时,可在既有工作区容器内用清单下载并校验:
|
||||
|
||||
```bash
|
||||
docker exec --user 1013:1014 llmuser-workspace /workspace/.venv/bin/python \
|
||||
/workspace/projects/cmvr-visual/scripts/download_tts_models.py \
|
||||
--manifest /workspace/projects/cmvr-visual/deploy/kokoro-manifest.json
|
||||
```
|
||||
|
||||
这只准备独立 CPU 配音模型,不安装或重启既有 GPU 服务。之后:
|
||||
|
||||
```bash
|
||||
docker compose config --quiet
|
||||
docker compose up -d --build api tts frontend
|
||||
docker compose ps
|
||||
docker compose logs --tail=100 api
|
||||
```
|
||||
|
||||
主 `compose.yaml` **不创建 preview-db 或任何生产数据库**。独立 MySQL 8 预览实例由运维单独管理。网站 API 固定单进程 `--workers 1`,协调器另持有工作区文件锁;当前不支持多 API 实例或分布式调度。
|
||||
|
||||
更新镜像使用 `docker compose up -d --build api tts frontend`。只改 `.env` 时使用 `docker compose up -d --force-recreate api tts` 让配置进入容器,单纯 `restart` 不会重新注入环境。停止本工程使用 `docker compose stop frontend api tts`;不要操作既有 GPU worker、全局 Docker/systemd,或使用全局清理命令。
|
||||
|
||||
## 访问方式与对外安全边界
|
||||
|
||||
当前宿主只监听 `127.0.0.1:18193`。从客户端建立隧道:
|
||||
|
||||
```bash
|
||||
ssh -N -L 127.0.0.1:18193:127.0.0.1:18193 root@192.168.28.10
|
||||
```
|
||||
|
||||
使用已有获准的运维 SSH 账号;`root` 仅是当前运维连接示例,命令没有内嵌密码。受限 `llmuser` 的 SSH 转发已禁用,不要为了网站访问放开其隔离规则。上述命令后访问 `http://127.0.0.1:18193`;当前已建立的隧道入口为 `http://127.0.0.1:8000`。默认管理员配置由本机私有 `.env.server` 安全取得,不在控制台回显。
|
||||
|
||||
当前回环 HTTP/SSH 验收使用 `COOKIE_SECURE=false`。互联网或不可信网络访问必须先配置 HTTPS 反代或受信加密隧道,并在 HTTPS 浏览器入口使用 `COOKIE_SECURE=true`。保持前后端同源;Cookie 为 HttpOnly/SameSite,CSRF 校验不得移除,推理密钥不得进入前端变量或 URL。
|
||||
|
||||
`deploy/nginx.conf` 已配置同源 CSP,限制脚本、媒体、网络连接来源。任何外层反代也要保持 SSE 不缓冲、不缓存,超时大于心跳间隔,并透传 `Range`、Cookie 和 CSRF 头,不要将素材端点改成绕过鉴权的静态文件服务。当前 API 支持单个字节 Range;多区间请求不支持。[Nginx proxy_buffering](https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_buffering)
|
||||
|
||||
## 备份与排查
|
||||
|
||||
备份必须包含正式库中的 `visual_*` 表、`/workspace/cmvr-visual/assets`、`jobs` 和 `state`;后两者含持久请求引用的预处理输入。秘密配置单独安全保管。网站备份不包含 GPU 模型权重或上游队列,相关结果保留策略由既有模型服务管理。
|
||||
|
||||
使用 DBA 的受保护客户端配置文件,不把密码作为命令参数。以下仅为备份步骤示例,需先准备兼容的 MySQL 客户端及安全目录:
|
||||
|
||||
```bash
|
||||
docker compose stop api
|
||||
# /secure/cmvr-visual-backup.cnf 由运维安全创建,权限600,不属于源码。
|
||||
mysqldump --defaults-extra-file=/secure/cmvr-visual-backup.cnf \
|
||||
--single-transaction --no-tablespaces --set-gtid-purged=OFF \
|
||||
cmvr-visual visual_users visual_sessions visual_jobs visual_assets visual_job_assets visual_job_events \
|
||||
> /secure/backups/cmvr-visual.sql
|
||||
tar -czf /secure/backups/cmvr-visual-files.tar.gz \
|
||||
-C /data/llmusers/llmuser/workspace/cmvr-visual assets jobs state
|
||||
docker compose up -d api
|
||||
```
|
||||
|
||||
先在独立数据库验证恢复,不将全库恢复脚本覆盖其他业务。API 停止不会自动取消已提交的上游 GPU 任务,重启后继续按同一 ID 查询。
|
||||
|
||||
- 页面显示验收环境:查看 `/api/system/status` 的 `environment` 与 `database_backend`,不要把它当成正式库故障。
|
||||
- 登录失败:检查是否设置管理员初始账号、密码和正确的 Cookie Secure/TLS 组合;已有账号不会被 bootstrap 重置。
|
||||
- 四卡繁忙或外部用户占卡:任务可能保持 queued 或从 running 回 queued,这是既有让卡策略;不要新建替代任务或手动删上游锁。
|
||||
- `sync_warning`:网络或产物导入正在恢复,不等于生成失败。
|
||||
- collecting:推理已完成,正在归档;当前不再接受新的取消。归档之前已提交的取消仍有事务优先保护。
|
||||
- SSE 不更新:检查外层代理缓冲/超时、会话是否有效,重新获取 HTTP 快照;不要为了重连再次生成。
|
||||
- `stale`/上游执行器异常:检查日志并交运维确认,不能删除数据库、锁或守护状态强制运行。
|
||||
8
backend/.dockerignore
Normal file
@ -0,0 +1,8 @@
|
||||
.venv
|
||||
data
|
||||
__pycache__
|
||||
**/__pycache__
|
||||
.pytest_cache
|
||||
.env*
|
||||
tests
|
||||
*.log
|
||||
27
backend/.env.example
Normal file
@ -0,0 +1,27 @@
|
||||
CMVR_MODE=production
|
||||
MYSQL_HOST=192.168.28.10
|
||||
MYSQL_PORT=3306
|
||||
MYSQL_DATABASE=cmvr-visual
|
||||
MYSQL_USER=
|
||||
MYSQL_PASSWORD=
|
||||
WORKSPACE_ROOT=/workspace
|
||||
ASSET_ROOT=/workspace/cmvr-visual/assets
|
||||
JOB_WORK_ROOT=/workspace/cmvr-visual/jobs
|
||||
STATE_ROOT=/workspace/cmvr-visual/state
|
||||
ADMIN_USERNAME=
|
||||
ADMIN_PASSWORD=
|
||||
ADMIN_DISPLAY_NAME=管理员
|
||||
COOKIE_SECURE=true
|
||||
RUN_COORDINATOR=true
|
||||
INFERENCE_BASE_URL=http://llmuser-workspace:18190
|
||||
INFERENCE_API_KEY_FILE=/workspace/projects/llm-services/config/api_key
|
||||
GPU_STATUS_PATH=/run/llm-gpu-policy/status.json
|
||||
GPU_SCHEDULER_PATH=/workspace/projects/llm-services/state/gpu-scheduler.json
|
||||
QWEN_BASE_URL=http://192.168.28.10:14081/v1
|
||||
QWEN_MODEL=Qwen/Qwen3.8-27B-FP8
|
||||
QWEN_API_KEY=
|
||||
TTS_BASE_URL=
|
||||
TTS_MODEL=
|
||||
TTS_API_KEY=
|
||||
FFMPEG_BIN=ffmpeg
|
||||
FFPROBE_BIN=ffprobe
|
||||
9
backend/Dockerfile
Normal file
@ -0,0 +1,9 @@
|
||||
FROM python:3.12-slim
|
||||
ENV PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 PIP_NO_CACHE_DIR=1
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends ffmpeg fonts-noto-cjk && rm -rf /var/lib/apt/lists/*
|
||||
WORKDIR /opt/app
|
||||
COPY requirements.txt ./requirements.txt
|
||||
RUN pip install -r requirements.txt
|
||||
COPY app ./app
|
||||
USER 1013:1014
|
||||
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "1"]
|
||||
1
backend/app/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
"""CMVR Visual CPU business backend."""
|
||||
277
backend/app/assets.py
Normal file
@ -0,0 +1,277 @@
|
||||
import asyncio
|
||||
import hashlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import stat
|
||||
from urllib.parse import quote
|
||||
from fastapi import APIRouter, Depends, File, Form, Request, Response, UploadFile
|
||||
from fastapi.responses import StreamingResponse
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy import func, select
|
||||
from starlette.background import BackgroundTask
|
||||
from .auth import Actor, csrf_actor, current_actor
|
||||
from .dto import asset_dto
|
||||
from .errors import fail
|
||||
from .events import emit_asset, emit_job
|
||||
from .models import Asset, Job, JobAsset, new_id, utcnow
|
||||
|
||||
router = APIRouter(prefix="/assets", tags=["assets"])
|
||||
|
||||
|
||||
def confined(root, value, *, exists=False):
|
||||
root = Path(root).resolve()
|
||||
path = Path(value)
|
||||
path = (path if path.is_absolute() else root / path).resolve(strict=exists)
|
||||
if not path.is_relative_to(root):
|
||||
raise ValueError("File is outside its permitted directory")
|
||||
return path
|
||||
|
||||
|
||||
def safe_file(root, value):
|
||||
path = confined(root, value, exists=True)
|
||||
fd = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0))
|
||||
try:
|
||||
if not stat.S_ISREG(os.fstat(fd).st_mode):
|
||||
raise ValueError("Regular file required")
|
||||
if os.name == "posix":
|
||||
confined(root, os.readlink(f"/proc/self/fd/{fd}"), exists=True)
|
||||
return os.fdopen(fd, "rb")
|
||||
except BaseException:
|
||||
os.close(fd)
|
||||
raise
|
||||
|
||||
|
||||
async def owned_asset(session, asset_id, owner_id, *, include_deleted=False):
|
||||
query = select(Asset).where(Asset.id == asset_id, Asset.owner_id == owner_id, Asset.ready.is_(True))
|
||||
if not include_deleted:
|
||||
query = query.where(Asset.deleted_at.is_(None))
|
||||
asset = await session.scalar(query)
|
||||
if asset is None:
|
||||
fail(404, "asset_not_found", "素材不存在")
|
||||
return asset
|
||||
|
||||
|
||||
async def touch_source_job(session, asset):
|
||||
if asset.source_job_id:
|
||||
source = await session.scalar(select(Job).where(Job.id == asset.source_job_id, Job.owner_id == asset.owner_id))
|
||||
if source is not None:
|
||||
await emit_job(session, source)
|
||||
|
||||
|
||||
async def build_asset(settings, owner_id, asset_id, path, name, **fields):
|
||||
from .media import inspect_media, make_thumbnail
|
||||
path = confined(settings.asset_root, path, exists=True)
|
||||
metadata = await inspect_media(path, settings)
|
||||
def hash_file():
|
||||
digest = hashlib.sha256()
|
||||
with safe_file(settings.asset_root, path) as source:
|
||||
while chunk := source.read(1024 * 1024):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
digest = await asyncio.to_thread(hash_file)
|
||||
thumbnail = await make_thumbnail(path, path.with_name("thumbnail.jpg"), settings)
|
||||
return Asset(id=asset_id, owner_id=owner_id, name=name[:255],
|
||||
storage_key=path.relative_to(settings.asset_root).as_posix(),
|
||||
thumbnail_key=Path(thumbnail).relative_to(settings.asset_root).as_posix() if thumbnail else None,
|
||||
kind=metadata["kind"], mime_type=metadata["mime_type"], size_bytes=path.stat().st_size,
|
||||
sha256=digest, width=metadata.get("width"), height=metadata.get("height"),
|
||||
duration_seconds=metadata.get("duration_seconds"), tags=[], favorite=False, **fields)
|
||||
|
||||
|
||||
async def import_output(db, settings, job, source, index):
|
||||
async with db.session() as session:
|
||||
existing = await session.scalar(select(Asset).where(Asset.source_job_id == job.id,
|
||||
Asset.source_output_index == index))
|
||||
if existing:
|
||||
return existing
|
||||
asset_id = new_id()
|
||||
source = confined(settings.job_work_root, source, exists=True)
|
||||
directory = confined(settings.asset_root, Path(job.owner_id) / asset_id)
|
||||
directory.mkdir(parents=True)
|
||||
suffix = source.suffix.lower() if re.fullmatch(r"\.[a-z0-9]{1,10}", source.suffix.lower()) else ".bin"
|
||||
destination = directory / ("original" + suffix)
|
||||
def copy():
|
||||
with safe_file(settings.job_work_root, source) as src, destination.open("xb") as dst:
|
||||
shutil.copyfileobj(src, dst, 1024 * 1024)
|
||||
try:
|
||||
await asyncio.to_thread(copy)
|
||||
asset = await build_asset(settings, job.owner_id, asset_id, destination, source.name,
|
||||
origin="generated", source_job_id=job.id, source_upstream_id=job.upstream_id,
|
||||
source_output_index=index, ready=False)
|
||||
async with db.session() as session:
|
||||
session.add(asset)
|
||||
await session.flush()
|
||||
await session.commit()
|
||||
return asset
|
||||
except BaseException:
|
||||
shutil.rmtree(directory, ignore_errors=True)
|
||||
raise
|
||||
|
||||
|
||||
@router.post("", status_code=201)
|
||||
async def upload(request: Request, file: UploadFile = File(), name: str | None = Form(default=None),
|
||||
actor: Actor = Depends(csrf_actor)):
|
||||
settings = request.app.state.settings
|
||||
asset_id = new_id()
|
||||
directory = confined(settings.asset_root, Path(actor.id) / asset_id)
|
||||
directory.mkdir(parents=True)
|
||||
original_name = (file.filename or "素材").replace("\\", "/").rsplit("/", 1)[-1]
|
||||
suffix = Path(original_name).suffix.lower()
|
||||
if not re.fullmatch(r"\.[a-z0-9]{1,10}", suffix):
|
||||
suffix = ".bin"
|
||||
path, size = directory / ("original" + suffix), 0
|
||||
try:
|
||||
with path.open("xb") as output:
|
||||
while chunk := await file.read(1024 * 1024):
|
||||
size += len(chunk)
|
||||
if size > settings.max_upload_bytes:
|
||||
fail(413, "upload_too_large", "文件超过上传大小限制")
|
||||
output.write(chunk)
|
||||
if not size:
|
||||
fail(422, "empty_upload", "文件不能为空")
|
||||
asset = await build_asset(settings, actor.id, asset_id, path, name or original_name or "素材", origin="upload")
|
||||
if asset.kind not in {"image", "video", "audio"}:
|
||||
fail(422, "unsupported_upload", "上传仅支持图片、视频或音频")
|
||||
async with request.app.state.db.session() as session:
|
||||
session.add(asset)
|
||||
await session.flush()
|
||||
emit_asset(session, actor.id, "asset.created", {"asset": asset_dto(asset)})
|
||||
await session.commit()
|
||||
return asset_dto(asset)
|
||||
except BaseException as exc:
|
||||
shutil.rmtree(directory, ignore_errors=True)
|
||||
if hasattr(exc, "code") and hasattr(exc, "message"):
|
||||
fail(422, exc.code, exc.message)
|
||||
raise
|
||||
finally:
|
||||
await file.close()
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_assets(request: Request, page: int = 1, page_size: int = 24, kind: str = "", q: str = "", tag: str = "",
|
||||
actor: Actor = Depends(current_actor)):
|
||||
if page < 1 or not 1 <= page_size <= 100:
|
||||
fail(422, "invalid_page", "分页参数无效")
|
||||
async with request.app.state.db.session() as session:
|
||||
query = select(Asset).where(Asset.owner_id == actor.id, Asset.deleted_at.is_(None), Asset.ready.is_(True))
|
||||
if kind:
|
||||
query = query.where(Asset.kind == kind)
|
||||
if q:
|
||||
query = query.where(Asset.name.contains(q[:255], autoescape=True))
|
||||
# JSON tags are filtered in Python for equivalent MySQL/SQLite preview semantics.
|
||||
rows = (await session.scalars(query.order_by(Asset.created_at.desc(), Asset.id.desc()))).all()
|
||||
if tag:
|
||||
rows = [asset for asset in rows if tag in (asset.tags or [])]
|
||||
return {"items": [asset_dto(a) for a in rows[(page - 1) * page_size:page * page_size]],
|
||||
"total": len(rows), "page": page, "page_size": page_size}
|
||||
|
||||
|
||||
@router.get("/{asset_id}")
|
||||
async def get_asset(asset_id: str, request: Request, actor: Actor = Depends(current_actor)):
|
||||
async with request.app.state.db.session() as session:
|
||||
return asset_dto(await owned_asset(session, asset_id, actor.id))
|
||||
|
||||
|
||||
class AssetPatch(BaseModel):
|
||||
name: str | None = Field(default=None, min_length=1, max_length=255)
|
||||
tags: list[str] | None = Field(default=None, max_length=30)
|
||||
favorite: bool | None = None
|
||||
|
||||
|
||||
@router.patch("/{asset_id}")
|
||||
async def patch_asset(asset_id: str, body: AssetPatch, request: Request, actor: Actor = Depends(csrf_actor)):
|
||||
async with request.app.state.db.session() as session:
|
||||
asset = await owned_asset(session, asset_id, actor.id)
|
||||
if body.name is not None:
|
||||
asset.name = body.name.strip() or asset.name
|
||||
if body.tags is not None:
|
||||
if any(not tag.strip() or len(tag) > 64 for tag in body.tags):
|
||||
fail(422, "invalid_tag", "标签须为 1–64 个字符")
|
||||
asset.tags = list(dict.fromkeys(tag.strip() for tag in body.tags))
|
||||
if body.favorite is not None:
|
||||
asset.favorite = body.favorite
|
||||
emit_asset(session, actor.id, "asset.updated", {"asset": asset_dto(asset)})
|
||||
await touch_source_job(session, asset)
|
||||
await session.commit()
|
||||
return asset_dto(asset)
|
||||
|
||||
|
||||
@router.delete("/{asset_id}", status_code=204)
|
||||
async def delete_asset(asset_id: str, request: Request, actor: Actor = Depends(csrf_actor)):
|
||||
async with request.app.state.db.session() as session:
|
||||
asset = await owned_asset(session, asset_id, actor.id)
|
||||
asset.deleted_at = utcnow()
|
||||
referenced = await session.scalar(select(JobAsset.job_id).where(JobAsset.asset_id == asset_id).limit(1))
|
||||
storage = asset.storage_key
|
||||
emit_asset(session, actor.id, "asset.deleted", {"id": asset.id})
|
||||
await touch_source_job(session, asset)
|
||||
await session.commit()
|
||||
if referenced is None:
|
||||
try:
|
||||
path = confined(request.app.state.settings.asset_root, storage)
|
||||
shutil.rmtree(path.parent)
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
def file_response(settings, asset, key, range_header, download):
|
||||
try:
|
||||
handle = safe_file(settings.asset_root, key)
|
||||
except (ValueError, OSError):
|
||||
fail(404, "file_unavailable", "素材文件不可用")
|
||||
size = os.fstat(handle.fileno()).st_size
|
||||
start, end, code = 0, size - 1, 200
|
||||
if range_header:
|
||||
match = re.fullmatch(r"bytes=(\d*)-(\d*)", range_header.strip())
|
||||
try:
|
||||
if not match or not any(match.groups()):
|
||||
raise ValueError
|
||||
a, b = match.groups()
|
||||
if a:
|
||||
start, end = int(a), min(int(b), size - 1) if b else size - 1
|
||||
else:
|
||||
start, end = max(0, size - int(b)), size - 1
|
||||
if start > end or start >= size or start < 0:
|
||||
raise ValueError
|
||||
code = 206
|
||||
except ValueError:
|
||||
handle.close()
|
||||
return Response(status_code=416, headers={"Content-Range": f"bytes */{size}"})
|
||||
handle.seek(start)
|
||||
def chunks():
|
||||
remaining = end - start + 1
|
||||
try:
|
||||
while remaining > 0:
|
||||
data = handle.read(min(1024 * 1024, remaining))
|
||||
if not data:
|
||||
break
|
||||
remaining -= len(data)
|
||||
yield data
|
||||
finally:
|
||||
handle.close()
|
||||
headers = {"Accept-Ranges": "bytes", "Content-Length": str(max(0, end - start + 1)),
|
||||
"X-Content-Type-Options": "nosniff", "Cache-Control": "private, no-store",
|
||||
"Content-Disposition": ("attachment" if download else "inline") + "; filename*=UTF-8''" + quote(asset.name, safe="")}
|
||||
if code == 206:
|
||||
headers["Content-Range"] = f"bytes {start}-{end}/{size}"
|
||||
return StreamingResponse(chunks(), status_code=code, media_type="image/jpeg" if key != asset.storage_key else asset.mime_type,
|
||||
headers=headers, background=BackgroundTask(handle.close))
|
||||
|
||||
|
||||
@router.get("/{asset_id}/content")
|
||||
async def content(asset_id: str, request: Request, download: bool = False, actor: Actor = Depends(current_actor)):
|
||||
async with request.app.state.db.session() as session:
|
||||
asset = await owned_asset(session, asset_id, actor.id)
|
||||
return file_response(request.app.state.settings, asset, asset.storage_key, request.headers.get("range"), download)
|
||||
|
||||
|
||||
@router.get("/{asset_id}/thumbnail")
|
||||
async def thumbnail(asset_id: str, request: Request, actor: Actor = Depends(current_actor)):
|
||||
async with request.app.state.db.session() as session:
|
||||
asset = await owned_asset(session, asset_id, actor.id)
|
||||
if not asset.thumbnail_key and asset.kind != "image":
|
||||
fail(404, "thumbnail_unavailable", "预览图暂不可用")
|
||||
return file_response(request.app.state.settings, asset, asset.thumbnail_key or asset.storage_key, None, False)
|
||||
158
backend/app/auth.py
Normal file
@ -0,0 +1,158 @@
|
||||
import asyncio
|
||||
from dataclasses import dataclass
|
||||
from datetime import timedelta
|
||||
import hashlib
|
||||
import hmac
|
||||
import re
|
||||
import secrets
|
||||
from fastapi import APIRouter, Depends, Request, Response
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy import delete, select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from .errors import fail
|
||||
from .models import Session, User, utcnow
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||
COOKIE = "cmvr_session"
|
||||
|
||||
|
||||
def token_hash(token):
|
||||
return hashlib.sha256(token.encode()).hexdigest()
|
||||
|
||||
|
||||
def hash_password(password):
|
||||
salt = secrets.token_bytes(16)
|
||||
key = hashlib.scrypt(password.encode(), salt=salt, n=32768, r=8, p=1, dklen=64, maxmem=128 * 1024 * 1024)
|
||||
return f"scrypt$32768$8$1${salt.hex()}${key.hex()}"
|
||||
|
||||
|
||||
def verify_password(password, encoded):
|
||||
try:
|
||||
_, n, r, p, salt, expected = encoded.split("$")
|
||||
key = hashlib.scrypt(password.encode(), salt=bytes.fromhex(salt), n=int(n), r=int(r), p=int(p),
|
||||
dklen=64, maxmem=128 * 1024 * 1024)
|
||||
return hmac.compare_digest(key.hex(), expected)
|
||||
except (ValueError, TypeError):
|
||||
hashlib.scrypt(password.encode(), salt=b"\0" * 16, n=32768, r=8, p=1, maxmem=128 * 1024 * 1024)
|
||||
return False
|
||||
|
||||
|
||||
def validate_password(password, *, minimum=12):
|
||||
if not minimum <= len(password) <= 256:
|
||||
fail(422, "weak_password", f"密码长度须为 {minimum}–256 个字符")
|
||||
|
||||
|
||||
def user_dto(user):
|
||||
return {"id": user.id, "username": user.username, "display_name": user.display_name, "role": user.role}
|
||||
|
||||
|
||||
@dataclass
|
||||
class Actor:
|
||||
id: str
|
||||
username: str
|
||||
display_name: str
|
||||
role: str
|
||||
csrf_token: str
|
||||
token_hash: str
|
||||
|
||||
|
||||
async def current_actor(request: Request):
|
||||
token = request.cookies.get(COOKIE)
|
||||
if not token or len(token) > 512:
|
||||
fail(401, "not_authenticated", "请先登录")
|
||||
async with request.app.state.db.session() as session:
|
||||
row = (await session.execute(select(Session, User).join(User, User.id == Session.user_id)
|
||||
.where(Session.token_hash == token_hash(token), Session.expires_at > utcnow(),
|
||||
User.disabled.is_(False)))).first()
|
||||
if row is None:
|
||||
fail(401, "session_expired", "登录已失效,请重新登录")
|
||||
saved, user = row
|
||||
return Actor(user.id, user.username, user.display_name, user.role, saved.csrf_token, saved.token_hash)
|
||||
|
||||
|
||||
async def csrf_actor(request: Request, actor: Actor = Depends(current_actor)):
|
||||
supplied = request.headers.get("X-CSRF-Token", "")
|
||||
if not hmac.compare_digest(supplied.encode("utf-8"), actor.csrf_token.encode("utf-8")):
|
||||
fail(403, "csrf_failed", "请求校验失败,请刷新登录状态")
|
||||
# Same-origin proxy is the deployment default; reject explicitly cross-site writes.
|
||||
if request.headers.get("sec-fetch-site") == "cross-site":
|
||||
fail(403, "cross_site_request", "不允许跨站写入")
|
||||
return actor
|
||||
|
||||
|
||||
class Login(BaseModel):
|
||||
username: str = Field(min_length=1, max_length=64)
|
||||
password: str = Field(min_length=1, max_length=256)
|
||||
|
||||
|
||||
class CreateUser(Login):
|
||||
display_name: str = Field(default="", max_length=80)
|
||||
|
||||
|
||||
async def bootstrap_admin(db, settings):
|
||||
if not settings.admin_username and not settings.admin_password:
|
||||
return
|
||||
if not settings.admin_username or not settings.admin_password:
|
||||
raise ValueError("Both ADMIN_USERNAME and ADMIN_PASSWORD are required for bootstrap")
|
||||
# The initial account may use the operator's explicitly chosen six-character
|
||||
# password. Ordinary user creation keeps the 12-character minimum.
|
||||
validate_password(settings.admin_password, minimum=6)
|
||||
async with db.session() as session:
|
||||
exists = await session.scalar(select(User).where(User.username == settings.admin_username.strip().lower()))
|
||||
if exists is not None:
|
||||
return
|
||||
session.add(User(username=settings.admin_username.strip().lower(), display_name=settings.admin_display_name,
|
||||
role="admin", password_hash=await asyncio.to_thread(hash_password, settings.admin_password)))
|
||||
await session.commit()
|
||||
|
||||
|
||||
@router.post("/login")
|
||||
async def login(body: Login, request: Request, response: Response):
|
||||
async with request.app.state.db.session() as session:
|
||||
user = await session.scalar(select(User).where(User.username == body.username.strip().lower()))
|
||||
valid = await asyncio.to_thread(verify_password, body.password, user.password_hash if user else "")
|
||||
if not valid or user is None or user.disabled:
|
||||
fail(401, "invalid_credentials", "用户名或密码不正确")
|
||||
token, csrf = secrets.token_urlsafe(32), secrets.token_urlsafe(32)
|
||||
settings = request.app.state.settings
|
||||
session.add(Session(token_hash=token_hash(token), user_id=user.id, csrf_token=csrf,
|
||||
expires_at=utcnow() + timedelta(hours=settings.session_hours)))
|
||||
await session.commit()
|
||||
response.set_cookie(COOKIE, token, httponly=True, secure=settings.cookie_secure, samesite="lax",
|
||||
max_age=settings.session_hours * 3600, path="/")
|
||||
return {"user": user_dto(user), "csrf_token": csrf}
|
||||
|
||||
|
||||
@router.get("/me")
|
||||
async def me(actor: Actor = Depends(current_actor)):
|
||||
return {"user": {"id": actor.id, "username": actor.username, "display_name": actor.display_name, "role": actor.role},
|
||||
"csrf_token": actor.csrf_token}
|
||||
|
||||
|
||||
@router.post("/logout", status_code=204)
|
||||
async def logout(request: Request, actor: Actor = Depends(csrf_actor)):
|
||||
async with request.app.state.db.session() as session:
|
||||
await session.execute(delete(Session).where(Session.token_hash == actor.token_hash))
|
||||
await session.commit()
|
||||
response = Response(status_code=204)
|
||||
response.delete_cookie(COOKIE, path="/")
|
||||
return response
|
||||
|
||||
|
||||
@router.post("/users", status_code=201)
|
||||
async def create_user(body: CreateUser, request: Request, actor: Actor = Depends(csrf_actor)):
|
||||
if actor.role != "admin":
|
||||
fail(403, "admin_required", "此操作仅限管理员")
|
||||
username = body.username.strip().lower()
|
||||
if not re.fullmatch(r"[a-z0-9_.-]{3,64}", username):
|
||||
fail(422, "invalid_username", "用户名须为 3–64 位字母、数字、点、横线或下划线")
|
||||
validate_password(body.password)
|
||||
async with request.app.state.db.session() as session:
|
||||
user = User(username=username, display_name=body.display_name.strip() or username,
|
||||
password_hash=await asyncio.to_thread(hash_password, body.password))
|
||||
session.add(user)
|
||||
try:
|
||||
await session.commit()
|
||||
except IntegrityError:
|
||||
fail(409, "username_exists", "用户名已存在")
|
||||
return user_dto(user)
|
||||
109
backend/app/config.py
Normal file
@ -0,0 +1,109 @@
|
||||
from dataclasses import dataclass
|
||||
import os
|
||||
from pathlib import Path
|
||||
from sqlalchemy.engine import URL, make_url
|
||||
|
||||
|
||||
def boolean(value):
|
||||
return str(value).lower() in {"1", "true", "yes", "on"}
|
||||
|
||||
|
||||
@dataclass
|
||||
class Settings:
|
||||
mode: str = "production"
|
||||
database_url: str | None = None
|
||||
mysql_host: str = "192.168.28.10"
|
||||
mysql_port: int = 3306
|
||||
mysql_database: str = "cmvr-visual"
|
||||
mysql_user: str = ""
|
||||
mysql_password: str = ""
|
||||
workspace_root: Path = Path("/workspace")
|
||||
asset_root: Path | None = None
|
||||
job_work_root: Path | None = None
|
||||
state_root: Path | None = None
|
||||
admin_username: str = ""
|
||||
admin_password: str = ""
|
||||
admin_display_name: str = "管理员"
|
||||
cookie_secure: bool = True
|
||||
session_hours: int = 12
|
||||
run_coordinator: bool = True
|
||||
poll_seconds: float = 1.0
|
||||
event_heartbeat_seconds: float = 15.0
|
||||
max_upload_bytes: int = 512 * 1024 * 1024
|
||||
max_output_bytes: int = 2 * 1024 * 1024 * 1024
|
||||
request_timeout_seconds: float = 30.0
|
||||
inference_base_url: str = "http://llmuser-workspace:18190"
|
||||
inference_api_key: str = ""
|
||||
inference_api_key_file: Path | None = Path("/workspace/projects/llm-services/config/api_key")
|
||||
gpu_status_path: Path | None = Path("/run/llm-gpu-policy/status.json")
|
||||
gpu_scheduler_path: Path | None = Path("/workspace/projects/llm-services/state/gpu-scheduler.json")
|
||||
qwen_base_url: str = "http://192.168.28.10:14081/v1"
|
||||
qwen_model: str = "Qwen/Qwen3.8-27B-FP8"
|
||||
qwen_api_key: str = ""
|
||||
ffmpeg_bin: str = "ffmpeg"
|
||||
ffprobe_bin: str = "ffprobe"
|
||||
tts_base_url: str = ""
|
||||
tts_model: str = "kokoro-82m"
|
||||
tts_api_key: str = ""
|
||||
tts_voices: tuple[str, ...] = ("zf_xiaobei", "zm_yunxi")
|
||||
|
||||
def __post_init__(self):
|
||||
if self.mode not in {"production", "preview", "test"}:
|
||||
raise ValueError("CMVR_MODE must be production, preview or test")
|
||||
self.workspace_root = Path(self.workspace_root).resolve()
|
||||
for field, leaf in (("asset_root", "assets"), ("job_work_root", "jobs"), ("state_root", "state")):
|
||||
value = Path(getattr(self, field) or self.workspace_root / "cmvr-visual" / leaf).resolve()
|
||||
if not value.is_relative_to(self.workspace_root):
|
||||
raise ValueError(field + " must stay inside WORKSPACE_ROOT")
|
||||
setattr(self, field, value)
|
||||
for field in ("inference_api_key_file", "gpu_status_path", "gpu_scheduler_path"):
|
||||
if getattr(self, field):
|
||||
setattr(self, field, Path(getattr(self, field)))
|
||||
if self.database_url:
|
||||
url = make_url(self.database_url)
|
||||
if url.drivername.startswith("sqlite"):
|
||||
if self.mode not in {"preview", "test"} or url.drivername != "sqlite+aiosqlite":
|
||||
raise ValueError("SQLite requires explicit test/preview mode and the aiosqlite driver")
|
||||
elif url.drivername != "mysql+aiomysql":
|
||||
raise ValueError("Production database must use mysql+aiomysql")
|
||||
elif self.mode != "production":
|
||||
raise ValueError("Test/preview mode requires an explicit DATABASE_URL")
|
||||
elif not self.mysql_user or not self.mysql_password:
|
||||
raise ValueError("Production MySQL credentials must be configured")
|
||||
|
||||
@property
|
||||
def sqlalchemy_url(self):
|
||||
if self.database_url:
|
||||
return make_url(self.database_url)
|
||||
return URL.create("mysql+aiomysql", username=self.mysql_user, password=self.mysql_password,
|
||||
host=self.mysql_host, port=self.mysql_port, database=self.mysql_database,
|
||||
query={"charset": "utf8mb4"})
|
||||
|
||||
@classmethod
|
||||
def from_env(cls):
|
||||
env = os.environ
|
||||
values = {}
|
||||
strings = ("database_url", "mysql_host", "mysql_database", "mysql_user", "mysql_password",
|
||||
"admin_username", "admin_password", "admin_display_name", "inference_base_url",
|
||||
"inference_api_key", "qwen_base_url", "qwen_model", "qwen_api_key", "ffmpeg_bin", "ffprobe_bin",
|
||||
"tts_base_url", "tts_model", "tts_api_key")
|
||||
for field in strings:
|
||||
if field.upper() in env:
|
||||
values[field] = env[field.upper()]
|
||||
for field in ("workspace_root", "asset_root", "job_work_root", "state_root", "inference_api_key_file",
|
||||
"gpu_status_path", "gpu_scheduler_path"):
|
||||
if field.upper() in env:
|
||||
values[field] = Path(env[field.upper()]) if env[field.upper()] else None
|
||||
for field in ("mysql_port", "session_hours", "max_upload_bytes", "max_output_bytes"):
|
||||
if field.upper() in env:
|
||||
values[field] = int(env[field.upper()])
|
||||
for field in ("poll_seconds", "event_heartbeat_seconds", "request_timeout_seconds"):
|
||||
if field.upper() in env:
|
||||
values[field] = float(env[field.upper()])
|
||||
for field in ("cookie_secure", "run_coordinator"):
|
||||
if field.upper() in env:
|
||||
values[field] = boolean(env[field.upper()])
|
||||
values["mode"] = env.get("CMVR_MODE", "production")
|
||||
if "TTS_VOICES" in env:
|
||||
values["tts_voices"] = tuple(v.strip() for v in env["TTS_VOICES"].split(",") if v.strip())
|
||||
return cls(**values)
|
||||
340
backend/app/coordinator.py
Normal file
@ -0,0 +1,340 @@
|
||||
import asyncio
|
||||
from datetime import timedelta
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
import re
|
||||
from filelock import FileLock
|
||||
from sqlalchemy import case, or_, select
|
||||
from .assets import confined, import_output, safe_file
|
||||
from .dto import asset_dto, public_value
|
||||
from .events import emit_asset, emit_job
|
||||
from .jobs import GPU_TYPES, TERMINAL
|
||||
from .models import Asset, Job, JobAsset, utcnow
|
||||
|
||||
LOG = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class Coordinator:
|
||||
def __init__(self, settings, db, provider):
|
||||
self.settings, self.db, self.provider = settings, db, provider
|
||||
self._task = None
|
||||
self._cpu = {}
|
||||
self._run_lock = asyncio.Lock()
|
||||
self._wake = asyncio.Event()
|
||||
self._file_lock = FileLock(str(settings.state_root / "coordinator.lock"))
|
||||
self._closing = False
|
||||
|
||||
def wake(self):
|
||||
self._wake.set()
|
||||
|
||||
async def start(self):
|
||||
self._file_lock.acquire(timeout=0)
|
||||
try:
|
||||
# CPU calls cannot be replayed after an unknown crash. GPU IDs and
|
||||
# persisted submit payload/key are resumed by their normal branches.
|
||||
async with self.db.session() as session:
|
||||
rows = (await session.scalars(select(Job).where(Job.state.notin_(TERMINAL),
|
||||
Job.task_type.notin_(GPU_TYPES), Job.phase == "cpu_running"))).all()
|
||||
for job in rows:
|
||||
job.state = "cancelled" if job.cancel_requested else "failed"
|
||||
job.phase, job.finished_at = job.state, utcnow()
|
||||
job.error_json = {"code": "worker_interrupted", "message": "服务重启中断了此任务,可手动重试", "retriable": True}
|
||||
await emit_job(session, job)
|
||||
await session.commit()
|
||||
self._task = asyncio.create_task(self._loop(), name="cmvr-coordinator")
|
||||
except BaseException:
|
||||
self._file_lock.release()
|
||||
raise
|
||||
|
||||
async def close(self):
|
||||
self._closing = True
|
||||
if self._task:
|
||||
self._task.cancel()
|
||||
await asyncio.gather(self._task, return_exceptions=True)
|
||||
for task in self._cpu.values():
|
||||
task.cancel()
|
||||
await asyncio.gather(*list(self._cpu.values()), return_exceptions=True)
|
||||
if self._file_lock.is_locked:
|
||||
self._file_lock.release()
|
||||
|
||||
async def _loop(self):
|
||||
while True:
|
||||
try:
|
||||
await self.run_once()
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception:
|
||||
LOG.exception("Coordinator tick failed; persisted work remains recoverable")
|
||||
self._wake.clear()
|
||||
try:
|
||||
await asyncio.wait_for(self._wake.wait(), timeout=self.settings.poll_seconds)
|
||||
except asyncio.TimeoutError:
|
||||
pass
|
||||
|
||||
async def _job(self, job_id):
|
||||
async with self.db.session() as session:
|
||||
return await session.get(Job, job_id)
|
||||
|
||||
async def _update(self, job_id, *, fresh_dispatch=False, **changes):
|
||||
async with self.db.session() as session:
|
||||
job = await session.get(Job, job_id)
|
||||
if job.state in TERMINAL:
|
||||
return job
|
||||
if job.cancel_requested:
|
||||
if fresh_dispatch or changes.get("state") in {"collecting", "succeeded", "failed", "timed_out", "cancelled"}:
|
||||
# Cancellation is arbitrated against the authoritative row
|
||||
# in the same transaction as any outcome/publication phase.
|
||||
changes = {"state": "cancelled", "phase": "cancelled", "finished_at": utcnow(),
|
||||
"result_json": None, "error_json": None, "sync_warning": None}
|
||||
elif changes.get("state") in {"queued", "running", "submitting"}:
|
||||
changes["state"], changes["phase"] = "cancelling", "cancellation_pending"
|
||||
changed = False
|
||||
for key, value in changes.items():
|
||||
if getattr(job, key) != value:
|
||||
setattr(job, key, value)
|
||||
if key not in {"next_action_at", "sync_failures"}:
|
||||
changed = True
|
||||
if changed:
|
||||
await emit_job(session, job)
|
||||
await session.commit()
|
||||
return job
|
||||
|
||||
async def _assets(self, job):
|
||||
async with self.db.session() as session:
|
||||
assets = (await session.scalars(select(Asset).join(JobAsset, JobAsset.asset_id == Asset.id)
|
||||
.where(JobAsset.job_id == job.id, Asset.owner_id == job.owner_id))).all()
|
||||
return {asset.id: confined(self.settings.asset_root, asset.storage_key, exists=True) for asset in assets}
|
||||
|
||||
async def _workdir(self, job):
|
||||
job = await self._update(job.id, work_attempt=job.work_attempt + 1)
|
||||
path = confined(self.settings.job_work_root, Path(job.id) / f"attempt-{job.work_attempt:04d}")
|
||||
path.mkdir(parents=True, exist_ok=False)
|
||||
return job, path
|
||||
|
||||
async def _warning(self, job_id, error):
|
||||
job = await self._job(job_id)
|
||||
await self._update(job_id, sync_warning="上游连接或结果导入暂不可用,正在恢复同步",
|
||||
sync_failures=job.sync_failures + 1,
|
||||
next_action_at=utcnow() + timedelta(seconds=min(30, 2 ** min(job.sync_failures, 5))))
|
||||
LOG.warning("Job %s external boundary unavailable: %s", job_id, type(error).__name__)
|
||||
|
||||
async def _failure(self, job_id, exc):
|
||||
job = await self._job(job_id)
|
||||
code = getattr(exc, "code", "processing_failed")
|
||||
message = getattr(exc, "message", "任务处理失败,请联系管理员查看服务日志")
|
||||
await self._update(job_id, state="cancelled" if job.cancel_requested else "failed",
|
||||
phase="cancelled" if job.cancel_requested else "failed", finished_at=utcnow(),
|
||||
error_json={"code": code, "message": message, "retriable": bool(getattr(exc, "retriable", False))})
|
||||
|
||||
async def _complete(self, job_id, result):
|
||||
async with self.db.session() as session:
|
||||
job = await session.get(Job, job_id)
|
||||
if job.state in TERMINAL:
|
||||
return
|
||||
if job.cancel_requested:
|
||||
job.state, job.phase = "cancelled", "cancelled"
|
||||
job.result_json, job.error_json, job.sync_warning = None, None, None
|
||||
job.finished_at = utcnow()
|
||||
await emit_job(session, job)
|
||||
await session.commit()
|
||||
return
|
||||
outputs = (await session.scalars(select(Asset).where(Asset.source_job_id == job_id)
|
||||
.order_by(Asset.source_output_index))).all()
|
||||
if not outputs:
|
||||
raise ValueError("Completed job has no imported artifacts")
|
||||
for asset in outputs:
|
||||
if not asset.ready:
|
||||
asset.ready = True
|
||||
emit_asset(session, job.owner_id, "asset.created", {"asset": asset_dto(asset)})
|
||||
job.state, job.phase = "succeeded", "completed"
|
||||
job.result_json, job.finished_at, job.sync_warning = result, utcnow(), None
|
||||
await emit_job(session, job)
|
||||
await session.commit()
|
||||
|
||||
async def run_once(self, *, force=False):
|
||||
async with self._run_lock:
|
||||
for job_id, task in list(self._cpu.items()):
|
||||
if task.done():
|
||||
self._cpu.pop(job_id)
|
||||
await asyncio.gather(task, return_exceptions=True)
|
||||
async with self.db.session() as session:
|
||||
query = select(Job).where(Job.state.notin_(TERMINAL))
|
||||
if not force:
|
||||
query = query.where(Job.next_action_at <= utcnow())
|
||||
ordering = (case((Job.cancel_requested.is_(True), 0), else_=1),
|
||||
Job.next_action_at, Job.created_at, Job.batch_index, Job.id)
|
||||
jobs = list((await session.scalars(query.order_by(*ordering).limit(50))).all())
|
||||
# Reserve one CPU candidate independently of a large GPU or
|
||||
# cancellation backlog; network/GPU waiting cannot consume its slot.
|
||||
cpu = await session.scalar(query.where(Job.task_type.notin_(GPU_TYPES),
|
||||
or_(Job.scheduled_at.is_(None), Job.scheduled_at <= utcnow())).order_by(*ordering).limit(1))
|
||||
if cpu is not None:
|
||||
# Start/cancel the independent CPU task before potentially
|
||||
# slow GPU HTTP calls, rather than merely adding a tail slot.
|
||||
jobs = [cpu] + [job for job in jobs if job.id != cpu.id]
|
||||
for job in jobs:
|
||||
if job.scheduled_at and job.scheduled_at > utcnow():
|
||||
continue
|
||||
# Every inspected candidate moves forward, even when CPU is
|
||||
# busy. This durable timestamp rotates bounded batches fairly.
|
||||
job = await self._update(job.id, next_action_at=utcnow() + timedelta(seconds=self.settings.poll_seconds))
|
||||
if job.state in TERMINAL:
|
||||
continue
|
||||
if job.id in self._cpu:
|
||||
if job.cancel_requested and job.state != "collecting":
|
||||
self._cpu[job.id].cancel()
|
||||
continue
|
||||
if job.task_type in GPU_TYPES:
|
||||
await self._gpu(job)
|
||||
elif job.state == "collecting":
|
||||
try:
|
||||
await self._collect_cpu(job)
|
||||
except Exception as exc:
|
||||
await self._warning(job.id, exc)
|
||||
elif not self._cpu:
|
||||
self._cpu[job.id] = asyncio.create_task(self._run_cpu(job), name=f"cpu-job-{job.id}")
|
||||
|
||||
async def _gpu(self, job):
|
||||
try:
|
||||
if job.state == "collecting":
|
||||
await self._collect_gpu(job)
|
||||
return
|
||||
if not job.upstream_id:
|
||||
if job.cancel_requested and job.upstream_payload is None:
|
||||
await self._update(job.id, state="cancelled", phase="cancelled", finished_at=utcnow())
|
||||
return
|
||||
if job.upstream_payload is None:
|
||||
job = await self._update(job.id, phase="preparing", state="submitting")
|
||||
job, work = await self._workdir(job)
|
||||
payload = await self.provider.prepare_gpu_payload(job.task_type, job.input_json, job.parameters,
|
||||
await self._assets(job), work)
|
||||
# This commit precedes POST; retries must reuse both values.
|
||||
job = await self._update(job.id, upstream_payload=payload, phase="dispatching", fresh_dispatch=True)
|
||||
if job.state in TERMINAL:
|
||||
return
|
||||
# This invocation knows no POST has started yet. An existing
|
||||
# persisted payload on restart is instead ambiguous and must
|
||||
# still recover its upstream ID using the same key below.
|
||||
job = await self._job(job.id)
|
||||
if job.cancel_requested:
|
||||
await self._update(job.id, state="cancelled", phase="cancelled", finished_at=utcnow())
|
||||
return
|
||||
remote = await self.provider.submit(job.upstream_payload, job.upstream_key)
|
||||
remote_id = remote.get("id")
|
||||
if not isinstance(remote_id, str) or not remote_id:
|
||||
raise ValueError("Upstream omitted its job ID")
|
||||
job = await self._update(job.id, upstream_id=remote_id)
|
||||
else:
|
||||
remote = await self.provider.cancel(job.upstream_id) if job.cancel_requested else await self.provider.query(job.upstream_id)
|
||||
# A cancellation arriving while POST was in flight is persisted and
|
||||
# sent against the same recovered ID on the next tick.
|
||||
await self._apply_remote(job.id, remote)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
if not job.upstream_id and getattr(exc, "code", None) == "upstream_rejected":
|
||||
await self._failure(job.id, exc)
|
||||
elif getattr(exc, "retriable", False) or job.upstream_payload is not None or job.upstream_id:
|
||||
await self._warning(job.id, exc)
|
||||
else:
|
||||
LOG.exception("Job %s preparation failed", job.id)
|
||||
await self._failure(job.id, exc)
|
||||
|
||||
async def _apply_remote(self, job_id, remote):
|
||||
state = remote.get("state")
|
||||
if state not in {"queued", "running", "succeeded", "failed", "cancelled", "timed_out"}:
|
||||
raise ValueError("Invalid upstream job state")
|
||||
job = await self._job(job_id)
|
||||
changes = {"state": state, "phase": remote.get("stage") or state,
|
||||
"attempt_count": int(remote.get("attempt_count", job.attempt_count)),
|
||||
"preemptions": int(remote.get("preemptions", job.preemptions)),
|
||||
"last_preempted_reason": public_value(remote.get("last_preempted_reason")),
|
||||
"sync_warning": None, "sync_failures": 0,
|
||||
"next_action_at": utcnow() + timedelta(seconds=self.settings.poll_seconds)}
|
||||
if state == "running" and not job.started_at:
|
||||
changes["started_at"] = utcnow()
|
||||
if state == "succeeded":
|
||||
changes.update(state="collecting", phase="importing_outputs", upstream_result=remote.get("result") or {})
|
||||
elif state in TERMINAL:
|
||||
changes["finished_at"] = utcnow()
|
||||
if state in {"failed", "timed_out"}:
|
||||
changes["error_json"] = {"code": "upstream_" + state, "message": "模型任务未完成,请检查参数或重试", "retriable": True}
|
||||
job = await self._update(job_id, **changes)
|
||||
if job.state == "collecting":
|
||||
await self._collect_gpu(job)
|
||||
|
||||
async def _collect_gpu(self, job):
|
||||
outputs = (job.upstream_result or {}).get("outputs")
|
||||
if not isinstance(outputs, list) or not outputs:
|
||||
raise ValueError("Succeeded upstream job has no outputs")
|
||||
directory = confined(self.settings.job_work_root, Path(job.id) / "imports")
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
assets = []
|
||||
for index, output in enumerate(outputs):
|
||||
async with self.db.session() as session:
|
||||
existing = await session.scalar(select(Asset).where(Asset.source_job_id == job.id,
|
||||
Asset.source_output_index == index))
|
||||
if existing:
|
||||
assets.append(existing)
|
||||
continue
|
||||
raw = output.get("path", "") if isinstance(output, dict) else str(output)
|
||||
suffix = Path(raw).suffix.lower()
|
||||
if not re.fullmatch(r"\.[a-z0-9]{1,10}", suffix):
|
||||
suffix = ".bin"
|
||||
destination = directory / f"output-{index:04d}{suffix}"
|
||||
await self.provider.download(job.upstream_id, index, destination)
|
||||
assets.append(await import_output(self.db, self.settings, job, destination, index))
|
||||
result = public_value((job.upstream_result or {}).get("metadata", {}))
|
||||
if job.task_type == "audio.transcribe":
|
||||
for asset in assets:
|
||||
if asset.kind == "json" and asset.size_bytes <= 5 * 1024 * 1024:
|
||||
with safe_file(self.settings.asset_root, asset.storage_key) as stream:
|
||||
transcript = json.load(stream)
|
||||
result = {"text": transcript.get("text", ""), "segments": transcript.get("segments", [])}
|
||||
break
|
||||
await self._complete(job.id, result)
|
||||
|
||||
async def _run_cpu(self, job):
|
||||
try:
|
||||
if job.cancel_requested:
|
||||
await self._update(job.id, state="cancelled", phase="cancelled", finished_at=utcnow())
|
||||
return
|
||||
job = await self._update(job.id, state="running", phase="cpu_running", started_at=utcnow(),
|
||||
attempt_count=job.attempt_count + 1)
|
||||
if job.state in TERMINAL or job.cancel_requested:
|
||||
if job.state not in TERMINAL:
|
||||
await self._update(job.id, state="cancelled", phase="cancelled", finished_at=utcnow())
|
||||
return
|
||||
job, work = await self._workdir(job)
|
||||
result = await self.provider.run_cpu(job.task_type, job.input_json, job.parameters, await self._assets(job), work)
|
||||
job = await self._job(job.id)
|
||||
if job.cancel_requested:
|
||||
await self._update(job.id, state="cancelled", phase="cancelled", finished_at=utcnow())
|
||||
return
|
||||
if not isinstance(result.outputs, list) or not result.outputs:
|
||||
raise ValueError("CPU provider returned no artifacts")
|
||||
private = {"cpu_outputs": [str(confined(self.settings.job_work_root, p, exists=True)) for p in result.outputs],
|
||||
"cpu_result": result.result, "metadata": result.metadata}
|
||||
job = await self._update(job.id, state="collecting", phase="importing_outputs", upstream_result=private)
|
||||
if job.state not in TERMINAL:
|
||||
await self._collect_cpu(job)
|
||||
except asyncio.CancelledError:
|
||||
job = await self._job(job.id)
|
||||
if job.state != "collecting":
|
||||
await self._update(job.id, state="cancelled" if job.cancel_requested else "failed",
|
||||
phase="cancelled" if job.cancel_requested else "interrupted", finished_at=utcnow(),
|
||||
error_json=None if job.cancel_requested else {"code": "worker_interrupted", "message": "任务因服务停止而中断", "retriable": True})
|
||||
except Exception as exc:
|
||||
job = await self._job(job.id)
|
||||
if job.state == "collecting":
|
||||
await self._warning(job.id, exc)
|
||||
else:
|
||||
LOG.exception("CPU job %s failed", job.id)
|
||||
await self._failure(job.id, exc)
|
||||
|
||||
async def _collect_cpu(self, job):
|
||||
private = job.upstream_result or {}
|
||||
for index, source in enumerate(private.get("cpu_outputs", [])):
|
||||
await import_output(self.db, self.settings, job, Path(source), index)
|
||||
await self._complete(job.id, public_value(private.get("cpu_result", {})))
|
||||
34
backend/app/database.py
Normal file
@ -0,0 +1,34 @@
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
|
||||
from sqlalchemy import event
|
||||
import asyncio
|
||||
from contextlib import asynccontextmanager
|
||||
from .models import Base
|
||||
|
||||
|
||||
class Database:
|
||||
def __init__(self, settings):
|
||||
self.engine = create_async_engine(settings.sqlalchemy_url, pool_pre_ping=True)
|
||||
if settings.sqlalchemy_url.drivername.startswith("sqlite"):
|
||||
@event.listens_for(self.engine.sync_engine, "connect")
|
||||
def sqlite_options(connection, _):
|
||||
cursor = connection.cursor()
|
||||
cursor.execute("PRAGMA foreign_keys=ON")
|
||||
cursor.execute("PRAGMA busy_timeout=10000")
|
||||
cursor.close()
|
||||
self._sessions = async_sessionmaker(self.engine, expire_on_commit=False)
|
||||
# One API process by deployment contract. Short DB units are serialized
|
||||
# so durable SSE IDs are observed in commit order, including CPU imports.
|
||||
self._unit_lock = asyncio.Lock()
|
||||
|
||||
@asynccontextmanager
|
||||
async def session(self):
|
||||
async with self._unit_lock:
|
||||
async with self._sessions() as session:
|
||||
yield session
|
||||
|
||||
async def initialize(self):
|
||||
async with self.engine.begin() as connection:
|
||||
await connection.run_sync(Base.metadata.create_all)
|
||||
|
||||
async def close(self):
|
||||
await self.engine.dispose()
|
||||
44
backend/app/dto.py
Normal file
@ -0,0 +1,44 @@
|
||||
import re
|
||||
from sqlalchemy import select
|
||||
from .models import Asset, JobAsset
|
||||
|
||||
|
||||
def iso(value):
|
||||
return value.isoformat(timespec="milliseconds") + "Z" if value is not None else None
|
||||
|
||||
|
||||
def public_value(value):
|
||||
if isinstance(value, dict):
|
||||
return {k: public_value(v) for k, v in value.items()
|
||||
if k not in {"path", "output_dir", "storage_key", "api_key", "token", "request_path"}}
|
||||
if isinstance(value, list):
|
||||
return [public_value(v) for v in value]
|
||||
if isinstance(value, str):
|
||||
value = re.sub(r"/(?:workspace|run|data|home|var|tmp|srv)/[^\s,;]+", "[server file]", value)
|
||||
return re.sub(r"[A-Za-z]:[\\/][^\s,;]+", "[server file]", value)
|
||||
return value
|
||||
|
||||
|
||||
def asset_dto(asset):
|
||||
return {"id": asset.id, "name": asset.name, "kind": asset.kind, "mime_type": asset.mime_type,
|
||||
"size_bytes": asset.size_bytes, "width": asset.width, "height": asset.height,
|
||||
"duration_seconds": asset.duration_seconds,
|
||||
"preview_url": f"/api/assets/{asset.id}/content",
|
||||
"thumbnail_url": f"/api/assets/{asset.id}/thumbnail" if asset.kind in {"image", "video"} else None,
|
||||
"download_url": f"/api/assets/{asset.id}/content?download=1", "source_job_id": asset.source_job_id,
|
||||
"origin": asset.origin, "tags": asset.tags or [], "favorite": asset.favorite,
|
||||
"created_at": iso(asset.created_at)}
|
||||
|
||||
|
||||
async def job_dto(session, job):
|
||||
assets = (await session.scalars(select(Asset).where(Asset.source_job_id == job.id, Asset.deleted_at.is_(None), Asset.ready.is_(True))
|
||||
.order_by(Asset.source_output_index))).all()
|
||||
inputs = (await session.scalars(select(JobAsset.asset_id).where(JobAsset.job_id == job.id))).all()
|
||||
return {"id": job.id, "task_type": job.task_type, "state": job.state, "phase": job.phase,
|
||||
"version": job.version, "prompt": job.input_json.get("prompt", ""), "parameters": job.parameters,
|
||||
"input_asset_ids": list(inputs), "result_assets": [asset_dto(a) for a in assets],
|
||||
"result": public_value(job.result_json), "progress": None, "queue_position": None,
|
||||
"upstream_id": job.upstream_id, "attempt_count": job.attempt_count, "preemptions": job.preemptions,
|
||||
"last_preempted_reason": job.last_preempted_reason, "cancel_requested": job.cancel_requested,
|
||||
"error": job.error_json, "sync_warning": job.sync_warning, "created_at": iso(job.created_at),
|
||||
"scheduled_at": iso(job.scheduled_at), "started_at": iso(job.started_at), "finished_at": iso(job.finished_at)}
|
||||
5
backend/app/errors.py
Normal file
@ -0,0 +1,5 @@
|
||||
from fastapi import HTTPException
|
||||
|
||||
|
||||
def fail(status, code, message):
|
||||
raise HTTPException(status, detail={"code": code, "message": message})
|
||||
77
backend/app/events.py
Normal file
@ -0,0 +1,77 @@
|
||||
import asyncio
|
||||
import json
|
||||
import time
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
from fastapi.responses import StreamingResponse
|
||||
from sqlalchemy import func, select
|
||||
from .auth import Actor, COOKIE, current_actor, token_hash
|
||||
from .dto import job_dto
|
||||
from .errors import fail
|
||||
from .models import Event, Session, User, utcnow
|
||||
|
||||
router = APIRouter(tags=["events"])
|
||||
|
||||
|
||||
async def emit_job(session, job, *, increment=True):
|
||||
if increment:
|
||||
job.version += 1
|
||||
await session.flush()
|
||||
session.add(Event(owner_id=job.owner_id, job_id=job.id, event_type="job.updated",
|
||||
data={"job": await job_dto(session, job)}))
|
||||
|
||||
|
||||
def emit_asset(session, owner_id, event_type, data):
|
||||
session.add(Event(owner_id=owner_id, event_type=event_type, data=data))
|
||||
|
||||
|
||||
async def event_batch(db, owner_id, after, limit=100):
|
||||
async with db.session() as session:
|
||||
events = (await session.scalars(select(Event).where(Event.owner_id == owner_id, Event.id > after)
|
||||
.order_by(Event.id).limit(limit))).all()
|
||||
return [{"id": event.id, "event": event.event_type, "data": event.data} for event in events]
|
||||
|
||||
|
||||
async def session_is_active(db, token):
|
||||
if not token:
|
||||
return False
|
||||
async with db.session() as session:
|
||||
return (await session.scalar(select(Session.token_hash).join(User, User.id == Session.user_id)
|
||||
.where(Session.token_hash == token_hash(token), Session.expires_at > utcnow(), User.disabled.is_(False)))) is not None
|
||||
|
||||
|
||||
async def event_stream(request, owner_id, token, after):
|
||||
# Authentication was checked by the endpoint. Flush a body immediately so
|
||||
# EventSource/proxies need not wait for the first durable event or heartbeat.
|
||||
yield ": connected\n\n"
|
||||
db = request.app.state.db
|
||||
heartbeat = request.app.state.settings.event_heartbeat_seconds
|
||||
last_heartbeat = time.monotonic()
|
||||
async with db.session() as session:
|
||||
maximum = await session.scalar(select(func.max(Event.id)).where(Event.owner_id == owner_id)) or 0
|
||||
if after > maximum:
|
||||
yield f"id: {maximum}\nevent: reset\ndata: {{}}\n\n"
|
||||
after = maximum
|
||||
while not await request.is_disconnected():
|
||||
if not await session_is_active(db, token):
|
||||
return
|
||||
rows = await event_batch(db, owner_id, after)
|
||||
for event in rows:
|
||||
after = event["id"]
|
||||
yield f"id: {after}\nevent: {event['event']}\ndata: {json.dumps(event['data'], ensure_ascii=False, separators=(',', ':'))}\n\n"
|
||||
if time.monotonic() - last_heartbeat >= heartbeat:
|
||||
yield ": heartbeat\n\n"
|
||||
last_heartbeat = time.monotonic()
|
||||
if not rows:
|
||||
await asyncio.sleep(min(.5, heartbeat))
|
||||
|
||||
|
||||
@router.get("/events")
|
||||
async def events(request: Request, after: int = 0, actor: Actor = Depends(current_actor)):
|
||||
try:
|
||||
cursor = int(request.headers.get("Last-Event-ID", after))
|
||||
if cursor < 0:
|
||||
raise ValueError
|
||||
except ValueError:
|
||||
fail(422, "invalid_cursor", "事件游标必须为非负整数")
|
||||
return StreamingResponse(event_stream(request, actor.id, request.cookies.get(COOKIE), cursor),
|
||||
media_type="text/event-stream", headers={"Cache-Control": "no-cache, no-transform", "X-Accel-Buffering": "no"})
|
||||
217
backend/app/jobs.py
Normal file
@ -0,0 +1,217 @@
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
import json
|
||||
from fastapi import APIRouter, Depends, Header, Request
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from .assets import owned_asset
|
||||
from .auth import Actor, csrf_actor, current_actor
|
||||
from .dto import job_dto
|
||||
from .errors import fail
|
||||
from .events import emit_job
|
||||
from .models import Event, Job, JobAsset, new_id, utcnow
|
||||
|
||||
router = APIRouter(prefix="/jobs", tags=["jobs"])
|
||||
GPU_TYPES = {"image.generate", "video.generate", "defect.generate", "audio.transcribe"}
|
||||
CPU_TYPES = {"math.solve", "media.structure", "video.compose", "audio.speech"}
|
||||
TERMINAL = {"succeeded", "failed", "cancelled", "timed_out"}
|
||||
|
||||
|
||||
class Submit(BaseModel):
|
||||
task_type: str
|
||||
input: dict = Field(default_factory=dict)
|
||||
parameters: dict = Field(default_factory=dict)
|
||||
count: int = Field(default=1, ge=1, le=4)
|
||||
scheduled_at: datetime | None = None
|
||||
|
||||
|
||||
async def owned_job(session, job_id, owner_id):
|
||||
job = await session.scalar(select(Job).where(Job.id == job_id, Job.owner_id == owner_id))
|
||||
if job is None:
|
||||
fail(404, "job_not_found", "任务不存在")
|
||||
return job
|
||||
|
||||
|
||||
def input_ids(inputs, parameters):
|
||||
result = []
|
||||
for field in ("image_asset_id", "audio_asset_id", "asset_id"):
|
||||
if inputs.get(field):
|
||||
result.append(inputs[field])
|
||||
if inputs.get("asset_ids"):
|
||||
if not isinstance(inputs["asset_ids"], list):
|
||||
fail(422, "invalid_assets", "asset_ids 必须为素材编号列表")
|
||||
result.extend(inputs["asset_ids"])
|
||||
for clip in parameters.get("clips", []):
|
||||
if not isinstance(clip, dict) or not isinstance(clip.get("asset_id"), str):
|
||||
fail(422, "invalid_clip", "每个片段需要素材编号")
|
||||
result.append(clip["asset_id"])
|
||||
if parameters.get("audio_asset_id"):
|
||||
result.append(parameters["audio_asset_id"])
|
||||
if any(not isinstance(value, str) or len(value) > 64 for value in result):
|
||||
fail(422, "invalid_assets", "素材编号格式不正确")
|
||||
return list(dict.fromkeys(result))
|
||||
|
||||
|
||||
async def validate_submission(session, body, owner_id, settings):
|
||||
if body.task_type not in GPU_TYPES | CPU_TYPES:
|
||||
fail(422, "unsupported_task", "不支持此任务类型")
|
||||
allowed = {"prompt", "negative_prompt", "image_asset_id", "audio_asset_id", "asset_id", "asset_ids"}
|
||||
if set(body.input) - allowed:
|
||||
fail(422, "invalid_input", "只允许提示词与素材编号,不接受服务器路径或 URL")
|
||||
if body.count > 1 and body.task_type not in {"image.generate", "defect.generate"}:
|
||||
fail(422, "batch_not_supported", "此任务类型不支持批量生成")
|
||||
if body.task_type == "audio.speech" and not settings.tts_base_url:
|
||||
fail(422, "speech_unavailable", "尚未配置真实配音服务")
|
||||
from .providers import ProviderError, validate_arguments
|
||||
try:
|
||||
validate_arguments(body.task_type, body.input, body.parameters, settings)
|
||||
except ProviderError as exc:
|
||||
fail(400, exc.code, exc.message)
|
||||
prompt = body.input.get("prompt", "")
|
||||
if not isinstance(prompt, str) or len(prompt) > 8000:
|
||||
fail(422, "invalid_prompt", "提示词须为不超过 8000 字符的文本")
|
||||
if body.task_type in {"image.generate", "video.generate", "defect.generate", "math.solve", "audio.speech"} and not prompt.strip():
|
||||
fail(422, "prompt_required", "请输入提示词或文本")
|
||||
ids = input_ids(body.input, body.parameters)
|
||||
assets = {asset_id: await owned_asset(session, asset_id, owner_id) for asset_id in ids}
|
||||
required = {"defect.generate": "image_asset_id", "audio.transcribe": "audio_asset_id", "media.structure": "asset_id"}
|
||||
if body.task_type in required:
|
||||
key = required[body.task_type]
|
||||
value = body.input.get(key) or (body.input.get("asset_id") if key == "audio_asset_id" else None)
|
||||
if not value:
|
||||
fail(422, "asset_required", "此任务需要输入素材")
|
||||
for key, kinds in (("image_asset_id", {"image"}), ("audio_asset_id", {"audio", "video"})):
|
||||
if body.input.get(key) and assets[body.input[key]].kind not in kinds:
|
||||
fail(422, "wrong_asset_kind", "输入素材类型不正确")
|
||||
if body.task_type == "media.structure" and assets[body.input["asset_id"]].kind not in {"image", "video"}:
|
||||
fail(422, "wrong_asset_kind", "素材理解需要图片或视频")
|
||||
if body.task_type == "audio.transcribe":
|
||||
source_id = body.input.get("audio_asset_id") or body.input.get("asset_id")
|
||||
if assets[source_id].kind not in {"audio", "video"}:
|
||||
fail(422, "wrong_asset_kind", "转写需要音频或视频素材")
|
||||
if body.task_type == "video.compose" and not ids:
|
||||
fail(422, "clips_required", "请添加待合成片段")
|
||||
if body.task_type == "video.compose":
|
||||
if any(assets[clip["asset_id"]].kind != "video" for clip in body.parameters.get("clips", [])):
|
||||
fail(422, "wrong_asset_kind", "编排片段必须为视频素材")
|
||||
audio_id = body.input.get("audio_asset_id") or body.parameters.get("audio_asset_id")
|
||||
if audio_id and assets[audio_id].kind != "audio":
|
||||
fail(422, "wrong_asset_kind", "成片音轨必须为音频素材")
|
||||
if body.scheduled_at is not None and body.scheduled_at.tzinfo is None:
|
||||
fail(422, "timezone_required", "定时任务时间须包含时区")
|
||||
return ids
|
||||
|
||||
|
||||
async def create_jobs(session, body, actor, settings, key=None):
|
||||
if key is not None and not 1 <= len(key) <= 128:
|
||||
fail(422, "invalid_idempotency_key", "幂等键长度须为 1–128")
|
||||
payload = body.model_dump(mode="json")
|
||||
try:
|
||||
fingerprint = hashlib.sha256(json.dumps(payload, sort_keys=True, ensure_ascii=False,
|
||||
allow_nan=False).encode()).hexdigest()
|
||||
except (ValueError, TypeError):
|
||||
fail(422, "invalid_json", "任务参数必须为有限数值和合法 JSON")
|
||||
if key:
|
||||
existing = (await session.scalars(select(Job).where(Job.owner_id == actor.id, Job.request_key == key)
|
||||
.order_by(Job.batch_index))).all()
|
||||
if existing:
|
||||
if existing[0].request_hash != fingerprint:
|
||||
fail(409, "idempotency_conflict", "此幂等键已用于不同的任务参数")
|
||||
return existing
|
||||
ids = await validate_submission(session, body, actor.id, settings)
|
||||
scheduled = body.scheduled_at.astimezone(timezone.utc).replace(tzinfo=None) if body.scheduled_at else None
|
||||
jobs = []
|
||||
for index in range(body.count):
|
||||
job_id = new_id()
|
||||
future = scheduled and scheduled > utcnow()
|
||||
parameters = dict(body.parameters)
|
||||
if body.count > 1:
|
||||
parameters["seed"] = (parameters.get("seed", 42) + index) % (2 ** 32)
|
||||
job = Job(id=job_id, owner_id=actor.id, task_type=body.task_type,
|
||||
state="scheduled" if future else "submitting", phase="scheduled" if future else "waiting_dispatch",
|
||||
version=1, input_json=body.input, parameters=parameters, request_key=key,
|
||||
request_hash=fingerprint, batch_index=index, upstream_key="cmvr-visual:" + job_id,
|
||||
scheduled_at=scheduled, next_action_at=scheduled if future else utcnow(),
|
||||
attempt_count=0, work_attempt=0, preemptions=0, cancel_requested=False)
|
||||
session.add(job)
|
||||
await session.flush()
|
||||
session.add_all(JobAsset(job_id=job.id, asset_id=asset_id) for asset_id in ids)
|
||||
await emit_job(session, job, increment=False)
|
||||
jobs.append(job)
|
||||
return jobs
|
||||
|
||||
|
||||
def wake(request):
|
||||
request.app.state.coordinator.wake()
|
||||
|
||||
|
||||
@router.post("", status_code=202)
|
||||
async def submit(body: Submit, request: Request, idempotency_key: str | None = Header(default=None),
|
||||
actor: Actor = Depends(csrf_actor)):
|
||||
async with request.app.state.db.session() as session:
|
||||
try:
|
||||
jobs = await create_jobs(session, body, actor, request.app.state.settings, idempotency_key)
|
||||
await session.commit()
|
||||
except IntegrityError:
|
||||
await session.rollback()
|
||||
jobs = await create_jobs(session, body, actor, request.app.state.settings, idempotency_key)
|
||||
result = {"jobs": [await job_dto(session, job) for job in jobs]}
|
||||
wake(request)
|
||||
return result
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_jobs(request: Request, page: int = 1, page_size: int = 24, task_type: str = "", state: str = "",
|
||||
actor: Actor = Depends(current_actor)):
|
||||
if page < 1 or not 1 <= page_size <= 100:
|
||||
fail(422, "invalid_page", "分页参数无效")
|
||||
async with request.app.state.db.session() as session:
|
||||
query = select(Job).where(Job.owner_id == actor.id)
|
||||
if task_type:
|
||||
query = query.where(Job.task_type == task_type)
|
||||
if state:
|
||||
query = query.where(Job.state == state)
|
||||
total = await session.scalar(select(func.count()).select_from(query.subquery()))
|
||||
jobs = (await session.scalars(query.order_by(Job.created_at.desc(), Job.id.desc())
|
||||
.offset((page - 1) * page_size).limit(page_size))).all()
|
||||
cursor = await session.scalar(select(func.max(Event.id)).where(Event.owner_id == actor.id)) or 0
|
||||
return {"items": [await job_dto(session, job) for job in jobs], "total": total,
|
||||
"page": page, "page_size": page_size, "cursor": cursor}
|
||||
|
||||
|
||||
@router.get("/{job_id}")
|
||||
async def get_job(job_id: str, request: Request, actor: Actor = Depends(current_actor)):
|
||||
async with request.app.state.db.session() as session:
|
||||
return await job_dto(session, await owned_job(session, job_id, actor.id))
|
||||
|
||||
|
||||
@router.post("/{job_id}/cancel")
|
||||
async def cancel(job_id: str, request: Request, actor: Actor = Depends(csrf_actor)):
|
||||
async with request.app.state.db.session() as session:
|
||||
job = await owned_job(session, job_id, actor.id)
|
||||
if job.state not in TERMINAL and job.state != "collecting":
|
||||
job.cancel_requested = True
|
||||
if job.upstream_id is None and job.upstream_payload is None and job.phase not in {"cpu_running", "preparing"}:
|
||||
job.state, job.phase, job.finished_at = "cancelled", "cancelled", utcnow()
|
||||
else:
|
||||
job.state, job.phase = "cancelling", "cancellation_pending"
|
||||
await emit_job(session, job)
|
||||
await session.commit()
|
||||
result = await job_dto(session, job)
|
||||
wake(request)
|
||||
return result
|
||||
|
||||
|
||||
@router.post("/{job_id}/retry", status_code=202)
|
||||
async def retry(job_id: str, request: Request, actor: Actor = Depends(csrf_actor)):
|
||||
async with request.app.state.db.session() as session:
|
||||
old = await owned_job(session, job_id, actor.id)
|
||||
if old.state not in TERMINAL:
|
||||
fail(409, "job_not_finished", "请先等待或取消当前任务")
|
||||
body = Submit(task_type=old.task_type, input=old.input_json, parameters=old.parameters)
|
||||
jobs = await create_jobs(session, body, actor, request.app.state.settings)
|
||||
await session.commit()
|
||||
result = {"jobs": [await job_dto(session, job) for job in jobs]}
|
||||
wake(request)
|
||||
return result
|
||||
76
backend/app/main.py
Normal file
@ -0,0 +1,76 @@
|
||||
from contextlib import asynccontextmanager
|
||||
import asyncio
|
||||
import logging
|
||||
from fastapi import Depends, FastAPI
|
||||
from fastapi.responses import JSONResponse
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from . import assets, auth, events, jobs
|
||||
from .config import Settings
|
||||
from .coordinator import Coordinator
|
||||
from .database import Database
|
||||
|
||||
|
||||
def create_app(settings=None, *, provider=None):
|
||||
@asynccontextmanager
|
||||
async def lifespan(app):
|
||||
configuration = settings or Settings.from_env()
|
||||
for root in (configuration.asset_root, configuration.job_work_root, configuration.state_root):
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
db = Database(configuration)
|
||||
app.state.settings, app.state.db = configuration, db
|
||||
live_provider = provider
|
||||
if live_provider is None:
|
||||
from .providers import Provider
|
||||
live_provider = Provider(configuration)
|
||||
app.state.provider = live_provider
|
||||
coordinator = Coordinator(configuration, db, live_provider)
|
||||
app.state.coordinator = coordinator
|
||||
try:
|
||||
await db.initialize()
|
||||
await auth.bootstrap_admin(db, configuration)
|
||||
if configuration.run_coordinator:
|
||||
await coordinator.start()
|
||||
yield
|
||||
finally:
|
||||
await coordinator.close()
|
||||
await live_provider.aclose()
|
||||
await db.close()
|
||||
|
||||
app = FastAPI(title="CMVR Visual", lifespan=lifespan)
|
||||
@app.exception_handler(SQLAlchemyError)
|
||||
async def database_failure(request, exc):
|
||||
logging.getLogger(__name__).error("Database request failed: %s", type(exc).__name__)
|
||||
return JSONResponse(status_code=503, content={"detail": {"code": "database_unavailable", "message": "数据库暂不可用,请稍后重试"}})
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def internal_failure(request, exc):
|
||||
logging.getLogger(__name__).exception("Unhandled application error")
|
||||
return JSONResponse(status_code=500, content={"detail": {"code": "internal_error", "message": "服务处理失败,请联系管理员"}})
|
||||
for router in (auth.router, assets.router, jobs.router, events.router):
|
||||
app.include_router(router, prefix="/api")
|
||||
|
||||
@app.get("/api/health")
|
||||
async def health():
|
||||
async with app.state.db.session() as session:
|
||||
await session.execute(text("SELECT 1"))
|
||||
return {"status": "ok", "database": app.state.settings.sqlalchemy_url.get_backend_name()}
|
||||
|
||||
@app.get("/api/capabilities", dependencies=[Depends(auth.current_actor)])
|
||||
async def capabilities():
|
||||
from .providers import capabilities as provider_capabilities
|
||||
return {"items": provider_capabilities(app.state.settings),
|
||||
"scheduler": await app.state.provider.scheduler_status()}
|
||||
|
||||
@app.get("/api/system/status", dependencies=[Depends(auth.current_actor)])
|
||||
async def status():
|
||||
from .providers import capabilities as provider_capabilities
|
||||
online, scheduler = await asyncio.gather(app.state.provider.health(), app.state.provider.scheduler_status())
|
||||
return {"inference_online": online, "scheduler": scheduler, "models": provider_capabilities(app.state.settings),
|
||||
"environment": app.state.settings.mode,
|
||||
"database_backend": app.state.settings.sqlalchemy_url.get_backend_name()}
|
||||
|
||||
return app
|
||||
|
||||
|
||||
app = create_app()
|
||||
235
backend/app/media.py
Normal file
@ -0,0 +1,235 @@
|
||||
"""Bounded CPU media operations. No shell, CUDA, external URLs or user filters."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import uuid
|
||||
|
||||
from PIL import Image, ImageOps, UnidentifiedImageError
|
||||
|
||||
|
||||
class MediaError(RuntimeError):
|
||||
def __init__(self, code: str, message: str, retriable: bool = False):
|
||||
super().__init__(message)
|
||||
self.code, self.message, self.retriable = code, message, retriable
|
||||
|
||||
|
||||
def confined(path: Path, settings, *, exists: bool = True, root: Path | None = None) -> Path:
|
||||
try:
|
||||
candidate = Path(path)
|
||||
boundary = Path(root or settings.workspace_root).resolve()
|
||||
if not candidate.is_absolute():
|
||||
raise ValueError
|
||||
resolved = candidate.resolve()
|
||||
if not resolved.is_relative_to(boundary) or (exists and not resolved.is_file()):
|
||||
raise ValueError
|
||||
return resolved
|
||||
except (OSError, ValueError, TypeError):
|
||||
raise MediaError('invalid_asset', '素材文件不存在或不可访问。') from None
|
||||
|
||||
|
||||
async def _stop(process):
|
||||
if process.returncode is None:
|
||||
try:
|
||||
process.terminate()
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
try:
|
||||
await asyncio.wait_for(process.wait(), 2)
|
||||
except asyncio.TimeoutError:
|
||||
try:
|
||||
process.kill()
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
await asyncio.wait_for(process.wait(), 5)
|
||||
|
||||
|
||||
async def _cleanup(process, readers):
|
||||
for task in readers:
|
||||
if not task.done():
|
||||
task.cancel()
|
||||
await asyncio.gather(*readers, return_exceptions=True)
|
||||
|
||||
async def discard(stream):
|
||||
while await stream.read(65536):
|
||||
pass
|
||||
|
||||
# Drain after a size rejection/cancel too. Otherwise a full paused pipe
|
||||
# can keep asyncio's process transport alive even after the child exited.
|
||||
drains = [asyncio.create_task(discard(process.stdout)), asyncio.create_task(discard(process.stderr))]
|
||||
try:
|
||||
await _stop(process)
|
||||
await asyncio.wait_for(asyncio.gather(*drains), 5)
|
||||
finally:
|
||||
for task in drains:
|
||||
if not task.done():
|
||||
task.cancel()
|
||||
await asyncio.gather(*drains, return_exceptions=True)
|
||||
|
||||
|
||||
async def run_process(argv: list[str], *, timeout: float = 120, max_output: int = 1024 * 1024,
|
||||
cwd: Path | None = None, return_stderr: bool = False) -> bytes | tuple[bytes, bytes]:
|
||||
"""Own one executable; cancellation does TERM/KILL/wait only on that child.
|
||||
|
||||
FFmpeg/ffprobe do not launch child programs. Pipe readers enforce their
|
||||
bounds while the child runs, rather than buffering arbitrary diagnostics.
|
||||
"""
|
||||
process = None
|
||||
readers = []
|
||||
|
||||
async def read_bounded(stream):
|
||||
chunks, count = [], 0
|
||||
while chunk := await stream.read(65536):
|
||||
count += len(chunk)
|
||||
if count > max_output:
|
||||
raise MediaError('media_output_limit', '媒体处理诊断超出限制。')
|
||||
chunks.append(chunk)
|
||||
return b''.join(chunks)
|
||||
|
||||
try:
|
||||
process = await asyncio.create_subprocess_exec(*[str(value) for value in argv],
|
||||
stdin=asyncio.subprocess.DEVNULL, stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE, cwd=str(cwd) if cwd else None,
|
||||
start_new_session=(os.name == 'posix'))
|
||||
readers = [asyncio.create_task(read_bounded(process.stdout)),
|
||||
asyncio.create_task(read_bounded(process.stderr))]
|
||||
async with asyncio.timeout(timeout):
|
||||
stdout, stderr = await asyncio.gather(*readers)
|
||||
await process.wait()
|
||||
if process.returncode != 0:
|
||||
raise MediaError('media_processing_failed', '媒体解码或处理失败,请检查素材格式。')
|
||||
return (stdout, stderr) if return_stderr else stdout
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except asyncio.TimeoutError:
|
||||
raise MediaError('media_timeout', '媒体处理超时,请缩短素材后重试。', True) from None
|
||||
except (OSError, ValueError):
|
||||
raise MediaError('media_unavailable', '媒体处理程序不可用。', True) from None
|
||||
finally:
|
||||
if process is not None:
|
||||
cleanup = asyncio.create_task(_cleanup(process, readers))
|
||||
recancelled = False
|
||||
while not cleanup.done():
|
||||
try:
|
||||
await asyncio.shield(cleanup)
|
||||
except asyncio.CancelledError:
|
||||
recancelled = True
|
||||
await cleanup
|
||||
if recancelled:
|
||||
raise asyncio.CancelledError
|
||||
|
||||
|
||||
def input_options() -> list[str]:
|
||||
# Exclude playlists, concat input, network protocols and nested file lists.
|
||||
return ['-protocol_whitelist', 'file,pipe', '-format_whitelist',
|
||||
'mov,matroska,webm,avi,wav,mp3,flac,ogg,aac,mpeg,mpegts']
|
||||
|
||||
|
||||
def _image_info(path):
|
||||
try:
|
||||
with Image.open(path) as image:
|
||||
mime = {'PNG': 'image/png', 'JPEG': 'image/jpeg', 'WEBP': 'image/webp'}.get(image.format)
|
||||
if mime is None or image.width * image.height > 40_000_000:
|
||||
raise MediaError('invalid_image', '仅支持像素数受限的 PNG、JPEG、WebP 图片。')
|
||||
image.load()
|
||||
return {'kind': 'image', 'mime_type': mime, 'width': image.width,
|
||||
'height': image.height, 'duration_seconds': None}
|
||||
except UnidentifiedImageError:
|
||||
return None
|
||||
except (OSError, ValueError, Image.DecompressionBombError):
|
||||
raise MediaError('invalid_image', '图片文件无法解码。') from None
|
||||
|
||||
|
||||
def _text_info(path):
|
||||
if path.suffix.lower() not in {'.json', '.txt', '.md', '.srt', '.vtt'}:
|
||||
return None
|
||||
try:
|
||||
if path.stat().st_size > 4 * 1024 * 1024:
|
||||
raise ValueError
|
||||
text = path.read_text(encoding='utf-8-sig')
|
||||
if '\x00' in text or not text.strip():
|
||||
raise ValueError
|
||||
is_json = path.suffix.lower() == '.json'
|
||||
if is_json:
|
||||
json.loads(text, parse_constant=lambda _: (_ for _ in ()).throw(ValueError()))
|
||||
return {'kind': 'json' if is_json else 'text',
|
||||
'mime_type': 'application/json' if is_json else 'text/plain',
|
||||
'width': None, 'height': None, 'duration_seconds': None}
|
||||
except (OSError, UnicodeError, ValueError, RecursionError):
|
||||
raise MediaError('invalid_text', '文本或 JSON 文件格式无效。') from None
|
||||
|
||||
|
||||
async def inspect_media(path: Path, settings) -> dict:
|
||||
source = confined(path, settings)
|
||||
if source.stat().st_size <= 0:
|
||||
raise MediaError('invalid_asset', '素材文件为空。')
|
||||
text = await asyncio.to_thread(_text_info, source)
|
||||
if text is not None:
|
||||
return text
|
||||
image = await asyncio.to_thread(_image_info, source)
|
||||
if image is not None:
|
||||
return image
|
||||
if source.suffix.lower() in {'.png', '.jpg', '.jpeg', '.webp'}:
|
||||
raise MediaError('invalid_image', '图片文件无法解码。')
|
||||
raw = await run_process([settings.ffprobe_bin, '-v', 'error', *input_options(),
|
||||
'-show_entries', 'format=format_name,duration,start_time:stream=codec_type,codec_name,width,height,duration:stream_disposition=attached_pic',
|
||||
'-of', 'json', str(source)], timeout=30, max_output=256 * 1024)
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
streams = data['streams']
|
||||
videos = [item for item in streams if item.get('codec_type') == 'video'
|
||||
and not item.get('disposition', {}).get('attached_pic')]
|
||||
audios = [item for item in streams if item.get('codec_type') == 'audio']
|
||||
if not videos and not audios:
|
||||
raise ValueError
|
||||
stream = videos[0] if videos else audios[0]
|
||||
duration = float(data.get('format', {}).get('duration', stream.get('duration', 0)))
|
||||
start_time = float(data.get('format', {}).get('start_time', 0))
|
||||
if not math.isfinite(start_time):
|
||||
raise ValueError
|
||||
if not math.isfinite(duration) or not 0 < duration <= 86400:
|
||||
raise ValueError
|
||||
width, height = stream.get('width'), stream.get('height')
|
||||
if videos and (type(width) is not int or type(height) is not int or width <= 0 or height <= 0
|
||||
or width * height > 40_000_000):
|
||||
raise ValueError
|
||||
formats = str(data.get('format', {}).get('format_name', '')).split(',')
|
||||
if videos:
|
||||
mime = 'video/webm' if 'webm' in formats and source.suffix.lower() == '.webm' else 'video/mp4' if 'mov' in formats else 'video/x-matroska' if 'matroska' in formats else 'video/mp2t' if 'mpegts' in formats else 'video/mpeg' if 'mpeg' in formats else 'video/x-msvideo'
|
||||
else:
|
||||
mime = 'audio/wav' if 'wav' in formats else 'audio/mpeg' if 'mp3' in formats else 'audio/flac' if 'flac' in formats else 'audio/ogg' if 'ogg' in formats else 'audio/aac' if 'aac' in formats else 'audio/mp4'
|
||||
return {'kind': 'video' if videos else 'audio', 'mime_type': mime, 'has_audio': bool(audios),
|
||||
'width': width if videos else None, 'height': height if videos else None,
|
||||
'duration_seconds': duration, 'start_seconds': start_time}
|
||||
except (ValueError, TypeError, KeyError, AttributeError):
|
||||
raise MediaError('invalid_media', '媒体文件信息无效。') from None
|
||||
|
||||
|
||||
async def make_thumbnail(path: Path, destination: Path, settings) -> Path | None:
|
||||
source, target = confined(path, settings), confined(destination, settings, exists=False)
|
||||
info = await inspect_media(source, settings)
|
||||
if info['kind'] not in {'image', 'video'}:
|
||||
return None
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = target.with_name(target.name + '.part-' + uuid.uuid4().hex + '.jpg')
|
||||
try:
|
||||
if info['kind'] == 'image':
|
||||
def convert():
|
||||
with Image.open(source) as image:
|
||||
image = ImageOps.exif_transpose(image).convert('RGB')
|
||||
image.thumbnail((512, 512))
|
||||
image.save(temporary, format='JPEG', quality=85)
|
||||
await asyncio.to_thread(convert)
|
||||
else:
|
||||
await run_process([settings.ffmpeg_bin, '-v', 'error', '-nostdin', *input_options(),
|
||||
'-i', str(source), '-frames:v', '1', '-vf', 'scale=512:512:force_original_aspect_ratio=decrease',
|
||||
'-threads', '2', '-f', 'image2', '-update', '1', str(temporary)], timeout=60)
|
||||
if not temporary.is_file() or temporary.stat().st_size == 0:
|
||||
raise MediaError('thumbnail_failed', '预览图生成失败。')
|
||||
os.replace(temporary, target)
|
||||
return target
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
120
backend/app/models.py
Normal file
@ -0,0 +1,120 @@
|
||||
from datetime import datetime, timezone
|
||||
import uuid
|
||||
from sqlalchemy import BigInteger, Boolean, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
|
||||
from sqlalchemy.dialects.mysql import DATETIME
|
||||
|
||||
# MySQL's plain DATETIME truncates fractions, scrambling FIFO for jobs created
|
||||
# within one second. Keep the same microsecond precision as SQLite/Python UTC.
|
||||
Timestamp = DateTime().with_variant(DATETIME(fsp=6), "mysql")
|
||||
|
||||
|
||||
def utcnow():
|
||||
return datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
|
||||
|
||||
def new_id():
|
||||
return uuid.uuid4().hex
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = "visual_users"
|
||||
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
|
||||
username: Mapped[str] = mapped_column(String(64), unique=True)
|
||||
display_name: Mapped[str] = mapped_column(String(80))
|
||||
password_hash: Mapped[str] = mapped_column(String(512))
|
||||
role: Mapped[str] = mapped_column(String(16), default="user")
|
||||
disabled: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow)
|
||||
|
||||
|
||||
class Session(Base):
|
||||
__tablename__ = "visual_sessions"
|
||||
token_hash: Mapped[str] = mapped_column(String(64), primary_key=True)
|
||||
user_id: Mapped[str] = mapped_column(ForeignKey("visual_users.id"), index=True)
|
||||
csrf_token: Mapped[str] = mapped_column(String(128))
|
||||
expires_at: Mapped[datetime] = mapped_column(Timestamp, index=True)
|
||||
created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow)
|
||||
|
||||
|
||||
class Asset(Base):
|
||||
__tablename__ = "visual_assets"
|
||||
__table_args__ = (UniqueConstraint("source_job_id", "source_output_index"),
|
||||
UniqueConstraint("source_upstream_id", "source_output_index"))
|
||||
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
|
||||
owner_id: Mapped[str] = mapped_column(ForeignKey("visual_users.id"), index=True)
|
||||
name: Mapped[str] = mapped_column(String(255))
|
||||
storage_key: Mapped[str] = mapped_column(String(512), unique=True)
|
||||
thumbnail_key: Mapped[str | None] = mapped_column(String(512), nullable=True)
|
||||
kind: Mapped[str] = mapped_column(String(16))
|
||||
mime_type: Mapped[str] = mapped_column(String(128))
|
||||
size_bytes: Mapped[int] = mapped_column(BigInteger)
|
||||
sha256: Mapped[str] = mapped_column(String(64))
|
||||
width: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
height: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
duration_seconds: Mapped[float | None] = mapped_column(nullable=True)
|
||||
tags: Mapped[list] = mapped_column(JSON, default=list)
|
||||
favorite: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
origin: Mapped[str] = mapped_column(String(16), default="upload")
|
||||
ready: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||
source_job_id: Mapped[str | None] = mapped_column(ForeignKey("visual_jobs.id"), nullable=True, index=True)
|
||||
source_upstream_id: Mapped[str | None] = mapped_column(String(128), nullable=True)
|
||||
source_output_index: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow, index=True)
|
||||
deleted_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True)
|
||||
|
||||
|
||||
class Job(Base):
|
||||
__tablename__ = "visual_jobs"
|
||||
__table_args__ = (UniqueConstraint("owner_id", "request_key", "batch_index"),
|
||||
Index("visual_jobs_dispatch", "state", "next_action_at"))
|
||||
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
|
||||
owner_id: Mapped[str] = mapped_column(ForeignKey("visual_users.id"), index=True)
|
||||
task_type: Mapped[str] = mapped_column(String(48))
|
||||
state: Mapped[str] = mapped_column(String(24))
|
||||
phase: Mapped[str] = mapped_column(String(48))
|
||||
version: Mapped[int] = mapped_column(Integer, default=1)
|
||||
input_json: Mapped[dict] = mapped_column(JSON)
|
||||
parameters: Mapped[dict] = mapped_column(JSON)
|
||||
request_key: Mapped[str | None] = mapped_column(String(128), nullable=True)
|
||||
request_hash: Mapped[str] = mapped_column(String(64))
|
||||
batch_index: Mapped[int] = mapped_column(Integer, default=0)
|
||||
upstream_key: Mapped[str] = mapped_column(String(128), unique=True)
|
||||
upstream_id: Mapped[str | None] = mapped_column(String(128), nullable=True, unique=True)
|
||||
upstream_payload: Mapped[dict | None] = mapped_column(JSON, nullable=True)
|
||||
upstream_result: Mapped[dict | None] = mapped_column(JSON, nullable=True)
|
||||
result_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)
|
||||
error_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)
|
||||
cancel_requested: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
attempt_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
work_attempt: Mapped[int] = mapped_column(Integer, default=0)
|
||||
preemptions: Mapped[int] = mapped_column(Integer, default=0)
|
||||
last_preempted_reason: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
sync_warning: Mapped[str | None] = mapped_column(String(512), nullable=True)
|
||||
sync_failures: Mapped[int] = mapped_column(Integer, default=0)
|
||||
next_action_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow)
|
||||
created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow, index=True)
|
||||
scheduled_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True)
|
||||
started_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True)
|
||||
finished_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True)
|
||||
|
||||
|
||||
class JobAsset(Base):
|
||||
__tablename__ = "visual_job_assets"
|
||||
job_id: Mapped[str] = mapped_column(ForeignKey("visual_jobs.id"), primary_key=True)
|
||||
asset_id: Mapped[str] = mapped_column(ForeignKey("visual_assets.id"), primary_key=True)
|
||||
|
||||
|
||||
class Event(Base):
|
||||
__tablename__ = "visual_job_events"
|
||||
__table_args__ = (Index("visual_events_owner_cursor", "owner_id", "id"),)
|
||||
id: Mapped[int] = mapped_column(BigInteger().with_variant(Integer, "sqlite"), primary_key=True, autoincrement=True)
|
||||
owner_id: Mapped[str] = mapped_column(ForeignKey("visual_users.id"))
|
||||
job_id: Mapped[str | None] = mapped_column(String(32), nullable=True)
|
||||
event_type: Mapped[str] = mapped_column(String(48))
|
||||
data: Mapped[dict] = mapped_column(JSON)
|
||||
created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow)
|
||||
775
backend/app/providers.py
Normal file
@ -0,0 +1,775 @@
|
||||
"""Database-independent adapters for deployed GPU jobs, text/vision and CPU media."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
import html
|
||||
from io import BytesIO
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import stat
|
||||
import time
|
||||
from urllib.parse import urlsplit
|
||||
import uuid
|
||||
|
||||
import httpx
|
||||
from PIL import Image, ImageOps
|
||||
|
||||
from .media import MediaError as ProviderError, confined, input_options, inspect_media, run_process
|
||||
|
||||
|
||||
GPU_TASKS = {'image.generate', 'video.generate', 'defect.generate', 'audio.transcribe'}
|
||||
LANGUAGES = ['zh', 'en', 'ja', 'ko', 'de', 'fr', 'es', 'ru', 'ar', 'pt', 'it', 'auto']
|
||||
_UUID = re.compile(r'GPU-[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}\Z')
|
||||
|
||||
|
||||
@dataclass
|
||||
class CpuResult:
|
||||
outputs: list[Path]
|
||||
result: dict
|
||||
metadata: dict
|
||||
|
||||
|
||||
def _invalid(message='任务输入或参数无效。'):
|
||||
return ProviderError('invalid_input', message)
|
||||
|
||||
|
||||
def _keys(value, allowed):
|
||||
if not isinstance(value, dict) or set(value) - set(allowed):
|
||||
raise _invalid('包含不支持的输入或参数。')
|
||||
|
||||
|
||||
def _int(value, low, high, step=1):
|
||||
if type(value) is not int or not low <= value <= high or value % step:
|
||||
raise _invalid('整数参数超出范围或步长不正确。')
|
||||
return value
|
||||
|
||||
|
||||
def _float(value, low, high):
|
||||
if isinstance(value, bool) or not isinstance(value, (float, int)):
|
||||
raise _invalid('数值参数无效。')
|
||||
try:
|
||||
normalized = float(value)
|
||||
except (ValueError, OverflowError):
|
||||
raise _invalid('数值参数无效。') from None
|
||||
if not math.isfinite(normalized) or not low <= normalized <= high:
|
||||
raise _invalid('数值参数超出范围。')
|
||||
return normalized
|
||||
|
||||
|
||||
def _string(value, maximum=8000, *, required=True):
|
||||
if not isinstance(value, str) or len(value) > maximum or (required and not value.strip()):
|
||||
raise _invalid('文字内容为空或超出长度限制。')
|
||||
return value
|
||||
|
||||
|
||||
def _voices(settings):
|
||||
values = getattr(settings, 'tts_voices', ['zf_xiaobei', 'zm_yunxi'])
|
||||
if isinstance(values, str):
|
||||
values = [item.strip() for item in values.split(',') if item.strip()]
|
||||
return [value for value in values if isinstance(value, str) and re.fullmatch(r'[A-Za-z0-9_-]{1,64}', value)]
|
||||
|
||||
|
||||
def capabilities(settings) -> list[dict]:
|
||||
image_defaults = {'width': 1024, 'height': 1024, 'num_inference_steps': 50, 'seed': 42, 'guidance_scale': 4.0}
|
||||
image_limits = {'width': {'min': 256, 'max': 2048, 'step': 16},
|
||||
'height': {'min': 256, 'max': 2048, 'step': 16},
|
||||
'num_inference_steps': {'min': 1, 'max': 100},
|
||||
'guidance_scale': {'min': 1, 'max': 20}, 'seed': {'min': 0, 'max': 2**32 - 1},
|
||||
'count': {'min': 1, 'max': 4}, 'max_pixels': 2048 * 2048}
|
||||
video_defaults = dict(image_defaults, width=1280, height=704, guidance_scale=5.0,
|
||||
num_frames=121, fps=24, upscale=True, upscale_width=1920, upscale_height=1080, tile_size=128)
|
||||
video_limits = {**image_limits, 'width': {'min': 256, 'max': 1280, 'step': 32},
|
||||
'height': {'min': 256, 'max': 1280, 'step': 32}, 'max_pixels': 1280 * 704,
|
||||
'count': {'min': 1, 'max': 1}, 'num_frames': {'min': 5, 'max': 121, 'step': 4},
|
||||
'fps': {'values': [24]}, 'upscale': {'values': [True, False]},
|
||||
'upscale_width': {'min': 256, 'max': 3840, 'step': 2},
|
||||
'upscale_height': {'min': 256, 'max': 2160, 'step': 2}, 'tile_size': {'min': 64, 'max': 256, 'step': 16}}
|
||||
configured = bool(getattr(settings, 'inference_base_url', ''))
|
||||
qwen = bool(getattr(settings, 'qwen_base_url', '') and getattr(settings, 'qwen_model', ''))
|
||||
speech = bool(getattr(settings, 'tts_base_url', '') and getattr(settings, 'tts_model', '') and _voices(settings))
|
||||
def item(task_type, label, model, available, types, defaults, constraints, description):
|
||||
return dict(task_type=task_type, label=label, model=model, available=available,
|
||||
input_types=types, defaults=defaults, constraints=constraints, description=description)
|
||||
return [
|
||||
item('image.generate', '图像生成', 'Qwen-Image', configured, ['text'], image_defaults, image_limits,
|
||||
'文字生成图片;不包含图像编辑或风格 LoRA 管理。'),
|
||||
item('video.generate', '视频生成', 'Wan2.2-TI2V-5B + Real-ESRGAN', configured, ['text', 'image'],
|
||||
video_defaults, video_limits, '最多121帧、24fps,约5秒无声视频;可选1080p增强。'),
|
||||
item('defect.generate', '条件样本生成', 'SDXL + Canny ControlNet', configured, ['text', 'image'],
|
||||
dict(image_defaults, guidance_scale=7.5, controlnet_conditioning_scale=.8, canny_low=100, canny_high=200),
|
||||
{**image_limits, 'controlnet_conditioning_scale': {'min': 0, 'max': 2},
|
||||
'canny_low': {'min': 0, 'max': 255}, 'canny_high': {'min': 0, 'max': 255}},
|
||||
'参考图片提供边缘结构;输出控制图不是缺陷真值掩膜。'),
|
||||
item('audio.transcribe', '语音转写', 'Whisper-large-v3-turbo', configured, ['audio', 'video'],
|
||||
{'language': 'zh', 'max_audio_seconds': 1800},
|
||||
{'language': {'values': LANGUAGES}, 'max_audio_seconds': {'min': 1, 'max': 1800}},
|
||||
'支持音频和有声视频;时间戳为30秒块边界,不是字词对齐。'),
|
||||
item('math.solve', '数学推演', getattr(settings, 'qwen_model', ''), qwen, ['text'],
|
||||
{'max_tokens': 2048, 'enable_thinking': False}, {'max_tokens': {'min': 1, 'max': 4096}},
|
||||
'调用现有文本服务给出解答,未集成形式化证明或准确率评测。'),
|
||||
item('media.structure', '素材理解', getattr(settings, 'qwen_model', ''), qwen, ['image', 'video'],
|
||||
{'frame_count': 6}, {'frame_count': {'min': 1, 'max': 12}},
|
||||
'视频均匀抽帧后理解画面、文字和标签;不承诺镜头切分准确率。'),
|
||||
item('video.compose', '成片编排', 'FFmpeg CPU', True, ['video', 'audio'],
|
||||
{'width': 1280, 'height': 720, 'fps': 24},
|
||||
{'width': {'min': 256, 'max': 3840, 'step': 2}, 'height': {'min': 256, 'max': 2160, 'step': 2},
|
||||
'fps': {'values': [24, 25, 30, 60]}, 'clips': {'min': 1, 'max': 24},
|
||||
'duration_seconds': {'min': .05, 'max': 1800}},
|
||||
'按顺序裁剪拼接片段,支持上传音轨和人工字幕;无热度预测。'),
|
||||
item('audio.speech', '中文配音', getattr(settings, 'tts_model', '') or '尚未配置', speech, ['text'],
|
||||
{'voice': (_voices(settings) or [''])[0], 'speed': 1.0},
|
||||
{'voice': {'values': _voices(settings)}, 'speed': {'min': .5, 'max': 2}, 'text': {'max': 2000}},
|
||||
'仅在配置真实语音服务后可用;输出 WAV,不提供音乐生成。'),
|
||||
]
|
||||
|
||||
|
||||
def validate_arguments(task_type: str, inputs: dict, parameters: dict, settings=None) -> None:
|
||||
"""Pure submission validation: no HTTP, file decoding, mkdir or model work."""
|
||||
p = parameters
|
||||
if task_type in GPU_TASKS:
|
||||
allowed = {'audio_asset_id', 'asset_id'} if task_type == 'audio.transcribe' else {'prompt', 'negative_prompt'}
|
||||
if task_type in {'video.generate', 'defect.generate'}:
|
||||
allowed.add('image_asset_id')
|
||||
_keys(inputs, allowed)
|
||||
defaults = next(item['defaults'] for item in capabilities(settings) if item['task_type'] == task_type)
|
||||
_keys(p, set(defaults) | ({'negative_prompt'} if task_type != 'audio.transcribe' else set()))
|
||||
p = {**defaults, **p}
|
||||
if task_type == 'audio.transcribe':
|
||||
if not (inputs.get('audio_asset_id') or inputs.get('asset_id')):
|
||||
raise _invalid('请选择转写素材。')
|
||||
if inputs.get('audio_asset_id') and inputs.get('asset_id') and inputs['audio_asset_id'] != inputs['asset_id']:
|
||||
raise _invalid('请仅选择一个转写素材。')
|
||||
if p['language'] not in LANGUAGES:
|
||||
raise _invalid('不支持此转写语言。')
|
||||
_int(p['max_audio_seconds'], 1, 1800)
|
||||
return
|
||||
_string(inputs.get('prompt'))
|
||||
_string(inputs.get('negative_prompt', ''), required=False)
|
||||
if 'negative_prompt' in p:
|
||||
_string(p['negative_prompt'], required=False)
|
||||
video = task_type == 'video.generate'
|
||||
for key in ('width', 'height'):
|
||||
_int(p[key], 256, 1280 if video else 2048, 32 if video else 16)
|
||||
if p['width'] * p['height'] > (1280 * 704 if video else 2048 * 2048):
|
||||
raise _invalid('画面像素总数超出服务限制。')
|
||||
_int(p['num_inference_steps'], 1, 100)
|
||||
_int(p['seed'], 0, 2**32 - 1)
|
||||
_float(p['guidance_scale'], 1, 20)
|
||||
if task_type == 'defect.generate':
|
||||
if not inputs.get('image_asset_id'):
|
||||
raise _invalid('条件样本任务需要参考图片。')
|
||||
_float(p['controlnet_conditioning_scale'], 0, 2)
|
||||
_int(p['canny_low'], 0, 255)
|
||||
_int(p['canny_high'], 0, 255)
|
||||
if p['canny_low'] >= p['canny_high']:
|
||||
raise _invalid('Canny低阈值必须小于高阈值。')
|
||||
if video:
|
||||
_int(p['num_frames'], 5, 121)
|
||||
if p['num_frames'] % 4 != 1 or type(p['fps']) is not int or p['fps'] != 24 or type(p['upscale']) is not bool:
|
||||
raise _invalid('视频帧数、帧率或增强开关无效。')
|
||||
_int(p['upscale_width'], 256, 3840, 2)
|
||||
_int(p['upscale_height'], 256, 2160, 2)
|
||||
_int(p['tile_size'], 64, 256, 16)
|
||||
return
|
||||
if task_type == 'math.solve':
|
||||
_keys(inputs, {'prompt'})
|
||||
_keys(p, {'max_tokens', 'enable_thinking'})
|
||||
_string(inputs.get('prompt'))
|
||||
_int(p.get('max_tokens', 2048), 1, 4096)
|
||||
if type(p.get('enable_thinking', False)) is not bool:
|
||||
raise _invalid('思考开关必须为布尔值。')
|
||||
return
|
||||
if task_type == 'media.structure':
|
||||
_keys(inputs, {'asset_id', 'image_asset_id'})
|
||||
_keys(p, {'frame_count'})
|
||||
if not (inputs.get('asset_id') or inputs.get('image_asset_id')):
|
||||
raise _invalid('请选择待理解素材。')
|
||||
if inputs.get('asset_id') and inputs.get('image_asset_id') and inputs['asset_id'] != inputs['image_asset_id']:
|
||||
raise _invalid('请选择一个待理解素材。')
|
||||
_int(p.get('frame_count', 6), 1, 12)
|
||||
return
|
||||
if task_type == 'audio.speech':
|
||||
_keys(inputs, {'prompt'})
|
||||
_keys(p, {'voice', 'speed'})
|
||||
_string(inputs.get('prompt'), 2000)
|
||||
voices = _voices(settings)
|
||||
if not voices or p.get('voice', voices[0]) not in voices:
|
||||
raise _invalid('请选择已配置的中文音色。')
|
||||
_float(p.get('speed', 1), .5, 2)
|
||||
return
|
||||
if task_type == 'video.compose':
|
||||
_keys(inputs, {'asset_ids', 'audio_asset_id'})
|
||||
_keys(p, {'clips', 'audio_asset_id', 'subtitles', 'width', 'height', 'fps'})
|
||||
clips = p.get('clips')
|
||||
if not isinstance(clips, list) or not 1 <= len(clips) <= 24:
|
||||
raise _invalid('请选择1至24个视频片段。')
|
||||
for clip in clips:
|
||||
_keys(clip, {'asset_id', 'start_seconds', 'end_seconds'})
|
||||
_string(clip.get('asset_id'), 64)
|
||||
start = _float(clip.get('start_seconds', 0), 0, 1800)
|
||||
if clip.get('end_seconds') is not None and _float(clip['end_seconds'], 0, 1800) <= start:
|
||||
raise _invalid('片段结束时间必须大于开始时间。')
|
||||
if 'asset_ids' in inputs and inputs['asset_ids'] != [clip['asset_id'] for clip in clips]:
|
||||
raise _invalid('素材顺序应与编排片段一致。')
|
||||
if inputs.get('audio_asset_id') and p.get('audio_asset_id') and inputs['audio_asset_id'] != p['audio_asset_id']:
|
||||
raise _invalid('请只选择一个成片音轨。')
|
||||
_int(p.get('width', 1280), 256, 3840, 2)
|
||||
_int(p.get('height', 720), 256, 2160, 2)
|
||||
if type(p.get('fps', 24)) is not int or p.get('fps', 24) not in {24, 25, 30, 60}:
|
||||
raise _invalid('不支持此成片帧率。')
|
||||
cues = p.get('subtitles', [])
|
||||
if not isinstance(cues, list) or len(cues) > 1000:
|
||||
raise _invalid('人工字幕数量超出限制。')
|
||||
for cue in cues:
|
||||
_keys(cue, {'start', 'end', 'text'})
|
||||
start, end = _float(cue.get('start'), 0, 1800), _float(cue.get('end'), 0, 1800)
|
||||
text = _string(cue.get('text'), 2000)
|
||||
if end <= start or '\n\n' in text or re.search(r'[\\{}\x00-\x08\x0b-\x1f]', text):
|
||||
raise _invalid('字幕时间或纯文本内容无效;不支持ASS控制语法。')
|
||||
return
|
||||
raise _invalid('不支持此任务类型。')
|
||||
|
||||
|
||||
def _read_key(path):
|
||||
descriptor = None
|
||||
try:
|
||||
path = Path(path)
|
||||
if not path.is_absolute() or path.is_symlink():
|
||||
raise ValueError
|
||||
descriptor = os.open(path, os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0))
|
||||
info = os.fstat(descriptor)
|
||||
if not stat.S_ISREG(info.st_mode) or (os.name == 'posix' and info.st_mode & 0o022):
|
||||
raise ValueError
|
||||
raw = os.read(descriptor, 4097)
|
||||
value = raw.decode('utf-8').strip()
|
||||
if not value or len(raw) > 4096 or '\n' in value or '\r' in value:
|
||||
raise ValueError
|
||||
return value
|
||||
except (OSError, ValueError, UnicodeError):
|
||||
raise ProviderError('provider_not_configured', '模型服务认证配置不可用。', True) from None
|
||||
finally:
|
||||
if descriptor is not None:
|
||||
os.close(descriptor)
|
||||
|
||||
|
||||
def _url(base, suffix):
|
||||
if not isinstance(base, str) or not base:
|
||||
raise ProviderError('capability_unavailable', '此能力尚未配置。')
|
||||
parsed = urlsplit(base)
|
||||
if parsed.scheme not in {'http', 'https'} or not parsed.hostname or parsed.username or parsed.password or parsed.query or parsed.fragment:
|
||||
raise ProviderError('provider_not_configured', '模型服务地址配置无效。', True)
|
||||
return base.rstrip('/') + suffix
|
||||
|
||||
|
||||
class Provider:
|
||||
def __init__(self, settings):
|
||||
self.settings = settings
|
||||
self.client = httpx.AsyncClient(trust_env=False, follow_redirects=False,
|
||||
timeout=httpx.Timeout(float(settings.request_timeout_seconds)),
|
||||
limits=httpx.Limits(max_connections=4, max_keepalive_connections=2))
|
||||
|
||||
async def aclose(self):
|
||||
await self.client.aclose()
|
||||
|
||||
def _headers(self, family='inference'):
|
||||
key = getattr(self.settings, family + '_api_key', '') or ''
|
||||
if family == 'inference' and getattr(self.settings, 'inference_api_key_file', None):
|
||||
key = _read_key(self.settings.inference_api_key_file)
|
||||
if not isinstance(key, str) or len(key) > 4096 or any(not 32 <= ord(char) <= 126 for char in key):
|
||||
raise ProviderError('provider_not_configured', '模型服务认证配置不可用。', True)
|
||||
return {'Authorization': 'Bearer ' + key} if key else {}
|
||||
|
||||
@staticmethod
|
||||
def _http_error(status):
|
||||
if status in {400, 413, 415, 422}:
|
||||
return ProviderError('upstream_rejected', '模型服务拒绝了任务输入或参数。')
|
||||
if status == 404:
|
||||
return ProviderError('upstream_not_found', '模型服务未找到请求的任务或结果。', True)
|
||||
if status == 409:
|
||||
return ProviderError('upstream_conflict', '模型任务或幂等请求发生冲突。')
|
||||
return ProviderError('upstream_unavailable', '模型服务暂时不可用。', True)
|
||||
|
||||
async def _json(self, method, url, *, payload=None, headers=None):
|
||||
try:
|
||||
async with asyncio.timeout(float(self.settings.request_timeout_seconds) + 1):
|
||||
async with self.client.stream(method, url, json=payload, headers=headers) as response:
|
||||
if not 200 <= response.status_code < 300:
|
||||
raise self._http_error(response.status_code)
|
||||
data, size = [], 0
|
||||
async for chunk in response.aiter_bytes():
|
||||
size += len(chunk)
|
||||
if size > 2 * 1024 * 1024:
|
||||
raise ProviderError('invalid_upstream_response', '模型服务响应超出限制。', True)
|
||||
data.append(chunk)
|
||||
value = json.loads(b''.join(data))
|
||||
if not isinstance(value, dict):
|
||||
raise ValueError
|
||||
return value
|
||||
except (httpx.HTTPError, asyncio.TimeoutError):
|
||||
raise ProviderError('upstream_unavailable', '模型服务连接失败或响应超时。', True) from None
|
||||
except (ValueError, UnicodeError, RecursionError):
|
||||
raise ProviderError('invalid_upstream_response', '模型服务返回了无效响应。', True) from None
|
||||
|
||||
async def health(self):
|
||||
try:
|
||||
value = await self._json('GET', _url(self.settings.inference_base_url, '/health'), headers=self._headers())
|
||||
return value.get('status') == 'ok'
|
||||
except ProviderError:
|
||||
return False
|
||||
|
||||
async def scheduler_status(self):
|
||||
unavailable = {'available': False, 'state': 'unavailable', 'reason': 'GPU状态暂时不可用。', 'gpus': [], 'updated_at': None}
|
||||
try:
|
||||
path = Path(self.settings.gpu_status_path)
|
||||
if path.stat().st_size > 1024 * 1024:
|
||||
return unavailable
|
||||
data = json.loads(path.read_bytes())
|
||||
now = time.time()
|
||||
generated = _float(data['generated_at'], 0, now + 1)
|
||||
if data['schema_version'] != 1 or data.get('error') is not None or now - generated > 5:
|
||||
return unavailable
|
||||
seen, gpus = set(), []
|
||||
for gpu in data['gpus']:
|
||||
index = _int(gpu['index'], 0, 1024)
|
||||
if index in seen or not isinstance(gpu['uuid'], str) or not _UUID.fullmatch(gpu['uuid']):
|
||||
return unavailable
|
||||
seen.add(index)
|
||||
total = _float(gpu['total_gib'], .001, 100000)
|
||||
free = _float(gpu['free_gib'], 0, total)
|
||||
external, own = gpu['external_pids'], gpu['own_pids']
|
||||
if not all(isinstance(values, list) and all(type(pid) is int and pid > 0 for pid in values)
|
||||
for values in (external, own)):
|
||||
return unavailable
|
||||
idle = gpu.get('idle_since')
|
||||
if idle is not None:
|
||||
idle = _float(idle, 0, now + 1)
|
||||
busy = bool(external or own)
|
||||
gpus.append({'index': index, 'name': f'GPU {index}', 'busy': busy,
|
||||
'eligible': not busy and free >= 76 and idle is not None and now - idle >= 15, 'free_gib': free})
|
||||
state = 'ready' if any(gpu['eligible'] for gpu in gpus) else 'waiting'
|
||||
reason = None if state == 'ready' else '等待可用GPU,外部任务优先。'
|
||||
try:
|
||||
scheduler_path = Path(self.settings.gpu_scheduler_path)
|
||||
if scheduler_path.stat().st_size <= 1024 * 1024:
|
||||
scheduler = json.loads(scheduler_path.read_bytes())
|
||||
if scheduler.get('state') in {'blocked', 'preempting'}:
|
||||
state = scheduler['state']
|
||||
reason = '正在释放GPU并等待重新排队。' if state == 'preempting' else '执行器需要管理员检查。'
|
||||
elif scheduler.get('state') == 'leased' and any(gpu['busy'] for gpu in gpus):
|
||||
state, reason = 'running', '模型任务正在执行。'
|
||||
except (OSError, ValueError, TypeError, AttributeError):
|
||||
pass
|
||||
return {'available': True, 'state': state, 'reason': reason, 'gpus': gpus,
|
||||
'updated_at': datetime.fromtimestamp(generated, timezone.utc).isoformat()}
|
||||
except (OSError, ValueError, TypeError, KeyError, AttributeError, ProviderError, OverflowError):
|
||||
return unavailable
|
||||
|
||||
def _work(self, path):
|
||||
work = confined(path, self.settings, exists=False, root=self.settings.job_work_root)
|
||||
if not work.is_dir():
|
||||
raise _invalid('任务工作目录不可用。')
|
||||
return work
|
||||
|
||||
def _asset(self, asset_id, assets):
|
||||
if not isinstance(asset_id, str) or asset_id not in assets:
|
||||
raise _invalid('请选择可访问的素材。')
|
||||
return confined(assets[asset_id], self.settings)
|
||||
|
||||
async def prepare_gpu_payload(self, task_type, inputs, parameters, assets, work_dir):
|
||||
validate_arguments(task_type, inputs, parameters, self.settings)
|
||||
work = self._work(work_dir)
|
||||
if task_type not in GPU_TASKS:
|
||||
raise _invalid('不支持此模型任务类型。')
|
||||
p = dict(parameters) if isinstance(parameters, dict) else parameters
|
||||
allowed_input = {'audio_asset_id', 'asset_id'} if task_type == 'audio.transcribe' else {'prompt', 'negative_prompt'}
|
||||
if task_type in {'video.generate', 'defect.generate'}:
|
||||
allowed_input.add('image_asset_id')
|
||||
_keys(inputs, allowed_input)
|
||||
defaults = next(item['defaults'] for item in capabilities(self.settings) if item['task_type'] == task_type)
|
||||
_keys(p, set(defaults) | ({'negative_prompt'} if task_type != 'audio.transcribe' else set()))
|
||||
normalized = {**defaults, **p}
|
||||
out = {}
|
||||
if task_type == 'audio.transcribe':
|
||||
asset_id = inputs.get('audio_asset_id') or inputs.get('asset_id')
|
||||
if inputs.get('audio_asset_id') and inputs.get('asset_id') and inputs['audio_asset_id'] != inputs['asset_id']:
|
||||
raise _invalid('请仅选择一个转写素材。')
|
||||
source = self._asset(asset_id, assets)
|
||||
info = await inspect_media(source, self.settings)
|
||||
if normalized['language'] not in LANGUAGES:
|
||||
raise _invalid('不支持此转写语言。')
|
||||
_int(normalized['max_audio_seconds'], 1, 1800)
|
||||
if info['kind'] not in {'audio', 'video'} or info['duration_seconds'] > normalized['max_audio_seconds']:
|
||||
raise _invalid('请选择时长受限的音频或有声视频。')
|
||||
if info['kind'] == 'video':
|
||||
target = work / 'asr-input.wav'
|
||||
temporary = work / ('asr-' + uuid.uuid4().hex + '.wav')
|
||||
try:
|
||||
await run_process([self.settings.ffmpeg_bin, '-v', 'error', '-nostdin', *input_options(),
|
||||
'-i', str(source), '-map', '0:a:0', '-vn', '-ac', '1', '-ar', '16000',
|
||||
'-c:a', 'pcm_s16le', '-t', str(normalized['max_audio_seconds']), '-threads', '2', str(temporary)], timeout=300)
|
||||
if not temporary.is_file() or not temporary.stat().st_size:
|
||||
raise _invalid('视频没有可转写的音轨。')
|
||||
os.replace(temporary, target)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
source = target
|
||||
out['audio_path'] = str(source)
|
||||
else:
|
||||
out['prompt'] = _string(inputs.get('prompt'))
|
||||
out['negative_prompt'] = _string(normalized.pop('negative_prompt', inputs.get('negative_prompt', '')), required=False)
|
||||
video = task_type == 'video.generate'
|
||||
for key in ('width', 'height'):
|
||||
_int(normalized[key], 256, 1280 if video else 2048, 32 if video else 16)
|
||||
if normalized['width'] * normalized['height'] > (1280 * 704 if video else 2048 * 2048):
|
||||
raise _invalid('画面像素总数超出服务限制。')
|
||||
_int(normalized['num_inference_steps'], 1, 100)
|
||||
_int(normalized['seed'], 0, 2**32 - 1)
|
||||
normalized['guidance_scale'] = _float(normalized['guidance_scale'], 1, 20)
|
||||
if 'image_asset_id' in inputs:
|
||||
source = self._asset(inputs['image_asset_id'], assets)
|
||||
if (await inspect_media(source, self.settings))['kind'] != 'image':
|
||||
raise _invalid('参考素材必须是图片。')
|
||||
out['image_path'] = str(source)
|
||||
if task_type == 'defect.generate':
|
||||
if 'image_path' not in out:
|
||||
raise _invalid('条件样本任务需要参考图片。')
|
||||
normalized['controlnet_conditioning_scale'] = _float(normalized['controlnet_conditioning_scale'], 0, 2)
|
||||
_int(normalized['canny_low'], 0, 255)
|
||||
_int(normalized['canny_high'], 0, 255)
|
||||
if normalized['canny_low'] >= normalized['canny_high']:
|
||||
raise _invalid('Canny低阈值必须小于高阈值。')
|
||||
if video:
|
||||
_int(normalized['num_frames'], 5, 121)
|
||||
if normalized['num_frames'] % 4 != 1 or type(normalized['fps']) is not int or normalized['fps'] != 24:
|
||||
raise _invalid('视频仅支持4n+1帧、最多121帧和24fps。')
|
||||
if type(normalized['upscale']) is not bool:
|
||||
raise _invalid('增强开关必须为布尔值。')
|
||||
_int(normalized['upscale_width'], 256, 3840, 2)
|
||||
_int(normalized['upscale_height'], 256, 2160, 2)
|
||||
_int(normalized['tile_size'], 64, 256, 16)
|
||||
return {'task_type': task_type, 'input': out, 'parameters': normalized, 'timeout_seconds': 3600}
|
||||
|
||||
async def submit(self, payload, idempotency_key):
|
||||
_string(idempotency_key, 128)
|
||||
if any(not 33 <= ord(char) <= 126 for char in idempotency_key):
|
||||
raise _invalid('幂等请求标识无效。')
|
||||
return self._sanitize_job(await self._json('POST', _url(self.settings.inference_base_url, '/jobs'), payload=payload,
|
||||
headers={**self._headers(), 'Idempotency-Key': idempotency_key}))
|
||||
|
||||
@staticmethod
|
||||
def _job_id(value):
|
||||
if not isinstance(value, str) or re.fullmatch(r'[0-9a-f]{32}', value) is None:
|
||||
raise _invalid('模型任务标识无效。')
|
||||
return value
|
||||
|
||||
@staticmethod
|
||||
def _sanitize_job(value):
|
||||
if value.get('error'):
|
||||
value['error'] = '模型任务执行失败,请检查任务输入或联系管理员。'
|
||||
if value.get('last_preempted_reason'):
|
||||
value['last_preempted_reason'] = 'GPU资源已让出,任务重新排队。'
|
||||
return value
|
||||
|
||||
async def query(self, upstream_id):
|
||||
return self._sanitize_job(await self._json('GET', _url(self.settings.inference_base_url,
|
||||
'/jobs/' + self._job_id(upstream_id)), headers=self._headers()))
|
||||
|
||||
async def cancel(self, upstream_id):
|
||||
return self._sanitize_job(await self._json('POST', _url(self.settings.inference_base_url,
|
||||
'/jobs/' + self._job_id(upstream_id) + '/cancel'), headers=self._headers()))
|
||||
|
||||
async def _download_url(self, url, destination, headers, *, payload=None):
|
||||
target = confined(destination, self.settings, exists=False)
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = target.with_name(target.name + '.part-' + uuid.uuid4().hex)
|
||||
try:
|
||||
async with asyncio.timeout(max(30, min(600, float(self.settings.request_timeout_seconds) * 4))):
|
||||
async with self.client.stream('POST' if payload is not None else 'GET', url,
|
||||
headers=headers, json=payload) as response:
|
||||
if not 200 <= response.status_code < 300:
|
||||
raise self._http_error(response.status_code)
|
||||
limit = int(self.settings.max_output_bytes)
|
||||
declared = response.headers.get('Content-Length')
|
||||
if declared is not None and (not declared.isdigit() or int(declared) > limit):
|
||||
raise ProviderError('output_too_large', '输出文件超出大小限制。')
|
||||
count = 0
|
||||
with temporary.open('xb') as stream:
|
||||
async for chunk in response.aiter_bytes():
|
||||
count += len(chunk)
|
||||
if count > limit:
|
||||
raise ProviderError('output_too_large', '输出文件超出大小限制。')
|
||||
stream.write(chunk)
|
||||
if not count or (declared is not None and count != int(declared)):
|
||||
raise ProviderError('invalid_upstream_response', '输出文件为空或未传输完整。', True)
|
||||
os.replace(temporary, target)
|
||||
except (httpx.HTTPError, asyncio.TimeoutError):
|
||||
raise ProviderError('upstream_unavailable', '输出文件传输失败,请稍后重试。', True) from None
|
||||
except OSError:
|
||||
raise ProviderError('output_unavailable', '无法保存输出文件。', True) from None
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
|
||||
async def download(self, upstream_id, index, destination):
|
||||
_int(index, 0, 1000)
|
||||
await self._download_url(_url(self.settings.inference_base_url,
|
||||
'/jobs/' + self._job_id(upstream_id) + '/outputs/' + str(index)), destination, self._headers())
|
||||
|
||||
async def _chat(self, messages, *, max_tokens=2048, thinking=False):
|
||||
if not self.settings.qwen_model:
|
||||
raise ProviderError('capability_unavailable', '文本与视觉服务尚未配置。')
|
||||
value = await self._json('POST', _url(self.settings.qwen_base_url, '/chat/completions'),
|
||||
headers=self._headers('qwen'), payload={'model': self.settings.qwen_model, 'messages': messages,
|
||||
'stream': False, 'temperature': 0, 'max_tokens': max_tokens,
|
||||
'chat_template_kwargs': {'enable_thinking': thinking}})
|
||||
choices = value.get('choices')
|
||||
if (isinstance(choices, list) and choices and isinstance(choices[0], dict)
|
||||
and choices[0].get('finish_reason') == 'length'):
|
||||
raise ProviderError('output_truncated', '模型输出达到长度上限,内容不完整;请提高输出长度或简化要求后重新提交。')
|
||||
try:
|
||||
content = value['choices'][0]['message']['content']
|
||||
if isinstance(content, list):
|
||||
content = ''.join(part['text'] for part in content if part.get('type') == 'text')
|
||||
content = _string(content, 200_000)
|
||||
inline = re.fullmatch(r'\s*<think>.*?</think>\s*(.*)', content, flags=re.DOTALL)
|
||||
if inline:
|
||||
content = inline.group(1).strip()
|
||||
if not content:
|
||||
raise ValueError
|
||||
return content
|
||||
except (ValueError, TypeError, KeyError, IndexError, AttributeError, ProviderError):
|
||||
raise ProviderError('invalid_upstream_response', '文本服务没有返回有效内容。', True) from None
|
||||
|
||||
@staticmethod
|
||||
def _json_file(work, name, value):
|
||||
target = work / name
|
||||
temporary = work / (name + '.part-' + uuid.uuid4().hex)
|
||||
try:
|
||||
temporary.write_text(json.dumps(value, ensure_ascii=False, allow_nan=False, indent=2), encoding='utf-8')
|
||||
os.replace(temporary, target)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
return target
|
||||
|
||||
async def run_cpu(self, task_type, inputs, parameters, assets, work_dir):
|
||||
work = self._work(work_dir)
|
||||
validate_arguments(task_type, inputs, parameters, self.settings)
|
||||
try:
|
||||
if task_type == 'math.solve':
|
||||
_keys(inputs, {'prompt'})
|
||||
_keys(parameters, {'max_tokens', 'enable_thinking'})
|
||||
tokens = _int(parameters.get('max_tokens', 2048), 1, 4096)
|
||||
thinking = parameters.get('enable_thinking', False)
|
||||
if type(thinking) is not bool:
|
||||
raise _invalid('思考开关必须为布尔值。')
|
||||
text = await self._chat([{'role': 'system', 'content': '请给出可复核的数学解题步骤和最终答案;不确定时明确说明。'},
|
||||
{'role': 'user', 'content': _string(inputs.get('prompt'))}], max_tokens=tokens, thinking=thinking)
|
||||
answer = work / 'answer.txt'
|
||||
answer.write_text(text + '\n', encoding='utf-8')
|
||||
result = {'text': text}
|
||||
return CpuResult([answer, self._json_file(work, 'answer.json', result)], result,
|
||||
{'provider': 'qwen', 'model': self.settings.qwen_model, 'formal_verification': False})
|
||||
if task_type == 'media.structure':
|
||||
return await self._structure(inputs, parameters, assets, work)
|
||||
if task_type == 'video.compose':
|
||||
return await self._compose(inputs, parameters, assets, work)
|
||||
if task_type == 'audio.speech':
|
||||
return await self._speech(inputs, parameters, work)
|
||||
raise _invalid('不支持此CPU任务类型。')
|
||||
except OSError:
|
||||
raise ProviderError('output_unavailable', '任务文件处理失败。', True) from None
|
||||
|
||||
async def _image_uri(self, source):
|
||||
def encode():
|
||||
with Image.open(source) as image:
|
||||
image = ImageOps.exif_transpose(image).convert('RGB')
|
||||
image.thumbnail((1280, 1280))
|
||||
buffer = BytesIO()
|
||||
image.save(buffer, format='JPEG', quality=85)
|
||||
return 'data:image/jpeg;base64,' + base64.b64encode(buffer.getvalue()).decode('ascii')
|
||||
return await asyncio.to_thread(encode)
|
||||
|
||||
async def _structure(self, inputs, p, assets, work):
|
||||
_keys(inputs, {'asset_id', 'image_asset_id'})
|
||||
_keys(p, {'frame_count'})
|
||||
asset_id = inputs.get('asset_id') or inputs.get('image_asset_id')
|
||||
if inputs.get('asset_id') and inputs.get('image_asset_id') and inputs['asset_id'] != inputs['image_asset_id']:
|
||||
raise _invalid('请选择一个待理解素材。')
|
||||
count = _int(p.get('frame_count', 6), 1, 12)
|
||||
source = self._asset(asset_id, assets)
|
||||
info = await inspect_media(source, self.settings)
|
||||
if info['kind'] not in {'image', 'video'}:
|
||||
raise _invalid('素材理解支持图片或视频。')
|
||||
samples, outputs = [(0.0, source)], []
|
||||
if info['kind'] == 'video':
|
||||
samples = []
|
||||
for index in range(count):
|
||||
timestamp = (index + .5) * info['duration_seconds'] / count
|
||||
frame = work / f'frame-{index:03d}.jpg'
|
||||
# Fixed filters and numeric seek only; never accept a filter from input.
|
||||
_, diagnostics = await run_process([self.settings.ffmpeg_bin, '-v', 'info', '-nostdin', '-copyts', *input_options(),
|
||||
'-ss', f'{timestamp:.6f}', '-i', str(source), '-frames:v', '1', '-vf',
|
||||
'scale=1280:1280:force_original_aspect_ratio=decrease,showinfo', '-threads', '2', str(frame)],
|
||||
timeout=90, return_stderr=True)
|
||||
if not frame.is_file() or not frame.stat().st_size:
|
||||
raise ProviderError('frame_extraction_failed', '视频抽帧失败。')
|
||||
actual_pts = re.search(rb'\bpts_time:([+-]?[0-9]+(?:\.[0-9]+)?)', diagnostics)
|
||||
if actual_pts is None:
|
||||
raise ProviderError('frame_extraction_failed', '无法确认抽帧的实际时间。')
|
||||
actual_time = float(actual_pts.group(1)) - info.get('start_seconds', 0)
|
||||
if not math.isfinite(actual_time) or not -.1 <= actual_time <= info['duration_seconds'] + .1:
|
||||
raise ProviderError('frame_extraction_failed', '抽帧时间超出素材范围。')
|
||||
samples.append((max(0, actual_time), frame))
|
||||
outputs.append(frame)
|
||||
frames = []
|
||||
prompt = ('仅根据画面可见内容输出JSON对象,不要Markdown。字段 subjects 为字符串数组,scene 为字符串,'
|
||||
'ocr 为画面实际可见文字的字符串数组,tags 为字符串数组。看不清请写不确定,不要臆测人物身份。')
|
||||
for timestamp, frame in samples:
|
||||
text = await self._chat([{'role': 'user', 'content': [
|
||||
{'type': 'image_url', 'image_url': {'url': await self._image_uri(frame)}},
|
||||
{'type': 'text', 'text': prompt}]}])
|
||||
try:
|
||||
fenced = re.fullmatch(r'\s*```(?:json)?\s*(.*?)\s*```\s*', text, flags=re.DOTALL | re.IGNORECASE)
|
||||
value = json.loads(fenced.group(1) if fenced else text)
|
||||
scene = _string(value['scene'], 2000, required=False)
|
||||
normalized = {}
|
||||
for key in ('subjects', 'ocr', 'tags'):
|
||||
items = value.get(key, []) if key == 'tags' else value[key]
|
||||
if not isinstance(items, list) or len(items) > 100:
|
||||
raise ValueError
|
||||
normalized[key] = list(dict.fromkeys(_string(item, 2000, required=False) for item in items))
|
||||
frames.append({'timestamp_seconds': round(timestamp, 6), 'scene': scene, **normalized})
|
||||
except (ValueError, KeyError, TypeError, AttributeError, ProviderError):
|
||||
raise ProviderError('invalid_visual_response', '视觉服务未返回有效的结构化内容。', True) from None
|
||||
result = {'subjects': list(dict.fromkeys(item for frame in frames for item in frame['subjects'])),
|
||||
'scene': ';'.join(dict.fromkeys(frame['scene'] for frame in frames)),
|
||||
'ocr': list(dict.fromkeys(item for frame in frames for item in frame['ocr'])),
|
||||
'tags': list(dict.fromkeys(item for frame in frames for item in frame['tags'])), 'frames': frames}
|
||||
outputs.append(self._json_file(work, 'structure.json', result))
|
||||
return CpuResult(outputs, result, {'provider': 'qwen', 'model': self.settings.qwen_model,
|
||||
'sampling': 'uniform seek' if info['kind'] == 'video' else 'single image',
|
||||
'timestamp_precision': 'decoded frame PTS relative to source start', 'frame_count': len(frames)})
|
||||
|
||||
async def _speech(self, inputs, p, work):
|
||||
if not self.settings.tts_base_url or not self.settings.tts_model or not _voices(self.settings):
|
||||
raise ProviderError('capability_unavailable', '中文配音服务尚未配置。')
|
||||
_keys(inputs, {'prompt'})
|
||||
_keys(p, {'voice', 'speed'})
|
||||
text = _string(inputs.get('prompt'), 2000)
|
||||
voice = p.get('voice', _voices(self.settings)[0])
|
||||
if voice not in _voices(self.settings):
|
||||
raise _invalid('请选择已配置的中文音色。')
|
||||
speed = _float(p.get('speed', 1.0), .5, 2)
|
||||
target = work / 'speech.wav'
|
||||
await self._download_url(_url(self.settings.tts_base_url, '/audio/speech'), target, self._headers('tts'),
|
||||
payload={'model': self.settings.tts_model, 'input': text, 'voice': voice, 'speed': speed, 'response_format': 'wav'})
|
||||
info = await inspect_media(target, self.settings)
|
||||
if info['kind'] != 'audio' or info['mime_type'] != 'audio/wav':
|
||||
target.unlink(missing_ok=True)
|
||||
raise ProviderError('invalid_speech_response', '配音服务未返回有效的 WAV 音频。', True)
|
||||
return CpuResult([target], {'text': text, 'voice': voice, 'duration_seconds': info['duration_seconds']},
|
||||
{'provider': 'openai-compatible-tts', 'model': self.settings.tts_model, 'speed': speed})
|
||||
|
||||
async def _compose(self, inputs, p, assets, work):
|
||||
_keys(inputs, {'asset_ids', 'audio_asset_id'})
|
||||
_keys(p, {'clips', 'audio_asset_id', 'subtitles', 'width', 'height', 'fps'})
|
||||
clips = p.get('clips')
|
||||
if not isinstance(clips, list) or not 1 <= len(clips) <= 24:
|
||||
raise _invalid('请选择1至24个视频片段。')
|
||||
width, height, fps = p.get('width', 1280), p.get('height', 720), p.get('fps', 24)
|
||||
_int(width, 256, 3840, 2)
|
||||
_int(height, 256, 2160, 2)
|
||||
if type(fps) is not int or fps not in {24, 25, 30, 60}:
|
||||
raise _invalid('不支持此成片帧率。')
|
||||
normalized = []
|
||||
for clip in clips:
|
||||
_keys(clip, {'asset_id', 'start_seconds', 'end_seconds'})
|
||||
start = _float(clip.get('start_seconds', 0), 0, 1800)
|
||||
end = clip.get('end_seconds')
|
||||
if end is not None and _float(end, 0, 1800) <= start:
|
||||
raise _invalid('片段结束时间必须大于开始时间。')
|
||||
normalized.append((self._asset(clip.get('asset_id'), assets), start, end))
|
||||
if 'asset_ids' in inputs and inputs['asset_ids'] != [clip['asset_id'] for clip in clips]:
|
||||
raise _invalid('素材顺序应与编排片段一致。')
|
||||
a, b = inputs.get('audio_asset_id'), p.get('audio_asset_id')
|
||||
if a and b and a != b:
|
||||
raise _invalid('请只选择一个成片音轨。')
|
||||
audio = self._asset(a or b, assets) if a or b else None
|
||||
subtitles = p.get('subtitles', [])
|
||||
if not isinstance(subtitles, list) or len(subtitles) > 1000:
|
||||
raise _invalid('人工字幕数量超出限制。')
|
||||
cues = []
|
||||
for cue in subtitles:
|
||||
_keys(cue, {'start', 'end', 'text'})
|
||||
start, end = _float(cue.get('start'), 0, 1800), _float(cue.get('end'), 0, 1800)
|
||||
text = _string(cue.get('text'), 2000)
|
||||
if end <= start or '\n\n' in text or re.search(r'[\\{}\x00-\x08\x0b-\x1f]', text):
|
||||
raise _invalid('字幕时间或纯文本内容无效;不支持ASS控制语法。')
|
||||
cues.append((start, end, html.escape(text, quote=False)))
|
||||
parts, total = [], 0.0
|
||||
for source, start, end in normalized:
|
||||
info = await inspect_media(source, self.settings)
|
||||
if info['kind'] != 'video':
|
||||
raise _invalid('编排片段必须是视频素材。')
|
||||
end = info['duration_seconds'] if end is None else end
|
||||
if start >= end or end > info['duration_seconds'] + .05 or end - start < .05:
|
||||
raise _invalid('裁剪范围超出视频实际时长。')
|
||||
total += end - start
|
||||
if total > 1800:
|
||||
raise _invalid('成片总时长不能超过30分钟。')
|
||||
parts.append((source, start, end - start, info.get('has_audio', False)))
|
||||
if any(end > total + .05 for _, end, _ in cues):
|
||||
raise _invalid('字幕超出成片时长。')
|
||||
if audio and (await inspect_media(audio, self.settings))['kind'] != 'audio':
|
||||
raise _invalid('成片音轨必须为音频素材。')
|
||||
files = []
|
||||
async with asyncio.timeout(900):
|
||||
for index, (source, start, duration, has_audio) in enumerate(parts):
|
||||
target = work / f'clip-{index:03d}.mp4'
|
||||
command = [self.settings.ffmpeg_bin, '-v', 'error', '-nostdin', *input_options(), '-i', str(source)]
|
||||
if not has_audio:
|
||||
command += ['-f', 'lavfi', '-i', 'anullsrc=channel_layout=stereo:sample_rate=48000']
|
||||
command += ['-ss', f'{start:.6f}', '-t', f'{duration:.6f}', '-map', '0:v:0', '-map',
|
||||
'0:a:0' if has_audio else '1:a:0', '-vf',
|
||||
f'scale={width}:{height}:force_original_aspect_ratio=decrease,pad={width}:{height}:(ow-iw)/2:(oh-ih)/2,setsar=1,fps={fps}',
|
||||
'-c:v', 'libx264', '-preset', 'veryfast', '-crf', '20', '-pix_fmt', 'yuv420p',
|
||||
'-c:a', 'aac', '-ar', '48000', '-ac', '2', '-threads', '2', '-fs', str(self.settings.max_output_bytes), str(target)]
|
||||
await run_process(command, timeout=min(600, max(60, duration * 5)))
|
||||
files.append(target)
|
||||
if sum(path.stat().st_size for path in files) >= self.settings.max_output_bytes:
|
||||
raise ProviderError('output_too_large', '成片中间文件超出大小限制。')
|
||||
listing = work / 'concat.txt'
|
||||
listing.write_text(''.join(f"file '{path.name}'\n" for path in files), encoding='utf-8')
|
||||
if cues:
|
||||
def stamp(value):
|
||||
milliseconds = round(value * 1000)
|
||||
hours, milliseconds = divmod(milliseconds, 3600000)
|
||||
minutes, milliseconds = divmod(milliseconds, 60000)
|
||||
seconds, milliseconds = divmod(milliseconds, 1000)
|
||||
return f'{hours:02}:{minutes:02}:{seconds:02},{milliseconds:03}'
|
||||
(work / 'subtitles.srt').write_text(''.join(f'{index}\n{stamp(start)} --> {stamp(end)}\n{text}\n\n'
|
||||
for index, (start, end, text) in enumerate(cues, 1)), encoding='utf-8')
|
||||
target = work / 'composition.mp4'
|
||||
command = [self.settings.ffmpeg_bin, '-v', 'error', '-nostdin', '-f', 'concat', '-safe', '1', '-i', listing.name]
|
||||
if audio:
|
||||
command += [*input_options(), '-i', str(audio)]
|
||||
command += ['-map', '0:v:0', '-map', '1:a:0' if audio else '0:a:0']
|
||||
if cues:
|
||||
command += ['-vf', 'subtitles=filename=subtitles.srt', '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '20', '-pix_fmt', 'yuv420p']
|
||||
else:
|
||||
command += ['-c:v', 'copy']
|
||||
command += ['-af', 'apad', '-t', f'{total:.6f}', '-c:a', 'aac', '-threads', '2',
|
||||
'-movflags', '+faststart', '-fs', str(self.settings.max_output_bytes), str(target)]
|
||||
await run_process(command, timeout=min(600, max(60, total * 5)), cwd=work)
|
||||
info = await inspect_media(target, self.settings)
|
||||
if abs(info['duration_seconds'] - total) > max(.2, 2 / fps) or target.stat().st_size >= self.settings.max_output_bytes:
|
||||
raise ProviderError('composition_incomplete', '成片未完整输出或超出大小限制。')
|
||||
result = {'duration_seconds': info['duration_seconds'], 'width': width, 'height': height,
|
||||
'fps': fps, 'clip_count': len(parts), 'subtitle_count': len(cues)}
|
||||
manifest = self._json_file(work, 'composition.json', result)
|
||||
return CpuResult([target, manifest], result, {'provider': 'ffmpeg-cpu', 'audio': 'uploaded' if audio else 'original-or-silence'})
|
||||
10
backend/pyproject.toml
Normal file
@ -0,0 +1,10 @@
|
||||
[project]
|
||||
name = "cmvr-visual-backend"
|
||||
version = "0.1.0"
|
||||
requires-python = ">=3.11"
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
asyncio_mode = "auto"
|
||||
asyncio_default_fixture_loop_scope = "function"
|
||||
testpaths = ["tests"]
|
||||
filterwarnings = ["error::ResourceWarning"]
|
||||
12
backend/requirements.txt
Normal file
@ -0,0 +1,12 @@
|
||||
fastapi>=0.115,<1
|
||||
uvicorn[standard]>=0.30,<1
|
||||
SQLAlchemy[asyncio]>=2.0,<3
|
||||
aiomysql>=0.2,<1
|
||||
aiosqlite>=0.20,<1
|
||||
cryptography>=43
|
||||
python-multipart>=0.0.18
|
||||
httpx>=0.27,<1
|
||||
filelock>=3.16,<5
|
||||
Pillow>=10.4
|
||||
pytest>=8,<10
|
||||
pytest-asyncio>=0.24,<2
|
||||
125
backend/tests/conftest.py
Normal file
@ -0,0 +1,125 @@
|
||||
import asyncio
|
||||
import io
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import httpx
|
||||
from PIL import Image
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
|
||||
|
||||
PASSWORD = "Sufficient-Password-194!"
|
||||
|
||||
|
||||
class BoundaryError(Exception):
|
||||
def __init__(self, message="network interrupted", retriable=True):
|
||||
self.code, self.message, self.retriable = "upstream_unavailable", message, retriable
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
class FakeProvider:
|
||||
"""External-service boundary only. DB, events, HTTP/auth and files are real."""
|
||||
def __init__(self):
|
||||
self.remote = {}
|
||||
self.accepted = {}
|
||||
self.lost_response = False
|
||||
self.fail_download_once = False
|
||||
self.fail_download_at = None
|
||||
self.submitted_payloads = []
|
||||
self.download_count = 0
|
||||
self.cpu_wait = False
|
||||
self.cpu_runs = 0
|
||||
self.reject_submission = False
|
||||
|
||||
async def health(self):
|
||||
return True
|
||||
|
||||
async def scheduler_status(self):
|
||||
return {"available": True, "state": "ready", "reason": None, "gpus": [], "updated_at": None}
|
||||
|
||||
async def prepare_gpu_payload(self, task_type, inputs, parameters, assets, work_dir):
|
||||
resolved = dict(inputs)
|
||||
for source, target in (("image_asset_id", "image_path"), ("audio_asset_id", "audio_path"),
|
||||
("asset_id", "audio_path")):
|
||||
if source in resolved:
|
||||
resolved[target] = str(assets[resolved.pop(source)])
|
||||
return {"task_type": task_type, "input": resolved, "parameters": parameters, "timeout_seconds": 3600}
|
||||
|
||||
async def submit(self, payload, idempotency_key):
|
||||
self.submitted_payloads.append((idempotency_key, payload))
|
||||
if self.reject_submission:
|
||||
error = BoundaryError("unsupported upstream input", retriable=False)
|
||||
error.code = "upstream_rejected"
|
||||
raise error
|
||||
if idempotency_key not in self.accepted:
|
||||
remote_id = f"remote-{len(self.accepted) + 1}"
|
||||
self.accepted[idempotency_key] = remote_id
|
||||
self.remote[remote_id] = {"id": remote_id, "state": "queued", "attempt_count": 0, "preemptions": 0}
|
||||
remote_id = self.accepted[idempotency_key]
|
||||
if self.lost_response:
|
||||
self.lost_response = False
|
||||
raise BoundaryError()
|
||||
return dict(self.remote[remote_id])
|
||||
|
||||
async def query(self, upstream_id):
|
||||
return dict(self.remote[upstream_id])
|
||||
|
||||
async def cancel(self, upstream_id):
|
||||
self.remote[upstream_id].update(state="cancelled")
|
||||
return dict(self.remote[upstream_id])
|
||||
|
||||
async def download(self, upstream_id, index, destination):
|
||||
self.download_count += 1
|
||||
if self.fail_download_once or self.fail_download_at == index:
|
||||
self.fail_download_once = False
|
||||
self.fail_download_at = None
|
||||
raise BoundaryError("download interrupted")
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
Image.new("RGB", (12, 10), "blue").save(destination, format="PNG")
|
||||
|
||||
async def run_cpu(self, task_type, inputs, parameters, assets, work_dir):
|
||||
self.cpu_runs += 1
|
||||
if self.cpu_wait:
|
||||
await asyncio.sleep(60)
|
||||
work_dir.mkdir(parents=True, exist_ok=True)
|
||||
output = work_dir / "answer.txt"
|
||||
output.write_text("The answer is 5", encoding="utf-8")
|
||||
return SimpleNamespace(outputs=[output], result={"text": "The answer is 5"}, metadata={})
|
||||
|
||||
async def aclose(self):
|
||||
pass
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def png_bytes():
|
||||
data = io.BytesIO()
|
||||
Image.new("RGB", (16, 12), "red").save(data, format="PNG")
|
||||
return data.getvalue()
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def system(tmp_path):
|
||||
from app.config import Settings
|
||||
from app.main import create_app
|
||||
settings = Settings(mode="test", database_url=f"sqlite+aiosqlite:///{tmp_path / 'test.sqlite3'}",
|
||||
workspace_root=tmp_path, admin_username="admin", admin_password=PASSWORD,
|
||||
run_coordinator=False, cookie_secure=False, event_heartbeat_seconds=.03)
|
||||
provider = FakeProvider()
|
||||
app = create_app(settings, provider=provider)
|
||||
async with app.router.lifespan_context(app):
|
||||
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:
|
||||
response = await client.post("/api/auth/login", json={"username": "admin", "password": PASSWORD})
|
||||
assert response.status_code == 200, response.text
|
||||
client.headers["X-CSRF-Token"] = response.json()["csrf_token"]
|
||||
yield SimpleNamespace(app=app, client=client, settings=settings, provider=provider)
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def other_client(system):
|
||||
response = await system.client.post("/api/auth/users", json={"username": "alice", "display_name": "Alice", "password": PASSWORD})
|
||||
assert response.status_code == 201, response.text
|
||||
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=system.app), base_url="http://test") as client:
|
||||
login = await client.post("/api/auth/login", json={"username": "alice", "password": PASSWORD})
|
||||
client.headers["X-CSRF-Token"] = login.json()["csrf_token"]
|
||||
yield client
|
||||
60
backend/tests/test_assets.py
Normal file
@ -0,0 +1,60 @@
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
async def test_assets_are_owned_range_enabled_and_deleted_inputs_are_retained(system, other_client, png_bytes):
|
||||
uploaded = await system.client.post("/api/assets", files={"file": ("../reference.png", png_bytes, "image/png")})
|
||||
assert uploaded.status_code == 201, uploaded.text
|
||||
asset = uploaded.json()
|
||||
assert asset["kind"] == "image" and asset["width"] == 16
|
||||
assert not any(key.endswith("path") for key in asset)
|
||||
for suffix in ("", "/content", "/thumbnail"):
|
||||
assert (await other_client.get(f"/api/assets/{asset['id']}{suffix}")).status_code == 404
|
||||
content = await system.client.get(asset["preview_url"], headers={"Range": "bytes=0-7"})
|
||||
assert content.status_code == 206 and content.content == png_bytes[:8]
|
||||
assert content.headers["content-range"] == f"bytes 0-7/{len(png_bytes)}"
|
||||
patched = await system.client.patch(f"/api/assets/{asset['id']}", json={"tags": ["product"], "favorite": True})
|
||||
assert patched.json()["favorite"] and patched.json()["tags"] == ["product"]
|
||||
response = await system.client.post("/api/jobs", json={"task_type": "video.generate",
|
||||
"input": {"prompt": "rotate", "image_asset_id": asset["id"]}, "parameters": {}})
|
||||
assert response.status_code == 202, response.text
|
||||
files_before = list(system.settings.asset_root.rglob("original*"))
|
||||
assert (await system.client.delete(f"/api/assets/{asset['id']}")).status_code == 204
|
||||
assert all(path.exists() for path in files_before)
|
||||
assert (await system.client.get(f"/api/assets/{asset['id']}/content")).status_code == 404
|
||||
await system.app.state.coordinator.run_once(force=True)
|
||||
assert len(system.provider.accepted) == 1
|
||||
|
||||
|
||||
async def test_foreign_asset_cannot_be_used_to_create_job(system, other_client, png_bytes):
|
||||
asset = (await system.client.post("/api/assets", files={"file": ("image.png", png_bytes, "image/png")})).json()
|
||||
response = await other_client.post("/api/jobs", json={"task_type": "defect.generate",
|
||||
"input": {"prompt": "scratch", "image_asset_id": asset["id"]}, "parameters": {}})
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
async def test_generated_asset_changes_update_source_job_version_and_sse_snapshot(system):
|
||||
from app.events import event_batch
|
||||
job = (await system.client.post("/api/jobs", json={"task_type": "image.generate",
|
||||
"input": {"prompt": "cup"}, "parameters": {}})).json()["jobs"][0]
|
||||
coordinator = system.app.state.coordinator
|
||||
await coordinator.run_once(force=True)
|
||||
system.provider.remote["remote-1"].update(state="succeeded", result={"outputs": [{"path": "image.png"}]})
|
||||
await coordinator.run_once(force=True)
|
||||
old = (await system.client.get(f"/api/jobs/{job['id']}")).json()
|
||||
asset_id = old["result_assets"][0]["id"]
|
||||
cursor = (await system.client.get("/api/jobs")).json()["cursor"]
|
||||
await system.client.patch(f"/api/assets/{asset_id}", json={"name": "renamed.png", "favorite": True})
|
||||
renamed = (await system.client.get(f"/api/jobs/{job['id']}")).json()
|
||||
assert renamed["version"] > old["version"]
|
||||
assert renamed["result_assets"][0]["name"] == "renamed.png"
|
||||
owner_id = (await system.client.get("/api/auth/me")).json()["user"]["id"]
|
||||
events = await event_batch(system.app.state.db, owner_id, cursor)
|
||||
snapshots = [event["data"]["job"] for event in events if event["event"] == "job.updated"]
|
||||
assert snapshots and snapshots[-1]["version"] == renamed["version"]
|
||||
cursor = events[-1]["id"]
|
||||
await system.client.delete(f"/api/assets/{asset_id}")
|
||||
deleted = (await system.client.get(f"/api/jobs/{job['id']}")).json()
|
||||
assert deleted["version"] > renamed["version"] and deleted["result_assets"] == []
|
||||
events = await event_batch(system.app.state.db, owner_id, cursor)
|
||||
snapshots = [event["data"]["job"] for event in events if event["event"] == "job.updated"]
|
||||
assert snapshots and snapshots[-1]["result_assets"] == []
|
||||
55
backend/tests/test_auth.py
Normal file
@ -0,0 +1,55 @@
|
||||
import httpx
|
||||
from conftest import PASSWORD
|
||||
|
||||
|
||||
async def test_login_cookie_csrf_and_revocation(system):
|
||||
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=system.app), base_url="http://test") as client:
|
||||
assert (await client.get("/api/auth/me")).status_code == 401
|
||||
denied = await client.post("/api/auth/login", json={"username": "admin", "password": "wrong"})
|
||||
assert denied.status_code == 401
|
||||
login = await client.post("/api/auth/login", json={"username": "admin", "password": PASSWORD})
|
||||
assert login.status_code == 200 and "HttpOnly" in login.headers["set-cookie"]
|
||||
assert (await client.post("/api/auth/logout")).status_code == 403
|
||||
assert (await client.post("/api/auth/logout", headers={"X-CSRF-Token": b"\xc3\xa9"})).status_code == 403
|
||||
csrf = login.json()["csrf_token"]
|
||||
assert (await client.get("/api/auth/me")).json()["csrf_token"] == csrf
|
||||
cookie = client.cookies.get("cmvr_session")
|
||||
assert (await client.post("/api/auth/logout", headers={"X-CSRF-Token": csrf})).status_code == 204
|
||||
client.cookies.set("cmvr_session", cookie)
|
||||
assert (await client.get("/api/auth/me")).status_code == 401
|
||||
|
||||
|
||||
async def test_non_admin_cannot_create_users_and_public_registration_is_absent(other_client):
|
||||
assert (await other_client.post("/api/auth/users", json={"username": "bob", "password": PASSWORD})).status_code == 403
|
||||
assert (await other_client.post("/api/auth/register", json={})).status_code == 404
|
||||
|
||||
|
||||
async def test_requested_initial_admin_password_is_hashed_and_not_reset_on_restart(tmp_path):
|
||||
from sqlalchemy import select
|
||||
from app.auth import verify_password
|
||||
from app.config import Settings
|
||||
from app.main import create_app
|
||||
from app.models import User
|
||||
from conftest import FakeProvider
|
||||
|
||||
settings = Settings(mode="test", database_url=f"sqlite+aiosqlite:///{tmp_path / 'admin.sqlite3'}",
|
||||
workspace_root=tmp_path, admin_username="admin", admin_password="123456",
|
||||
run_coordinator=False, cookie_secure=False)
|
||||
app = create_app(settings, provider=FakeProvider())
|
||||
async with app.router.lifespan_context(app):
|
||||
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:
|
||||
login = await client.post("/api/auth/login", json={"username": "admin", "password": "123456"})
|
||||
assert login.status_code == 200 and login.json()["user"]["role"] == "admin"
|
||||
async with app.state.db.session() as session:
|
||||
user = await session.scalar(select(User).where(User.username == "admin"))
|
||||
assert user.password_hash != "123456" and verify_password("123456", user.password_hash)
|
||||
client.headers["X-CSRF-Token"] = login.json()["csrf_token"]
|
||||
denied = await client.post("/api/auth/users", json={"username": "ordinary", "password": "123456"})
|
||||
assert denied.status_code == 422 # Ordinary accounts retain their stronger password policy.
|
||||
|
||||
settings.admin_password = PASSWORD
|
||||
restarted = create_app(settings, provider=FakeProvider())
|
||||
async with restarted.router.lifespan_context(restarted):
|
||||
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=restarted), base_url="http://test") as client:
|
||||
assert (await client.post("/api/auth/login", json={"username": "admin", "password": "123456"})).status_code == 200
|
||||
assert (await client.post("/api/auth/login", json={"username": "admin", "password": PASSWORD})).status_code == 401
|
||||
44
backend/tests/test_core.py
Normal file
@ -0,0 +1,44 @@
|
||||
import pytest
|
||||
|
||||
|
||||
def test_production_never_silently_uses_sqlite(tmp_path):
|
||||
from app.config import Settings
|
||||
with pytest.raises(ValueError):
|
||||
Settings(mode="production", database_url="sqlite+aiosqlite:///:memory:", workspace_root=tmp_path)
|
||||
|
||||
|
||||
def test_mysql_url_preserves_hyphen_database_and_password_special_characters(tmp_path):
|
||||
from app.config import Settings
|
||||
settings = Settings(mode="production", mysql_user="visual", mysql_password="p@ss:/?#&",
|
||||
workspace_root=tmp_path)
|
||||
assert settings.sqlalchemy_url.database == "cmvr-visual"
|
||||
assert settings.sqlalchemy_url.password == "p@ss:/?#&"
|
||||
assert settings.sqlalchemy_url.drivername == "mysql+aiomysql"
|
||||
|
||||
|
||||
async def test_application_creates_only_prefixed_tables(system):
|
||||
from sqlalchemy import inspect
|
||||
async with system.app.state.db.engine.connect() as connection:
|
||||
names = await connection.run_sync(lambda sync: inspect(sync).get_table_names())
|
||||
assert names and all(name.startswith("visual_") for name in names)
|
||||
|
||||
|
||||
async def test_status_discloses_preview_mode_without_connection_details(system):
|
||||
response = await system.client.get("/api/system/status")
|
||||
assert response.status_code == 200
|
||||
status = response.json()
|
||||
assert status["environment"] == "test" and status["database_backend"] == "sqlite"
|
||||
assert "database_url" not in response.text and "password" not in response.text
|
||||
|
||||
|
||||
async def test_only_one_coordinator_can_hold_the_workspace_lock(system):
|
||||
from app.coordinator import Coordinator
|
||||
from filelock import Timeout
|
||||
first = Coordinator(system.settings, system.app.state.db, system.provider)
|
||||
second = Coordinator(system.settings, system.app.state.db, system.provider)
|
||||
try:
|
||||
await first.start()
|
||||
with pytest.raises(Timeout):
|
||||
await second.start()
|
||||
finally:
|
||||
await first.close()
|
||||
64
backend/tests/test_events.py
Normal file
@ -0,0 +1,64 @@
|
||||
from sqlalchemy import select
|
||||
from types import SimpleNamespace
|
||||
import asyncio
|
||||
|
||||
|
||||
async def test_empty_stream_immediately_sends_connection_comment(system):
|
||||
from app.events import event_stream
|
||||
system.settings.event_heartbeat_seconds = 15
|
||||
owner = (await system.client.get("/api/auth/me")).json()["user"]["id"]
|
||||
async def connected():
|
||||
return False
|
||||
request = SimpleNamespace(app=system.app, is_disconnected=connected)
|
||||
stream = event_stream(request, owner, system.client.cookies.get("cmvr_session"), 0)
|
||||
try:
|
||||
assert await asyncio.wait_for(anext(stream), timeout=.1) == ": connected\n\n"
|
||||
finally:
|
||||
await stream.aclose()
|
||||
|
||||
|
||||
async def test_durable_events_owner_replay_and_session_revocation(system, other_client):
|
||||
from app.events import event_batch, session_is_active
|
||||
job = (await system.client.post("/api/jobs", json={"task_type": "image.generate",
|
||||
"input": {"prompt": "cup"}, "parameters": {}})).json()["jobs"][0]
|
||||
actor = (await system.client.get("/api/auth/me")).json()["user"]
|
||||
other = (await other_client.get("/api/auth/me")).json()["user"]
|
||||
events = await event_batch(system.app.state.db, actor["id"], 0)
|
||||
assert events and events[-1]["data"]["job"]["id"] == job["id"]
|
||||
assert await event_batch(system.app.state.db, other["id"], 0) == []
|
||||
assert await event_batch(system.app.state.db, actor["id"], events[-1]["id"]) == []
|
||||
token = system.client.cookies.get("cmvr_session")
|
||||
assert await session_is_active(system.app.state.db, token)
|
||||
assert (await system.client.post("/api/auth/logout")).status_code == 204
|
||||
assert not await session_is_active(system.app.state.db, token)
|
||||
|
||||
|
||||
async def test_real_stream_replays_ids_heartbeats_then_stops_after_logout(system):
|
||||
from app.events import event_stream
|
||||
await system.client.post("/api/jobs", json={"task_type": "image.generate", "input": {"prompt": "cup"}, "parameters": {}})
|
||||
owner = (await system.client.get("/api/auth/me")).json()["user"]["id"]
|
||||
async def connected():
|
||||
return False
|
||||
request = SimpleNamespace(app=system.app, is_disconnected=connected)
|
||||
stream = event_stream(request, owner, system.client.cookies.get("cmvr_session"), 0)
|
||||
assert await anext(stream) == ": connected\n\n"
|
||||
event = await anext(stream)
|
||||
assert "event: job.updated" in event and "id: " in event
|
||||
heartbeat = await asyncio.wait_for(anext(stream), timeout=1)
|
||||
assert heartbeat == ": heartbeat\n\n"
|
||||
await system.client.post("/api/auth/logout")
|
||||
try:
|
||||
await anext(stream)
|
||||
assert False, "revoked sessions must stop SSE"
|
||||
except StopAsyncIteration:
|
||||
pass
|
||||
|
||||
|
||||
async def test_http_eventsource_last_event_id_overrides_initial_query(system, monkeypatch):
|
||||
import app.events as events
|
||||
async def one_event(request, owner_id, token, after):
|
||||
yield f"id: {after}\nevent: reset\ndata: {{}}\n\n"
|
||||
monkeypatch.setattr(events, "event_stream", one_event)
|
||||
response = await system.client.get("/api/events?after=2", headers={"Last-Event-ID": "19"})
|
||||
assert response.status_code == 200 and response.text.startswith("id: 19\n")
|
||||
assert response.headers["x-accel-buffering"] == "no"
|
||||
254
backend/tests/test_jobs.py
Normal file
@ -0,0 +1,254 @@
|
||||
import json
|
||||
import asyncio
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from sqlalchemy import select
|
||||
|
||||
|
||||
async def submit(system, **changes):
|
||||
body = {"task_type": "image.generate", "input": {"prompt": "a blue cup"}, "parameters": {}}
|
||||
body.update(changes)
|
||||
response = await system.client.post("/api/jobs", json=body)
|
||||
assert response.status_code == 202, response.text
|
||||
return response.json()["jobs"]
|
||||
|
||||
|
||||
async def test_batch_idempotency_and_scheduled_jobs_do_not_dispatch_early(system):
|
||||
future = (datetime.now(timezone.utc) + timedelta(hours=1)).isoformat()
|
||||
body = {"task_type": "image.generate", "input": {"prompt": "cup"}, "parameters": {}, "count": 3, "scheduled_at": future}
|
||||
first = await system.client.post("/api/jobs", json=body, headers={"Idempotency-Key": "batch-one"})
|
||||
second = await system.client.post("/api/jobs", json=body, headers={"Idempotency-Key": "batch-one"})
|
||||
assert first.status_code == 202 and second.json() == first.json()
|
||||
assert len(first.json()["jobs"]) == 3
|
||||
assert [job["parameters"]["seed"] for job in first.json()["jobs"]] == [42, 43, 44]
|
||||
assert {job["state"] for job in first.json()["jobs"]} == {"scheduled"}
|
||||
body["input"]["prompt"] = "changed"
|
||||
assert (await system.client.post("/api/jobs", json=body, headers={"Idempotency-Key": "batch-one"})).status_code == 409
|
||||
await system.app.state.coordinator.run_once(force=True)
|
||||
assert not system.provider.accepted
|
||||
|
||||
|
||||
async def test_lost_submit_response_recovers_same_id_and_known_id_never_resubmits(system):
|
||||
job = (await submit(system))[0]
|
||||
system.provider.lost_response = True
|
||||
await system.app.state.coordinator.run_once(force=True)
|
||||
await system.app.state.coordinator.run_once(force=True)
|
||||
current = (await system.client.get(f"/api/jobs/{job['id']}")).json()
|
||||
assert current["upstream_id"] == "remote-1" and len(system.provider.accepted) == 1
|
||||
assert system.provider.submitted_payloads[0] == system.provider.submitted_payloads[1]
|
||||
submitted = len(system.provider.submitted_payloads)
|
||||
system.provider.remote["remote-1"].update(state="running", attempt_count=1)
|
||||
await system.app.state.coordinator.run_once(force=True)
|
||||
running = (await system.client.get(f"/api/jobs/{job['id']}")).json()
|
||||
system.provider.remote["remote-1"].update(state="queued", attempt_count=1, preemptions=1,
|
||||
last_preempted_reason="External user arrived")
|
||||
await system.app.state.coordinator.run_once(force=True)
|
||||
queued = (await system.client.get(f"/api/jobs/{job['id']}")).json()
|
||||
assert queued["state"] == "queued" and queued["version"] > running["version"]
|
||||
assert queued["preemptions"] == 1 and queued["upstream_id"] == "remote-1"
|
||||
assert len(system.provider.submitted_payloads) == submitted
|
||||
|
||||
|
||||
async def test_output_import_retry_does_not_generate_again_or_duplicate_assets(system):
|
||||
job = (await submit(system))[0]
|
||||
await system.app.state.coordinator.run_once(force=True)
|
||||
system.provider.remote["remote-1"].update(state="succeeded", attempt_count=1,
|
||||
result={"outputs": [{"path": "/workspace/private/should-not-leak.png"}], "metadata": {"engine": "real"}})
|
||||
system.provider.fail_download_once = True
|
||||
await system.app.state.coordinator.run_once(force=True)
|
||||
collecting = (await system.client.get(f"/api/jobs/{job['id']}")).json()
|
||||
assert collecting["state"] == "collecting"
|
||||
await system.app.state.coordinator.run_once(force=True)
|
||||
completed = (await system.client.get(f"/api/jobs/{job['id']}")).json()
|
||||
assert completed["state"] == "succeeded" and len(completed["result_assets"]) == 1
|
||||
assert "/workspace/" not in json.dumps(completed)
|
||||
await system.app.state.coordinator.run_once(force=True)
|
||||
assets = (await system.client.get("/api/assets")).json()
|
||||
assert assets["total"] == 1 and len(system.provider.accepted) == 1
|
||||
|
||||
|
||||
async def test_partial_outputs_remain_private_until_every_output_is_imported(system):
|
||||
job = (await submit(system))[0]
|
||||
await system.app.state.coordinator.run_once(force=True)
|
||||
system.provider.remote["remote-1"].update(state="succeeded", result={"outputs": [{"path": "one.png"}, {"path": "two.png"}]})
|
||||
system.provider.fail_download_at = 1
|
||||
await system.app.state.coordinator.run_once(force=True)
|
||||
assert (await system.client.get(f"/api/jobs/{job['id']}")).json()["state"] == "collecting"
|
||||
assert (await system.client.get("/api/assets")).json()["total"] == 0
|
||||
await system.app.state.coordinator.run_once(force=True)
|
||||
completed = (await system.client.get(f"/api/jobs/{job['id']}")).json()
|
||||
assert completed["state"] == "succeeded" and len(completed["result_assets"]) == 2
|
||||
assert (await system.client.get("/api/assets")).json()["total"] == 2
|
||||
|
||||
|
||||
async def test_owner_isolation_cancel_and_explicit_retry(system, other_client):
|
||||
job = (await submit(system))[0]
|
||||
for method, path in (("get", f"/api/jobs/{job['id']}"), ("post", f"/api/jobs/{job['id']}/cancel"),
|
||||
("post", f"/api/jobs/{job['id']}/retry")):
|
||||
assert (await getattr(other_client, method)(path)).status_code == 404
|
||||
cancelled = await system.client.post(f"/api/jobs/{job['id']}/cancel")
|
||||
assert cancelled.json()["state"] == "cancelled"
|
||||
retried = await system.client.post(f"/api/jobs/{job['id']}/retry")
|
||||
assert retried.status_code == 202 and retried.json()["jobs"][0]["id"] != job["id"]
|
||||
|
||||
|
||||
async def test_unsupported_parameters_are_rejected_before_job_creation(system):
|
||||
response = await system.client.post("/api/jobs", json={"task_type": "image.generate",
|
||||
"input": {"prompt": "cup"}, "parameters": {"steps": 1}})
|
||||
assert response.status_code == 400
|
||||
assert (await system.client.get("/api/jobs")).json()["total"] == 0
|
||||
|
||||
|
||||
async def test_definitive_upstream_input_rejection_is_terminal_not_retried_forever(system):
|
||||
job = (await submit(system))[0]
|
||||
system.provider.reject_submission = True
|
||||
await system.app.state.coordinator.run_once(force=True)
|
||||
current = (await system.client.get(f"/api/jobs/{job['id']}")).json()
|
||||
assert current["state"] == "failed" and current["error"]["code"] == "upstream_rejected"
|
||||
count = len(system.provider.submitted_payloads)
|
||||
await system.app.state.coordinator.run_once(force=True)
|
||||
assert len(system.provider.submitted_payloads) == count
|
||||
|
||||
|
||||
async def test_coordinator_restart_recovers_id_and_cancel_unknown_submit(system):
|
||||
from app.coordinator import Coordinator
|
||||
job = (await submit(system))[0]
|
||||
system.provider.lost_response = True
|
||||
await system.app.state.coordinator.run_once(force=True)
|
||||
cancelled = await system.client.post(f"/api/jobs/{job['id']}/cancel")
|
||||
assert cancelled.json()["state"] == "cancelling"
|
||||
restarted = Coordinator(system.settings, system.app.state.db, system.provider)
|
||||
await restarted.run_once(force=True)
|
||||
await restarted.run_once(force=True)
|
||||
current = (await system.client.get(f"/api/jobs/{job['id']}")).json()
|
||||
assert current["state"] == "cancelled" and current["upstream_id"] == "remote-1"
|
||||
assert len(system.provider.accepted) == 1
|
||||
|
||||
|
||||
async def test_cpu_provider_results_are_real_assets_and_cancelled_stale_job_never_runs(system):
|
||||
job = (await submit(system, task_type="math.solve", input={"prompt": "2+3?"}))[0]
|
||||
coordinator = system.app.state.coordinator
|
||||
await coordinator.run_once(force=True)
|
||||
await asyncio.gather(*list(coordinator._cpu.values()))
|
||||
completed = (await system.client.get(f"/api/jobs/{job['id']}")).json()
|
||||
assert completed["state"] == "succeeded" and completed["result"]["text"] == "The answer is 5"
|
||||
content = await system.client.get(completed["result_assets"][0]["preview_url"])
|
||||
assert content.content == b"The answer is 5"
|
||||
stale_job = (await submit(system, task_type="math.solve", input={"prompt": "next"}))[0]
|
||||
stale = await coordinator._job(stale_job["id"])
|
||||
await system.client.post(f"/api/jobs/{stale_job['id']}/cancel")
|
||||
before = system.provider.cpu_runs
|
||||
await coordinator._run_cpu(stale)
|
||||
assert system.provider.cpu_runs == before
|
||||
|
||||
|
||||
async def test_running_cpu_cancellation_waits_provider_task(system):
|
||||
job = (await submit(system, task_type="math.solve", input={"prompt": "2+3?"}))[0]
|
||||
system.provider.cpu_wait = True
|
||||
coordinator = system.app.state.coordinator
|
||||
await coordinator.run_once(force=True)
|
||||
for _ in range(100):
|
||||
if system.provider.cpu_runs:
|
||||
break
|
||||
await asyncio.sleep(.01)
|
||||
await system.client.post(f"/api/jobs/{job['id']}/cancel")
|
||||
tasks = list(coordinator._cpu.values())
|
||||
await coordinator.run_once(force=True)
|
||||
await asyncio.gather(*tasks, return_exceptions=True)
|
||||
current = (await system.client.get(f"/api/jobs/{job['id']}")).json()
|
||||
assert current["state"] == "cancelled"
|
||||
|
||||
|
||||
async def test_cancel_during_gpu_preparation_never_starts_new_upstream_job(system):
|
||||
job = (await submit(system))[0]
|
||||
entered, release = asyncio.Event(), asyncio.Event()
|
||||
original = system.provider.prepare_gpu_payload
|
||||
async def blocked_prepare(*args, **kwargs):
|
||||
entered.set()
|
||||
await release.wait()
|
||||
return await original(*args, **kwargs)
|
||||
system.provider.prepare_gpu_payload = blocked_prepare
|
||||
task = asyncio.create_task(system.app.state.coordinator.run_once(force=True))
|
||||
try:
|
||||
await asyncio.wait_for(entered.wait(), 2)
|
||||
response = await system.client.post(f"/api/jobs/{job['id']}/cancel")
|
||||
assert response.json()["state"] == "cancelling"
|
||||
release.set()
|
||||
await asyncio.wait_for(task, 3)
|
||||
finally:
|
||||
release.set()
|
||||
await asyncio.gather(task, return_exceptions=True)
|
||||
final = (await system.client.get(f"/api/jobs/{job['id']}")).json()
|
||||
assert final["state"] == "cancelled"
|
||||
assert not system.provider.accepted and not system.provider.submitted_payloads
|
||||
|
||||
|
||||
async def test_cpu_cancel_after_result_read_wins_collection_and_publication(system):
|
||||
job = (await submit(system, task_type="math.solve", input={"prompt": "2+3?"}))[0]
|
||||
coordinator = system.app.state.coordinator
|
||||
entered, release = asyncio.Event(), asyncio.Event()
|
||||
original = coordinator._update
|
||||
async def blocked_collect(job_id, **changes):
|
||||
if changes.get("state") == "collecting":
|
||||
entered.set()
|
||||
await release.wait()
|
||||
return await original(job_id, **changes)
|
||||
coordinator._update = blocked_collect
|
||||
try:
|
||||
await coordinator.run_once(force=True)
|
||||
await asyncio.wait_for(entered.wait(), 2)
|
||||
response = await system.client.post(f"/api/jobs/{job['id']}/cancel")
|
||||
assert response.json()["state"] == "cancelling"
|
||||
release.set()
|
||||
await asyncio.gather(*list(coordinator._cpu.values()))
|
||||
finally:
|
||||
release.set()
|
||||
current = (await system.client.get(f"/api/jobs/{job['id']}")).json()
|
||||
assert current["state"] == "cancelled" and not current["result_assets"]
|
||||
assert (await system.client.get("/api/assets")).json()["total"] == 0
|
||||
|
||||
|
||||
async def test_final_publication_reloads_committed_cancel_and_keeps_pending_private(system):
|
||||
from app.models import Job
|
||||
job = (await submit(system, task_type="math.solve", input={"prompt": "2+3?"}))[0]
|
||||
coordinator = system.app.state.coordinator
|
||||
entered, release = asyncio.Event(), asyncio.Event()
|
||||
original = coordinator._complete
|
||||
async def blocked_complete(*args, **kwargs):
|
||||
entered.set()
|
||||
await release.wait()
|
||||
return await original(*args, **kwargs)
|
||||
coordinator._complete = blocked_complete
|
||||
await coordinator.run_once(force=True)
|
||||
try:
|
||||
await asyncio.wait_for(entered.wait(), 2)
|
||||
# Simulates a previously committed cancellation surviving a stale
|
||||
# collection transition; _complete must defend publication itself.
|
||||
async with system.app.state.db.session() as session:
|
||||
saved = await session.get(Job, job["id"])
|
||||
saved.cancel_requested, saved.state = True, "cancelling"
|
||||
await session.commit()
|
||||
release.set()
|
||||
await asyncio.gather(*list(coordinator._cpu.values()))
|
||||
finally:
|
||||
release.set()
|
||||
final = (await system.client.get(f"/api/jobs/{job['id']}")).json()
|
||||
assert final["state"] == "cancelled" and not final["result_assets"]
|
||||
assert (await system.client.get("/api/assets")).json()["total"] == 0
|
||||
|
||||
|
||||
async def test_large_waiting_gpu_queue_does_not_starve_later_cpu_or_cancel(system):
|
||||
ids = []
|
||||
for _ in range(13):
|
||||
ids.extend(job["id"] for job in await submit(system, count=4))
|
||||
cpu = (await submit(system, task_type="math.solve", input={"prompt": "2+3?"}))[0]
|
||||
coordinator = system.app.state.coordinator
|
||||
await coordinator.run_once(force=True)
|
||||
await coordinator.run_once(force=True)
|
||||
await asyncio.gather(*list(coordinator._cpu.values()))
|
||||
assert system.provider.cpu_runs == 1 and len(system.provider.accepted) == 52
|
||||
assert (await system.client.get(f"/api/jobs/{cpu['id']}")).json()["state"] == "succeeded"
|
||||
last = (await system.client.get(f"/api/jobs/{ids[-1]}")).json()
|
||||
assert last["upstream_id"]
|
||||
await system.client.post(f"/api/jobs/{ids[-1]}/cancel")
|
||||
await coordinator.run_once(force=True)
|
||||
assert (await system.client.get(f"/api/jobs/{ids[-1]}" )).json()["state"] == "cancelled"
|
||||
121
backend/tests/test_media.py
Normal file
@ -0,0 +1,121 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import gc
|
||||
import importlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
import warnings
|
||||
from unittest.mock import patch
|
||||
|
||||
from PIL import Image
|
||||
|
||||
|
||||
class MediaTests(unittest.IsolatedAsyncioTestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.root = Path(self.temp.name).resolve()
|
||||
self.settings = SimpleNamespace(workspace_root=self.root, asset_root=self.root / 'assets',
|
||||
job_work_root=self.root / 'jobs', ffmpeg_bin=shutil.which('ffmpeg') or 'ffmpeg',
|
||||
ffprobe_bin=shutil.which('ffprobe') or 'ffprobe', request_timeout_seconds=3,
|
||||
max_output_bytes=1024 * 1024)
|
||||
self.media = importlib.import_module('app.media')
|
||||
|
||||
async def test_image_is_decoded_and_thumbnail_really_exists(self):
|
||||
source = self.root / 'source.png'
|
||||
Image.new('RGB', (800, 400), 'red').save(source)
|
||||
info = await self.media.inspect_media(source, self.settings)
|
||||
self.assertEqual((info['kind'], info['mime_type'], info['width'], info['height']),
|
||||
('image', 'image/png', 800, 400))
|
||||
target = await self.media.make_thumbnail(source, self.root / 'thumb.jpg', self.settings)
|
||||
with Image.open(target) as thumbnail:
|
||||
self.assertEqual(thumbnail.size, (512, 256))
|
||||
|
||||
async def test_generated_json_and_text_are_validated_as_assets(self):
|
||||
source = self.root / 'answer.json'
|
||||
source.write_text('{"text":"数学"}', encoding='utf-8')
|
||||
self.assertEqual((await self.media.inspect_media(source, self.settings))['kind'], 'json')
|
||||
source.write_text('{broken', encoding='utf-8')
|
||||
with self.assertRaises(self.media.MediaError):
|
||||
await self.media.inspect_media(source, self.settings)
|
||||
source = self.root / 'answer.txt'
|
||||
source.write_text('答案是 42', encoding='utf-8')
|
||||
self.assertEqual((await self.media.inspect_media(source, self.settings))['mime_type'], 'text/plain')
|
||||
self.assertIsNone(await self.media.make_thumbnail(source, self.root / 'unused.jpg', self.settings))
|
||||
|
||||
async def test_outside_path_and_fake_image_fail_without_path_disclosure(self):
|
||||
with self.assertRaises(self.media.MediaError) as caught:
|
||||
await self.media.inspect_media(self.root.parent / 'PRIVATE-SECRET.png', self.settings)
|
||||
self.assertNotIn('PRIVATE-SECRET', str(caught.exception))
|
||||
broken = self.root / 'fake.png'
|
||||
broken.write_bytes(b'not an image')
|
||||
with self.assertRaises(self.media.MediaError):
|
||||
await self.media.inspect_media(broken, self.settings)
|
||||
|
||||
async def test_cancel_waits_for_owned_subprocess_and_preserves_unrelated_process(self):
|
||||
observed = []
|
||||
create = asyncio.create_subprocess_exec
|
||||
|
||||
async def record(*args, **kwargs):
|
||||
process = await create(*args, **kwargs)
|
||||
observed.append(process)
|
||||
return process
|
||||
|
||||
unrelated = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(60)'])
|
||||
try:
|
||||
with patch.object(self.media.asyncio, 'create_subprocess_exec', side_effect=record):
|
||||
task = asyncio.create_task(self.media.run_process(
|
||||
[sys.executable, '-c', 'import time; time.sleep(60)'], timeout=30))
|
||||
for _ in range(100):
|
||||
if observed:
|
||||
break
|
||||
await asyncio.sleep(.01)
|
||||
self.assertTrue(observed)
|
||||
task.cancel()
|
||||
with self.assertRaises(asyncio.CancelledError):
|
||||
await asyncio.wait_for(task, 5)
|
||||
self.assertIsNotNone(observed[0].returncode)
|
||||
self.assertIsNone(unrelated.poll())
|
||||
finally:
|
||||
unrelated.kill()
|
||||
unrelated.wait(timeout=5)
|
||||
|
||||
async def test_process_timeout_and_output_bound_are_enforced(self):
|
||||
with self.assertRaises(self.media.MediaError) as caught:
|
||||
await self.media.run_process([sys.executable, '-c', 'import time; time.sleep(60)'], timeout=.1)
|
||||
self.assertEqual(caught.exception.code, 'media_timeout')
|
||||
with self.assertRaises(self.media.MediaError):
|
||||
await self.media.run_process([sys.executable, '-c', 'print("x"*100000)'], timeout=3, max_output=256)
|
||||
with warnings.catch_warnings(record=True) as captured:
|
||||
warnings.simplefilter('always', ResourceWarning)
|
||||
with self.assertRaises(self.media.MediaError):
|
||||
await asyncio.wait_for(self.media.run_process([sys.executable, '-c',
|
||||
'import sys; sys.stdout.write("x"*10000000); sys.stdout.flush()'], timeout=3, max_output=256), 5)
|
||||
await asyncio.sleep(.05)
|
||||
gc.collect()
|
||||
self.assertFalse([warning for warning in captured if issubclass(warning.category, ResourceWarning)])
|
||||
|
||||
async def test_bounded_diagnostics_can_return_actual_frame_timestamps(self):
|
||||
stdout, stderr = await self.media.run_process([sys.executable, '-c',
|
||||
'import sys; print("result"); print("pts_time:0.541667",file=sys.stderr)'],
|
||||
timeout=3, return_stderr=True)
|
||||
self.assertIn(b'result', stdout)
|
||||
self.assertIn(b'pts_time:0.541667', stderr)
|
||||
|
||||
@unittest.skipUnless(shutil.which('ffmpeg') and shutil.which('ffprobe'), 'FFmpeg not installed')
|
||||
async def test_real_video_probe_and_thumbnail(self):
|
||||
video = self.root / 'tiny.mp4'
|
||||
await self.media.run_process([self.settings.ffmpeg_bin, '-v', 'error', '-f', 'lavfi', '-i',
|
||||
'color=c=blue:s=320x240:r=24:d=0.5', '-c:v', 'libx264', '-pix_fmt', 'yuv420p', str(video)], timeout=30)
|
||||
info = await self.media.inspect_media(video, self.settings)
|
||||
self.assertEqual((info['kind'], info['width'], info['height']), ('video', 320, 240))
|
||||
self.assertGreater(info['duration_seconds'], .4)
|
||||
thumb = await self.media.make_thumbnail(video, self.root / 'video.jpg', self.settings)
|
||||
self.assertTrue(thumb.is_file())
|
||||
274
backend/tests/test_providers.py
Normal file
@ -0,0 +1,274 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from io import BytesIO
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
import importlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
import wave
|
||||
|
||||
from PIL import Image
|
||||
|
||||
|
||||
UPSTREAM_ID = 'a' * 32
|
||||
|
||||
|
||||
class ProviderTests(unittest.IsolatedAsyncioTestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.root = Path(self.temp.name).resolve()
|
||||
(self.root / 'assets').mkdir()
|
||||
(self.root / 'jobs').mkdir()
|
||||
self.work = self.root / 'jobs' / 'attempt'
|
||||
self.work.mkdir()
|
||||
self.requests = []
|
||||
self.reply = {'id': UPSTREAM_ID, 'state': 'queued'}
|
||||
self.status = 200
|
||||
self.binary = b'actual-file'
|
||||
owner = self
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self, *_):
|
||||
pass
|
||||
|
||||
def respond(self):
|
||||
data = self.rfile.read(int(self.headers.get('Content-Length', '0')))
|
||||
owner.requests.append((self.command, self.path, dict(self.headers), json.loads(data) if data else None))
|
||||
blob = owner.binary if '/outputs/' in self.path or self.path.endswith('/audio/speech') else json.dumps(owner.reply).encode()
|
||||
self.send_response(owner.status)
|
||||
self.send_header('Content-Type', 'application/json')
|
||||
self.send_header('Content-Length', str(len(blob)))
|
||||
self.end_headers()
|
||||
self.wfile.write(blob)
|
||||
|
||||
do_GET = do_POST = respond
|
||||
|
||||
self.server = ThreadingHTTPServer(('127.0.0.1', 0), Handler)
|
||||
self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
|
||||
self.thread.start()
|
||||
self.addCleanup(self.server.server_close)
|
||||
self.addCleanup(self.server.shutdown)
|
||||
url = f'http://127.0.0.1:{self.server.server_port}'
|
||||
self.settings = SimpleNamespace(inference_base_url=url, inference_api_key='PRIVATE-KEY',
|
||||
inference_api_key_file=None, workspace_root=self.root, asset_root=self.root / 'assets',
|
||||
job_work_root=self.root / 'jobs', gpu_status_path=self.root / 'status.json',
|
||||
gpu_scheduler_path=self.root / 'scheduler.json', qwen_base_url=url + '/v1',
|
||||
qwen_model='existing-model', qwen_api_key='QWEN-PRIVATE', ffmpeg_bin=shutil.which('ffmpeg') or 'ffmpeg',
|
||||
ffprobe_bin=shutil.which('ffprobe') or 'ffprobe', tts_base_url='', tts_model='', tts_api_key='',
|
||||
request_timeout_seconds=3, max_output_bytes=1024 * 1024)
|
||||
self.module = importlib.import_module('app.providers')
|
||||
self.provider = self.module.Provider(self.settings)
|
||||
self.addAsyncCleanup(self.provider.aclose)
|
||||
self.image = self.root / 'assets' / 'source.png'
|
||||
Image.new('RGB', (320, 240), 'red').save(self.image)
|
||||
|
||||
async def test_video_payload_has_real_frame_limit_and_owned_image_path(self):
|
||||
payload = await self.provider.prepare_gpu_payload('video.generate',
|
||||
{'prompt': '镜头缓慢移动', 'image_asset_id': 'owned'}, {}, {'owned': self.image}, self.work)
|
||||
self.assertEqual(payload['input']['image_path'], str(self.image))
|
||||
self.assertEqual((payload['parameters']['num_frames'], payload['parameters']['fps']), (121, 24))
|
||||
self.assertEqual(payload['parameters']['num_inference_steps'], 50)
|
||||
for parameters in ({'num_frames': 361}, {'num_frames': 120}, {'fps': 8},
|
||||
{'width': 1280, 'height': 736}, {'unknown': True}):
|
||||
with self.subTest(parameters=parameters), self.assertRaises(self.module.ProviderError):
|
||||
await self.provider.prepare_gpu_payload('video.generate', {'prompt': 'x'}, parameters, {}, self.work)
|
||||
|
||||
async def test_submission_validation_rejects_unknown_fields_before_creating_job(self):
|
||||
validate = self.module.validate_arguments
|
||||
validate('video.generate', {'prompt': 'x'}, {'num_frames': 121}, self.settings)
|
||||
for task, inputs, parameters in (
|
||||
('image.generate', {'prompt': 'x'}, {'steps': 10}),
|
||||
('math.solve', {'prompt': 'x'}, {'shell': 'evil'}),
|
||||
('media.structure', {'asset_id': 'x'}, {'frame_count': 13}),
|
||||
('audio.speech', {'prompt': 'x'}, {'voice': '/tmp/foreign.npy'}),
|
||||
('video.compose', {}, {'clips': [{'asset_id': 'x'}], 'filter': 'unsafe'}),
|
||||
('video.generate', {'prompt': 'x'}, {'num_frames': 361}),
|
||||
):
|
||||
with self.subTest(task=task), self.assertRaises(self.module.ProviderError):
|
||||
validate(task, inputs, parameters, self.settings)
|
||||
|
||||
async def test_unknown_inputs_and_foreign_paths_are_rejected(self):
|
||||
for inputs, assets in (({'prompt': 'x', 'image_path': '/etc/passwd'}, {}),
|
||||
({'prompt': 'x', 'image_asset_id': 'x'}, {'x': self.root.parent / 'secret.png'})):
|
||||
with self.assertRaises(self.module.ProviderError) as caught:
|
||||
await self.provider.prepare_gpu_payload('video.generate', inputs, {}, assets, self.work)
|
||||
self.assertNotIn('passwd', caught.exception.message)
|
||||
self.assertNotIn('secret.png', caught.exception.message)
|
||||
with self.assertRaises(self.module.ProviderError):
|
||||
await self.provider.prepare_gpu_payload('defect.generate', {'prompt': 'scratch'}, {}, {}, self.work)
|
||||
|
||||
async def test_image_and_defect_constraints_match_actual_runner(self):
|
||||
payload = await self.provider.prepare_gpu_payload('defect.generate',
|
||||
{'prompt': 'scratch', 'image_asset_id': 'x'}, {}, {'x': self.image}, self.work)
|
||||
self.assertEqual(payload['parameters']['controlnet_conditioning_scale'], .8)
|
||||
for parameters in ({'canny_low': 200, 'canny_high': 100}, {'guidance_scale': float('nan')},
|
||||
{'width': True}, {'num_inference_steps': 101}, {'mask_asset_id': 'x'}):
|
||||
with self.subTest(parameters=parameters), self.assertRaises(self.module.ProviderError):
|
||||
await self.provider.prepare_gpu_payload('defect.generate',
|
||||
{'prompt': 'scratch', 'image_asset_id': 'x'}, parameters, {'x': self.image}, self.work)
|
||||
|
||||
async def test_submit_preserves_immutable_key_and_error_never_leaks_secret(self):
|
||||
payload = {'task_type': 'image.generate', 'input': {'prompt': 'x'}, 'parameters': {}, 'timeout_seconds': 3600}
|
||||
for _ in range(2):
|
||||
await self.provider.submit(payload, 'same-key')
|
||||
self.assertEqual([request[2]['Idempotency-Key'] for request in self.requests], ['same-key', 'same-key'])
|
||||
self.assertEqual(self.requests[0][3], self.requests[1][3])
|
||||
self.status, self.reply = 500, {'detail': 'PRIVATE-KEY /workspace/private'}
|
||||
with self.assertRaises(self.module.ProviderError) as caught:
|
||||
await self.provider.query(UPSTREAM_ID)
|
||||
self.assertTrue(caught.exception.retriable)
|
||||
self.assertNotIn('PRIVATE', caught.exception.message)
|
||||
self.assertNotIn('/workspace', caught.exception.message)
|
||||
|
||||
async def test_replayed_submit_and_cancel_errors_are_sanitized(self):
|
||||
self.reply = {'id': UPSTREAM_ID, 'state': 'failed', 'error': 'PRIVATE-KEY /workspace/private',
|
||||
'last_preempted_reason': 'PRIVATE /run/private'}
|
||||
payload = {'task_type': 'image.generate', 'input': {'prompt': 'x'}, 'parameters': {}, 'timeout_seconds': 3600}
|
||||
for value in (await self.provider.submit(payload, 'fixed'), await self.provider.cancel(UPSTREAM_ID)):
|
||||
self.assertNotIn('PRIVATE', json.dumps(value))
|
||||
self.assertNotIn('/workspace', json.dumps(value))
|
||||
|
||||
async def test_download_is_real_atomic_and_bounded(self):
|
||||
target = self.work / 'result.png'
|
||||
await self.provider.download(UPSTREAM_ID, 0, target)
|
||||
self.assertEqual(target.read_bytes(), b'actual-file')
|
||||
self.settings.max_output_bytes = 4
|
||||
with self.assertRaises(self.module.ProviderError):
|
||||
await self.provider.download(UPSTREAM_ID, 1, self.work / 'too-large.png')
|
||||
self.assertFalse((self.work / 'too-large.png').exists())
|
||||
self.assertFalse(list(self.work.glob('*.part-*')))
|
||||
|
||||
async def test_private_key_file_is_bounded_and_not_symlink_followed(self):
|
||||
key = self.root / 'private-key'
|
||||
key.write_text('FILE-SECRET', encoding='utf-8')
|
||||
if os.name != 'nt':
|
||||
key.chmod(0o600)
|
||||
self.settings.inference_api_key_file, self.settings.inference_api_key = key, ''
|
||||
await self.provider.query(UPSTREAM_ID)
|
||||
self.assertEqual(self.requests[-1][2]['Authorization'], 'Bearer FILE-SECRET')
|
||||
key.write_text('x' * 5000)
|
||||
with self.assertRaises(self.module.ProviderError):
|
||||
await self.provider.query(UPSTREAM_ID)
|
||||
|
||||
async def test_math_and_visual_structure_return_real_text_json_files(self):
|
||||
self.reply = {'choices': [{'message': {'content': '答案为 4。'}, 'finish_reason': 'stop'}]}
|
||||
result = await self.provider.run_cpu('math.solve', {'prompt': '2+2'}, {}, {}, self.work)
|
||||
self.assertEqual(result.result, {'text': '答案为 4。'})
|
||||
self.assertTrue(all(path.is_file() for path in result.outputs))
|
||||
self.assertNotIn('reasoning_content', result.result)
|
||||
self.reply = {'choices': [{'message': {'content': '{"subjects":["红色画面"],"scene":"室内","ocr":[],"tags":["红色"]}'}}]}
|
||||
result = await self.provider.run_cpu('media.structure', {'asset_id': 'x'}, {}, {'x': self.image}, self.work)
|
||||
self.assertEqual(result.result['subjects'], ['红色画面'])
|
||||
content = self.requests[-1][3]['messages'][-1]['content']
|
||||
self.assertTrue(content[0]['image_url']['url'].startswith('data:image/jpeg;base64,'))
|
||||
self.assertEqual(result.result['frames'][0]['timestamp_seconds'], 0)
|
||||
self.assertTrue(all(path.is_file() for path in result.outputs))
|
||||
|
||||
async def test_math_length_finish_is_failure_and_creates_no_answer_artifacts(self):
|
||||
self.reply = {'choices': [{'message': {'content': '计算尚未完成:17*3='}, 'finish_reason': 'length'}]}
|
||||
with self.assertRaises(self.module.ProviderError) as caught:
|
||||
await self.provider.run_cpu('math.solve', {'prompt': '17*3?'}, {'max_tokens': 128}, {}, self.work)
|
||||
self.assertEqual(caught.exception.code, 'output_truncated')
|
||||
self.assertIn('提高输出长度', caught.exception.message)
|
||||
self.assertFalse((self.work / 'answer.txt').exists())
|
||||
self.assertFalse((self.work / 'answer.json').exists())
|
||||
|
||||
async def test_visual_length_finish_is_failure_even_when_partial_output_parses_as_json(self):
|
||||
self.reply = {'choices': [{'message': {'content': '{"subjects":[],"scene":"部分内容","ocr":[],"tags":[]}'},
|
||||
'finish_reason': 'length'}]}
|
||||
with self.assertRaises(self.module.ProviderError) as caught:
|
||||
await self.provider.run_cpu('media.structure', {'asset_id': 'x'}, {}, {'x': self.image}, self.work)
|
||||
self.assertEqual(caught.exception.code, 'output_truncated')
|
||||
self.assertFalse((self.work / 'structure.json').exists())
|
||||
|
||||
async def test_visual_non_json_and_unconfigured_speech_are_explicit_failures(self):
|
||||
self.reply = {'choices': [{'message': {'content': 'not json'}}]}
|
||||
with self.assertRaises(self.module.ProviderError):
|
||||
await self.provider.run_cpu('media.structure', {'asset_id': 'x'}, {}, {'x': self.image}, self.work)
|
||||
with self.assertRaises(self.module.ProviderError) as caught:
|
||||
await self.provider.run_cpu('audio.speech', {'prompt': 'hello'}, {'voice': 'zf_xiaobei'}, {}, self.work)
|
||||
self.assertEqual(caught.exception.code, 'capability_unavailable')
|
||||
|
||||
async def test_composition_rejects_url_filter_and_invalid_subtitles_before_ffmpeg(self):
|
||||
for parameters in ({'clips': [{'asset_id': 'x', 'url': 'http://evil'}]},
|
||||
{'clips': [{'asset_id': 'x'}], 'filter': 'movie=/etc/passwd'},
|
||||
{'clips': [{'asset_id': 'x', 'start_seconds': 2, 'end_seconds': 1}]},
|
||||
{'clips': [{'asset_id': 'x'}], 'subtitles': [{'start': 0, 'end': 1, 'text': '{\\p1}'}]}):
|
||||
with self.subTest(parameters=parameters), self.assertRaises(self.module.ProviderError):
|
||||
await self.provider.run_cpu('video.compose', {}, parameters, {'x': self.image}, self.work)
|
||||
|
||||
async def test_capabilities_and_scheduler_do_not_overstate_or_disclose_pids(self):
|
||||
items = {item['task_type']: item for item in self.module.capabilities(self.settings)}
|
||||
self.assertFalse(items['audio.speech']['available'])
|
||||
self.assertEqual(items['video.generate']['constraints']['num_frames'], {'min': 5, 'max': 121, 'step': 4})
|
||||
status = {'schema_version': 1, 'generated_at': time.time(), 'error': None, 'container_id': 'b' * 64,
|
||||
'gpus': [{'index': 2, 'uuid': 'GPU-00000000-0000-0000-0000-000000000002',
|
||||
'total_gib': 79.6, 'free_gib': 79.5, 'idle_since': time.time() - 20,
|
||||
'own_pids': [], 'external_pids': [], 'baseline_pids': [2880]}]}
|
||||
self.settings.gpu_status_path.write_text(json.dumps(status))
|
||||
scheduler = await self.provider.scheduler_status()
|
||||
self.assertTrue(scheduler['available'])
|
||||
self.assertTrue(scheduler['gpus'][0]['eligible'])
|
||||
self.assertNotIn('2880', json.dumps(scheduler))
|
||||
status['generated_at'] -= 10
|
||||
self.settings.gpu_status_path.write_text(json.dumps(status))
|
||||
self.assertFalse((await self.provider.scheduler_status())['available'])
|
||||
|
||||
@unittest.skipUnless(shutil.which('ffmpeg') and shutil.which('ffprobe'), 'FFmpeg not installed')
|
||||
async def test_real_compose_preserves_order_trims_and_video_asr_prepares_wav(self):
|
||||
from app.media import run_process, inspect_media
|
||||
video = self.root / 'assets' / 'tiny.mp4'
|
||||
await run_process([self.settings.ffmpeg_bin, '-v', 'error', '-f', 'lavfi', '-i',
|
||||
'color=c=blue:s=320x256:r=24:d=1', '-f', 'lavfi', '-i', 'sine=frequency=440:duration=1',
|
||||
'-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-c:a', 'aac', '-shortest', str(video)], timeout=30)
|
||||
red = self.root / 'assets' / 'red.mp4'
|
||||
await run_process([self.settings.ffmpeg_bin, '-v', 'error', '-f', 'lavfi', '-i',
|
||||
'color=c=red:s=320x256:r=24:d=1', '-c:v', 'libx264', '-pix_fmt', 'yuv420p', str(red)], timeout=30)
|
||||
result = await self.provider.run_cpu('video.compose', {}, {'clips': [
|
||||
{'asset_id': 'v', 'start_seconds': 0, 'end_seconds': .25},
|
||||
{'asset_id': 'r', 'start_seconds': .5, 'end_seconds': .75}], 'width': 320, 'height': 256,
|
||||
'subtitles': [{'start': 0, 'end': .4, 'text': 'Safe <title> & credits'}]}, {'v': video, 'r': red}, self.work)
|
||||
info = await inspect_media(result.outputs[0], self.settings)
|
||||
self.assertEqual((info['width'], info['height']), (320, 256))
|
||||
self.assertAlmostEqual(info['duration_seconds'], .5, delta=.15)
|
||||
for timestamp, dominant in ((.1, 2), (.4, 0)):
|
||||
frame = await run_process([self.settings.ffmpeg_bin, '-v', 'error', '-ss', str(timestamp),
|
||||
'-i', str(result.outputs[0]), '-frames:v', '1', '-f', 'image2pipe', '-c:v', 'png', 'pipe:1'], timeout=30)
|
||||
with Image.open(BytesIO(frame)) as image:
|
||||
color = image.convert('RGB').getpixel((10, 10))
|
||||
self.assertGreater(color[dominant], 150)
|
||||
self.assertLess(color[2 if dominant == 0 else 0], 50)
|
||||
payload = await self.provider.prepare_gpu_payload('audio.transcribe', {'audio_asset_id': 'v'}, {}, {'v': video}, self.work)
|
||||
self.assertEqual(Path(payload['input']['audio_path']).suffix, '.wav')
|
||||
self.assertEqual((await inspect_media(Path(payload['input']['audio_path']), self.settings))['kind'], 'audio')
|
||||
self.reply = {'choices': [{'message': {'content': '{"subjects":[],"scene":"blue","ocr":[],"tags":[]}'}}]}
|
||||
structure = await self.provider.run_cpu('media.structure', {'asset_id': 'v'}, {'frame_count': 2}, {'v': video}, self.work)
|
||||
self.assertEqual(len(structure.result['frames']), 2)
|
||||
self.assertAlmostEqual(structure.result['frames'][0]['timestamp_seconds'], .25, delta=.05)
|
||||
self.assertAlmostEqual(structure.result['frames'][1]['timestamp_seconds'], .75, delta=.05)
|
||||
self.assertTrue(all(path.is_file() for path in structure.outputs))
|
||||
|
||||
@unittest.skipUnless(shutil.which('ffprobe'), 'FFprobe not installed')
|
||||
async def test_configured_speech_posts_only_allowed_voice_and_real_wav_output(self):
|
||||
stream = BytesIO()
|
||||
with wave.open(stream, 'wb') as audio:
|
||||
audio.setnchannels(1)
|
||||
audio.setsampwidth(2)
|
||||
audio.setframerate(16000)
|
||||
audio.writeframes(b'\x00\x00' * 1600)
|
||||
self.binary = stream.getvalue()
|
||||
self.settings.tts_base_url = self.settings.inference_base_url + '/v1'
|
||||
self.settings.tts_model = 'kokoro-82m'
|
||||
result = await self.provider.run_cpu('audio.speech', {'prompt': '你好'}, {'voice': 'zf_xiaobei', 'speed': 1.2}, {}, self.work)
|
||||
self.assertEqual(result.outputs[0].read_bytes(), self.binary)
|
||||
self.assertEqual(self.requests[-1][3], {'model': 'kokoro-82m', 'input': '你好', 'voice': 'zf_xiaobei',
|
||||
'speed': 1.2, 'response_format': 'wav'})
|
||||
87
compose.yaml
Normal file
@ -0,0 +1,87 @@
|
||||
name: cmvr-visual
|
||||
services:
|
||||
api:
|
||||
build: ./backend
|
||||
image: cmvr-visual-api:20261110
|
||||
container_name: cmvr-visual-api
|
||||
env_file: .env
|
||||
environment:
|
||||
WORKSPACE_ROOT: /workspace
|
||||
ASSET_ROOT: /workspace/cmvr-visual/assets
|
||||
JOB_WORK_ROOT: /workspace/cmvr-visual/jobs
|
||||
STATE_ROOT: /workspace/cmvr-visual/state
|
||||
INFERENCE_BASE_URL: http://llmuser-workspace:18190
|
||||
INFERENCE_API_KEY_FILE: /workspace/projects/llm-services/config/api_key
|
||||
GPU_STATUS_PATH: /run/llm-gpu-policy/status.json
|
||||
GPU_SCHEDULER_PATH: /workspace/projects/llm-services/state/gpu-scheduler.json
|
||||
TTS_BASE_URL: http://cmvr-visual-tts:8001/v1
|
||||
TTS_MODEL: kokoro-82m
|
||||
TTS_VOICES: zf_xiaobei,zm_yunxi
|
||||
TMPDIR: /workspace/cmvr-visual/tmp
|
||||
volumes:
|
||||
- ${WORKSPACE_HOST:-/data/llmusers/llmuser/workspace}:/workspace
|
||||
- /var/lib/llmuser-gpu-policy:/run/llm-gpu-policy:ro
|
||||
networks: [visual]
|
||||
user: '1013:1014'
|
||||
read_only: true
|
||||
cap_drop: [ALL]
|
||||
security_opt: [no-new-privileges:true]
|
||||
init: true
|
||||
pids_limit: 256
|
||||
cpus: 4
|
||||
mem_limit: 4g
|
||||
memswap_limit: 4g
|
||||
stop_grace_period: 45s
|
||||
restart: unless-stopped
|
||||
logging: {driver: json-file, options: {max-size: 10m, max-file: '3'}}
|
||||
frontend:
|
||||
build: {context: ., dockerfile: deploy/Dockerfile.frontend}
|
||||
image: cmvr-visual-frontend:20261110
|
||||
container_name: cmvr-visual-frontend
|
||||
ports: ['127.0.0.1:${WEB_PORT:-18193}:8080']
|
||||
depends_on: [api]
|
||||
networks: [visual]
|
||||
user: '1013:1014'
|
||||
read_only: true
|
||||
cap_drop: [ALL]
|
||||
security_opt: [no-new-privileges:true]
|
||||
tmpfs: ['/tmp:rw,nosuid,nodev,size=32m,mode=1777']
|
||||
pids_limit: 64
|
||||
cpus: 1
|
||||
mem_limit: 128m
|
||||
restart: unless-stopped
|
||||
logging: {driver: json-file, options: {max-size: 5m, max-file: '2'}}
|
||||
tts:
|
||||
build: ./tts
|
||||
image: cmvr-visual-tts:20261110
|
||||
container_name: cmvr-visual-tts
|
||||
environment:
|
||||
TTS_API_KEY: ${TTS_API_KEY:-}
|
||||
TTS_MODEL_DIR: /workspace/models/kokoro-82m
|
||||
TTS_WORK_DIR: /workspace/cmvr-visual/tts-work
|
||||
HF_HOME: /workspace/cmvr-visual/tts-cache
|
||||
XDG_CACHE_HOME: /workspace/cmvr-visual/tts-cache
|
||||
TMPDIR: /workspace/cmvr-visual/tmp
|
||||
CUDA_VISIBLE_DEVICES: ''
|
||||
HF_HUB_OFFLINE: '1'
|
||||
TRANSFORMERS_OFFLINE: '1'
|
||||
volumes:
|
||||
- ${WORKSPACE_HOST:-/data/llmusers/llmuser/workspace}/models/kokoro-82m:/workspace/models/kokoro-82m:ro
|
||||
- ${WORKSPACE_HOST:-/data/llmusers/llmuser/workspace}/cmvr-visual/tts-work:/workspace/cmvr-visual/tts-work
|
||||
- ${WORKSPACE_HOST:-/data/llmusers/llmuser/workspace}/cmvr-visual/tts-cache:/workspace/cmvr-visual/tts-cache
|
||||
- ${WORKSPACE_HOST:-/data/llmusers/llmuser/workspace}/cmvr-visual/tmp:/workspace/cmvr-visual/tmp
|
||||
networks: [visual]
|
||||
user: '1013:1014'
|
||||
read_only: true
|
||||
cap_drop: [ALL]
|
||||
security_opt: [no-new-privileges:true]
|
||||
init: true
|
||||
pids_limit: 128
|
||||
cpus: 4
|
||||
mem_limit: 4g
|
||||
memswap_limit: 4g
|
||||
stop_grace_period: 15s
|
||||
restart: unless-stopped
|
||||
logging: {driver: json-file, options: {max-size: 5m, max-file: '2'}}
|
||||
networks:
|
||||
visual: {external: true, name: cmvr-visual-net}
|
||||
6
deploy/Dockerfile.frontend
Normal file
@ -0,0 +1,6 @@
|
||||
FROM nginx:1.30.6-alpine
|
||||
COPY deploy/nginx.conf /etc/nginx/nginx.conf
|
||||
COPY frontend/dist /usr/share/nginx/html
|
||||
USER 1013:1014
|
||||
EXPOSE 8080
|
||||
ENTRYPOINT ["nginx", "-g", "daemon off;"]
|
||||
49
deploy/kokoro-manifest.json
Normal file
@ -0,0 +1,49 @@
|
||||
{
|
||||
"repo": "hexgrad/Kokoro-82M",
|
||||
"revision": "f3ff3571791e39611d31c381e3a41a3af07b4987",
|
||||
"files": [
|
||||
{
|
||||
"rfilename": "config.json",
|
||||
"blobId": "14a726edd3718279eac426630879ff743955b16a",
|
||||
"size": 2351,
|
||||
"sha256": "5abb01e2403b072bf03d04fde160443e209d7a0dad49a423be15196b9b43c17f",
|
||||
"download_url": "https://www.modelscope.cn/api/v1/models/AI-ModelScope/Kokoro-82M/repo?Revision=7e4304e4a2b8b8fdeef357c7d4bcb987865677a0&FilePath=config.json"
|
||||
},
|
||||
{
|
||||
"rfilename": "kokoro-v1_0.pth",
|
||||
"blobId": "15769c415594dcb424579ba3dfae3085578aac4e",
|
||||
"size": 327212226,
|
||||
"lfs": {
|
||||
"sha256": "496dba118d1a58f5f3db2efc88dbdc216e0483fc89fe6e47ee1f2c53f18ad1e4",
|
||||
"size": 327212226,
|
||||
"pointerSize": 134
|
||||
},
|
||||
"sha256": "496dba118d1a58f5f3db2efc88dbdc216e0483fc89fe6e47ee1f2c53f18ad1e4",
|
||||
"download_url": "https://www.modelscope.cn/api/v1/models/AI-ModelScope/Kokoro-82M/repo?Revision=7e4304e4a2b8b8fdeef357c7d4bcb987865677a0&FilePath=kokoro-v1_0.pth"
|
||||
},
|
||||
{
|
||||
"rfilename": "voices/zf_xiaobei.pt",
|
||||
"blobId": "98d012c808d0c720f343605125b378c0390e7cfe",
|
||||
"size": 523435,
|
||||
"lfs": {
|
||||
"sha256": "9b76be63dab4f4f96962030acc0126a9aee9728608fbbe115e2b58a2bd504df6",
|
||||
"size": 523435,
|
||||
"pointerSize": 131
|
||||
},
|
||||
"sha256": "9b76be63dab4f4f96962030acc0126a9aee9728608fbbe115e2b58a2bd504df6",
|
||||
"download_url": "https://www.modelscope.cn/api/v1/models/AI-ModelScope/Kokoro-82M/repo?Revision=3cbf1fa40f92ebf18fcbf80866b4765561d16e70&FilePath=voices/zf_xiaobei.pt"
|
||||
},
|
||||
{
|
||||
"rfilename": "voices/zm_yunxi.pt",
|
||||
"blobId": "ab5b4af8e051d3940b7f265e0ff6a113a7a68f2a",
|
||||
"size": 523425,
|
||||
"lfs": {
|
||||
"sha256": "dbe6e1ce7c3dbaf2f5667432947b638b1c6831ccbe154c4610dbcc44f431e27b",
|
||||
"size": 523425,
|
||||
"pointerSize": 131
|
||||
},
|
||||
"sha256": "dbe6e1ce7c3dbaf2f5667432947b638b1c6831ccbe154c4610dbcc44f431e27b",
|
||||
"download_url": "https://www.modelscope.cn/api/v1/models/AI-ModelScope/Kokoro-82M/repo?Revision=3cbf1fa40f92ebf18fcbf80866b4765561d16e70&FilePath=voices/zm_yunxi.pt"
|
||||
}
|
||||
]
|
||||
}
|
||||
47
deploy/nginx.conf
Normal file
@ -0,0 +1,47 @@
|
||||
pid /tmp/nginx.pid;
|
||||
worker_processes 2;
|
||||
error_log /dev/stderr warn;
|
||||
events { worker_connections 1024; }
|
||||
http {
|
||||
include /etc/nginx/mime.types;
|
||||
default_type application/octet-stream;
|
||||
access_log /dev/stdout;
|
||||
sendfile on;
|
||||
server_tokens off;
|
||||
client_body_temp_path /tmp/client_temp;
|
||||
proxy_temp_path /tmp/proxy_temp;
|
||||
fastcgi_temp_path /tmp/fastcgi_temp;
|
||||
uwsgi_temp_path /tmp/uwsgi_temp;
|
||||
scgi_temp_path /tmp/scgi_temp;
|
||||
server {
|
||||
listen 8080;
|
||||
server_name _;
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
client_max_body_size 512m;
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
add_header Referrer-Policy same-origin always;
|
||||
add_header X-Frame-Options SAMEORIGIN always;
|
||||
add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; media-src 'self' blob:; connect-src 'self'; font-src 'self' data:; frame-ancestors 'self'; object-src 'none'; base-uri 'self'" always;
|
||||
location /api/ {
|
||||
proxy_pass http://cmvr-visual-api:8000;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header Connection "";
|
||||
proxy_buffering off;
|
||||
proxy_cache off;
|
||||
proxy_request_buffering off;
|
||||
proxy_read_timeout 3600s;
|
||||
proxy_send_timeout 3600s;
|
||||
}
|
||||
# The library SPA route shares the build directory's name. Serve the
|
||||
# entry point explicitly so Nginx cannot redirect it to container :8080.
|
||||
location = /assets { try_files /index.html =404; expires -1; }
|
||||
location = /assets/ { try_files /index.html =404; expires -1; }
|
||||
location /assets/ { try_files $uri =404; expires 7d; }
|
||||
location = /index.html { try_files $uri =404; expires -1; }
|
||||
location / { try_files $uri $uri/ /index.html; }
|
||||
}
|
||||
}
|
||||
36
deploy/production.sql.example
Normal file
@ -0,0 +1,36 @@
|
||||
-- CMVR Visual / MySQL 专用账号最小权限示例
|
||||
-- 仅供有权限的 DBA 审核后逐项执行。全部语句默认注释,不含真实密码。
|
||||
-- 用户指定的正式目标库已存在:192.168.28.10:3306/cmvr-visual。
|
||||
-- 不创建/删除数据库,不读取其他项目凭据,不操作其他库。
|
||||
--
|
||||
-- 先替换两种占位:
|
||||
-- <API_SOURCE_HOST>:MySQL 实际看到的 API 来源主机或受限网段;不要直接用 %。
|
||||
-- <INDEPENDENT_RANDOM_PASSWORD>:独立随机强密码,安全交付,不提交源码。
|
||||
-- Docker NAT/桥接可能使来源不同于浏览器或服务器公网 IP,需由 DBA 实测确定。
|
||||
|
||||
-- CREATE USER 'cmvr_visual_app'@'<API_SOURCE_HOST>'
|
||||
-- IDENTIFIED BY '<INDEPENDENT_RANDOM_PASSWORD>';
|
||||
|
||||
-- 阶段1:首次由应用 create_all 建立 visual_* 表,需要库内 DDL 权限。
|
||||
-- GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, INDEX, REFERENCES
|
||||
-- ON `cmvr-visual`.*
|
||||
-- TO 'cmvr_visual_app'@'<API_SOURCE_HOST>';
|
||||
|
||||
-- 应用启动、表结构确认且已有正式备份后,撤销临时建表权限。
|
||||
-- 阶段2:日常运行仅保留该库的 DML;不是全局权限或管理账号。
|
||||
-- REVOKE CREATE, INDEX, REFERENCES
|
||||
-- ON `cmvr-visual`.*
|
||||
-- FROM 'cmvr_visual_app'@'<API_SOURCE_HOST>';
|
||||
|
||||
-- 验证权限:
|
||||
-- SHOW GRANTS FOR 'cmvr_visual_app'@'<API_SOURCE_HOST>';
|
||||
|
||||
-- 应用使用以下六张表,均有 visual_ 前缀:
|
||||
-- visual_users, visual_sessions, visual_jobs,
|
||||
-- visual_assets, visual_job_assets, visual_job_events
|
||||
-- 当前 create_all 不提供 ALTER/迁移能力;升级应先备份,由 DBA 审查迁移。
|
||||
-- 不授予 DROP、ALTER、FILE、PROCESS、SUPER、CREATE USER 或 GRANT OPTION。
|
||||
-- 不需要 FLUSH PRIVILEGES;使用 CREATE USER / GRANT / REVOKE 后权限即生效。
|
||||
-- 若数据库由其他应用共用,DBA 可在表创建后进一步按 visual_* 具体表授权,
|
||||
-- 而不使用库级 DML。不要假定此示例授权可访问其他项目的数据。
|
||||
-- 官方说明:https://dev.mysql.com/doc/refman/8.0/en/grant.html
|
||||
242
docs/API-examples.md
Normal file
@ -0,0 +1,242 @@
|
||||
# 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`,验证错误可能附字段位置。不要向用户显示服务器绝对路径或上游认证内容。
|
||||
70
docs/api-contract.md
Normal file
@ -0,0 +1,70 @@
|
||||
# Shared API contract
|
||||
|
||||
All endpoints use `/api`. JSON errors: `{detail:{code,message}}`; normal FastAPI validation errors may additionally contain field locations. Session cookie `cmvr_session` is HttpOnly, same-origin. POST/PATCH/DELETE except login need `X-CSRF-Token` from auth response. Never expose inference keys or absolute server paths.
|
||||
|
||||
## Authentication
|
||||
|
||||
- POST `/auth/login` `{username,password}` → `{user:{id,username,display_name,role},csrf_token}` plus session cookie.
|
||||
- GET `/auth/me` → same shape; 401 when signed out.
|
||||
- POST `/auth/logout` → 204; close SSE on frontend.
|
||||
- Admin POST `/auth/users` `{username,display_name,password}` → user.
|
||||
|
||||
## Capabilities and resources
|
||||
|
||||
- GET `/capabilities` → `{items:Capability[],scheduler:Scheduler}`.
|
||||
- GET `/system/status` → `{inference_online:boolean,scheduler:Scheduler,models:Capability[]}`.
|
||||
- Capability: `{task_type,label,model,available,input_types:string[],defaults:object,constraints:object,description:string}`.
|
||||
- Scheduler: `{available:boolean,state:string,reason:string|null,gpus:[{index,name,busy:boolean,eligible:boolean,free_gib:number|null}],updated_at:string|null}`. No PID or user identity.
|
||||
- Types: `image.generate`, `video.generate`, `defect.generate`, `audio.transcribe`, `math.solve`, `media.structure`, `video.compose`, optional `audio.speech` (only available when a real provider is configured).
|
||||
|
||||
## Assets
|
||||
|
||||
- POST `/assets` multipart field `file`, optional `name` → Asset.
|
||||
- GET `/assets?page=1&page_size=24&kind=&q=&tag=` → `{items:Asset[],total,page,page_size}`.
|
||||
- GET `/assets/{id}` → Asset.
|
||||
- PATCH `/assets/{id}` `{name?,tags?:string[],favorite?:boolean}` → Asset.
|
||||
- DELETE `/assets/{id}` → 204; retain referenced physical input.
|
||||
- GET `/assets/{id}/content` inline, Range supported; `?download=1` attachment.
|
||||
- GET `/assets/{id}/thumbnail` authenticated image preview (fallback image content when no separate thumbnail).
|
||||
- Asset: `{id,name,kind:'image'|'video'|'audio'|'text'|'json',mime_type,size_bytes,width:null|number,height:null|number,duration_seconds:null|number,preview_url,thumbnail_url:null|string,download_url,source_job_id:null|string,origin:'upload'|'generated',tags:string[],favorite:boolean,created_at:string}`.
|
||||
|
||||
## Jobs
|
||||
|
||||
- POST `/jobs`, optional `Idempotency-Key`, body `{task_type,input:{prompt?,negative_prompt?,image_asset_id?,audio_asset_id?,asset_id?,asset_ids?:string[]},parameters:object,count?:1..4,scheduled_at?:ISO8601|null}` → `{jobs:Job[]}`. Batch only for image/defect; each gets its own serial upstream job. Composition clip order and trims live in `parameters.clips:[{asset_id,start_seconds?,end_seconds?}]`, optional `audio_asset_id`, `subtitles:[{start,end,text}]`, width/height/fps. Server resolves owned assets only.
|
||||
- GET `/jobs?page=1&page_size=24&task_type=&state=` → `{items:Job[],total,page,page_size,cursor:number}`.
|
||||
- GET `/jobs/{id}` → Job.
|
||||
- POST `/jobs/{id}/cancel` → Job, cancellation may remain pending.
|
||||
- POST `/jobs/{id}/retry` → `{jobs:Job[]}` (user requested new generation, new business ID).
|
||||
- Job: `{id,task_type,state,phase,version,prompt:string,parameters:object,input_asset_ids:string[],result_assets:Asset[],result:object|null,progress:number|null,queue_position:number|null,upstream_id:string|null,attempt_count:number,preemptions:number,last_preempted_reason:string|null,cancel_requested:boolean,error:null|{code,message,retriable},sync_warning:string|null,created_at:string,scheduled_at:string|null,started_at:string|null,finished_at:string|null}`.
|
||||
- States: `scheduled,submitting,queued,running,collecting,cancelling,succeeded,failed,cancelled,timed_out`. Remote sync failures do not invent terminal failures; set sync_warning. Requeue is the same job ID and may go running→queued.
|
||||
- Image defaults1024²/50 steps; video defaults1280×704/121frames/24fps/50steps, 1080p enhancement optional. Advanced field is exactly `num_inference_steps`. No fake generation percentage.
|
||||
- ASR input accepts audio asset or video asset (CPU extract to owned WAV before upstream dispatch). Structure accepts image/video; result `subjects,scene,ocr,tags,frames?`, timestamps reflect actual sampled frames. Math result `{text}`; ASR result `{text,segments}`; composition produces video asset.
|
||||
|
||||
## Events
|
||||
|
||||
- GET `/events?after=0` authenticated EventSource. `Last-Event-ID` header overrides query on reconnect.
|
||||
- Durable event: `id: <integer>\nevent: job.updated\ndata: {"job":Job}\n\n`.
|
||||
- Other events: `asset.created` data `{asset:Asset}`, `asset.updated` same; `asset.deleted` `{id}`, `reset` asks client to refetch snapshots. Heartbeat comments do not change cursor. Stream owner-filtered; logout/expiry ends stream.
|
||||
- Fetch jobs snapshot and cursor before opening stream; after reconnection refresh HTTP state as well. Ignore Job versions older than or equal to the current version.
|
||||
|
||||
## Backend provider interface
|
||||
|
||||
Implemented in `app/providers.py` and `app/media.py`, independent of database models.
|
||||
|
||||
`Provider(settings)` methods (async):
|
||||
|
||||
- `health() -> bool`
|
||||
- `scheduler_status() -> dict` sanitized Scheduler above.
|
||||
- `prepare_gpu_payload(task_type:str, inputs:dict, parameters:dict, assets:dict[str,Path], work_dir:Path) -> dict` validated original upstream payload `{task_type,input,parameters,timeout_seconds}`. Input paths must be within shared workspace. Preprocess video ASR as needed.
|
||||
- `submit(payload:dict,idempotency_key:str) -> dict` original upstream job response; retry only same immutable payload/key.
|
||||
- `query(upstream_id:str) -> dict`, `cancel(upstream_id:str) -> dict`.
|
||||
- `download(upstream_id:str,index:int,destination:Path) -> None` atomic streamed output, size bounded.
|
||||
- `run_cpu(task_type:str, inputs:dict, parameters:dict, assets:dict[str,Path], work_dir:Path) -> CpuResult`.
|
||||
- `aclose() -> None`.
|
||||
- `CpuResult` dataclass: `outputs:list[Path]`, `result:dict`, `metadata:dict`.
|
||||
- `ProviderError(code,message,retriable=False)` has those attributes; no secret/path leaks in public messages.
|
||||
- Settings attributes consumed: `inference_base_url,inference_api_key,inference_api_key_file,workspace_root,asset_root,job_work_root,gpu_status_path,gpu_scheduler_path,qwen_base_url,qwen_model,qwen_api_key,ffmpeg_bin,ffprobe_bin,tts_base_url,tts_model,tts_api_key,request_timeout_seconds,max_output_bytes`.
|
||||
- `app/media.py`: `inspect_media(path:Path,settings)->dict` (kind,mime_type,width,height,duration_seconds); `make_thumbnail(path:Path,destination:Path,settings)->Path|None`. These are async, subprocess is fixed argv, bounded time/resources; no shell. Image validation can use Pillow. JSON/text generated outputs supported.
|
||||
- `capabilities(settings)->list[dict]` returns exact DTO above. Optional speech is false unless real service configured; provider speech through OpenAI-compatible `/audio/speech` if selected later.
|
||||
|
||||
Production files live under `/workspace/cmvr-visual`. Tests/explicit local preview use isolated configured roots, never implicitly access host files. CPU provider cancellation must kill/wait only its own subprocess. The coordinator supplies one task-private work directory per attempt.
|
||||
35
docs/design.md
Normal file
@ -0,0 +1,35 @@
|
||||
# CMVR Visual 实施设计
|
||||
|
||||
用户指定 Vue 3、Element Plus、Pinia 前端与 Python、FastAPI、MySQL 后端,工程位于 `E:\workspace\hybrid\cmvr-visual`。产品借鉴即梦的集中创作入口,使用自己的品牌、组件与真实本地模型结果。
|
||||
|
||||
本文描述已实现基线。最新复核与已确认的“三分镜15秒、交互全天/批量夜间”见 [落地方案](需求复核与落地方案_20261110.md),相关功能尚待实施。
|
||||
|
||||
## 产品与能力
|
||||
|
||||
提供创作工作台、素材库、任务中心、素材理解、数学推演、成片编排。图像使用 Qwen-Image;视频使用 Wan2.2-TI2V-5B 和可选 Real-ESRGAN,严格限定当前已部署的 121 帧/24fps,约 5 秒;缺陷功能为 SDXL+Canny ControlNet,控制图不是缺陷掩膜;语音转写使用 Whisper。数学和视觉理解复用已有 Qwen3.8-27B-FP8。FFmpeg 负责 CPU 媒体探测、抽帧、转码、片段拼接、上传音轨和人工字幕。
|
||||
|
||||
声音生成按中文旁白需求先实现 Kokoro-82M CPU 本地配音,提供小贝、云希两个普通话音色和 WAV 输出;Whisper 负责语音转写。音频类型已向用户询问,尚未收到进一步偏好,音乐和音效不在本轮实现范围。能力接口不伪造音乐、热度预测、训练掩膜、15秒视频或模型内部百分比。专业数学准确率、镜头切分准确率等原方案指标不作为已验收事实。
|
||||
|
||||
## 架构决策
|
||||
|
||||
浏览器只调用业务后端。HTTP 处理登录、上传、查询、任务提交/取消与文件下载,单个用户 SSE 流负责持久任务事件及断线重放。无需双向持续交互,故不引入 WebSocket。Nginx/开发代理统一同源,使用 HttpOnly 会话 Cookie 和 CSRF 头保护写操作。
|
||||
|
||||
生产后端为独立 CPU 容器,和既有 `llmuser-workspace` 接入专用 Docker 网络,通过内部名称访问私有模型 API,保留其原有认证和 host loopback 发布限制。后端与模型容器只共享 llmuser 的 `/workspace`,素材存放专用子目录。无需修改已验收 GPU 队列、驱动、系统或其他业务;生产部署脚本不会停止已有服务。
|
||||
|
||||
GPU 工作仍只有现有模型 worker 执行。业务后端持久化请求与固定上游幂等键,再提交原样请求;网络结果不明时只能重试相同幂等键和相同请求,绝不创建替代生成。已知上游 ID 后只恢复查询,取消等待确认清理完成。抢占反映为同一业务任务 running→queued、尝试次数增加。CPU FFmpeg/Qwen HTTP 作业由业务协调器处理,不占用新 GPU worker。
|
||||
|
||||
MySQL 已接入 `192.168.28.10:3306/cmvr-visual`,按用户本次要求暂用 root;接入前确认空库,初始化六张本应用 `visual_` 表和默认管理员。之后再创建独立数据库账号。旧独立 MySQL 验收实例及样例数据保留,没有自动迁移。当前运行环境为production,但HTTP仍仅回环发布;SQLite仅用于显式本地preview/test,MySQL失败绝不自动回退。
|
||||
|
||||
## 可靠性与权限
|
||||
|
||||
任务、事件和结果导入状态存入数据库;事件和任务版本在一个事务内提交。SSE 通过 owner+递增ID查询,不长期占用数据库事务,支持 Last-Event-ID、心跳和重连同步。模型不提供进度时 progress=null;前端允许 running→queued,按 version 去重。
|
||||
|
||||
所有素材、任务、SSE 和文件内容均校验 owner。浏览器只传 asset ID,不接受服务器绝对路径、任意 URL、FFmpeg filter 或 shell 命令。文件名由服务端生成,临时文件验证后原子发布,引用中的输入不物理删除。最终产物导入后才进入素材库,视频使用带 Range 支持的鉴权文件响应。会话令牌只存哈希,密码使用加盐强哈希,凭据通过部署环境/私有文件传入,禁止进入源码或前端。
|
||||
|
||||
## 交互
|
||||
|
||||
深色创作工作台、窄侧栏、宽结果区域、集中提示词和参数面板。Element Plus 用于真实表单/上传/抽屉交互,Pinia 管理会话、创作草稿、素材及任务流。示例只能明确标记为模型验收样例;用户任务和素材库初始为空。支持上传预览、筛选搜索、素材详情、取消、再次生成、下载和将图片用于视频、将视频用于编排。
|
||||
|
||||
## 验证
|
||||
|
||||
先测试权限、上游幂等提交、断线恢复、抢占重排、取消、结果导入与 SSE 事件重放。构建检查前端,测试事件版本去重和重排状态,最后使用实际浏览器验证布局、上传、生成、视频/音频播放和下载。MySQL 连通及真实模型调用均单独报告,不将测试替身称为线上验收。
|
||||
25
docs/implementation-plan.md
Normal file
@ -0,0 +1,25 @@
|
||||
# CMVR Visual Implementation Plan
|
||||
|
||||
**Goal:** Deliver the requested Vue3/Element Plus/Pinia and FastAPI/MySQL creative studio connected to the server's real inference queue.
|
||||
|
||||
**Architecture:** Same-origin HTTP plus durable authenticated SSE; business data in MySQL; original upstream worker remains the only GPU executor. Production web CPU containers share the isolated workspace and a private Docker network with the inference container. Local test databases require explicit mode.
|
||||
|
||||
**Spec:** `docs/design.md`, shared interfaces `docs/api-contract.md`.
|
||||
|
||||
## Constraints and review focus
|
||||
|
||||
- Preserve existing GPU priority, serial execution, services and confinement. No database-wide deletion, driver changes, global Docker/systemd restart or public publication.
|
||||
- Credentials absent from source and browser; session/owner/CSRF checks protect every mutation/content stream.
|
||||
- Persist immutable upstream request/key before dispatch. No duplicate inference after timeout/restart; no job replay after known upstream ID.
|
||||
- Preserve running→queued preemption, cancellation races, idempotent output import and event ordering.
|
||||
- Only genuine capabilities and samples; five-second video limit, no defect mask claim, no synthetic GPU percentages.
|
||||
- Detached SSE must not hold transactions or cancel inference. Reconnection uses event cursor and HTTP reconciliation.
|
||||
|
||||
## Implementation
|
||||
|
||||
- [ ] Backend core: write failing auth/ownership/jobs/event recovery tests; implement MySQL/explicit SQLite config, schema, auth, asset storage, job coordinator and SSE. Prove negative access and upstream lifecycle transitions.
|
||||
- [ ] Providers: test actual parameter/path validation, HTTP boundary, safe subprocess and output handling; implement existing GPU API adapter, Qwen math/vision, CPU FFmpeg analysis/composition, bounded file probing and optional speech provider.
|
||||
- [ ] Frontend: implement shared DTOs and HTTP client, cookie/CSRF flow, Pinia versioned job/SSE store, creation forms, real asset previews/library, task center and composition. Test requeue/version handling; build/typecheck.
|
||||
- [ ] Integration: install isolated dependencies, verify OpenAPI/schema contract, run tests and MySQL connectivity if credentials arrive, package private-network deployment and environment examples. Do not auto-switch DB on failure.
|
||||
- [ ] Visual and live verification: run browser, inspect desktop/mobile layouts and actual actions; perform real image/ASR or CPU generation against the model host without interrupting existing users. Record any capability or credential blocker honestly.
|
||||
- [ ] Deliver source, setup guide, communication recommendation, verified URLs and acceptance report.
|
||||
183
docs/superpowers/plans/2026-11-10-cmvr-visual-v2.md
Normal file
@ -0,0 +1,183 @@
|
||||
# CMVR Visual V2 Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development or superpowers:executing-plans to implement this plan task-by-task. Checkboxes track implementation, not this planning review.
|
||||
|
||||
**Goal:** 在现有正式库与模型服务上交付可靠提交、三分镜15秒工作流及交互/夜间批量调度。
|
||||
|
||||
**Architecture:** 保留单FastAPI业务协调器、MySQL任务/事件与既有独立GPUworker。先升级受版本约束的上游调度/停止协议,再开放工作流;资源池new_gpu/cpu_media/qwen_http分别最多1个执行。MySQL只由业务进程产生有序领域事件,不直接扩成多API实例。
|
||||
|
||||
**Tech Stack:** Vue3、Element Plus、Pinia、TypeScript;Python/FastAPI、SQLAlchemy async、MySQL8、Alembic;既有vLLM-Omni/Diffusers/Whisper、共享Qwen HTTP、CPU FFmpeg/Kokoro。
|
||||
|
||||
**Spec:** [实施方案V2](../../实施方案V2_20261110.md)。接口、状态与配额冲突时以Spec为准;旧R1–R12继续纳入下述任务。
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- 主工程根目录 `E:\workspace\hybrid\cmvr-visual`,下文无前缀的路径均相对此根。
|
||||
- `GPU/`前缀指另一个现有源码根 `C:\Users\Administrator\Documents\ChatGPT\大模型部署到服务器\llm-services`,部署到既有 `/workspace/projects/llm-services`;不创建另一套GPU worker。
|
||||
- 正式MySQL及admin已存在,不重复初始化、不覆盖密码、不迁移旧验收样例。
|
||||
- 三段各120个成片帧,最终360帧、24fps;保持多镜头定义。
|
||||
- Asia/Shanghai `[21:00,次日08:00)`;外部用户优先、新GPU任务全局1个。
|
||||
- 现有Qwen批量必须先通过单请求停止确认;未通过就关闭该项,不能杀共享服务PID。
|
||||
- 不读写其他项目数据库,不全局重启Docker/驱动,不修改宿主时钟;秘密不进入源码、命令行参数或测试输出。
|
||||
- 每任务先写有意义的失败测试,再最小实现、回归、独立审查并提交;只有对应验收通过才勾选。生产操作只在任务12执行。
|
||||
|
||||
## Review Focus
|
||||
|
||||
1. 响应丢失与进程/DB故障不产生未经明确意图的新计算——任务3/4。
|
||||
2. 08点与claim、崩溃、时钟回拨竞争,不越界派发且不假称释放——任务5/6。
|
||||
3. 旧Run/旧Execution晚到,不能覆盖新成片或停止新进程——任务4/8。
|
||||
4. 部分镜头失败、短源、跨镜头字幕和超长旁白仍能得到确定结果——任务7/8。
|
||||
5. 已有正式数据升级、恢复及跨账号访问保持一致——任务1/9/10/12。
|
||||
|
||||
---
|
||||
|
||||
## Task 1:基线核验、迁移机制与恢复点
|
||||
|
||||
**Files:** 新建 `backend/alembic.ini`、`backend/alembic/env.py`、`backend/alembic/versions/001_legacy_baseline.py`、`scripts/schema_preflight.py`、`scripts/backup_checkpoint.py`、`backend/tests/test_schema_migrations.py`;修改 `backend/app/database.py`、`backend/requirements.txt`。
|
||||
|
||||
**Interfaces:** `schema_preflight(connection) -> SchemaDiff`;`check_schema_revision(connection, supported: set[str]) -> None`;备份清单包含checkpoint_id、应用/上游/schema版本、文件哈希、上游job IDs、执行状态和时间。
|
||||
|
||||
- [ ] 在隔离MySQL8.0.36复制当前六表基线,测试 `test_baseline_matches_existing_schema` 与 `test_drift_refuses_stamp`:准确基线可stamp001,少唯一约束或DATETIME精度不对必须拒绝,用户和任务行不变。
|
||||
- [ ] 实现显式迁移入口和只检查的生产启动;空库upgrade,已有库先核验再stamp;include_object只管理本应用表。
|
||||
- [ ] 写 `test_checkpoint_rejects_live_execution`、`test_restore_preserves_upstream_identity`:无停止ACK不能宣称静态恢复点;恢复不得把旧ID误接到独立前进的队列。
|
||||
- [ ] 隔离库实跑upgrade、失败中断修复、镜像兼容回退与备份恢复;输出schema diff、行数与校验结果。未演练前不做正式DDL。
|
||||
|
||||
## Task 2:冻结V2 DTO、表和媒体规范
|
||||
|
||||
**Files:** 新建 `backend/app/contracts_v2.py`、`backend/alembic/versions/002_workflow_execution.py`、`backend/tests/test_contracts_v2.py`;修改 `backend/app/models.py`、`frontend/src/types.ts`。以现有六表为起点新增Spec第3节表;素材标签使用 `visual_asset_tags` 关联表。
|
||||
|
||||
**Interfaces:** `WorkflowSpec`、`DraftDTO`、`RunDTO`、`StepDTO`、`ExecutionDTO`、`BatchDTO`、`BatchItemDTO`、`SchedulingEnvelope`;新输入 `extra=forbid`,输出完整标识/模式/版本/等待原因。关键spec固定为:
|
||||
|
||||
```json
|
||||
{
|
||||
"schema_version": 1,
|
||||
"shots": [
|
||||
{"key":"shot_1","prompt":"...","image_asset_id":null,"parameters":{"seed":42}},
|
||||
{"key":"shot_2","prompt":"...","image_asset_id":null,"parameters":{"seed":43}},
|
||||
{"key":"shot_3","prompt":"...","image_asset_id":null,"parameters":{"seed":44}}
|
||||
],
|
||||
"profile":"landscape_1080_v1",
|
||||
"render":{"fps":24,"total_frames":360,"fit":"contain","audio":null,"subtitles":[],"template_version":"plain-v1"}
|
||||
}
|
||||
```
|
||||
|
||||
profile由服务器编译成冻结的模型默认参数/版本,横版1280×704→1920×1056内容→1920×1080画布;竖版对应704×1280→1056×1920→1080×1920。字幕字段start_frame/end_frame/text;audio字段以Spec为准。客户端不提交路径、父Job关系或宿主信息。
|
||||
|
||||
- [ ] `test_rejects_unknown_scheduling_and_timeline_fields`、`test_requires_exact_three_shot_keys`、`test_preset_compilation_is_frozen`:多/少镜头、重复key、非法帧区间和未知参数失败;已接受快照不随后续默认值变化。
|
||||
- [ ] 实现002的新增/回填,保留旧hash算法及旧attempt计数;所有旧Job回填interactive,历史Execution明细保持“未知/未提供”。
|
||||
- [ ] 在MySQL与SQLite测试执行同一DTO/唯一约束规则;生产schema指纹与新版本检查通过。
|
||||
|
||||
## Task 3:端到端提交幂等和额度原子性
|
||||
|
||||
**Files:** 新建 `backend/app/submissions.py`、`backend/tests/test_submissions.py`、`frontend/src/stores/submissions.ts`、`frontend/src/stores/submissions.test.ts`;修改 `backend/app/jobs.py`、`frontend/src/api.ts`、提交入口。
|
||||
|
||||
**Interfaces:** `accept_submission(session, owner_id, operation, key, payload_schema, body) -> Submission`;`GET /api/submissions/{key}?operation=...`;前端 `submitOrRecover(operation, immutableBody) -> resource`,使用按用户隔离的本地持久存储。
|
||||
|
||||
- [ ] 测试服务器commit后丢响应,客户端刷新/重试仍返回同批Job、同资源引用;同key改body返回409,复用不重复扣配额;GET404后原POST迟到也不重复。
|
||||
- [ ] 实现版本化canonical body哈希及旧v1幂等记录回填;原Job键继续能恢复。显式retry/Run创建也要求幂等键,不能仅保护第一层POST/jobs。
|
||||
- [ ] 前端持久化发送前意图,提供“确认提交状态”与“明确新建”两种行为;离线编辑不触发自动生成,退出用户清除敏感缓存。
|
||||
- [ ] 后端对应pytest、前端submissions.test通过;注入延迟/重复HTTP的集成断言只有一组实际子任务。
|
||||
|
||||
## Task 4:Execution、结果manifest与安全取消
|
||||
|
||||
**Files:** 新建 `backend/app/executions.py`、`backend/app/artifacts.py`、`backend/tests/test_execution_recovery.py`、`backend/tests/test_artifact_reconcile.py`;修改 `coordinator.py`、`assets.py`、`media.py`、`providers.py`、`events.py`。
|
||||
|
||||
**Interfaces:** `begin_execution(session, job_id) -> Execution`;`accept_manifest(session, execution_id, fence_token, manifest) -> bool`;`request_control(session, job_id, desired_state, expected_execution_id) -> ControlResult`;`reconcile_artifacts(...) -> ReconcileReport`。
|
||||
|
||||
- [ ] 先固定R2/R3故障:provider执行后写DB失败、manifest写前后崩溃、commit已成功但客户端收到异常,断言不自动重新provider调用、不误删已提交文件。
|
||||
- [ ] 明确Job可领取状态集合,paused/needs_attention不执行、collecting只导入;当前Execution与fence不匹配的回调拒绝;CPU可信manifest仅恢复归档。
|
||||
- [ ] 固定R5:重复cancel只发一次停止并等待清理;当前media/TTS shield规则保留。控制先提交但已经领取的任务允许在途停止,不再领取后续步骤。
|
||||
- [ ] 所有状态变化与领域事件同事务;SSE drain/20秒Uvicorn graceful与45秒Docker宽限配套测试。保持长连接重启时必须在强杀前完成清理。
|
||||
|
||||
## Task 5:GPU上游V2协议与队列资格
|
||||
|
||||
**Files:** 新建 `GPU/llm_services/scheduling.py`、`GPU/tests/test_scheduling_v2.py`;修改 `GPU/llm_services/api.py`、`store.py`、`worker.py`、网站`providers.py`与协议契约。
|
||||
|
||||
**Interfaces:** `GET /capabilities`;v2 `Submission.scheduling: SchedulingEnvelope`;`PUT /jobs/{id}/control`请求/ACK含command_id、control_version、expected_execution_id;`claim_eligible(now_utc, policy) -> Lease|None`;`evaluate_window(now_utc, mode, closed_windows) -> Eligibility`。
|
||||
|
||||
- [ ] 旧上游不支持v2时batch明确不可用;同key更改mode409;旧key仍返回原ID;所有未知新字段不能静默忽略。
|
||||
- [ ] 测试窗口 `[21:00,08:00)`、最后30秒禁新batch、07:59领取08点spawn被挡、关闭窗口回拨不重新开放;不改宿主时钟,注入Clock。
|
||||
- [ ] 原子claim跳过不合格队首,交互/批次/用户按Spec公平规则;子任务与重试mode继承,HTTP伪造父ID或通过retry降级拒绝。
|
||||
- [ ] 以desired_state+hold而非外部直接改running实现控制;cancel高于pause、终态不可逆,旧command不影响新Execution。原124项基线范围及新增协议测试回归。
|
||||
|
||||
## Task 6:独立监管、CPU窗口与Qwen前置验证
|
||||
|
||||
**Files:** 修改 `GPU/admin/gpu_guard.py`、`GPU/llm_services/gpu_policy.py`、`GPU/tests/test_gpu_guard.py`;新建 `GPU/tests/test_deadline_guardian.py`、`backend/app/resource_policy.py`、`backend/tests/test_resource_policy.py`、`scripts/probe_qwen_control.py`;修改 `tts/app.py`及生命周期测试。
|
||||
|
||||
**Interfaces:** `register_execution(identity, policy) -> LeaseAck`;`stop_execution(execution_id, fence_token) -> StopAck`;`resource_plan(task_type, input_kind) -> list[PhaseRequirement]`;`acquire_phase(execution_id, phase_key) -> SlotLease`。PhaseRequirement含phase_key与pool,分阶段checkpoint后释放再取得下一槽。探测报告必须区分“连接关闭”与“服务端计算结束ACK”。
|
||||
|
||||
- [ ] 用自有隔离进程夹具测试cgroup/UID、PID重用、starttime/boot_id、旧fence和任意宿主PID均不能误杀;worker07:59:59退出后监管仍对已登记batch截止。
|
||||
- [ ] 清理ACK加清理后的新GPU快照才释放槽;旧快照、尾进程、监控丢失、超15秒未ACK保持blocked。外部占用时不要求总显存回旧基线。
|
||||
- [ ] 将CPU编码/Kokoro pause和cancel分开,作业/子进程带Execution身份;按Spec实现TTS私有异步execution v2、control ACK和音频获取,原同步交互接口兼容。同ID重试不再次启动,登记/监管许可前不运行模型。batch停止依然保留已完成步骤,三个资源池各1,未知Qwen请求只挡新的Qwen请求。
|
||||
- [ ] 对现有Qwen的request_id/abort/结束确认及低优先能力只做获准的可控验证;没有证据输出false并禁用Qwen batch。不得通过停止共享进程让测试“通过”。
|
||||
- [ ] 视频ASR抽音与GPU转写、视频理解抽帧与Qwen请求分别计入对应槽;两任务交错不出现cpu_media并发2或槽互等死锁。暂停发生在阶段间时不运行下一阶段。
|
||||
|
||||
## Task 7:15秒媒体规范化
|
||||
|
||||
**Files:** 新建 `backend/app/timeline.py`、`backend/tests/test_timeline_v2.py`;修改 `media.py`、`providers.py`、`GPU/llm_services/adapters.py`的工作流增强配置与相应测试。
|
||||
|
||||
**Interfaces:** `compile_timeline(spec, owned_assets) -> TimelinePlan`;`compose_workflow(plan, work_dir, control) -> CpuResult`;`inspect_video_track(path) -> {frames,fps,width,height,duration}`。保留现有普通video.compose兼容接口,V2走独立白名单。
|
||||
|
||||
- [ ] 真实FFmpeg夹具:三个121帧24fps源各取120帧;结果视频流精确360帧、24fps、15秒,容器尾差≤0.10秒,横/竖版分别验证。
|
||||
- [ ] 119帧短源拒绝,不能借音轨时长或冻结补帧通过;超长音轨默认拒绝,显式3–18秒裁切通过;10秒音轨offset120通过/121拒绝,15秒音轨任何正偏移拒绝;短音轨补静音。
|
||||
- [ ] 字幕跨120/240帧边界、end=360通过,负数/越界/非法控制语法拒绝;片头在360帧内叠加。文件解码/规格为硬门槛,疑似黑帧或静帧作为可人工复核的质量提示。
|
||||
- [ ] 明确增强不先烧黑边,contain/cover各测试真实内容与输出画幅。全过程固定FFmpeg argv,不接收滤镜脚本、外部URL或字体路径。
|
||||
|
||||
## Task 8:Draft/Run/Step服务和父子SSE
|
||||
|
||||
**Files:** 新建 `backend/app/workflows.py`、`backend/app/workflow_engine.py`、`backend/app/batches.py`、`backend/tests/test_workflows_v2.py`、`backend/tests/test_workflow_races.py`;修改 `main.py`、`events.py`、`dto.py`和`jobs.py`。
|
||||
|
||||
**Interfaces:** Spec第5.3节接口;`create_run(session, owner_id, draft_id, expected_version, revision, mode) -> RunSnapshot`;`advance_run(session, run_id) -> None`;`snapshot_run(session, owner_id, run_id) -> {run,steps,jobs,cursor}`;所有service沿用调用方事务,不嵌套申请当前进程的DB单元锁。
|
||||
|
||||
- [ ] 两标签页Draft冲突409,旧revision不能提交;运行期间草稿变更不变更Run快照。
|
||||
- [ ] 第二镜头失败仅它新增Job,抢占两次仍为同Job新Execution;compose失败不再生成三镜头;模式和政策继承。needs_attention未确认无残留执行不能重试,safe_to_retry后才允许显式新尝试。
|
||||
- [ ] 修改成功镜头产生新Run并复用其它已验证素材;旧合成晚到不改current_run_id/output;输入hash和引用检查覆盖裁切、音轨、字幕、模板变更。
|
||||
- [ ] 父取消与claim/完成/导入竞争;已领取者停止ACK后终态,未领取者不启动;pause/resume只处理手工hold,不解除夜间或维护限制。新增workflow.updated/draft.updated完整version快照,乱序与重连不倒退。
|
||||
- [ ] Batch有独立DTO、成员表、查询/control及batch.updated;Run和独立Job均能归属,刷新恢复混合成员且每批最多1个活动成员;安全清理完成后的失败项不堵其它项,全部终态混合结果为completed_with_errors,批次取消不删除成功产物。
|
||||
|
||||
## Task 9:账号、机器调用与额度/回收
|
||||
|
||||
**Files:** 新建 `backend/app/tokens.py`、`quotas.py`、`retention.py`、`maintenance.py`、`backend/tests/test_tokens_quotas.py`、`backend/tests/test_retention.py`;修改 `auth.py`、`assets.py`、`models.py`和对应增量迁移。
|
||||
|
||||
**Interfaces:** 本人改密、admin用户列表/停用/撤销会话、owner机器Token创建/撤销;`reserve_budget(session, owner_id, operation) -> Reservation`;`collect_garbage(dry_run=True) -> GCReport`;维护状态阻止新写入与claim而保留查询。
|
||||
|
||||
- [ ] 默认admin在私有验收仍能用初始密码登录且不被重启重置;公网preflight要求先在私有入口改密,未完成不能先暴露登录入口。停用/改密撤销会话,停用给任务加admin_suspend并停止,重新启用不自动重跑;不能停用最后一个有效管理员。Token仅哈希、到期/撤销生效并关闭其事件流,scope不授管理权限。
|
||||
- [ ] 配额事务内预留、复用幂等键不重复扣;batch mode权限、跨owner资产、每池并发及入口限流覆盖直接HTTP绕过测试。
|
||||
- [ ] 上传在multipart解析前限制流量并预留空间;输出/临时空间纳入预算,达到水位停止接新任务。实际超预留需原子追加预算,失败仅保留可恢复结果,不重生成。
|
||||
- [ ] SQL分页和标签关联索引;删除与引用互斥,非终态/commit不明文件不GC;事件过期cursor返回reset。先dry-run和隔离数据测试,禁止首次上线直接删除历史文件。
|
||||
|
||||
## Task 10:Vue工作流与持久草稿
|
||||
|
||||
**Files:** 新建 `frontend/src/stores/workflows.ts`、`draftPersistence.ts`及对应测试、`frontend/src/views/WorkflowView.vue`、`BatchView.vue`、`AccountView.vue`;修改router、api、types、Workbench/Compose/Tools/Tasks/Assets与capabilities。
|
||||
|
||||
**Interfaces:** 消费任务2/8/9 DTO;Pinia提供 `saveDraft(expectedVersion)`、`startRun(revision,mode)`、`recoverSubmission(key)`、`applyRunSnapshot(version)`,步骤Job事件必须匹配当前selected_job。
|
||||
|
||||
- [ ] 测试保存中/已保存/提交待确认/已接受区别,跨页配音回填和刷新不丢草稿;版本冲突保留本地内容,离线不自动提交。
|
||||
- [ ] 父任务按镜头完成数和合成阶段显示,展开Job/Execution记录;旧Run迟到不盖新版,window/manual/resource/cleanup理由可读。
|
||||
- [ ] batch在协议/Qwen能力不足时禁用对应项;前端受限参数与后端错误field一致,标签确认合并,历史分页和收藏/来源筛选。
|
||||
- [ ] 账号/改密/Token入口使用既有Element Plus规范;桌面1440×1000和手机390×844测试表单、抽屉、播放与seek;不新增外部CDN依赖。
|
||||
|
||||
## Task 11:完整故障和兼容性回归
|
||||
|
||||
**Files:** 新建 `backend/tests/test_acceptance_v2.py`、`GPU/tests/test_upgrade_compatibility.py`、`qa/browser-v2.cjs`;更新原服务/网站契约、README和验收矩阵。
|
||||
|
||||
- [ ] 在隔离MySQL8.0.36而非仅SQLite跑任务1–10;对比现有52后端基线、TTS/前端测试及原GPU服务测试,无跳过地报告媒体和迁移覆盖。
|
||||
- [ ] 使用可控Clock、假上游和自有Linux子进程遍历Spec控制竞争表;不得改宿主时间、伪造生产guard状态或让他人作业承担压力测试。
|
||||
- [ ] 兼容矩阵覆盖新网站/旧上游拒绝batch、旧幂等恢复、老前端字段/未知字段处理、旧镜像schema支持范围;覆盖保留期reset。
|
||||
- [ ] 浏览器断网/刷新、多标签、两用户、父子SSE乱序和媒体边界;保留无密码、Cookie、Token的报告。
|
||||
|
||||
## Task 12:受控发布与真实验收
|
||||
|
||||
**Files:** 修改 `compose.yaml`、`backend/Dockerfile`、`deploy/nginx.conf`;新建 `deploy/release-checklist.md`,输出版本、迁移、恢复和真实模型记录。
|
||||
|
||||
- [ ] 先确认维护开关、恢复点、独立监管健康;冻结镜像/依赖/模型revision。按Spec顺序做兼容上游、迁移、API、前端,未通过gate保持维护。
|
||||
- [ ] 缩窄API挂载并验证原子替换状态文件仍更新;Uvicorn20秒退出/容器45秒;重建执行容器后监管allowlist匹配真实ID/UID/镜像再开admission,新API IP的Nginx解析可恢复;不全局重启其它服务。
|
||||
- [ ] 先真实小规格三镜头验证控制链,再选空闲资源执行一次冻结默认规格360帧交付;记录排队/冷加载/推理/增强/归档而非承诺原GPU·秒。夜间与抢占测试使用自己的受控作业,单独记录观察到的停止ACK延迟。
|
||||
- [ ] 配置用户提供的HTTPS域名或受信隧道后验证Secure Cookie、SSE、Range、机器Token和限流;用户决定的独立DB账号按后续授权创建,不能擅改共享root密码。
|
||||
- [ ] 完成至少一次库+文件+上游checkpoint恢复演练。发布只在各门槛实际通过后记为完成,代码合并/测试数量不能替代上线验收。
|
||||
|
||||
## Commands and completion records
|
||||
|
||||
开发环境:在`backend/`执行 `.venv/Scripts/python.exe -m pytest tests -q`;在`frontend/`执行 `pnpm test`、`pnpm build`。Linux媒体/迁移/监管与GPU仓库测试在各自隔离环境执行。只运行本任务对应检查,新的失败或依赖变更才扩大回归。
|
||||
|
||||
每任务记录:变更文件、失败→通过的测试、MySQL/媒体/真实GPU分别覆盖什么、剩余阻塞、回退版本。审查批准后再提交相应变更;当前清单保持未勾选,表示**尚未实施V2**。
|
||||
222
docs/实施方案V2_20261110.md
Normal file
@ -0,0 +1,222 @@
|
||||
# CMVR Visual 实施方案 V2
|
||||
|
||||
日期:2026-11-10,Asia/Shanghai。状态:**方案复审完成,待实施;本轮未修改运行中的应用或服务器**。
|
||||
|
||||
本方案承接[上一版复核](需求复核与落地方案_20261110.md),保留其中R1–R12和业务质量专项;以下规则解决上一版尚未明确的实施边界。发生冲突时以本方案为准。已完成的正式MySQL接入和默认管理员不重复执行。
|
||||
|
||||
## 1. 结论与一期范围
|
||||
|
||||
技术上可落地,现有Vue3/Element Plus/Pinia、FastAPI/MySQL、HTTP+SSE与独立GPU队列继续复用。上一版仍缺少上游调度协议、状态竞争、依赖失效、迁移回退和资源边界,不能直接按其概述并行开发。
|
||||
|
||||
用户已经确认:三段约5秒分镜合成15秒多镜头成片;交互创作全天使用空闲卡,批量任务仅21:00–08:00;新GPU任务全局最多一个,外部用户优先。保持这些决定。
|
||||
|
||||
一期验收范围:现有八种单任务能力、可靠提交与恢复、账号维护、持久草稿、三分镜工作流、夜间批量、标签/历史检索和受控对外API。基础质量检查使用固定文件规则;LoRA、数学专业指标、真实缺陷mask、镜头切分、热度预测和音乐生成仍按独立数据专项评测,不作为一期已具备能力。
|
||||
|
||||
**一个必须先验证的条件:**现有Qwen HTTP服务没有已实现的单请求取消及停止确认。关闭HTTP连接不能证明服务端GPU已停止。本期先验证该能力;未通过时,数学/视觉理解保持交互可用,Qwen批量明确标记不可用,不承诺其08:00硬截止,也不杀共享服务进程或重部署其模型。其它自管GPU与CPU批量可独立交付。如果必须一期同时包含Qwen夜间批量,则此验证是该项的放行阻塞。
|
||||
|
||||
## 2. 再次审查发现的九类遗漏
|
||||
|
||||
| 遗漏 | 为什么阻碍实施 | 本版决定 |
|
||||
| --- | --- | --- |
|
||||
| 上游不识别调度字段 | 当前Submission无scheduling,额外字段默认忽略,队列仍FIFO | 升级v2协议和能力协商;batch不允许降级为旧行为 |
|
||||
| 数据身份与attempt含义混用 | 抢占重启、用户重新生成、修改草稿会混成同一次尝试 | 分离Draft、Run、Step、Job显式尝试、Execution运行尝试 |
|
||||
| 暂停/取消/完成竞争 | HTTP直接改running可能与worker冲突;旧结果可能覆盖新版本 | 控制意图与执行状态分离,用执行代次和事务提交裁决 |
|
||||
| 重做后依赖失效未定义 | 镜头变了,旧合成晚到仍可能显示为最新成片 | 成功镜头修改产生新Run,合成绑定有序输入哈希 |
|
||||
| 夜间范围与进程故障缺约束 | 只在网页检查挡不住08点越界或worker崩溃后的runner | 所有batch计算步骤受窗口约束,独立监管确认停止 |
|
||||
| 草稿和父子事件缺契约 | 多标签覆盖、重连失真、父任务显示过早完成 | 乐观版本锁、一致快照、workflow.updated及阶段计数 |
|
||||
| 15秒只有时长描述 | 音频可撑长容器,横竖画幅、字幕和片头也会改变时长 | 固定视频轨360帧24fps,明确时间轴、音轨与画幅 |
|
||||
| 正式库迁移/恢复只有口号 | 已有6表且无Alembic版本;DDL失败不能当普通事务回滚 | 校验基线后stamp、只增不删迁移、两类回退与联合备份 |
|
||||
| 对外API、配额、回收边界缺数字与权限 | 自动客户端可冒充交互,积压与临时文件可无限增长 | 服务端分类、有限队列和空间预留、机器令牌及引用回收 |
|
||||
|
||||
代码证据:前四项分别涉及现有 `llm_services/api.py:21`、`store.py:260/308`、`worker.py:294`,以及网站 `models.py`、`coordinator.py`、`jobs.py:212`;当前[API契约](api-contract.md)尚未定义工作流对象。该结论来自只读源码复审,不代表这些新功能已经实现。
|
||||
|
||||
## 3. 一致的数据模型和幂等规则
|
||||
|
||||
### 3.1 对象关系
|
||||
|
||||
`Draft → Run → Step → Job(一次显式尝试)→ Execution(一次真实运行)`。
|
||||
|
||||
| 对象 | 主要字段和职责 |
|
||||
| --- | --- |
|
||||
| `visual_drafts` | owner_id、name、kind、spec、revision、version、current_run_id、updated_at。revision只在内容变化时增加,version对记录变化增加;草稿可编辑 |
|
||||
| `visual_workflow_runs` | draft_id/revision、owner_id、不可变spec_snapshot/spec_hash、execution_mode、batch_id、state、desired_state、version。运行不随草稿编辑变化 |
|
||||
| `visual_batches` / `visual_batch_items` | owner、不可变项规范、desired_state、state、version;成员唯一(batch_id,item_index),target_kind=job/run、target_id。Run和独立Job关联成员,workflow子Job从Run继承,不能自行换批次 |
|
||||
| `visual_workflow_steps` | run_id、step_key、kind、dependencies、semantic_input_hash、selected_job_id、state。首期固定shot_1/shot_2/shot_3/compose;配音/转写先在声音页生成素材后放入草稿,不隐式扩展新节点 |
|
||||
| 现有 `visual_jobs` 扩展 | run_id/step_key、batch_id/batch_item_index、显式尝试序号、execution_mode、policy_version。Run也有batch_id/batch_item_index;子Job由Run继承这些只读关系。一次用户重试产生新Job;自动让卡保持原Job和原上游ID |
|
||||
| `visual_job_executions` | job_id、execution_id、ordinal、phase_key、resource_pool、fence_token、upstream_attempt、lease_id、state、start/end、结果manifest引用。每次真实启动另记一次;不把旧attempt_count兼作镜头版本 |
|
||||
| `visual_submissions` | owner_id、operation、幂等key、payload_schema、body_hash、resource_refs、accepted_at。与创建资源在一个事务提交,唯一约束(owner,operation,key) |
|
||||
| `visual_asset_refs` | 对Run快照、输入、复用产物和导出文件的引用;与现有JobAsset共同决定是否可物理回收 |
|
||||
|
||||
保留旧字段和历史数据;对已完成旧任务不伪造不存在的execution明细。旧request_key/hash按v1算法恢复,新请求存payload_schema=2;升级不能让原幂等键取不到旧任务。
|
||||
|
||||
### 3.2 三种重试必须分清
|
||||
|
||||
- **响应丢失/网络重试:**同owner、同operation、同key和同一版本化请求,返回原资源;参数变化返回409。客户端发送前持久保存key与不可变body;离线恢复不自动启动新生成。
|
||||
- **外部抢占/夜间暂停:**同Job、同上游ID,新Execution;只重算被打断的当前步骤。
|
||||
- **用户明确重试失败步骤:**在同Run/Step创建新Job及新上游key,旧成功步骤继续复用。
|
||||
|
||||
不承诺计算exactly-once:抢占会丢弃当前推理进度,进程崩溃和HTTP超时也可能产生不明确结果。承诺的是逻辑提交幂等、产物按当前执行代次发布一次,不能确定的CPU/HTTP执行进入needs_attention,不偷偷再执行。
|
||||
|
||||
CPU计算完成先写原子结果manifest,含execution_id、输入哈希、输出相对路径/大小/哈希,再登记数据库。若结果可验证就仅恢复导入;没有可靠manifest且执行已发生,则等待明确重试。资产commit结果不明时保留文件并对账,不在异常处理里无条件删除。
|
||||
|
||||
### 3.3 修改与旧结果
|
||||
|
||||
修改已成功镜头、配音、字幕或画幅后创建新Run,可复用输入哈希和模型配置完全一致、归属正确且文件校验通过的素材;不修改旧Run快照。
|
||||
|
||||
合成input_hash覆盖:有序视频内容哈希、裁切范围、画幅/适配方式、音轨范围、字幕帧区间、模板版本。旧Run晚到结果只进入历史;只有 `Draft.current_run_id == completed_run_id` 时才更新当前成片。每个步骤也只接受selected_job及匹配fence_token的结果。
|
||||
|
||||
删除素材先软删除;已被运行引用的文件保留。新Run不能选择已删除素材,旧Run可用已固定引用完成。管理员也不在普通接口中绕过owner读取他人素材;管理角色和内容归属是两套权限。
|
||||
|
||||
### 3.4 状态的唯一含义
|
||||
|
||||
Run使用第5节的八种状态;Step使用waiting/ready/running/paused/blocked/succeeded/cancelled,当前Job失败使Step进入blocked。Job保留现有十种状态并增加pausing/paused/needs_attention;cleanup_pending是phase与资源状态,不另作“已停止”的终态。Execution使用allocated/running/stopping/exited/results_ready/unknown,另记结束原因。
|
||||
|
||||
调度查询改为明确的可领取状态集合,不能用“不是终态”来决定重执行。collecting只做导入;paused和needs_attention不会调用provider。window/resource hold不会改用户desired_state,只有手工暂停改变用户意图;恢复条件为desired_state=run且所有hold均已解除。
|
||||
|
||||
## 4. 调度、暂停和资源回收协议
|
||||
|
||||
### 4.1 网站、上游、监管各自负责什么
|
||||
|
||||
网站MySQL持久保存用户意图、工作流、输入快照和事件;既有上游Store/worker负责唯一GPU领取与进程执行;独立监管负责自己的进程身份核验、执行截止和释放确认。保留一个FastAPI业务协调器,显式定义三个资源池:new_gpu=1、cpu_media=1(FFmpeg/Kokoro)、qwen_http=1;后两者不创建自管GPU租约。Qwen未知请求阻塞新Qwen请求,不把无关联CPU合成一起堵住;不能将它笼统称为CPU推理。
|
||||
|
||||
资源按阶段取得,不只按task_type分类。视频转写为 `extract_audio(cpu_media) → transcribe(new_gpu)`,视频理解为 `sample_frames(cpu_media) → describe_frames(qwen_http)`;数学为qwen_http,独立配音/合成为cpu_media。各阶段完成持久checkpoint后释放自己的槽,再取得下一槽,不持有一个槽等另一个槽。GPU runner内部必要的编解码由GPU容器的CPU配额约束并随该Execution整体停止,不再嵌套领取cpu_media。
|
||||
|
||||
上游新增 `GET /capabilities` 返回 `protocol_version=2`、支持的scheduling/pause/execution_ack/result_manifest能力;网站不满足最低版本时禁止batch并给出可读错误。新Submission明确 `extra=forbid`,增加独立的:
|
||||
|
||||
`scheduling={execution_mode, principal_id, batch_id?, run_id?, step_key?, policy_version}`。
|
||||
|
||||
这些字段由网站验证/继承,并纳入v2幂等请求,不混入模型parameters。旧v1请求保留恢复路径。不得接受浏览器传入宿主PID、容器ID或任意截止时间。
|
||||
|
||||
### 4.2 窗口和队列
|
||||
|
||||
窗口为Asia/Shanghai的 `[21:00,次日08:00)`,以UTC存储绝对时间及window_id;执行计时使用monotonic。claim、spawn前和运行循环重新校验资格。已关闭window_id持久记录,时间回拨不得重新打开;检测到明显时钟偏移先暂停batch admission并告警。
|
||||
|
||||
interactive定义为一次受限单任务(图片1–4张或单个其它任务),或一次三分镜Run;多Run/清单批次只能由batch入口创建。服务端给子任务、重试和重做继承mode,客户端不能覆盖父关系或借普通retry降为interactive。
|
||||
|
||||
GPU原子领取时跳过不具执行资格的任务,白天batch队首不能堵住interactive。夜间建议每完成4个interactive GPU作业后,若有合格batch则给1个batch作业;用户之间轮转,批次内部FIFO。该策略只在领取时生效,不因新交互任务打断自己的当前作业;外部占卡规则始终优先。
|
||||
|
||||
无GPU时保持queued,不生成真实运行attempt、不消耗执行超时。返回blocked_reason/blocked_since/next_eligible_at,不虚构预计完成时间。
|
||||
|
||||
### 4.3 控制意图与状态
|
||||
|
||||
持久 `desired_state=run|pause|cancel` 与 `hold_reasons`(window/manual/resource/maintenance)分开保存。HTTP只提交控制意图,不能提前把正在运行的进程改成paused。恢复窗口只解除window hold,不解除manual或maintenance hold。
|
||||
|
||||
| 竞争或控制 | 固定规则 |
|
||||
| --- | --- |
|
||||
| 已有持久终态 | 不逆转;完成后取消返回原终态并提示未取消 |
|
||||
| 取消与暂停同时发生 | cancel优先;清理结束后才能cancelled |
|
||||
| 取消先提交、尚未领取 | 不派发新的步骤 |
|
||||
| 已领取后取消 | 可有已在途执行,必须发停止并等待ACK,不再领取下一步 |
|
||||
| 暂停先提交、完成尚未登记 | 当前Execution结果按暂停裁决,不发布过期结果;清理后排队 |
|
||||
| 完成先提交、随后暂停 | 保留成功素材,暂停后续步骤 |
|
||||
| 旧回调迟到 | execution_id、fence_token或控制版本不匹配即拒绝,不能停止/覆盖新执行 |
|
||||
|
||||
API新增内部控制命令 `PUT /jobs/{id}/control`,含唯一command_id、expected_execution_id、control_version及desired_state。命令幂等;不存在当前执行时只登记意图。worker清理后返回带相同执行代次的ACK。已有 `/cancel` 保持用户取消终态语义,不能拿它冒充夜间暂停。
|
||||
|
||||
### 4.4 08:00与故障
|
||||
|
||||
所有标为batch的计算步骤受窗口限制:自管GPU、Whisper、CPU编码、Kokoro,以及经验证可停止的远端HTTP推理。08:00后禁止新计算;运行中的步骤请求停止并释放,下一窗口恢复未完成步骤。状态同步、清理、文件归档可以白天继续,它们不得启动新的模型或编码。
|
||||
|
||||
初始配置:窗口检查0.5秒,独立监管检查1秒,最后30秒不启动新的batch执行,清理ACK等待15秒;这些是待实测的工程默认值。截止触发不等于显存已经释放;超15秒未确认则cleanup_pending/blocked并告警,不能宣称零延迟或继续领取新任务。
|
||||
|
||||
worker在启动计算前登记带执行代次的本地lease/deadline,并取得监管确认。API或worker卡死后,监管仍能终止已登记的自有执行。监管只接受固定允许容器/cgroup/UID,并核验PID、starttime、boot_id、execution/fence;不从可写metadata接受任意宿主PID。CPU/TTS的batch子进程同样需要单执行标识与停止确认。
|
||||
|
||||
停止确认需进程清理ACK和清理动作之后的新监控快照证明自己的GPU PID已消失;进程组为空、TTL过期或显存数值下降都不能单独当释放证明。若外部用户正在用卡,不要求显存回到原基线,只确认自有资源消失。异常时保留全局槽并blocked,不进行双运行。
|
||||
|
||||
Kokoro私有服务增加execution v2能力:`POST /internal/executions/{id}/speech`登记后返回202,`GET /internal/executions/{id}`查询,`PUT .../control`停止并返回执行代次ACK,`GET .../audio`仅在完成后取WAV;全部沿用私有Bearer认证。登记、deadline、结果manifest在本地持久化,确认监管接管前不启动模型子进程;同ID不同请求409。现有同步 `/v1/audio/speech` 保持交互兼容,网站未检测到v2能力时不把同步断连当成batch停止。FFmpeg启动前也使用同样的登记/许可门槛。
|
||||
|
||||
上述承诺覆盖网站/API登记的任务;它不能替代整个服务器所有用户的统一准入系统。现有Qwen请求若没有request_id、abort与结束ACK,则batch能力保持关闭;交互调用继续复用且单独限额。
|
||||
|
||||
## 5. 工作流、时间轴与前后端契约
|
||||
|
||||
### 5.1 一期固定工作流
|
||||
|
||||
三镜头提示词和参考图在提交前确认。若需要Qwen辅助写脚本,先作为交互步骤完成并写入草稿;不在未验证可取消的batch中隐式调用Qwen。
|
||||
|
||||
Run状态:queued/running/paused/blocked/cancelling/succeeded/cancelled/failed。blocked/step_failed表示需要重试某一步,不能自动合成;failed用于不可恢复错误,用户结束使用cancel。succeeded/cancelled/failed均为终态。
|
||||
|
||||
三个shot步骤依次完成,每个输出经验证达到目标画幅、至少120帧。compose只能读取三个当前selected_job的已发布视频。失败镜头只重做该Step;合成失败只重做compose。needs_attention只有在确认无残留执行、safe_to_retry=true后才允许用户显式重试;仍未知时返回cleanup_pending,不以点击按钮代替停止证明。草稿变更不影响运行中的Run。
|
||||
|
||||
### 5.2 画幅和音视频边界
|
||||
|
||||
- 横版生成1280×704,超分内容保持1920×1056,最终画布1920×1080;竖版生成704×1280,超分内容1056×1920,最终画布1080×1920,24fps。工作流增强步骤保留原内容比例,避免先烧入黑边再无法实现cover;明确generation_size、enhancement_target、canvas和fit=contain|cover,界面展示补边或裁切,不默默拉伸。
|
||||
- 每镜头规范化为120帧,总360帧。使用视频流实际解码帧数、avg_frame_rate、时间基准验证,不能只看容器duration。短源失败,不用黑帧、重复末帧或长音轨凑足时间。
|
||||
- 最终视频轨15.000秒,音频AAC编码尾差使容器时长允许±0.10秒;帧率、分辨率和解码检查同时通过。15秒模板在360帧内叠加或占用原镜头,延长版单独计时。
|
||||
- 音轨字段为asset_id、source_start_ms、source_end_ms、offset_frame、short_policy=silence。毫秒/偏移均为非负整数,源区间有序且不越过源音频;还须满足 `(source_end_ms-source_start_ms)*24 ≤ (360-offset_frame)*1000`,否则invalid_timeline。18秒旁白默认拒绝无提示截断,显式选3–18秒且offset=0后通过;10秒音轨offset=120通过、121拒绝,短音轨剩余部分补静音。
|
||||
- 字幕采用全片帧区间 `[start_frame,end_frame)`,满足 `0≤start<end≤360`;统一模板字体与样式,禁止任意FFmpeg/ASS指令。首期允许人工编辑,不把Whisper块边界当逐词对齐。
|
||||
|
||||
### 5.3 API与错误
|
||||
|
||||
浏览器仍使用Cookie+CSRF和同源SSE,不引入WebSocket。所有变更语义明确的POST(包括运行、重试和重做)要求Idempotency-Key。
|
||||
|
||||
| 接口 | 关键约定 |
|
||||
| --- | --- |
|
||||
| `POST/GET/PATCH /api/workflows` | 管理Draft;PATCH带If-Match版本,冲突409,返回当前version且保留本地未保存内容 |
|
||||
| `POST /api/workflows/{id}/runs` | 指定draft_revision、预期Draft版本和mode;原子创建快照、步骤及提交记录,返回更新后的draft以及run/steps/jobs/cursor |
|
||||
| `GET /api/workflow-runs/{id}` | 同一事务的一致父子快照和cursor |
|
||||
| `POST /api/workflow-runs/{id}/cancel` | 持久取消意图;保持cancelling直到子执行停止 |
|
||||
| `POST /api/workflow-runs/{id}/pause`、`/resume` | owner控制手工hold;resume不解除window/resource/maintenance hold,均需要幂等键 |
|
||||
| `POST /api/workflow-runs/{id}/steps/{key}/retry` | expected_run_version和target_job_id;仅当前失败或已确认safe_to_retry的尝试可重试,已取消父Run不可恢复,模式继承 |
|
||||
| `POST /api/batches` | 最多100个Run/单任务规范,服务端固定batch;整批先校验再创建,子项用batch_id+item_index派生key |
|
||||
| `GET /api/batches`、`GET /api/batches/{id}` | owner分页列表、成员/计数/当前执行项及一致snapshot+cursor |
|
||||
| `POST /api/batches/{id}/control` | desired_state=run/pause/cancel,幂等键+expected_version;继承到成员,不清除成员独立的manual hold |
|
||||
| `GET /api/submissions/{key}?operation=...` | 仅owner可查询;404不证明在途POST没被接受,恢复仍复用原key |
|
||||
|
||||
成功镜头重做或参数变化通过修改Draft并新建Run处理,避免同时存在“修改旧Run”和“创建新Run”两套语义。普通Job retry拒绝直接操作workflow子Job,要求使用Step接口。
|
||||
|
||||
错误码补齐:draft_version_conflict、idempotency_conflict、step_not_retryable、dependency_changed、invalid_timeline、upstream_protocol_incompatible、batch_capability_unavailable、quota_exceeded、storage_insufficient、maintenance、cleanup_pending。字段错误返回field定位;409为版本/语义冲突,422为输入,429为额度,503为暂不可服务;返回可恢复条件,不默认提示重新生成。
|
||||
|
||||
Batch默认遇独立项失败继续其它项;失败Run保持blocked以便只重试其失败Step。其它可运行项全部结束后若仍有需要处理的成员,Batch为blocked;用户重试后继续。用户放弃某项使用该项cancel,全部成员已终态且有失败/取消时Batch为completed_with_errors;全成功才succeeded。批次取消不撤销已成功产物。Batch状态另有queued/running/paused/cancelling/cancelled。
|
||||
|
||||
SSE新增 `workflow.updated`、`draft.updated`、`batch.updated`,完整DTO有各自version;与其状态在同一DB事务写入现有owner流。忽略旧版本/旧selected_job事件,重连后HTTP刷新当前Run/Batch;cursor过旧时reset。显示镜头完成数和当前阶段,全部镜头完成仍需合成,不能提前显示整流程100%。
|
||||
|
||||
草稿先保存后提交;离线允许编辑,不悄悄排队自动生成。两标签页冲突不静默覆盖,退出用户清除本地敏感缓存,服务器草稿按owner读取。
|
||||
|
||||
## 6. 正式库升级、恢复和容量
|
||||
|
||||
### 6.1 已有六表如何纳入Alembic
|
||||
|
||||
建立001基线,精确对应当前六表及索引/唯一约束/字符集和DATETIME(6)。已有库先生成schema指纹并核对,完全匹配才stamp 001;不匹配停止并输出差异,不盲目stamp head。空库直接upgrade。之后002起只增表/可空字段/索引,分批回填并校验,再收紧约束;只管理本应用表,不能自动删除其它表。
|
||||
|
||||
生产启动只校验schema支持范围,不自动create_all/upgrade;不满足则不启动协调器。Alembic stamp只记录版本,不替代迁移。[Alembic命令说明](https://alembic.sqlalchemy.org/en/latest/api/commands.html#alembic.command.stamp)
|
||||
|
||||
MySQL DDL可能隐式提交,升级失败不能当成普通事务rollback即可恢复。优先使用兼容性增量变更和修复迁移;只回滚镜像须确认旧版能读当前schema且新任务功能关闭。不能安全读时保持维护状态,使用同一恢复点的库+文件备份在隔离环境恢复验证后切换,不自动downgrade删新数据。[MySQL DDL提交说明](https://dev.mysql.com/doc/refman/8.0/en/implicit-commit.html)
|
||||
|
||||
### 6.2 联合备份和上游队列
|
||||
|
||||
维护模式先禁止新写入与派发,结束/暂停自己的活动计算并确认ACK,关闭SSE、停止业务协调器、上游worker及回收器后取快照;只操作本项目服务。备份MySQL应用表、assets/jobs/state、上游SQLite(使用其backup/checkpoint方式)与完成manifest/必要输出,另加受保护配置和版本/校验清单。
|
||||
|
||||
恢复时不能让恢复出的旧上游ID指向仍独立前进的当前队列:先校验同一checkpoint、对账IDs、execution代次和文件,启动监管后再开放调度。历史不明确的CPU执行转needs_attention,不自动重算。每日库备份可先做逻辑备份,但上线前至少完成一次联合恢复演练;保留7个每日点和4个每周点,容量预留计入专用目录。
|
||||
|
||||
### 6.3 建议初始配额(配置项,实施时校准)
|
||||
|
||||
交互每用户最多8个未结束GPU子Job、每分钟6次创建命令,最多1个活动交互Run。单batch最多100项,每批最多1个成员(Run或独立Job)进入执行,其余可排队;每用户未结束叶任务最多500、全局最多2000。三个资源池各自全局1槽,各池每用户不超过1个活跃执行。创建前事务内检查配额,复用同幂等提交不二次扣额。
|
||||
|
||||
单文件仍512MiB;每用户保留素材100GiB,业务数据总预算2TiB。专用卷剩余低于max(50GiB,5%卷容量)或工作区预算不足时拒绝新计算/上传;为已接受任务预留预估输出与临时空间,实际超限终止自己的作业并明确失败。数字为起始配置,不是已验证产能,不允许耗尽整个服务器共享盘。
|
||||
|
||||
待定提交记录/非终态任务不自动过期删除;排队不计执行超时。已确认的临时同步采用1/2/4…30秒退避。执行状态不明的网络错误不据此新建任务;明确可重试的本地失败最多自动重试2次,OOM/参数错误不盲目重跑。抢占与窗口暂停单独计数。
|
||||
|
||||
SSE事件保留30天,最小可重放cursor单独记录;早于它的客户端收到reset,而不是悄悄漏事件。成功作业的可再生成中间文件保留7天,失败/中断尝试保留14天;资产原件、活动执行、当前Run引用和提交结果不明的文件不按年龄直接删除。回收器先对账、引用检查、标记与宽限,再物理删除;删除与新引用必须互斥,回收过程中不会重新引用待删文件。已清理结果的幂等提交保留tombstone,旧key返回410资源已清理,不能重新当新任务执行。
|
||||
|
||||
## 7. 管理、外部调用与发布
|
||||
|
||||
默认admin初始密码保持用户指定;补 `must_change_password`、本人改密、用户列表/停用、撤销会话。公开部署要求改密后才开放计算和Token创建;私有验收模式可保留初始化用法,不能靠客户端参数关闭公网限制。停用用户撤销认证并给未完成任务加admin_suspend hold,停止其计算;重新启用不自动重跑,需明确恢复。保留成功素材,不允许停用最后一个有效管理员。初始化不得覆盖已有账号;MySQL暂用root按用户原决定,后续另建专用账号时限制本库与实际来源,不改其它业务账号。
|
||||
|
||||
互联网发布前,先在私有入口完成默认管理员改密,再开放公网,不能把已知初始密码暴露后等待首次改密。公网preflight检查该状态、专用数据库权限、HTTPS/Secure Cookie、登录节流、额度、备份与恢复;未满足保持私有验收。IP限流只采信配置过的反代链,不能信任任意X-Forwarded-For。网站状态区分配置存在、模型在线、调度可用和等待资源。活性检查与readiness分离,后者包含schema、协调器心跳和协议兼容;无空闲GPU不是应用不健康。
|
||||
|
||||
外部机器调用增加按owner的可撤销API令牌,仅保存哈希、一次展示明文,配置到期时间和jobs/asset最小scope;默认只能batch,interactive另行授权并共用额度。令牌明文不进入URL、事件payload或前端构建产物;机器订阅SSE须有events:read并走Authorization头,撤销/到期结束流。浏览器继续Cookie+CSRF和原生EventSource。令牌不能调用管理员建用户/改权限接口。原登录会话方式保留为兼容调用路径。
|
||||
|
||||
容器镜像和模型revision/配置固定入部署清单;前后端与上游协议兼容范围明确。维护窗口采用“备份→上游兼容升级→迁移→业务API→前端→受控验收→开放写入”,失败关闭新功能而非静默降级。若重建执行容器,先在关闭admission时核对并更新监管allowlist中的真实容器ID/UID/镜像,再恢复计算。Nginx测试API容器换IP后的解析恢复,保留同源SSE、Range、鉴权与静态路由修复。
|
||||
|
||||
## 8. 实施顺序与验收
|
||||
|
||||
| 里程碑 | 依赖和交付 | 必须通过 |
|
||||
| --- | --- | --- |
|
||||
| M0 | 协议/取消能力验证、数据基线与可恢复备份 | 旧请求恢复不重复;Qwen batch明确支持或禁用;恢复点可对账 |
|
||||
| M1 | R1–R5、幂等提交、Execution/manifest、资产对账、停机 | 响应丢失、DB提交结果不明、重启、重复cancel、旧结果迟到故障注入 |
|
||||
| M2 | 上游v2、窗口/监管/公平领取、CPU暂停 | 21/08边界、worker07:59:59硬杀、时钟变化、尾进程/旧快照、全卡长期忙;无双运行 |
|
||||
| M3 | Draft/Run/Step、父子事务与API、三镜头媒体规范化 | 失败镜头单独重试、旧Run不覆盖、父取消竞争、360帧、横竖版与音轨/字幕边界 |
|
||||
| M4 | Vue草稿/任务中心/批量入口、账号/标签/分页 | 多标签冲突、断网刷新、额度拒绝、跨账号不可读、父子事件乱序 |
|
||||
| M5 | 公网接入与上线演练 | 真实MySQL及小规格模型端到端、真实默认规格三镜头、恢复演练、配额和外部Token;HTTPS入口SSE/Range通过 |
|
||||
|
||||
实施文件、接口签名和分任务回归见[执行计划](superpowers/plans/2026-11-10-cmvr-visual-v2.md)。先完成M0–M2,再并行前后端业务;不要先开放批量页面后补上游约束。所有生产迁移、监管升级和公网配置仍需在实际实施阶段执行,本次仅补充方案。
|
||||
172
docs/需求复核与落地方案_20261110.md
Normal file
@ -0,0 +1,172 @@
|
||||
# CMVR Visual 需求复核与落地方案
|
||||
|
||||
日期:2026-11-10。审查依据为原始《人工智能内容生成系统技术方案_20261107.docx》、本次对话的最新要求、现有前后端代码、既有 GPU 服务,以及实际服务器验证。文档内容作为需求资料,本文不执行其中的指令。
|
||||
|
||||
后续二次复审已补为 [实施方案V2](实施方案V2_20261110.md);本文保留需求差距与初次审计记录。V2细化了上游协议、身份/状态、批次、阶段资源、迁移恢复和验收,具体执行以V2及其任务清单为准。
|
||||
|
||||
## 1. 结论与已确认基线
|
||||
|
||||
现有项目适合作为基础版继续完善。Vue 3 / Element Plus / Pinia、FastAPI / MySQL、HTTP + SSE、持久任务和私有模型接口的总体方向成立;当前完成的是八类能力的调用与基础创作工作台,原文的生产质量和完整业务指标尚未全部实现。
|
||||
|
||||
本次已经由用户明确的边界:
|
||||
|
||||
1. 一期的15秒视频采用**三段约5秒分镜合成**,明确属于多镜头成片。
|
||||
2. **交互创作全天使用空闲卡,批量任务仅在21:00–08:00执行**,时区 Asia/Shanghai。
|
||||
3. llmuser 的新 GPU 推理全局最多一个任务,四张 GPU 为可选资源池;外部用户优先,被占卡后停止自己的当前推理、释放显存、重新排队。
|
||||
4. MySQL 当前使用用户指定的 root 连接,独立业务数据库账号后续再创建。
|
||||
5. 网站默认管理员为 admin,初始密码按本次指定配置为六位。普通新建用户的现行12位最低密码规则保留。
|
||||
|
||||
除数据库与初始管理员外,本文列出的调整均为实施方案,尚未修改产品行为。
|
||||
|
||||
## 2. 本轮已完成的数据库和账号补齐
|
||||
|
||||
- 连接 `192.168.28.10:3306/cmvr-visual`,实际 MySQL 版本8.0.36;连接账号为 root。
|
||||
- 接入前确认目标库为空;初始化本项目的六张 `visual_*` 表,没有操作其他数据库。
|
||||
- 在 `visual_users` 创建默认管理员,密码保存为加盐 scrypt 哈希。实际 HTTP 登录与 Chrome 页面登录通过,角色为 admin。
|
||||
- 初始管理员允许用户指定的六位密码;普通用户创建仍要求12–256字符。启动时仅创建不存在的管理员,不因重启或修改环境变量重置已有密码。
|
||||
- 已验证正式库中的中文与四字节 Unicode 任务读写、预约取消、SSE 事件持久化;该验收任务未执行模型。
|
||||
- 原独立验收 MySQL 和样例数据保留,没有自动迁入正式库。旧配置保存为工作区私有备份。
|
||||
- 数据库凭据仅存私有环境配置;本机当前配置为 `.env.server`,服务器为项目 `.env`,均不提交 Git。
|
||||
- 后端本轮完整测试 **52项通过、20个subtests通过**;新增初始账号哈希与重启不重置回归先失败后通过。
|
||||
|
||||
证据:[正式库验证](../qa/mysql-integration-20261110.json)、[实际页面](../qa/mysql-admin-login.png)。网站仍只发布服务器回环18193,通过本机 SSH 隧道8000访问;连接正式数据库不等于已经开放互联网。
|
||||
|
||||
初始弱密码按用户要求保留。本期上线准备应补本人改密入口,公网发布前将它作为初始化密码完成更换,并将常驻 root 数据库连接换为专用账号;本轮没有修改 MySQL root 密码或创建额外数据库账号。
|
||||
|
||||
## 3. 原文要求与当前差距
|
||||
|
||||
| 能力 | 当前实际实现 | 尚未满足的原文要求 | 落地处理 |
|
||||
| --- | --- | --- | --- |
|
||||
| 图像 | Qwen-Image、尺寸、批量1–4张、提示词和种子 | 风格LoRA、系列一致性校验、13 GPU·秒与70%可用率验收 | 一期保留基础生图;建立业务提示词评分集,风格方案在样例评测后定 |
|
||||
| 视频 | 文生/首帧图生约5秒,Real-ESRGAN可选增强 | 单段15秒、自动质量筛选、TensorRT+FP8、8路并发 | 已确认一期做三分镜15秒;其余作为独立性能/质量专项,移除8路承诺 |
|
||||
| 数学 | 现有Qwen返回可读解答 | 符号计算、单位校验、作图、题型集和步骤/答案正确率 | 继续复用Qwen;二期加入受限计算工具和教学评测集 |
|
||||
| 缺陷样本 | SDXL+Canny结构约束,生成图和边缘控制图 | 缺陷位置/形态控制、真实缺陷掩膜、下游召回提升8个百分点 | 先标明条件样本;真实工业训练数据另建标注与检测A/B流程 |
|
||||
| 素材结构化 | 均匀抽帧最多12帧、画面理解、OCR、Whisper转写 | 每5秒抽帧、镜头切分、人物/场景/情绪/景别标签、标签检索闭环及质量评测 | 补时间/场景抽帧、标签应用与编辑、检索索引,单独评测镜头和标签 |
|
||||
| 成片合成 | FFmpeg裁剪、直切、音轨、人工字幕 | 脚本关联、片头片尾、转场、热度模型与65%准确率 | 一期围绕三分镜成片补工作流和模板;热度模型等待历史业务数据 |
|
||||
| 声音 | Whisper转写、Kokoro中文配音 | 精确字幕对齐、音乐/音效等扩展未实现 | 一期明确中文旁白与ASR,补字幕编辑;音乐不纳入本期承诺 |
|
||||
| 生产作业 | 单任务预约、GPU空闲选择、外部抢占重排 | 每日夜间窗口、批次/分镜持久编排、暂停恢复、容量与质量报表 | 按已确认的交互/批量两种模式补调度 |
|
||||
|
||||
精确视频型号应统一为 `Wan2.2-TI2V-5B`。当前约5秒限制是已部署服务的边界,需要通过新增编排完成15秒交付,不将其描述为模型的理论时长上限。[Wan官方仓库](https://github.com/Wan-Video/Wan2.2)
|
||||
|
||||
现有 `Qwen/Qwen3.8-27B-FP8` 是原生视觉语言模型,可继续承担文本推演和图像/视频帧理解。应记录实际运行权重版本与配置,并使用业务题目、OCR和标签集验证替代效果;单次数学和图片调用不能证明92%/95%等指标。[官方模型卡](https://huggingface.co/Qwen/Qwen3.8-27B-FP8)
|
||||
|
||||
模型服务内部继续按能力使用 vLLM-Omni、vLLM core、Diffusers 和现有 Qwen 服务,网站统一业务 API。当前 SDXL+Canny 使用 Diffusers;不能将“统一接口”写成所有模型都由 vLLM core 执行。[Omni支持表](https://docs.vllm.ai/projects/vllm-omni/en/v0.32.0/models/supported_models/)、[Diffusers SDXL ControlNet](https://huggingface.co/docs/diffusers/v0.40.0/api/pipelines/controlnet_sdxl)
|
||||
|
||||
Real-ESRGAN 当前确实执行神经网络超分,再缩放/补边到目标画幅;默认1280×704内容适配到1920×1056并上下补边为1920×1080。需要把成品分辨率、原片分辨率和超分方式分别记录,不能宣称为原生1080p生成。
|
||||
|
||||
## 4. 代码审查发现与优先级
|
||||
|
||||
P1为正式业务或公网前优先解决,P2为本期工作流/运维完善,P3为体验优化。故障注入均使用隔离内存数据库,没有对线上任务注入故障。
|
||||
|
||||
| 编号 | 等级 | 问题、触发与证据 | 最小改动与验收 |
|
||||
| --- | --- | --- | --- |
|
||||
| R1 | P1 | 前端每次调用submit换幂等键。POST落库但响应丢失后再次点击会新建昂贵任务。[api.ts:44](../frontend/src/api.ts#L44);后端已支持复用同键 | 持久保存一次提交的key和不可变payload;结果不明时复用。断网、刷新、恢复后仍是同批任务;明确再次生成才换key |
|
||||
| R2 | P1 | CPU执行失败且失败状态写库也失败时,done task异常被忽略,仍running的记录下一轮可再次执行。隔离故障注入得到执行次数2。[coordinator.py:157](../backend/app/coordinator.py#L157)、[195](../backend/app/coordinator.py#L195) | 增加持久attempt与运行时丢失任务守卫;不明确的执行转待确认/中断,不能自动当新执行。故障注入确认未经显式重试不重复执行 |
|
||||
| R3 | P1 | 资产commit结果不明时外层异常无条件删目录,存在“库中有行、文件已删”的窗口;这是源码确认的故障窗口,尚未完整注入复现。[assets.py:106](../backend/app/assets.py#L106)、[141](../backend/app/assets.py#L141) | commit开始后结果不明保留暂存文件;数据库与文件对账后清理。复用pending记录前检查文件;恢复只重导入,不重生成 |
|
||||
| R4 | P1 | SSE长连接使Uvicorn更新时等待,Docker45秒后强停;本轮切库实际观察到了这段等待。[Dockerfile](../backend/Dockerfile)、[events.py](../backend/app/events.py)、[compose](../compose.yaml) | Uvicorn graceful timeout约20秒,小于Docker45秒;配合drain与协调器清理。保持SSE连接更新,验证未进入强杀且恢复任务不重复 |
|
||||
| R5 | P2 | 协调器每轮再次cancel正在清理的CPU task,可打断一般provider异步清理。[coordinator.py:184](../backend/app/coordinator.py#L184) | 取消信号只发一次,等待清理确认再终态。现有media与TTS已有shield,不能据此宣称当前FFmpeg必然遗留进程 |
|
||||
| R6 | P2 | 成片草稿存组件ref,去声音页配音再返回就丢片段、字幕、裁切。[ComposeView.vue:18](../frontend/src/views/ComposeView.vue#L18) | Pinia管理并按用户持久保存草稿;跨页和刷新不丢,显式新建才清空 |
|
||||
| R7 | P2 | 素材列表先读取全库后内存分页;标签也在Python过滤,数据库全局单元锁会放大阻塞。[assets.py:164](../backend/app/assets.py#L164)、[database.py:25](../backend/app/database.py#L25) | SQL计数/分页;标签关联表或MySQL索引;owner/状态/时间复合索引。较大素材库下查询不拖住SSE与提交 |
|
||||
| R8 | P2 | 当前只有创建用户API,没有本人改密、用户停用/会话撤销及管理页;登录无节流且密码计算位于数据库全局锁内。[auth.py](../backend/app/auth.py)、[router.ts](../frontend/src/router.ts) | 补改密、建用户/列表/停用、会话撤销;密码计算移出DB锁,账号/IP登录限流;沿用admin/user与owner权限 |
|
||||
| R9 | P2 | UI可输入不满足步长/Canny关系的值、超2000字配音、超24片段,依赖提交后报错。[WorkbenchView.vue](../frontend/src/views/WorkbenchView.vue)、[ToolsView.vue](../frontend/src/views/ToolsView.vue) | 共用参数schema/校验函数、字数与时长提示;错误定位到字段,后端继续保留最终校验 |
|
||||
| R10 | P2 | 理解标签未应用到原素材;工具历史从混合最近48条筛选,旧记录易被挤出;“已配置”可能显示为“就绪” | 增加标签确认合并、按任务类型分页、区分配置/在线/可执行;加入故障断连与旧数据测试 |
|
||||
| R11 | P2 | API整个workspace可写;没有schema升级、文件回收和容量控制闭环。[compose.yaml:22](../compose.yaml#L22)、[database.py:31](../backend/app/database.py#L31) | 缩窄挂载、模型密钥/状态目录只读;Alembic迁移;用户容量/任务上限、对账回收、联合备份恢复演练 |
|
||||
| R12 | P3 | 收藏无筛选入口,上传与生成作品混合查找 | 复用素材库增加favorite/origin服务端筛选,无须另建复杂项目管理系统 |
|
||||
|
||||
## 5. 架构取舍
|
||||
|
||||
### 方案A:保留现有单实例协调器,推荐本期采用
|
||||
|
||||
继续使用一个FastAPI进程、一套MySQL持久任务/事件表和既有独立GPU队列。先补上述可靠性与业务工作流。改动范围较小,适合当前全局仅一个新GPU推理任务的吞吐,不新增Redis/Celery依赖。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
U[Vue3 创作与管理页面] -->|HTTP 操作/文件| A[FastAPI 单实例业务层]
|
||||
A -->|SSE 事件| U
|
||||
A --> D[(MySQL 业务/任务/事件)]
|
||||
A --> W[持久分镜与批量协调器]
|
||||
W --> G[既有GPU串行队列]
|
||||
G --> P[四卡空闲资源池 / 单任务租约]
|
||||
W --> Q[现有Qwen文本视觉服务]
|
||||
W --> C[CPU FFmpeg / Kokoro]
|
||||
```
|
||||
|
||||
HTTP适合上传、任务命令和结果下载,SSE负责状态、让卡与结果事件,保留Last-Event-ID重放和HTTP快照恢复。本期没有持续双向音视频交互需求,WebSocket不增加必要能力。
|
||||
|
||||
### 方案B:API与业务Worker分离,作为后续扩展
|
||||
|
||||
当需要频繁无影响发布、多个API实例或多节点执行时再拆分。当前数据库单元锁仅在进程内;直接增加API workers或拆出协调器,会破坏现有事件提交顺序保证。MySQL自增ID分配顺序不等于事务提交顺序,SSE游标可能越过晚提交事件。拆分前必须落地事务outbox与单发布器,或数据库级序列锁,并明确全局唯一调度租约。本期不直接启用多worker。
|
||||
|
||||
## 6. 一期的具体实现
|
||||
|
||||
### 6.1 可靠性与账户
|
||||
|
||||
先完成R1–R5的故障恢复和取消修复;新增的attempt/checkpoint字段使用Alembic迁移,不用create_all代替升级。保留正式库现有用户、素材和任务;上线前做库与文件联合备份,并验证回退。
|
||||
|
||||
补本人改密、管理员创建/查看/停用普通用户、撤销会话,普通用户继续只访问自己的素材和任务。默认管理员用于初始化。后续创建仅授权本库的数据库业务账号,来源限制按实际Docker网络连接地址配置,不改其他业务root账号。
|
||||
|
||||
### 6.2 三分镜15秒工作流
|
||||
|
||||
新增持久workflow与step记录,现有Job通过workflow_id/step_key/attempt关联。工作流保存三段提示词、参考图、顺序、种子、画幅和模型配置快照,子任务保持各自幂等键。
|
||||
|
||||
1. 用户填写或审阅三个分镜,每段目标5秒,可以共用参考图。
|
||||
2. 顺序提交三个Wan子任务,由同一GPU队列串行执行。
|
||||
3. 三段完成后,CPU FFmpeg各裁取5秒;视频轨按24fps、总360帧输出15秒成片。
|
||||
4. 可选中文配音、人工/校正字幕与模板,输出成片及参数清单。15秒版片头片尾在已有360帧内叠加或占用已有镜头时长;额外插入的延长版另计时长和验收。配音时长超出画面时应提示调整文稿、语速或音轨裁切范围。
|
||||
5. 失败镜头可单独重新生成;成功镜头保留。网络重试仍复用原attempt键,明确重做才创建新attempt。
|
||||
6. 取消父工作流后不再启动新步骤;运行中的子任务清理后才确认取消,已有成功素材保留。
|
||||
|
||||
验收应检查视频轨360帧、24fps、15秒;封装音频允许合理编码尾部误差,并检验无黑帧、花屏、字幕缺字和音轨错位。三个镜头之间的身份/风格一致性需人工评分,不用拼接成功替代质量验收。
|
||||
|
||||
### 6.3 交互与夜间批量
|
||||
|
||||
在业务任务和上游GPU任务元数据中新增 `execution_mode=interactive|batch`,与模型推理parameters分开;当前模型参数白名单保持有效。
|
||||
|
||||
| 情形 | 规则 |
|
||||
| --- | --- |
|
||||
| 交互任务 | 全天可进入空闲卡队列 |
|
||||
| 批量任务 | 仅Asia/Shanghai 21:00–次日08:00具备执行资格,白天明确显示等待窗口 |
|
||||
| 同用户有多个等待任务 | 交互优先选取,批量之间按批次公平和创建顺序;不因新交互请求无条件打断已经执行的自身任务 |
|
||||
| 其他用户开始占卡 | 停止自己的当前GPU推理、等待显存回收后重排,同一上游任务ID继续跟踪 |
|
||||
| 到08:00仍有批量执行 | 暂停当前批量步骤并清理/释放资源,保留已完成步骤,下一窗口重新执行未完成步骤;白天不能以“恢复中”为由继续批量生成 |
|
||||
| 夜间中断/抢占 | 当前模型推理进度可能丢失;已完成镜头不重跑。这里的恢复是工作流步骤级,不承诺保存扩散latent或模型计算断点 |
|
||||
|
||||
不能简单用现有 `/cancel` 模拟夜间暂停:cancel是终态,同幂等键会返回已取消任务。应在既有GPU worker补可重排的窗口资格与暂停原因,并让被时间窗口挡住的批量任务不阻塞交互任务;网页显示等待时间与原因。
|
||||
|
||||
“立即让卡”实际包含检测、停止、CUDA回收延迟。现有方案为软件机会调度;要达到所有用户绝对无争用,需要全体任务统一准入,超出本应用单方面可保证的范围。本期记录并测量让卡延迟,不承诺零毫秒抢占。
|
||||
|
||||
Qwen文本/视觉通过已存在的HTTP服务共享,不是将其常驻GPU分配给llmuser;该服务的每请求优先级由自己的入口调度决定。若要求Qwen请求同样严格低优先级,应追加网关限额/队列设计,不能仅靠检测Linux GPU进程区分HTTP用户。
|
||||
|
||||
### 6.4 创作与素材闭环
|
||||
|
||||
将编排草稿、提示词、参考素材与字幕按用户持久保存,跨声音页、素材页和刷新后可恢复。素材理解结果提供“应用标签”操作,合并而非覆盖人工标签;人物、场景、情绪、景别采用可编辑词表。
|
||||
|
||||
历史记录按任务类型分页;素材支持名称、标签、来源、收藏筛选。第一阶段先做好这些确定性检索,再评估向量检索,避免引入尚无验收需求的额外数据库。
|
||||
|
||||
### 6.5 公网前的部署准备
|
||||
|
||||
配置HTTPS域名或受信穿透入口,Secure Cookie、同源代理、登录限流和用户资源配额。保留SSE不缓冲、文件鉴权与Range。API仅挂业务数据可写,模型密钥和原服务状态目录只读;原状态采用原子替换时须挂目录,避免单文件绑定读到旧inode。
|
||||
|
||||
增加任务积压/最老等待时间、协调器心跳、显存/让卡事件、磁盘余量与服务在线状态。建立任务/中间文件保留期和“先对账、后回收”策略;引用中的素材不随意删除,CPU工作目录与上游输出副本不能无限保留。
|
||||
|
||||
## 7. 原方案应重写的性能和验收口径
|
||||
|
||||
- 四张可选卡不等于同时四卡工作。本期全局一个新GPU任务时,11小时窗口的理论上限是11 GPU·小时;仍按80%有效时间假设,仅为8.8 GPU·小时,外部占用和抢占还会降低。不能沿用35.2 GPU·小时/夜、8路并发和月产12部承诺。
|
||||
- 并发数不能直接把单任务耗时除以8作为该任务延迟。分别报告单段延迟、完成吞吐与GPU占用,明确计量分母。
|
||||
- 旧记录为包含加载的墙钟:Qwen-Image1024²/50步约96.6秒;Wan121帧/50步含超分约291.9秒;SDXL768²/30步约22.6秒。它们规格不同、包含加载,不能直接与原文GPU·秒目标判定达标/不达标或推导15秒产能。
|
||||
- 以固定权重revision、GPU、分辨率、步数、帧数和增强配置测试,分别记录排队、冷启动加载、推理、超分、归档、让卡浪费、P50/P95和显存峰值。
|
||||
- 原文操作系统和依赖版本属于需要修订的部署基线;应记录现有稳定宿主/容器实际版本,不为了匹配旧文字直接重装或降级正在承载其他业务的服务器。若Ubuntu为强制合同项,则另做迁移与回退计划。
|
||||
|
||||
业务指标需要独立数据:图像可用率/风格评分、视频可用率/闪烁/失败率、数学按题型的步骤和答案评审、镜头边界与标签标注集、缺陷真实留出集上的检测A/B、历史业务数据上的热度分类。准确率、失败率和样本量应在测试前约定,不以官方通用榜单或小样例代替。
|
||||
|
||||
## 8. 分阶段交付和验收门槛
|
||||
|
||||
| 阶段 | 交付 | 放行条件 |
|
||||
| --- | --- | --- |
|
||||
| 0,已完成 | 正式MySQL、默认管理员、私有配置与回归 | 实际登录、哈希、正式库读写与SSE验证通过 |
|
||||
| 1,先做 | 幂等/attempt/资产提交/取消/停机修复,账号维护、数据库迁移与基础限额 | 网络结果不明不重复生成;失败状态写库异常不重复执行;不出现数据库有记录而文件被误删;更新能清理退出;权限/改密/限流通过 |
|
||||
| 2,一期核心 | 三分镜15秒、持久草稿、夜间批量窗口、标签和历史检索 | 360帧15秒视频;只重做失败分镜;21/08边界正确;批量暂停不堵交互;外部占卡后让行重排;跨页刷新不丢草稿 |
|
||||
| 3,质量专项 | 字幕对齐、风格LoRA、数学工具、缺陷标注、镜头切分、自动质检 | 各自业务数据集、指标口径和人工评审通过,才写入已交付能力 |
|
||||
| 后续数据项目 | 热度预测、音乐/音效、连续长镜头、业务Worker拆分 | 需求、训练数据、资源成本和迁移方案另行确认 |
|
||||
|
||||
建议从阶段1开始实施,在阶段2完成后形成可试用的一期交付。原文研究型指标逐项评估进入阶段3;现有可运行代码和已有模型继续复用,不重建整个项目。
|
||||
51
docs/验收报告.md
Normal file
@ -0,0 +1,51 @@
|
||||
# CMVR Visual 验收记录
|
||||
|
||||
后续更新(2026-11-10):现已接入用户指定的正式MySQL并创建默认管理员,见 [实际接入记录](../qa/mysql-integration-20261110.json)。后端新增初始账号回归后52项通过。下面保留的是**数据库切换之前的功能验收基线**,其中“账号待提供”“独立验收库”等均为当时状态;样例数据未迁入正式库。最新差距与后续计划见 [需求复核方案](需求复核与落地方案_20261110.md)。
|
||||
|
||||
验收日期:2026-11-10。代码位于 `E:\workspace\hybrid\cmvr-visual`;服务器源码位于受限工作区 `/workspace/projects/cmvr-visual`。
|
||||
|
||||
## 交付与访问
|
||||
|
||||
- Vue 3 + Element Plus + Pinia;Python FastAPI + SQLAlchemy async + MySQL;HTTP 提交与文件传输,SSE 实时事件。
|
||||
- 已启动 API、中文配音、Nginx 前端三个独立容器。仅 Nginx 发布宿主 `127.0.0.1:18193`,当前本机 SSH 隧道访问入口为 `http://127.0.0.1:8000`。隧道断开后按 [README](../README.md) 重建;网站容器继续运行。
|
||||
- 本机私有 `.env.preview` 中的 `ADMIN_USERNAME`、`ADMIN_PASSWORD` 为临时验收登录信息,不进入源码、镜像或报告。
|
||||
- **当前使用独立 MySQL 8.0.36 验收实例。正式 `192.168.28.10:3306/cmvr-visual` 的专用账号仍未提供,未连接、未修改正式库。**页面持续显示“验收环境 · MySQL”。互联网域名、HTTPS 或穿透入口尚未配置。
|
||||
|
||||
## 真实调用
|
||||
|
||||
以下八类任务均通过网站业务 API 创建,使用真实服务执行并归档到 MySQL 与素材库,无模拟生成。
|
||||
|
||||
| 能力 | 实际验证 |
|
||||
| --- | --- |
|
||||
| 图像生成 | Qwen-Image,512×512、10步;成品可下载、上传和预览 |
|
||||
| 首帧视频 | Wan2.2-TI2V-5B,512×288、25帧、4步,使用真实图片首帧 |
|
||||
| 条件样本 | SDXL+Canny ControlNet,512×512、6步,输出生成图与控制图 |
|
||||
| 中文配音 | 本地 CPU Kokoro-82M,两个普通话音色均通过 HTTP 生成有效 WAV;小贝样例8.45秒,云希样例3.4秒 |
|
||||
| 语音转写 | Whisper 将上述配音转为中文,与测试文本内容相符 |
|
||||
| 数学推演 | 现有 Qwen 文本服务得到 `17×23=391`;浏览器实际提交 `2+3` 得到 `5` |
|
||||
| 素材理解 | 现有 Qwen 视觉服务返回图片主体、场景、标签与 OCR 结构 |
|
||||
| 成片编排 | CPU FFmpeg 拼接两个真实视频片段,加入配音和中文字幕,输出640×360、24fps、约2.12秒成片 |
|
||||
|
||||
以上低分辨率、低步数任务验证功能连接,不代表默认生成质量、生产吞吐或耗时承诺。当前生成视频上限为121帧/24fps,约5秒;配音不是音乐生成;Canny 控制图不是缺陷真值掩膜;数学结果没有专业正确率或形式化证明保证。
|
||||
|
||||
## 自动化与浏览器
|
||||
|
||||
- Linux 后端:**51项通过,20个 subtests 通过,无跳过**;包含实际 FFmpeg 媒体处理、幂等恢复、取消与归档竞争、队列公平、归属权限和 SSE 重放。
|
||||
- TTS:**12项通过**;包含等待取消、重复取消、进程组清理、响应发送失败清理以及子进程不继承服务密钥。测试框架有1条 Starlette TestClient 依赖弃用提示,不影响本次断言。
|
||||
- 前端:**12项通过**;TypeScript 类型检查与生产构建通过。合计75项测试,subtests 另计。
|
||||
- 真实业务脚本:21项断言通过,八类任务成功;收到81条真实事件;验证上传、修改、收藏、标签、删除、预约取消、显式重试、CSRF、跨账号不可读与视频 Range。
|
||||
- 正式 Nginx 构建浏览器验收:1440×1000、390×844,共35条页面记录与34张截图;无页面脚本错误、HTTP错误、重试或横向溢出。
|
||||
- 桌面与手机图片可解码;视频/音频四次播放和定位均成功;捕获10次 Range 206。冷缓存任务直达链接会实际读取任务详情。
|
||||
- 实际 UI 数学任务的 SSE 连续经过 submitting → running → collecting → succeeded,版本1至5;流连接1次、断连0次。
|
||||
- Nginx 配置检查通过;首次 SSE 注释约0.094秒到达本机;首页与素材库路由不缓存,静态哈希文件保留长缓存;同源 CSP 生效。
|
||||
- 实际设置 `max_tokens=1` 时返回明确 `output_truncated`,不发布不完整答案为成功产物。
|
||||
|
||||
最终页面截图见 [桌面](../qa/browser-desktop-create-image.png)、[手机](../qa/browser-mobile-create-image.png)、[手机任务详情](../qa/browser-mobile-task-detail.png);真实成片字幕帧见 [字幕帧](../qa/composition-frame.png)。
|
||||
|
||||
原始记录:[服务器测试](../qa/server-tests.json)、[业务调用](../qa/e2e.json)、[浏览器](../qa/browser.json)、[代理](../qa/proxy-check.json)、[截断处理](../qa/truncation-check.json)、[部署与文件校验](../qa/deployment.json)。
|
||||
|
||||
## 资源与后续接入
|
||||
|
||||
新 API 与配音容器均无 GPU grant。GPU 推理继续使用原 `llmuser` worker、四卡空闲选择与外部用户优先守护;网站不重部署驱动、既有模型或其他用户服务。原 `llmuser-workspace` 容器 ID 保持不变,GPU 守护仍运行。CPU 配音仅挂载自己的模型只读目录、work、cache、tmp,不挂载推理服务密钥所在项目。
|
||||
|
||||
正式接入尚需数据库专用用户名和密码。收到后按 [正式配置说明](../README.md#正式-mysql-配置) 修改私有配置、初始化本应用 `visual_*` 表并重新连接验证;不会自动搬迁或覆盖数据。公网使用须提供 HTTPS 域名/反代或用户选择的受信穿透入口,设置 Secure Cookie 并保留 SSE 与鉴权文件代理行为。
|
||||
1
frontend/.env.example
Normal file
@ -0,0 +1 @@
|
||||
VITE_API_PROXY=http://127.0.0.1:8000
|
||||
2
frontend/index.html
Normal file
@ -0,0 +1,2 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN"><head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width, initial-scale=1.0"/><meta name="theme-color" content="#0e1116"/><meta name="description" content="CMVR Visual,本地多模态视觉创作工作台。"/><title>CMVR Visual · 视觉创作台</title></head><body><div id="app"></div><script type="module" src="/src/main.ts"></script></body></html>
|
||||
32
frontend/package.json
Normal file
@ -0,0 +1,32 @@
|
||||
{
|
||||
"name": "cmvr-visual-frontend",
|
||||
"private": true,
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite --host 127.0.0.1",
|
||||
"typecheck": "vue-tsc --noEmit",
|
||||
"build": "vue-tsc --noEmit && vite build",
|
||||
"test": "vitest run",
|
||||
"preview": "vite preview --host 127.0.0.1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@element-plus/icons-vue": "2.3.2",
|
||||
"@fontsource-variable/noto-sans-sc": "5.3.1",
|
||||
"element-plus": "2.14.8",
|
||||
"katex": "0.19.1",
|
||||
"pinia": "4.1.0",
|
||||
"vue": "3.5.45",
|
||||
"vue-router": "4.6.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/katex": "0.16.8",
|
||||
"@types/node": "24.10.1",
|
||||
"@vitejs/plugin-vue": "6.0.10",
|
||||
"typescript": "5.9.3",
|
||||
"vite": "8.3.7",
|
||||
"vitest": "5.1.0",
|
||||
"vue-tsc": "3.3.14"
|
||||
},
|
||||
"packageManager": "pnpm@11.25.0"
|
||||
}
|
||||
1228
frontend/pnpm-lock.yaml
generated
Normal file
18
frontend/pnpm-workspace.yaml
Normal file
@ -0,0 +1,18 @@
|
||||
minimumReleaseAgeExclude:
|
||||
- '@rolldown/binding-android-arm-eabi@1.2.18'
|
||||
- '@rolldown/binding-android-arm64@1.2.18'
|
||||
- '@rolldown/binding-darwin-arm64@1.2.18'
|
||||
- '@rolldown/binding-darwin-x64@1.2.18'
|
||||
- '@rolldown/binding-freebsd-x64@1.2.18'
|
||||
- '@rolldown/binding-linux-arm-gnueabihf@1.2.18'
|
||||
- '@rolldown/binding-linux-arm64-gnu@1.2.18'
|
||||
- '@rolldown/binding-linux-arm64-musl@1.2.18'
|
||||
- '@rolldown/binding-linux-ppc64-gnu@1.2.18'
|
||||
- '@rolldown/binding-linux-s390x-gnu@1.2.18'
|
||||
- '@rolldown/binding-linux-x64-gnu@1.2.18'
|
||||
- '@rolldown/binding-linux-x64-musl@1.2.18'
|
||||
- '@rolldown/binding-openharmony-arm64@1.2.18'
|
||||
- '@rolldown/binding-win32-arm64-msvc@1.2.18'
|
||||
- '@rolldown/binding-win32-x64-msvc@1.2.18'
|
||||
- rolldown@1.2.18
|
||||
- vite@8.3.7
|
||||
BIN
frontend/public/inspiration/priority-retry-image.png
Normal file
|
After Width: | Height: | Size: 197 KiB |
BIN
frontend/public/inspiration/qwen-image.png
Normal file
|
After Width: | Height: | Size: 700 KiB |
BIN
frontend/public/inspiration/sdxl-controlnet.png
Normal file
|
After Width: | Height: | Size: 748 KiB |
BIN
frontend/public/inspiration/wan-middle.png
Normal file
|
After Width: | Height: | Size: 1.5 MiB |
30
frontend/src/App.vue
Normal file
@ -0,0 +1,30 @@
|
||||
<script setup lang="ts">
|
||||
import { computed,onBeforeUnmount,onMounted,ref,watch } from 'vue'
|
||||
import { useRoute,useRouter } from 'vue-router'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { MagicStick,Headset,Document,DataAnalysis,Scissor,FolderOpened,Clock,Connection,SwitchButton,ArrowRight,RefreshRight,Warning } from '@element-plus/icons-vue'
|
||||
import { useAuthStore } from './stores/auth'
|
||||
import { useJobsStore } from './stores/jobs'
|
||||
import { useAssetsStore } from './stores/assets'
|
||||
import { useDraftsStore } from './stores/drafts'
|
||||
import { useCapabilitiesStore } from './stores/capabilities'
|
||||
import { errorMessage } from './api'
|
||||
import { phaseLabel,stateLabel } from './format'
|
||||
const route=useRoute(),router=useRouter(),auth=useAuthStore(),jobs=useJobsStore(),assets=useAssetsStore(),drafts=useDraftsStore(),caps=useCapabilitiesStore(),systemOpen=ref(false)
|
||||
const nav=[{path:'/create/image',label:'创作',icon:MagicStick},{path:'/audio',label:'声音',icon:Headset},{path:'/math',label:'推演',icon:Document},{path:'/analyze',label:'理解',icon:DataAnalysis},{path:'/compose',label:'成片',icon:Scissor},{path:'/assets',label:'素材',icon:FolderOpened},{path:'/tasks',label:'任务',icon:Clock}]
|
||||
const ongoing=computed(()=>jobs.active.find(job=>['running','collecting','cancelling'].includes(job.state))||jobs.active.find(job=>job.state==='queued'))
|
||||
const connectionLabel=computed(()=>jobs.connection==='live'?'实时同步':jobs.connection==='connecting'?'连接中':'正在恢复连接')
|
||||
let poll:ReturnType<typeof setInterval>|undefined
|
||||
function clearSession(){jobs.reset();assets.clear();drafts.clear();caps.items=[];clearInterval(poll)}
|
||||
function expired(){auth.clear();clearSession();if(route.path!=='/login')void router.replace({path:'/login',query:{redirect:route.fullPath}})}
|
||||
watch(()=>auth.user?.id,id=>{clearInterval(poll);if(id){void caps.load();void jobs.connect();poll=setInterval(()=>{void caps.load()},30000)}else clearSession()},{immediate:true})
|
||||
async function logout(){try{await auth.logout();clearSession();await router.replace('/login')}catch(error){ElMessage.error(errorMessage(error))}}
|
||||
onMounted(()=>window.addEventListener('cmvr:unauthorized',expired));onBeforeUnmount(()=>{window.removeEventListener('cmvr:unauthorized',expired);clearInterval(poll);jobs.disconnect()})
|
||||
</script>
|
||||
<template>
|
||||
<RouterView v-if="route.path==='/login'" />
|
||||
<div v-else class="app-shell"><aside class="sidebar"><router-link to="/create/image" class="brand" aria-label="CMVR Visual 创作首页"><span class="brand-glyph">V</span><span class="brand-caption">CMVR</span></router-link><nav class="side-nav"><router-link v-for="item in nav" :key="item.path" :to="item.path" :class="{selected:item.path==='/create/image'?route.path.startsWith('/create'):route.path.startsWith(item.path)}"><el-icon><component :is="item.icon" /></el-icon><span>{{ item.label }}</span><i v-if="item.path==='/tasks'&&jobs.active.length" class="nav-notification"/></router-link></nav><div class="sidebar-bottom"><el-tooltip content="服务状态" placement="right"><button aria-label="服务状态" @click="systemOpen=true"><el-icon><Connection /></el-icon></button></el-tooltip><el-dropdown trigger="click" placement="right-end"><button class="avatar-button" :aria-label="auth.user?.display_name||'账户'">{{ (auth.user?.display_name||auth.user?.username||'U').slice(0,1) }}</button><template #dropdown><el-dropdown-menu><el-dropdown-item disabled>{{ auth.user?.display_name||auth.user?.username }}</el-dropdown-item><el-dropdown-item divided :icon="SwitchButton" @click="logout">退出登录</el-dropdown-item></el-dropdown-menu></template></el-dropdown></div></aside>
|
||||
<div class="app-main"><header class="app-header"><div class="header-breadcrumb"><span>CMVR Visual</span><span class="breadcrumb-separator">/</span><strong>{{ route.meta.title }}</strong></div><div class="header-actions"><button class="connection-status" :class="jobs.connection" @click="systemOpen=true"><span class="live-dot"/>{{ connectionLabel }}</button><span class="header-divider"/><span class="local-label">{{ caps.environment === 'production' ? '本地创作空间' : caps.environment ? '验收环境' : '环境待确认' }}<template v-if="caps.environment && caps.environment !== 'production'"> · {{ caps.databaseBackend === 'mysql' ? 'MySQL' : 'SQLite' }}</template></span></div></header><div v-if="jobs.connection==='reconnecting'" class="connection-banner"><el-icon><Warning /></el-icon>连接恢复中,任务状态待同步。<button @click="jobs.refresh().catch(()=>undefined)">重新同步</button></div><main class="page-content"><RouterView /></main><button v-if="ongoing" class="global-queue-bar" @click="router.push({path:'/tasks',query:{job:ongoing.id}})"><span class="queue-spinner"/><strong>{{ stateLabel(ongoing) }}</strong><span>{{ phaseLabel(ongoing) }}</span><small v-if="jobs.active.length>1">另有 {{ jobs.active.length-1 }} 项活动任务</small><el-icon><ArrowRight /></el-icon></button></div>
|
||||
<el-drawer v-model="systemOpen" title="创作服务状态" size="400px"><div class="system-status"><span class="eyebrow">LOCAL CREATIVE ENGINE</span><h2>让算力,为灵感留白。</h2><p>GPU 任务串行执行,外部使用优先。抢占后自动让行并重新排队。</p><el-button :icon="RefreshRight" :loading="caps.loading" @click="caps.load">刷新状态</el-button><div v-if="caps.error" class="notice warning">{{ caps.error }}</div><h3>模型能力</h3><div v-for="cap in caps.items" :key="cap.task_type" class="system-model"><span class="status-dot" :class="cap.available?'succeeded':'failed'"/><div><strong>{{ cap.label }}</strong><small>{{ cap.model }}</small><p>{{ cap.description }}</p></div><span>{{ cap.available?'就绪':'未配置' }}</span></div><h3>算力资源</h3><p class="muted">{{ caps.scheduler?.reason||caps.scheduler?.state||'尚未读取调度状态' }}</p><div v-for="gpu in caps.scheduler?.gpus||[]" :key="gpu.index" class="gpu-status"><strong>GPU {{ gpu.index }}</strong><span>{{ gpu.eligible?'可用':gpu.busy?'占用中':'等待确认' }}</span><small>{{ gpu.free_gib===null?'—':`${gpu.free_gib.toFixed(1)} GiB 空闲` }}</small></div></div></el-drawer>
|
||||
</div>
|
||||
</template>
|
||||
53
frontend/src/api.ts
Normal file
@ -0,0 +1,53 @@
|
||||
import type { Asset, AuthResponse, CapabilitiesResponse, Job, JobRequest, JobsPage, Page, Scheduler, Capability } from './types'
|
||||
|
||||
let csrfToken = ''
|
||||
export function setCsrfToken(token: string) { csrfToken = token }
|
||||
export class ApiError extends Error {
|
||||
constructor(public code: string, message: string, public status = 0) { super(message) }
|
||||
}
|
||||
export function queryString(values: Record<string, unknown> = {}) {
|
||||
const search = new URLSearchParams()
|
||||
for (const [key, value] of Object.entries(values)) if (value !== undefined && value !== null && value !== '') search.set(key, String(value))
|
||||
return search.size ? `?${search}` : ''
|
||||
}
|
||||
export function newRequestId() { return globalThis.crypto?.randomUUID?.() || `${Date.now()}-${Math.random().toString(36).slice(2)}` }
|
||||
async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
|
||||
const method = (options.method || 'GET').toUpperCase()
|
||||
const headers = new Headers(options.headers)
|
||||
if (options.body && !(options.body instanceof FormData)) headers.set('Content-Type', 'application/json')
|
||||
if (!['GET', 'HEAD'].includes(method) && path !== '/auth/login') {
|
||||
if (!csrfToken) throw new ApiError('session_required', '登录状态已失效,请重新登录', 401)
|
||||
headers.set('X-CSRF-Token', csrfToken)
|
||||
}
|
||||
let response: Response
|
||||
try { response = await fetch(`/api${path}`, { ...options, headers, credentials: 'include' }) }
|
||||
catch { throw new ApiError('network_error', '暂时无法连接服务,请检查网络后重试') }
|
||||
if (!response.ok) {
|
||||
const data = await response.json().catch(() => null)
|
||||
const detail = data?.detail
|
||||
const message = typeof detail === 'string' ? detail : Array.isArray(detail)
|
||||
? detail.map((item: { msg: string }) => item.msg).join(';') : detail?.message || `请求失败(${response.status})`
|
||||
if (response.status === 401 && path !== '/auth/login' && typeof window !== 'undefined') window.dispatchEvent(new Event('cmvr:unauthorized'))
|
||||
throw new ApiError(detail?.code || 'request_failed', message, response.status)
|
||||
}
|
||||
if (response.status === 204) return undefined as T
|
||||
return response.json() as Promise<T>
|
||||
}
|
||||
export const api = {
|
||||
me: () => request<AuthResponse>('/auth/me'),
|
||||
login: (username: string, password: string) => request<AuthResponse>('/auth/login', { method: 'POST', body: JSON.stringify({ username, password }) }),
|
||||
logout: () => request<void>('/auth/logout', { method: 'POST' }),
|
||||
capabilities: () => request<CapabilitiesResponse>('/capabilities'),
|
||||
systemStatus: () => request<{ inference_online: boolean; scheduler: Scheduler; models: Capability[]; environment: 'production' | 'preview' | 'test'; database_backend: 'mysql' | 'sqlite' }>('/system/status'),
|
||||
jobs: (filters: Record<string, unknown> = {}) => request<JobsPage>(`/jobs${queryString(filters)}`),
|
||||
job: (id: string) => request<Job>(`/jobs/${encodeURIComponent(id)}`),
|
||||
submit: (body: JobRequest) => request<{ jobs: Job[] }>('/jobs', { method: 'POST', headers: { 'Idempotency-Key': newRequestId() }, body: JSON.stringify(body) }),
|
||||
cancel: (id: string) => request<Job>(`/jobs/${encodeURIComponent(id)}/cancel`, { method: 'POST' }),
|
||||
retry: (id: string) => request<{ jobs: Job[] }>(`/jobs/${encodeURIComponent(id)}/retry`, { method: 'POST' }),
|
||||
assets: (filters: Record<string, unknown> = {}) => request<Page<Asset>>(`/assets${queryString(filters)}`),
|
||||
asset: (id: string) => request<Asset>(`/assets/${encodeURIComponent(id)}`),
|
||||
upload: (file: File) => { const form = new FormData(); form.set('file', file); return request<Asset>('/assets', { method: 'POST', body: form }) },
|
||||
updateAsset: (id: string, patch: { name?: string; tags?: string[]; favorite?: boolean }) => request<Asset>(`/assets/${encodeURIComponent(id)}`, { method: 'PATCH', body: JSON.stringify(patch) }),
|
||||
deleteAsset: (id: string) => request<void>(`/assets/${encodeURIComponent(id)}`, { method: 'DELETE' }),
|
||||
}
|
||||
export function errorMessage(error: unknown) { return error instanceof Error ? error.message : '操作未完成,请稍后重试' }
|
||||
37
frontend/src/components/AssetInput.vue
Normal file
@ -0,0 +1,37 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { Plus, FolderOpened, Close, Headset, VideoCamera, Upload } from '@element-plus/icons-vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { useAssetsStore } from '../stores/assets'
|
||||
import { errorMessage } from '../api'
|
||||
import type { Asset, AssetKind } from '../types'
|
||||
import AssetPicker from './AssetPicker.vue'
|
||||
const props = defineProps<{ modelValue: Asset | null; kinds: AssetKind[]; label?: string; hint?: string }>()
|
||||
const emit = defineEmits<{ 'update:modelValue': [Asset | null] }>()
|
||||
const store = useAssetsStore(), picker = ref(false), busy = ref(false), fileInput = ref<HTMLInputElement>()
|
||||
async function upload(event: Event) {
|
||||
const input = event.target as HTMLInputElement, file = input.files?.[0]
|
||||
if (!file) return
|
||||
busy.value = true
|
||||
try { const asset = await store.upload(file); if (!props.kinds.includes(asset.kind)) ElMessage.warning('素材类型不适用于当前创作'); else emit('update:modelValue', asset) }
|
||||
catch (error) { ElMessage.error(errorMessage(error)) }
|
||||
finally { busy.value = false; input.value = '' }
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<div class="asset-input" :class="{ populated: modelValue }" v-loading="busy">
|
||||
<template v-if="modelValue">
|
||||
<img v-if="modelValue.kind === 'image' || modelValue.thumbnail_url" :src="modelValue.thumbnail_url || modelValue.preview_url" :alt="modelValue.name" />
|
||||
<el-icon v-else :size="30"><Headset v-if="modelValue.kind === 'audio'" /><VideoCamera v-else /></el-icon>
|
||||
<div class="asset-input-description"><strong>{{ modelValue.name }}</strong><small>已归属你的素材库 · 点击更换</small></div>
|
||||
<el-button text :icon="FolderOpened" aria-label="更换素材" @click="picker = true" />
|
||||
<el-button text :icon="Close" aria-label="移除参考素材" @click="emit('update:modelValue', null)" />
|
||||
</template>
|
||||
<template v-else>
|
||||
<button class="upload-trigger" @click="fileInput?.click()"><el-icon><Plus /></el-icon><span>{{ label || '添加参考素材' }}</span><small>{{ hint || '点击上传,或从素材库选择' }}</small></button>
|
||||
<el-button text :icon="FolderOpened" class="from-library" @click="picker = true">素材库</el-button>
|
||||
</template>
|
||||
<input ref="fileInput" type="file" hidden :accept="kinds.map(value => `${value}/*`).join(',')" @change="upload" />
|
||||
<AssetPicker v-model="picker" :kinds="kinds" @select="emit('update:modelValue', $event)" />
|
||||
</div>
|
||||
</template>
|
||||
51
frontend/src/components/AssetPicker.vue
Normal file
@ -0,0 +1,51 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from 'vue'
|
||||
import { Upload, Search, VideoCamera, Headset, Document } from '@element-plus/icons-vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { api, errorMessage } from '../api'
|
||||
import { useAssetsStore } from '../stores/assets'
|
||||
import type { Asset, AssetKind } from '../types'
|
||||
import { formatBytes } from '../format'
|
||||
const props = defineProps<{ modelValue: boolean; kinds?: AssetKind[] }>()
|
||||
const emit = defineEmits<{ 'update:modelValue': [boolean]; select: [Asset] }>()
|
||||
const store = useAssetsStore()
|
||||
const items = ref<Asset[]>([]), total = ref(0), page = ref(1), q = ref(''), kind = ref(''), busy = ref(false), uploading = ref(false)
|
||||
const fileInput = ref<HTMLInputElement>()
|
||||
async function load() {
|
||||
busy.value = true
|
||||
try { const result = await api.assets({ page: page.value, page_size: 12, q: q.value, kind: kind.value || (props.kinds?.length === 1 ? props.kinds[0] : '') }); items.value = result.items; total.value = result.total; result.items.forEach(store.upsert) }
|
||||
catch (error) { ElMessage.error(errorMessage(error)) }
|
||||
finally { busy.value = false }
|
||||
}
|
||||
function choose(asset: Asset) { if (props.kinds && !props.kinds.includes(asset.kind)) return; emit('select', asset); emit('update:modelValue', false) }
|
||||
async function upload(event: Event) {
|
||||
const file = (event.target as HTMLInputElement).files?.[0]
|
||||
if (!file) return
|
||||
uploading.value = true
|
||||
try { const asset = await store.upload(file); if (props.kinds && !props.kinds.includes(asset.kind)) { ElMessage.warning('这个素材类型不适用于当前操作'); await load() } else choose(asset) }
|
||||
catch (error) { ElMessage.error(errorMessage(error)) }
|
||||
finally { uploading.value = false; (event.target as HTMLInputElement).value = '' }
|
||||
}
|
||||
watch(() => props.modelValue, open => { if (open) { page.value = 1; void load() } })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<el-dialog :model-value="modelValue" title="选择你的素材" width="820px" class="asset-picker" @update:model-value="emit('update:modelValue', $event)">
|
||||
<div class="picker-toolbar">
|
||||
<el-input v-model="q" placeholder="搜索素材名称" :prefix-icon="Search" clearable @keyup.enter="page = 1; load()" @clear="page = 1; load()" />
|
||||
<el-button :icon="Search" @click="page = 1; load()">搜索</el-button>
|
||||
<el-button type="primary" :icon="Upload" :loading="uploading" @click="fileInput?.click()">上传素材</el-button>
|
||||
<input ref="fileInput" type="file" hidden :accept="kinds?.map(value => `${value}/*`).join(',')" @change="upload" />
|
||||
</div>
|
||||
<div v-loading="busy" class="picker-grid">
|
||||
<button v-for="asset in items" :key="asset.id" class="picker-item" :disabled="kinds && !kinds.includes(asset.kind)" @click="choose(asset)">
|
||||
<img v-if="asset.kind === 'image' || asset.thumbnail_url" :src="asset.thumbnail_url || asset.preview_url" :alt="asset.name" loading="lazy" />
|
||||
<video v-else-if="asset.kind === 'video'" :src="asset.preview_url" preload="metadata" muted />
|
||||
<div v-else class="file-cover"><el-icon><Headset v-if="asset.kind === 'audio'" /><Document v-else /></el-icon></div>
|
||||
<span class="picker-name">{{ asset.name }}</span><small>{{ asset.kind }} · {{ formatBytes(asset.size_bytes) }}</small>
|
||||
</button>
|
||||
<div v-if="!busy && !items.length" class="empty-state compact"><el-icon><Upload /></el-icon><h3>这里还没有素材</h3><p>上传图片、视频或音频,开始下一步创作。</p></div>
|
||||
</div>
|
||||
<el-pagination v-if="total > 12" v-model:current-page="page" :page-size="12" :total="total" layout="prev, pager, next" @current-change="load" />
|
||||
</el-dialog>
|
||||
</template>
|
||||
60
frontend/src/components/AssetPreview.vue
Normal file
@ -0,0 +1,60 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { Star, StarFilled, Download, Delete, VideoCamera, Scissor, DataAnalysis } from '@element-plus/icons-vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { useAssetsStore } from '../stores/assets'
|
||||
import { errorMessage } from '../api'
|
||||
import { formatBytes, formatDate, formatDuration } from '../format'
|
||||
import type { Asset } from '../types'
|
||||
const props = defineProps<{ asset: Asset | null }>()
|
||||
const emit = defineEmits<{ 'update:asset': [Asset | null]; deleted: [string] }>()
|
||||
const router = useRouter(), store = useAssetsStore(), name = ref(''), tags = ref(''), saving = ref(false), text = ref('')
|
||||
const current = computed(() => props.asset ? store.byId[props.asset.id] || props.asset : null)
|
||||
watch(() => props.asset, async asset => {
|
||||
name.value = asset?.name || ''; tags.value = asset?.tags.join(',') || ''; text.value = ''
|
||||
if (asset && ['text', 'json'].includes(asset.kind)) {
|
||||
try { const response = await fetch(asset.preview_url, { credentials: 'include' }); if (!response.ok) throw new Error('无法读取文本产物'); const value = await response.text(); if (props.asset?.id !== asset.id) return; text.value = value }
|
||||
catch (error) { ElMessage.error(errorMessage(error)) }
|
||||
}
|
||||
})
|
||||
async function save() {
|
||||
if (!current.value || !name.value.trim()) { ElMessage.warning('请输入素材名称'); return }
|
||||
saving.value = true
|
||||
try { await store.update(current.value.id, { name: name.value.trim(), tags: tags.value.split(/[,,]/).map(value => value.trim()).filter(Boolean) }); ElMessage.success('素材信息已保存') }
|
||||
catch (error) { ElMessage.error(errorMessage(error)) } finally { saving.value = false }
|
||||
}
|
||||
async function favorite() { if (!current.value) return; try { await store.update(current.value.id, { favorite: !current.value.favorite }) } catch (error) { ElMessage.error(errorMessage(error)) } }
|
||||
async function remove() {
|
||||
if (!current.value) return
|
||||
try { await ElMessageBox.confirm('从素材库移除此素材?已被任务引用的输入将由服务保留。', '删除素材', { confirmButtonText: '删除', cancelButtonText: '保留', type: 'warning' }) }
|
||||
catch { return }
|
||||
try { const id = current.value.id; await store.remove(id); emit('deleted', id); emit('update:asset', null); ElMessage.success('素材已移除') }
|
||||
catch (error) { ElMessage.error(errorMessage(error)) }
|
||||
}
|
||||
function useFor(path: string, key: string) { const id = current.value?.id; emit('update:asset', null); if (id) void router.push({ path, query: { [key]: id } }) }
|
||||
</script>
|
||||
<template>
|
||||
<el-dialog :model-value="!!asset" :title="current?.name || '素材预览'" width="1080px" class="preview-dialog" destroy-on-close @update:model-value="!$event && emit('update:asset', null)">
|
||||
<div v-if="current" class="preview-layout">
|
||||
<div class="preview-stage">
|
||||
<img v-if="current.kind === 'image'" :src="current.preview_url" :alt="current.name" />
|
||||
<video v-else-if="current.kind === 'video'" :src="current.preview_url" controls playsinline :poster="current.thumbnail_url || undefined" />
|
||||
<div v-else-if="current.kind === 'audio'" class="audio-preview"><div class="audio-wave">▂ ▅ ▃ ▇ ▄ ▆ ▂ ▅ ▇ ▃ ▅ ▂</div><audio :src="current.preview_url" controls /></div>
|
||||
<pre v-else>{{ text || '正在读取文本产物…' }}</pre>
|
||||
</div>
|
||||
<aside class="preview-meta">
|
||||
<span class="eyebrow">ASSET DETAILS</span>
|
||||
<el-form label-position="top"><el-form-item label="素材名称"><el-input v-model="name" maxlength="200" /></el-form-item><el-form-item label="标签 · 用逗号分隔"><el-input v-model="tags" placeholder="产品,光影,教学" /></el-form-item></el-form>
|
||||
<el-button type="primary" :loading="saving" @click="save">保存修改</el-button>
|
||||
<dl class="metadata-list"><dt>类型</dt><dd>{{ current.mime_type }}</dd><dt>尺寸</dt><dd>{{ current.width && current.height ? `${current.width} × ${current.height}` : '—' }}</dd><dt>时长</dt><dd>{{ formatDuration(current.duration_seconds) }}</dd><dt>大小</dt><dd>{{ formatBytes(current.size_bytes) }}</dd><dt>来源</dt><dd>{{ current.origin === 'upload' ? '我的上传' : '模型生成' }}</dd><dt>时间</dt><dd>{{ formatDate(current.created_at) }}</dd></dl>
|
||||
<div class="asset-actions"><el-button :icon="current.favorite ? StarFilled : Star" @click="favorite">{{ current.favorite ? '已收藏' : '收藏' }}</el-button><a :href="current.download_url" :download="current.name" class="el-button"><el-icon><Download /></el-icon><span>下载原件</span></a></div>
|
||||
<el-button v-if="current.kind === 'image'" :icon="VideoCamera" @click="useFor('/create/video', 'image')">让画面动起来</el-button>
|
||||
<el-button v-if="current.kind === 'video'" :icon="Scissor" @click="useFor('/compose', 'asset')">加入成片编排</el-button>
|
||||
<el-button v-if="['image', 'video'].includes(current.kind)" :icon="DataAnalysis" @click="useFor('/analyze', 'asset')">理解这个素材</el-button>
|
||||
<el-button v-if="current.source_job_id" text @click="router.push({path:'/tasks',query:{job:current.source_job_id}}); emit('update:asset', null)">查看来源任务</el-button>
|
||||
<el-button text type="danger" :icon="Delete" @click="remove">删除素材</el-button>
|
||||
</aside>
|
||||
</div>
|
||||
</el-dialog>
|
||||
</template>
|
||||
22
frontend/src/components/JobCard.vue
Normal file
@ -0,0 +1,22 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { Picture, VideoPlay, MoreFilled, Clock, Document, Warning, Loading } from '@element-plus/icons-vue'
|
||||
import type { Asset, Job } from '../types'
|
||||
import { formatDate, isActive, phaseLabel, stateLabel, taskLabels } from '../format'
|
||||
const props = defineProps<{ job: Job }>()
|
||||
const emit = defineEmits<{ open: [string]; preview: [Asset] }>()
|
||||
const cover = computed(() => props.job.result_assets?.find(asset => ['image', 'video'].includes(asset.kind)))
|
||||
function open() { if (cover.value && props.job.state === 'succeeded') emit('preview', cover.value); else emit('open', props.job.id) }
|
||||
</script>
|
||||
<template>
|
||||
<article class="result-card" :class="{ working: isActive(job), failed: ['failed', 'timed_out'].includes(job.state) }">
|
||||
<button class="result-media" @click="open">
|
||||
<img v-if="cover?.kind === 'image' || cover?.thumbnail_url" :src="cover.thumbnail_url || cover.preview_url" :alt="job.prompt" loading="lazy" />
|
||||
<video v-else-if="cover?.kind === 'video'" :src="cover.preview_url" preload="metadata" muted playsinline />
|
||||
<div v-else class="pending-art"><div v-if="isActive(job)" class="generation-orbit" /><el-icon v-else :size="34"><Warning v-if="job.error" /><Document v-else /></el-icon><strong>{{ stateLabel(job) }}</strong><span>{{ phaseLabel(job) }}</span></div>
|
||||
<span class="media-badge" :class="job.state"><i :class="{ pulse: isActive(job) }" />{{ stateLabel(job) }}</span>
|
||||
<span v-if="cover?.kind === 'video'" class="play-circle"><el-icon><VideoPlay /></el-icon></span>
|
||||
</button>
|
||||
<div class="result-caption"><div class="result-kicker"><span>{{ taskLabels[job.task_type] }}</span><button class="icon-button" aria-label="查看任务详情" @click="emit('open', job.id)"><el-icon><MoreFilled /></el-icon></button></div><button class="result-prompt" @click="emit('open', job.id)">{{ job.prompt || taskLabels[job.task_type] }}</button><div class="result-footnote"><span>{{ formatDate(job.created_at) }}</span><span v-if="job.preemptions">让行 {{ job.preemptions }} 次</span><span v-else-if="job.parameters.width">{{ job.parameters.width }} × {{ job.parameters.height }}</span></div></div>
|
||||
</article>
|
||||
</template>
|
||||
22
frontend/src/components/JobDetail.test.ts
Normal file
@ -0,0 +1,22 @@
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
import { createSSRApp, defineComponent, h } from 'vue'
|
||||
import { renderToString } from 'vue/server-renderer'
|
||||
import { createPinia } from 'pinia'
|
||||
import JobDetail from './JobDetail.vue'
|
||||
import { api } from '../api'
|
||||
|
||||
vi.mock('./AssetPreview.vue', () => ({ default: { render: () => null } }))
|
||||
|
||||
afterEach(() => vi.restoreAllMocks())
|
||||
|
||||
it('fetches an initially selected deep-linked task without depending on recent-list cache', async () => {
|
||||
const request = vi.spyOn(api, 'job').mockReturnValue(new Promise(() => {}))
|
||||
const application = createSSRApp(JobDetail, { jobId: 'archived-owned-job' })
|
||||
application.use(createPinia())
|
||||
application.component('ElDrawer', defineComponent({ setup: (_, { slots }) => () => h('aside', slots.default?.()) }))
|
||||
application.component('ElProgress', { render: () => null })
|
||||
application.component('ElButton', { render: () => null })
|
||||
application.directive('loading', {})
|
||||
await renderToString(application)
|
||||
expect(request).toHaveBeenCalledExactlyOnceWith('archived-owned-job')
|
||||
})
|
||||
38
frontend/src/components/JobDetail.vue
Normal file
@ -0,0 +1,38 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { RefreshRight, Close, CopyDocument } from '@element-plus/icons-vue'
|
||||
import { useJobsStore } from '../stores/jobs'
|
||||
import type { Asset } from '../types'
|
||||
import { errorMessage } from '../api'
|
||||
import { copyText, formatDate, isActive, phaseLabel, reasonText, stateLabel, taskLabels } from '../format'
|
||||
import MathText from './MathText.vue'
|
||||
import AssetPreview from './AssetPreview.vue'
|
||||
const props = defineProps<{ jobId: string | null }>()
|
||||
const emit = defineEmits<{ 'update:jobId': [string | null] }>()
|
||||
const store = useJobsStore(), busy = ref(false), loading = ref(false), selected = ref<Asset | null>(null)
|
||||
const job = computed(() => props.jobId ? store.byId[props.jobId] : undefined)
|
||||
watch(() => props.jobId, async id => { if (!id) return; loading.value = true; try { await store.fetchOne(id) } catch (error) { ElMessage.error(errorMessage(error)) } finally { loading.value = false } }, { immediate: true })
|
||||
async function cancel() { if (!job.value) return; busy.value = true; try { await store.cancel(job.value.id); ElMessage.success('取消请求已提交,正在等待释放资源') } catch (error) { ElMessage.error(errorMessage(error)) } finally { busy.value = false } }
|
||||
async function retry() { if (!job.value) return; busy.value = true; try { const created = await store.retry(job.value.id); if (created[0]) emit('update:jobId', created[0].id); ElMessage.success('已创建新的生成任务') } catch (error) { ElMessage.error(errorMessage(error)) } finally { busy.value = false } }
|
||||
async function copy(value: string) { try { await copyText(value); ElMessage.success('已复制') } catch { ElMessage.warning('当前浏览器无法读取剪贴板,请手动选择复制') } }
|
||||
</script>
|
||||
<template>
|
||||
<el-drawer :model-value="!!jobId" title="任务详情" size="560px" destroy-on-close @update:model-value="!$event && emit('update:jobId', null)">
|
||||
<div v-loading="loading" class="job-detail">
|
||||
<template v-if="job">
|
||||
<div class="detail-heading"><span class="status-pill" :class="job.state">{{ stateLabel(job) }}</span><small>{{ taskLabels[job.task_type] }}</small></div>
|
||||
<h2>{{ job.prompt || taskLabels[job.task_type] }}</h2><p class="muted">{{ phaseLabel(job) }}</p>
|
||||
<el-progress v-if="job.progress !== null && isActive(job)" :percentage="Math.max(0, Math.min(100, job.progress))" :stroke-width="5" :show-text="true" />
|
||||
<div class="detail-actions"><el-button v-if="isActive(job)" :icon="Close" :loading="busy" :disabled="job.cancel_requested" @click="cancel">{{ job.cancel_requested ? '正在取消' : '取消任务' }}</el-button><el-button v-else type="primary" :icon="RefreshRight" :loading="busy" @click="retry">{{ job.state === 'succeeded' ? '再生成一次' : '重新提交' }}</el-button><el-button text :icon="CopyDocument" @click="copy(job.prompt)">复制提示词</el-button></div>
|
||||
<div v-if="job.sync_warning" class="notice warning">{{ job.sync_warning }}<br />尚未将同步中断视为生成失败。</div>
|
||||
<div v-if="job.error" class="notice danger"><strong>{{ job.error.code }}</strong><p>{{ job.error.message }}</p></div>
|
||||
<section v-if="job.result_assets.length" class="detail-section"><h3>最终产物 <span>{{ job.result_assets.length }}</span></h3><div class="detail-assets"><button v-for="asset in job.result_assets" :key="asset.id" @click="selected = asset"><img v-if="asset.kind === 'image' || asset.thumbnail_url" :src="asset.thumbnail_url || asset.preview_url" :alt="asset.name" /><span v-else class="file-cover">{{ asset.kind.toUpperCase() }}</span><strong>{{ asset.name }}</strong></button></div></section>
|
||||
<section v-if="job.result" class="detail-section"><h3>结果内容</h3><MathText v-if="job.result.text" :text="String(job.result.text)" /><pre v-else class="json-output">{{ JSON.stringify(job.result, null, 2) }}</pre></section>
|
||||
<section class="detail-section"><h3>执行记录</h3><div class="execution-timeline"><div><i /><strong>创建任务</strong><span>{{ formatDate(job.created_at) }}</span></div><div v-if="job.scheduled_at"><i /><strong>预约时间</strong><span>{{ formatDate(job.scheduled_at) }}</span></div><div v-if="job.attempt_count"><i /><strong>已尝试 {{ job.attempt_count }} 次</strong><span>当前任务 ID 保持不变</span></div><div v-if="job.preemptions"><i /><strong>已让出算力 {{ job.preemptions }} 次</strong><span>{{ reasonText(job.last_preempted_reason) }}</span><code>{{ job.last_preempted_reason }}</code></div><div v-if="job.finished_at"><i /><strong>{{ stateLabel(job) }}</strong><span>{{ formatDate(job.finished_at) }}</span></div></div></section>
|
||||
<section class="detail-section"><h3>生成参数</h3><pre class="json-output">{{ JSON.stringify(job.parameters, null, 2) }}</pre><small class="task-identity">任务 {{ job.id }} · 版本 {{ job.version }}</small></section>
|
||||
</template><p v-else-if="!loading" class="muted">暂无可读取的任务详情。</p>
|
||||
</div>
|
||||
<AssetPreview v-model:asset="selected" />
|
||||
</el-drawer>
|
||||
</template>
|
||||
17
frontend/src/components/MathText.vue
Normal file
@ -0,0 +1,17 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import katex from 'katex'
|
||||
const props = defineProps<{ text: string }>()
|
||||
function escape(text: string) { return text.replace(/[&<>"']/g, character => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[character]!) }
|
||||
const rendered = computed(() => {
|
||||
const pattern = /(\$\$[\s\S]*?\$\$|\\\[[\s\S]*?\\\]|\\\([\s\S]*?\\\)|\$[^\n$]+\$)/g
|
||||
return props.text.split(pattern).map(part => {
|
||||
const display = part.startsWith('$$') || part.startsWith('\\[')
|
||||
const math = display || part.startsWith('\\(') || (part.startsWith('$') && part.endsWith('$'))
|
||||
if (!math) return escape(part)
|
||||
try { return katex.renderToString(part.slice(display || part.startsWith('\\(') ? 2 : 1, display || part.startsWith('\\(') ? -2 : -1), { displayMode: display, throwOnError: false, trust: false, strict: 'ignore' }) }
|
||||
catch { return escape(part) }
|
||||
}).join('')
|
||||
})
|
||||
</script>
|
||||
<template><div class="math-text" v-html="rendered" /></template>
|
||||
34
frontend/src/format.ts
Normal file
@ -0,0 +1,34 @@
|
||||
import type { Job, TaskType } from './types'
|
||||
export const taskLabels: Record<TaskType, string> = {
|
||||
'image.generate': '图像生成', 'video.generate': '视频生成', 'defect.generate': '缺陷样本',
|
||||
'audio.transcribe': '语音转写', 'audio.speech': '语音生成', 'math.solve': '数学推演',
|
||||
'media.structure': '素材理解', 'video.compose': '成片合成',
|
||||
}
|
||||
export const activeStates = new Set(['scheduled', 'submitting', 'queued', 'running', 'collecting', 'cancelling'])
|
||||
export function isActive(job: Job) { return activeStates.has(job.state) }
|
||||
export function stateLabel(job: Job) {
|
||||
if (job.cancel_requested && isActive(job)) return '正在取消'
|
||||
if (job.state === 'queued' && job.preemptions > 0) return '等待自动重试'
|
||||
return { scheduled: '预约中', submitting: '正在提交', queued: '等待算力', running: '正在创作', collecting: '正在归档', cancelling: '正在取消', succeeded: '已完成', failed: '未完成', cancelled: '已取消', timed_out: '已超时' }[job.state]
|
||||
}
|
||||
export function reasonText(reason: string | null) {
|
||||
if (!reason) return ''
|
||||
if (/monitor|nvidia_query|stale|snapshot|监控/i.test(reason)) return '正在确认算力状态,任务将自动重试'
|
||||
if (/external|foreign|other|busy|占用/i.test(reason)) return '已让出算力,等待空闲后自动重试'
|
||||
return reason
|
||||
}
|
||||
export function phaseLabel(job: Job) {
|
||||
if (job.error) return job.error.message
|
||||
if (job.sync_warning) return job.sync_warning
|
||||
if (job.cancel_requested && isActive(job)) return '等待当前进程释放资源'
|
||||
if (job.state === 'queued' && job.preemptions) return reasonText(job.last_preempted_reason)
|
||||
if (job.state === 'queued') return job.queue_position === null ? '等待空闲算力,任务会自动开始' : `队列位置 ${job.queue_position}`
|
||||
if (job.state === 'scheduled') return job.scheduled_at ? `预约 ${formatDate(job.scheduled_at)}` : '等待预约时间'
|
||||
if (job.state === 'collecting') return '正在安全保存最终产物'
|
||||
if (job.state === 'running') return job.attempt_count > 1 ? `第 ${job.attempt_count} 次尝试 · ${job.phase || '执行中'}` : ({ loading: '正在加载模型', upscale: '正在增强画质', executing: '模型正在生成', launching: '正在准备模型' }[job.phase] || '模型正在执行')
|
||||
return job.state === 'succeeded' ? '产物已归档到素材库' : ''
|
||||
}
|
||||
export function formatDate(value: string | null) { return value ? new Intl.DateTimeFormat('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false }).format(new Date(value)) : '—' }
|
||||
export function formatBytes(bytes: number) { if (bytes < 1024) return `${bytes} B`; if (bytes < 1048576) return `${(bytes / 1024).toFixed(1)} KB`; return `${(bytes / 1048576).toFixed(1)} MB` }
|
||||
export function formatDuration(value: number | null) { if (value === null) return '—'; return value >= 60 ? `${Math.floor(value / 60)}:${Math.round(value % 60).toString().padStart(2, '0')}` : `${value.toFixed(1)} 秒` }
|
||||
export async function copyText(value: string) { await navigator.clipboard.writeText(value) }
|
||||
6
frontend/src/inspirations.ts
Normal file
@ -0,0 +1,6 @@
|
||||
export const inspirations = [
|
||||
{ id: 'teapot', image: '/inspiration/qwen-image.png', title: '把日常,放进一束光', category: '产品摄影', model: 'Qwen-Image', size: '1024 × 1024', prompt: '一把红釉陶瓷茶壶放在浅色木桌上,午后自然侧光,柔和阴影,真实产品摄影,干净背景。' },
|
||||
{ id: 'robot', image: '/inspiration/wan-middle.png', title: '让小小角色,拥有下一秒', category: '动态分镜', model: 'Wan2.2 · 视频帧', size: '1920 × 1080', prompt: '一只橙色玩具机器人站在桌面上,轻轻挥手,镜头缓慢靠近,温暖自然光,保持角色造型一致。' },
|
||||
{ id: 'metal', image: '/inspiration/sdxl-controlnet.png', title: '看见材质的细微变化', category: '工业材质', model: 'SDXL + ControlNet', size: '768 × 768', prompt: '拉丝金属零件表面的细长划痕,真实工业摄影,保留零件边缘和原始结构,清晰的金属质感。' },
|
||||
{ id: 'light', image: '/inspiration/priority-retry-image.png', title: '在留白中,寻找新的构图', category: '光影练习', model: 'Qwen-Image', size: '512 × 512', prompt: '红色陶瓷茶壶置于木桌上,暖色窗光与大面积留白,安静简洁的生活摄影。' },
|
||||
]
|
||||
15
frontend/src/main.ts
Normal file
@ -0,0 +1,15 @@
|
||||
import { createApp } from 'vue'
|
||||
import { createPinia } from 'pinia'
|
||||
import ElementPlus from 'element-plus'
|
||||
import zhCn from 'element-plus/es/locale/lang/zh-cn'
|
||||
import 'element-plus/dist/index.css'
|
||||
import 'element-plus/theme-chalk/dark/css-vars.css'
|
||||
import 'katex/dist/katex.min.css'
|
||||
import '@fontsource-variable/noto-sans-sc'
|
||||
import './style.css'
|
||||
import App from './App.vue'
|
||||
import { router } from './router'
|
||||
document.documentElement.classList.add('dark')
|
||||
const app=createApp(App)
|
||||
app.use(createPinia()).use(ElementPlus,{locale:zhCn}).use(router)
|
||||
void router.isReady().then(()=>app.mount('#app'))
|
||||
15
frontend/src/router.ts
Normal file
@ -0,0 +1,15 @@
|
||||
import { createRouter, createWebHistory } from 'vue-router'
|
||||
import { useAuthStore } from './stores/auth'
|
||||
export const router=createRouter({history:createWebHistory(),routes:[
|
||||
{path:'/login',component:()=>import('./views/LoginView.vue'),meta:{public:true,title:'登录'}},
|
||||
{path:'/',redirect:'/create/image'},
|
||||
{path:'/create/:mode',component:()=>import('./views/WorkbenchView.vue'),meta:{title:'创作工作台'}},
|
||||
{path:'/audio',component:()=>import('./views/ToolsView.vue'),meta:{title:'声音工作台'}},
|
||||
{path:'/math',component:()=>import('./views/ToolsView.vue'),meta:{title:'数学推演'}},
|
||||
{path:'/analyze',component:()=>import('./views/ToolsView.vue'),meta:{title:'素材理解'}},
|
||||
{path:'/compose',component:()=>import('./views/ComposeView.vue'),meta:{title:'成片编排'}},
|
||||
{path:'/assets',component:()=>import('./views/AssetsView.vue'),meta:{title:'素材库'}},
|
||||
{path:'/tasks',component:()=>import('./views/TasksView.vue'),meta:{title:'任务中心'}},
|
||||
{path:'/:pathMatch(.*)*',redirect:'/create/image'},
|
||||
]})
|
||||
router.beforeEach(async to=>{const auth=useAuthStore();if(!auth.checked)await auth.load();if(!to.meta.public&&!auth.user)return{path:'/login',query:{redirect:to.fullPath}};if(to.path==='/login'&&auth.user)return'/create/image';document.title=`${String(to.meta.title||'创作工作台')} · CMVR Visual`})
|
||||
20
frontend/src/stores/assets.ts
Normal file
@ -0,0 +1,20 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref } from 'vue'
|
||||
import { api } from '../api'
|
||||
import type { Asset } from '../types'
|
||||
|
||||
export const useAssetsStore = defineStore('assets', () => {
|
||||
const byId = ref<Record<string, Asset>>({})
|
||||
const revision = ref(0)
|
||||
const remoteRevision = ref(0)
|
||||
let epoch = 0
|
||||
function upsert(asset: Asset) { byId.value[asset.id] = asset; revision.value++ }
|
||||
function forget(id: string) { delete byId.value[id]; revision.value++ }
|
||||
async function get(id: string) { const session = epoch; const asset = await api.asset(id); if (session === epoch) upsert(asset); return asset }
|
||||
async function upload(file: File) { const session = epoch; const asset = await api.upload(file); if (session === epoch) upsert(asset); return asset }
|
||||
async function update(id: string, patch: { name?: string; tags?: string[]; favorite?: boolean }) { const session = epoch; const asset = await api.updateAsset(id, patch); if (session === epoch) upsert(asset); return asset }
|
||||
async function remove(id: string) { await api.deleteAsset(id); forget(id) }
|
||||
function notifyRemote() { remoteRevision.value++ }
|
||||
function clear() { epoch++; byId.value = {}; revision.value++; remoteRevision.value++ }
|
||||
return { byId, revision, remoteRevision, notifyRemote, clear, upsert, forget, get, upload, update, remove }
|
||||
})
|
||||
21
frontend/src/stores/auth.ts
Normal file
@ -0,0 +1,21 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref } from 'vue'
|
||||
import { api, setCsrfToken } from '../api'
|
||||
import type { User } from '../types'
|
||||
|
||||
export const useAuthStore = defineStore('auth', () => {
|
||||
const user = ref<User | null>(null)
|
||||
const checked = ref(false)
|
||||
function clear() { user.value = null; checked.value = true; setCsrfToken('') }
|
||||
async function load() {
|
||||
try { const response = await api.me(); user.value = response.user; setCsrfToken(response.csrf_token) }
|
||||
catch { clear() }
|
||||
finally { checked.value = true }
|
||||
}
|
||||
async function login(username: string, password: string) {
|
||||
const response = await api.login(username, password)
|
||||
user.value = response.user; checked.value = true; setCsrfToken(response.csrf_token)
|
||||
}
|
||||
async function logout() { await api.logout(); clear() }
|
||||
return { user, checked, clear, load, login, logout }
|
||||
})
|
||||
21
frontend/src/stores/capabilities.ts
Normal file
@ -0,0 +1,21 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref } from 'vue'
|
||||
import { api } from '../api'
|
||||
import type { Capability, Scheduler, TaskType } from '../types'
|
||||
|
||||
export const useCapabilitiesStore = defineStore('capabilities', () => {
|
||||
const items = ref<Capability[]>([])
|
||||
const scheduler = ref<Scheduler | null>(null)
|
||||
const loading = ref(false)
|
||||
const error = ref('')
|
||||
const environment = ref<'production' | 'preview' | 'test' | null>(null)
|
||||
const databaseBackend = ref<'mysql' | 'sqlite' | null>(null)
|
||||
async function load() {
|
||||
loading.value = true
|
||||
try { const [response, status] = await Promise.all([api.capabilities(), api.systemStatus()]); items.value = response.items; scheduler.value = status.scheduler || response.scheduler; environment.value = status.environment; databaseBackend.value = status.database_backend; error.value = '' }
|
||||
catch (caught) { error.value = caught instanceof Error ? caught.message : '无法读取模型能力' }
|
||||
finally { loading.value = false }
|
||||
}
|
||||
function forTask(type: TaskType) { return items.value.find(item => item.task_type === type) }
|
||||
return { items, scheduler, loading, error, environment, databaseBackend, load, forTask }
|
||||
})
|
||||
14
frontend/src/stores/drafts.ts
Normal file
@ -0,0 +1,14 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { reactive } from 'vue'
|
||||
import type { TaskType } from '../types'
|
||||
export interface Draft { prompt: string; negative_prompt: string; parameters: Record<string, any>; imageAssetId: string | null; count: number; scheduledAt: string | null }
|
||||
export const useDraftsStore = defineStore('drafts', () => {
|
||||
const drafts = reactive<Record<string, Draft>>({})
|
||||
function forTask(type: TaskType, defaults: Record<string, any> = {}) {
|
||||
if (!drafts[type]) drafts[type] = { prompt: '', negative_prompt: '', parameters: { ...defaults }, imageAssetId: null, count: 1, scheduledAt: null }
|
||||
for (const [key, value] of Object.entries(defaults)) if (drafts[type]!.parameters[key] === undefined) drafts[type]!.parameters[key] = value
|
||||
return drafts[type]!
|
||||
}
|
||||
function clear() { for (const key of Object.keys(drafts)) delete drafts[key] }
|
||||
return { drafts, forTask, clear }
|
||||
})
|
||||
107
frontend/src/stores/jobs.test.ts
Normal file
@ -0,0 +1,107 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import { useJobsStore } from './jobs'
|
||||
import type { Job } from '../types'
|
||||
import { api } from '../api'
|
||||
|
||||
class FakeEventSource {
|
||||
static instances: FakeEventSource[] = []
|
||||
onopen: (() => void) | null = null
|
||||
onerror: (() => void) | null = null
|
||||
listeners: Record<string, (event: any) => void> = {}
|
||||
close = vi.fn()
|
||||
constructor(public url: string) { FakeEventSource.instances.push(this) }
|
||||
addEventListener(name: string, listener: (event: any) => void) { this.listeners[name] = listener }
|
||||
update(value: Job, id: number) { this.listeners['job.updated']?.({ data: JSON.stringify({ job: value }), lastEventId: String(id) }) }
|
||||
}
|
||||
|
||||
function job(overrides: Partial<Job> = {}): Job {
|
||||
return {
|
||||
id: 'job-a', task_type: 'image.generate', state: 'running', phase: 'executing', version: 4,
|
||||
prompt: '红釉茶壶', parameters: { seed: 42 }, input_asset_ids: [], result_assets: [], result: null,
|
||||
progress: null, queue_position: null, upstream_id: 'upstream-a', attempt_count: 1,
|
||||
preemptions: 0, last_preempted_reason: null, cancel_requested: false, error: null,
|
||||
sync_warning: null, created_at: '2026-11-10T10:00:00Z', scheduled_at: null,
|
||||
started_at: '2026-11-10T10:00:02Z', finished_at: null, ...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('durable task updates', () => {
|
||||
beforeEach(() => setActivePinia(createPinia()))
|
||||
afterEach(() => { useJobsStore().reset(); vi.restoreAllMocks(); vi.unstubAllGlobals(); FakeEventSource.instances = [] })
|
||||
|
||||
it('accepts a higher-version running-to-queued preemption without inventing failure', () => {
|
||||
const store = useJobsStore()
|
||||
store.applyJob(job())
|
||||
store.applyJob(job({ version: 5, state: 'queued', phase: 'preempted', preemptions: 1,
|
||||
last_preempted_reason: 'external_gpu_usage', started_at: null }))
|
||||
expect(store.byId['job-a']?.state).toBe('queued')
|
||||
expect(store.byId['job-a']?.preemptions).toBe(1)
|
||||
expect(store.byId['job-a']?.error).toBeNull()
|
||||
})
|
||||
|
||||
it('discards older and equal versions so stale HTTP snapshots cannot undo SSE', () => {
|
||||
const store = useJobsStore()
|
||||
store.applyJob(job({ version: 8, state: 'succeeded', phase: 'completed', finished_at: '2026-11-10T10:03:00Z' }))
|
||||
store.ingestSnapshot([job({ version: 7 }), job({ version: 8, state: 'queued' })], 40)
|
||||
expect(store.byId['job-a']?.state).toBe('succeeded')
|
||||
expect(store.byId['job-a']?.version).toBe(8)
|
||||
})
|
||||
|
||||
it('keeps attempt progression and the same business ID through requeue', () => {
|
||||
const store = useJobsStore()
|
||||
store.applyJob(job({ version: 5, state: 'queued', preemptions: 1 }))
|
||||
store.applyJob(job({ version: 6, state: 'running', attempt_count: 2, preemptions: 1 }))
|
||||
expect(Object.keys(store.byId)).toEqual(['job-a'])
|
||||
expect(store.byId['job-a']?.attempt_count).toBe(2)
|
||||
expect(store.byId['job-a']?.progress).toBeNull()
|
||||
})
|
||||
|
||||
it('does not move the durable event cursor backwards on stale reconciliation', () => {
|
||||
const store = useJobsStore()
|
||||
store.ingestSnapshot([job()], 120)
|
||||
store.applyEvent(job({ version: 6, state: 'queued', preemptions: 1 }), 125)
|
||||
store.ingestSnapshot([job({ version: 5 })], 121)
|
||||
expect(store.cursor).toBe(125)
|
||||
expect(store.byId['job-a']?.version).toBe(6)
|
||||
expect(store.byId['job-a']?.state).toBe('queued')
|
||||
})
|
||||
|
||||
it('waits for a successful HTTP snapshot before opening the SSE stream', async () => {
|
||||
vi.stubGlobal('EventSource', FakeEventSource)
|
||||
vi.spyOn(api, 'jobs').mockRejectedValue(new Error('offline'))
|
||||
const store = useJobsStore()
|
||||
await store.connect()
|
||||
expect(FakeEventSource.instances).toHaveLength(0)
|
||||
expect(store.connection).toBe('reconnecting')
|
||||
})
|
||||
|
||||
it('starts from the snapshot cursor and reconciles HTTP after stream reconnection', async () => {
|
||||
vi.stubGlobal('EventSource', FakeEventSource)
|
||||
const fetchJobs = vi.spyOn(api, 'jobs').mockResolvedValue({ items: [job()], cursor: 40, total: 1, page: 1, page_size: 48 })
|
||||
const store = useJobsStore()
|
||||
await store.connect()
|
||||
const source = FakeEventSource.instances[0]!
|
||||
expect(source.url).toBe('/api/events?after=40')
|
||||
source.onopen?.()
|
||||
source.update(job({ version: 5, state: 'queued', preemptions: 1 }), 41)
|
||||
source.onopen?.()
|
||||
await vi.waitFor(() => expect(fetchJobs).toHaveBeenCalledTimes(2))
|
||||
expect(store.byId['job-a']?.state).toBe('queued')
|
||||
expect(store.byId['job-a']?.version).toBe(5)
|
||||
expect(store.cursor).toBe(41)
|
||||
})
|
||||
|
||||
it('closes the stream and rejects late events after signing out', async () => {
|
||||
vi.stubGlobal('EventSource', FakeEventSource)
|
||||
vi.spyOn(api, 'jobs').mockResolvedValue({ items: [job()], cursor: 40, total: 1, page: 1, page_size: 48 })
|
||||
const store = useJobsStore()
|
||||
await store.connect()
|
||||
const source = FakeEventSource.instances[0]!
|
||||
store.reset()
|
||||
source.update(job({ version: 9, state: 'succeeded' }), 50)
|
||||
expect(source.close).toHaveBeenCalledOnce()
|
||||
expect(store.byId).toEqual({})
|
||||
expect(store.cursor).toBe(0)
|
||||
})
|
||||
})
|
||||
94
frontend/src/stores/jobs.ts
Normal file
@ -0,0 +1,94 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { computed, ref } from 'vue'
|
||||
import { api } from '../api'
|
||||
import { isActive } from '../format'
|
||||
import type { Job, JobRequest } from '../types'
|
||||
import { useAssetsStore } from './assets'
|
||||
|
||||
export const useJobsStore = defineStore('jobs', () => {
|
||||
const byId = ref<Record<string, Job>>({})
|
||||
const cursor = ref(0)
|
||||
const connection = ref<'idle' | 'connecting' | 'live' | 'reconnecting'>('idle')
|
||||
const loaded = ref(false)
|
||||
const recent = computed(() => Object.values(byId.value).sort((a, b) => b.created_at.localeCompare(a.created_at)))
|
||||
const active = computed(() => recent.value.filter(isActive))
|
||||
let stream: EventSource | null = null
|
||||
let refreshPending: Promise<void> | null = null
|
||||
let epoch = 0
|
||||
let recoveryTimer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
function applyJob(job: Job) {
|
||||
const old = byId.value[job.id]
|
||||
if (old && old.version >= job.version) return false
|
||||
byId.value[job.id] = job
|
||||
const assets = useAssetsStore()
|
||||
for (const asset of job.result_assets || []) assets.upsert(asset)
|
||||
return true
|
||||
}
|
||||
function ingestSnapshot(jobs: Job[], after: number) {
|
||||
for (const job of jobs) applyJob(job)
|
||||
cursor.value = Math.max(cursor.value, after || 0)
|
||||
loaded.value = true
|
||||
}
|
||||
function applyEvent(job: Job, id: number) { applyJob(job); cursor.value = Math.max(cursor.value, id || 0) }
|
||||
function refresh() {
|
||||
if (refreshPending) return refreshPending
|
||||
const session = epoch
|
||||
const pending = api.jobs({ page_size: 48 }).then(response => {
|
||||
if (session === epoch) ingestSnapshot(response.items, response.cursor)
|
||||
}).finally(() => { if (refreshPending === pending) refreshPending = null })
|
||||
refreshPending = pending
|
||||
return refreshPending
|
||||
}
|
||||
async function fetchOne(id: string) { const session = epoch; const job = await api.job(id); if (session === epoch) applyJob(job); return job }
|
||||
async function submit(body: JobRequest) { const session = epoch; const response = await api.submit(body); if (session === epoch) response.jobs.forEach(applyJob); return response.jobs }
|
||||
async function cancel(id: string) { const session = epoch; const job = await api.cancel(id); if (session === epoch) applyJob(job); return job }
|
||||
async function retry(id: string) { const session = epoch; const response = await api.retry(id); if (session === epoch) response.jobs.forEach(applyJob); return response.jobs }
|
||||
function disconnect() {
|
||||
epoch++; stream?.close(); stream = null
|
||||
clearTimeout(recoveryTimer); connection.value = 'idle'
|
||||
refreshPending = null
|
||||
}
|
||||
function reset() { disconnect(); byId.value = {}; cursor.value = 0; loaded.value = false }
|
||||
async function connect() {
|
||||
if (stream || connection.value === 'connecting') return
|
||||
connection.value = 'connecting'
|
||||
const session = epoch
|
||||
try { await refresh() } catch {
|
||||
if (session === epoch) {
|
||||
connection.value = 'reconnecting'
|
||||
recoveryTimer = setTimeout(() => { void connect() }, 2000)
|
||||
}
|
||||
return
|
||||
}
|
||||
if (session !== epoch) return
|
||||
const source = new EventSource(`/api/events?after=${cursor.value}`, { withCredentials: true })
|
||||
stream = source
|
||||
let opened = false
|
||||
source.onopen = () => {
|
||||
if (session !== epoch) return
|
||||
connection.value = 'live'
|
||||
if (opened) { void refresh().catch(() => undefined); useAssetsStore().notifyRemote() }
|
||||
opened = true
|
||||
}
|
||||
const listen = (event: string, operation: (value: any, id: number) => void) => {
|
||||
source.addEventListener(event, ((message: MessageEvent<string>) => {
|
||||
if (session !== epoch) return
|
||||
try { operation(JSON.parse(message.data), Number(message.lastEventId) || 0) }
|
||||
catch { void refresh().catch(() => undefined) }
|
||||
}) as EventListener)
|
||||
}
|
||||
listen('job.updated', (value, id) => { if (value.job) applyEvent(value.job, id) })
|
||||
listen('asset.created', (value, id) => { useAssetsStore().upsert(value.asset); useAssetsStore().notifyRemote(); cursor.value = Math.max(cursor.value, id) })
|
||||
listen('asset.updated', (value, id) => { useAssetsStore().upsert(value.asset); useAssetsStore().notifyRemote(); cursor.value = Math.max(cursor.value, id) })
|
||||
listen('asset.deleted', (value, id) => { useAssetsStore().forget(value.id); useAssetsStore().notifyRemote(); cursor.value = Math.max(cursor.value, id) })
|
||||
listen('reset', () => { void refresh().catch(() => undefined); useAssetsStore().notifyRemote() })
|
||||
source.onerror = () => {
|
||||
if (session !== epoch) return
|
||||
connection.value = 'reconnecting'
|
||||
clearTimeout(recoveryTimer)
|
||||
recoveryTimer = setTimeout(() => { void refresh().catch(() => undefined) }, 2000)
|
||||
}
|
||||
}
|
||||
return { byId, cursor, connection, loaded, recent, active, applyJob, ingestSnapshot, applyEvent, refresh, fetchOne, submit, cancel, retry, connect, disconnect, reset }
|
||||
})
|
||||
18
frontend/src/style.css
Normal file
42
frontend/src/taskForms.test.ts
Normal file
@ -0,0 +1,42 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { buildToolRequest, composeFrameRates, isComposeFrameRateAllowed } from './taskForms'
|
||||
import type { Capability } from './types'
|
||||
|
||||
const composition: Capability = {
|
||||
task_type: 'video.compose', label: '成片合成', model: 'FFmpeg', available: true,
|
||||
input_types: ['video'], defaults: { width: 1280, height: 720, fps: 24 },
|
||||
constraints: { fps: { values: [24, 25, 30, 60] } }, description: '',
|
||||
}
|
||||
|
||||
describe('task-specific request contracts', () => {
|
||||
it('drops speech controls when the user switches from speech to image understanding', () => {
|
||||
const request = buildToolRequest('media.structure', '', {
|
||||
frame_count: 6, voice: 'zf_xiaobei', speed: 1.2,
|
||||
}, { id: 'owned-image', kind: 'image' })
|
||||
expect(request).toEqual({ task_type: 'media.structure', input: { asset_id: 'owned-image' }, parameters: { frame_count: 1 } })
|
||||
})
|
||||
|
||||
it('retains only the video-understanding sampling parameter from an old speech draft', () => {
|
||||
const request = buildToolRequest('media.structure', '', {
|
||||
frame_count: 8, voice: 'zm_yunxi', speed: 0.9,
|
||||
}, { id: 'owned-video', kind: 'video' })
|
||||
expect(request.parameters).toEqual({ frame_count: 8 })
|
||||
expect(request.input).toEqual({ asset_id: 'owned-video' })
|
||||
})
|
||||
|
||||
it('keeps voice and speed only on a speech request and drops other tool fields', () => {
|
||||
const request = buildToolRequest('audio.speech', ' 你好,创作。 ', {
|
||||
voice: 'zf_xiaobei', speed: 1, frame_count: 6, language: 'zh', max_tokens: 2048,
|
||||
})
|
||||
expect(request).toEqual({ task_type: 'audio.speech', input: { prompt: '你好,创作。' }, parameters: { voice: 'zf_xiaobei', speed: 1 } })
|
||||
})
|
||||
|
||||
it('uses the live discrete frame-rate contract instead of treating it as a numeric range', () => {
|
||||
expect(composeFrameRates(composition)).toEqual([24, 25, 30, 60])
|
||||
expect(isComposeFrameRateAllowed(26, composition)).toBe(false)
|
||||
expect(isComposeFrameRateAllowed(25, composition)).toBe(true)
|
||||
const limited = { ...composition, constraints: { fps: { values: [30] } } }
|
||||
expect(composeFrameRates(limited)).toEqual([30])
|
||||
expect(isComposeFrameRateAllowed(24, limited)).toBe(false)
|
||||
})
|
||||
})
|
||||
34
frontend/src/taskForms.ts
Normal file
@ -0,0 +1,34 @@
|
||||
import type { Asset, Capability, JobRequest, TaskType } from './types'
|
||||
|
||||
const toolFields: Partial<Record<TaskType, readonly string[]>> = {
|
||||
'math.solve': ['max_tokens'],
|
||||
'media.structure': ['frame_count'],
|
||||
'audio.transcribe': ['language', 'max_audio_seconds'],
|
||||
'audio.speech': ['voice', 'speed'],
|
||||
}
|
||||
|
||||
/** Build the actual request boundary, independent of which tool was visible before. */
|
||||
export function buildToolRequest(taskType: TaskType, prompt: string, values: Record<string, any>, asset: Pick<Asset, 'id' | 'kind'> | null = null): JobRequest {
|
||||
const fields = toolFields[taskType]
|
||||
if (!fields) throw new Error('当前任务不属于素材与文本工具')
|
||||
const parameters = Object.fromEntries(fields.filter(field => values[field] !== undefined).map(field => [field, values[field]]))
|
||||
const input: Record<string, string> = {}
|
||||
if (taskType === 'math.solve' || taskType === 'audio.speech') input.prompt = prompt.trim()
|
||||
else {
|
||||
if (!asset) throw new Error('请先选择或上传素材')
|
||||
input[taskType === 'audio.transcribe' ? 'audio_asset_id' : 'asset_id'] = asset.id
|
||||
if (taskType === 'media.structure' && asset.kind === 'image') parameters.frame_count = 1
|
||||
}
|
||||
return { task_type: taskType, input, parameters }
|
||||
}
|
||||
|
||||
export function composeFrameRates(capability?: Capability): number[] {
|
||||
const values = capability?.constraints.fps?.values
|
||||
if (Array.isArray(values)) return [...new Set(values.filter((value): value is number => typeof value === 'number' && Number.isInteger(value) && value > 0))]
|
||||
const fallback = capability?.defaults.fps
|
||||
return typeof fallback === 'number' && Number.isInteger(fallback) && fallback > 0 ? [fallback] : []
|
||||
}
|
||||
|
||||
export function isComposeFrameRateAllowed(value: unknown, capability?: Capability) {
|
||||
return typeof value === 'number' && composeFrameRates(capability).includes(value)
|
||||
}
|
||||
35
frontend/src/types.ts
Normal file
@ -0,0 +1,35 @@
|
||||
export type TaskType = 'image.generate' | 'video.generate' | 'defect.generate' | 'audio.transcribe' | 'audio.speech' | 'math.solve' | 'media.structure' | 'video.compose'
|
||||
export type AssetKind = 'image' | 'video' | 'audio' | 'text' | 'json'
|
||||
export type JobState = 'scheduled' | 'submitting' | 'queued' | 'running' | 'collecting' | 'cancelling' | 'succeeded' | 'failed' | 'cancelled' | 'timed_out'
|
||||
export interface User { id: string; username: string; display_name: string; role: string }
|
||||
export interface AuthResponse { user: User; csrf_token: string }
|
||||
export interface Asset {
|
||||
id: string; name: string; kind: AssetKind; mime_type: string; size_bytes: number
|
||||
width: number | null; height: number | null; duration_seconds: number | null
|
||||
preview_url: string; thumbnail_url: string | null; download_url: string
|
||||
source_job_id: string | null; origin: 'upload' | 'generated'; tags: string[]; favorite: boolean; created_at: string
|
||||
}
|
||||
export interface NumericConstraint { min?: number; max?: number; step?: number; values?: (string | number)[] }
|
||||
export interface Capability {
|
||||
task_type: TaskType; label: string; model: string; available: boolean; input_types: string[]
|
||||
defaults: Record<string, any>; constraints: Record<string, any>; description: string
|
||||
}
|
||||
export interface Scheduler {
|
||||
available: boolean; state: string; reason: string | null
|
||||
gpus: { index: number; name: string; busy: boolean; eligible: boolean; free_gib: number | null }[]
|
||||
updated_at: string | null
|
||||
}
|
||||
export interface Job {
|
||||
id: string; task_type: TaskType; state: JobState; phase: string; version: number; prompt: string
|
||||
parameters: Record<string, any>; input_asset_ids: string[]; result_assets: Asset[]; result: Record<string, any> | null
|
||||
progress: number | null; queue_position: number | null; upstream_id: string | null
|
||||
attempt_count: number; preemptions: number; last_preempted_reason: string | null; cancel_requested: boolean
|
||||
error: { code: string; message: string; retriable: boolean } | null; sync_warning: string | null
|
||||
created_at: string; scheduled_at: string | null; started_at: string | null; finished_at: string | null
|
||||
}
|
||||
export interface JobRequest {
|
||||
task_type: TaskType; input: Record<string, any>; parameters: Record<string, any>; count?: number; scheduled_at?: string | null
|
||||
}
|
||||
export interface Page<T> { items: T[]; total: number; page: number; page_size: number }
|
||||
export interface JobsPage extends Page<Job> { cursor: number }
|
||||
export interface CapabilitiesResponse { items: Capability[]; scheduler: Scheduler }
|
||||
29
frontend/src/views/AssetsView.vue
Normal file
@ -0,0 +1,29 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { Search, Upload, Star, StarFilled, VideoPlay, Headset, Document, FolderOpened } from '@element-plus/icons-vue'
|
||||
import { api, errorMessage } from '../api'
|
||||
import { useAssetsStore } from '../stores/assets'
|
||||
import type { Asset, AssetKind } from '../types'
|
||||
import { formatBytes, formatDuration } from '../format'
|
||||
import AssetPreview from '../components/AssetPreview.vue'
|
||||
const store = useAssetsStore(), ids = ref<string[]>([]), total = ref(0), page = ref(1), q = ref(''), tag = ref(''), kind = ref(''), loading = ref(false), uploading = ref(false), selected = ref<Asset | null>(null), fileInput = ref<HTMLInputElement>()
|
||||
const items = computed(() => ids.value.map(id => store.byId[id]).filter((asset): asset is Asset => !!asset))
|
||||
let requestVersion = 0, timer: ReturnType<typeof setTimeout> | undefined
|
||||
async function load() { const version = ++requestVersion; loading.value = true; try { const result = await api.assets({ page: page.value, page_size: 24, q: q.value, kind: kind.value, tag: tag.value }); if (version !== requestVersion) return; result.items.forEach(store.upsert); ids.value = result.items.map(item => item.id); total.value = result.total } catch (error) { ElMessage.error(errorMessage(error)) } finally { if (version === requestVersion) loading.value = false } }
|
||||
function search() { page.value = 1; void load() }
|
||||
async function upload(event: Event) { const input = event.target as HTMLInputElement, files = Array.from(input.files || []); if (!files.length) return; uploading.value = true; try { for (const file of files) await store.upload(file); ElMessage.success(`已上传 ${files.length} 个素材`); await load() } catch (error) { ElMessage.error(errorMessage(error)) } finally { uploading.value = false; input.value = '' } }
|
||||
async function star(asset: Asset) { try { await store.update(asset.id, { favorite: !asset.favorite }) } catch (error) { ElMessage.error(errorMessage(error)) } }
|
||||
// SSE updates refresh the current HTTP filter, without a request loop from our own upserts.
|
||||
watch(() => store.remoteRevision, () => { clearTimeout(timer); timer = setTimeout(() => { void load() }, 400) })
|
||||
onMounted(load); onBeforeUnmount(() => { clearTimeout(timer); requestVersion++ })
|
||||
</script>
|
||||
<template>
|
||||
<div class="library-page"><header class="page-heading split-heading"><div><span class="eyebrow">YOUR CREATIVE COLLECTION</span><h1>每个好画面,都值得留下。</h1><p>管理你的上传与生成产物,让灵感在下一次创作中继续生长。</p></div><el-button type="primary" :icon="Upload" :loading="uploading" @click="fileInput?.click()">上传素材</el-button><input ref="fileInput" type="file" multiple hidden @change="upload" /></header>
|
||||
<div class="library-toolbar"><div class="filter-tabs"><button v-for="option in [{value:'',label:'全部素材'},{value:'image',label:'图片'},{value:'video',label:'视频'},{value:'audio',label:'音频'},{value:'text',label:'文本'},{value:'json',label:'结构数据'}]" :key="option.value" :class="{ active: kind === option.value }" @click="kind = option.value; search()">{{ option.label }}</button></div><div class="library-search"><el-input v-model="tag" placeholder="筛选标签" clearable @keyup.enter="search" @clear="search" /><el-input v-model="q" :prefix-icon="Search" placeholder="搜索素材名称" clearable @keyup.enter="search" @clear="search" /><el-button :icon="Search" @click="search">搜索</el-button></div></div>
|
||||
<div v-loading="loading" class="asset-library-grid"><article v-for="asset in items" :key="asset.id" class="library-card"><button class="library-media" @click="selected = asset"><img v-if="asset.kind === 'image' || asset.thumbnail_url" :src="asset.thumbnail_url || asset.preview_url" :alt="asset.name" loading="lazy" /><video v-else-if="asset.kind === 'video'" :src="asset.preview_url" preload="metadata" muted /><div v-else class="file-cover"><el-icon :size="38"><Headset v-if="asset.kind === 'audio'" /><Document v-else /></el-icon></div><span v-if="asset.kind === 'video'" class="media-duration"><el-icon><VideoPlay /></el-icon>{{ formatDuration(asset.duration_seconds) }}</span></button><button class="favorite-button" :class="{ selected: asset.favorite }" :aria-label="asset.favorite ? '取消收藏' : '收藏素材'" @click="star(asset)"><el-icon><StarFilled v-if="asset.favorite" /><Star v-else /></el-icon></button><div class="library-caption"><button @click="selected = asset">{{ asset.name }}</button><div><span>{{ asset.width ? `${asset.width} × ${asset.height}` : asset.kind.toUpperCase() }}</span><span>{{ formatBytes(asset.size_bytes) }}</span></div><div v-if="asset.tags.length" class="asset-tag-row"><span v-for="label in asset.tags.slice(0, 3)" :key="label" @click="tag = label; search()">{{ label }}</span></div></div></article>
|
||||
<div v-if="!loading && !items.length" class="empty-state full-empty"><el-icon :size="42"><FolderOpened /></el-icon><h3>{{ q || tag || kind ? '没有找到符合条件的素材' : '你的素材库,等待第一份灵感' }}</h3><p>{{ q || tag || kind ? '换一个关键词或类型,继续寻找。' : '上传已有素材,或去创作工作台生成你的第一张作品。' }}</p><el-button v-if="!q && !tag && !kind" type="primary" @click="fileInput?.click()">上传第一份素材</el-button></div>
|
||||
</div><el-pagination v-if="total > 24" v-model:current-page="page" :page-size="24" :total="total" layout="total, prev, pager, next" @current-change="load" />
|
||||
<AssetPreview v-model:asset="selected" @deleted="load" />
|
||||
</div>
|
||||
</template>
|
||||
50
frontend/src/views/ComposeView.vue
Normal file
@ -0,0 +1,50 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { Plus, ArrowUp, ArrowDown, Delete, Film, Scissor, MagicStick, ArrowRight } from '@element-plus/icons-vue'
|
||||
import { useAssetsStore } from '../stores/assets'
|
||||
import { useCapabilitiesStore } from '../stores/capabilities'
|
||||
import { useJobsStore } from '../stores/jobs'
|
||||
import { errorMessage, newRequestId } from '../api'
|
||||
import { composeFrameRates, isComposeFrameRateAllowed } from '../taskForms'
|
||||
import type { Asset } from '../types'
|
||||
import { formatDuration, phaseLabel, stateLabel } from '../format'
|
||||
import AssetInput from '../components/AssetInput.vue'
|
||||
import AssetPicker from '../components/AssetPicker.vue'
|
||||
import AssetPreview from '../components/AssetPreview.vue'
|
||||
import JobDetail from '../components/JobDetail.vue'
|
||||
interface Clip { key: string; asset: Asset; start: number; end: number | null }
|
||||
const route=useRoute(), assets=useAssetsStore(), caps=useCapabilitiesStore(), jobs=useJobsStore(), clips=ref<Clip[]>([]), picker=ref(false), selected=ref(0), audio=ref<Asset|null>(null), subtitles=ref<{start:number;end:number;text:string}[]>([]), busy=ref(false), lastJobId=ref<string|null>(null), detailId=ref<string|null>(null), preview=ref<Asset|null>(null)
|
||||
const capability=computed(()=>caps.forTask('video.compose')), parameters=ref<Record<string,any>>({}), activeClip=computed(()=>clips.value[selected.value]), job=computed(()=>lastJobId.value?jobs.byId[lastJobId.value]:undefined)
|
||||
const frameRates=computed(()=>composeFrameRates(capability.value))
|
||||
const totalDuration=computed(()=>clips.value.reduce((total,clip)=>total+Math.max(0,(clip.end??clip.asset.duration_seconds??0)-clip.start),0))
|
||||
let dragged=-1
|
||||
watch(()=>capability.value?.defaults, defaults=>{if(defaults)parameters.value={...defaults,...parameters.value}}, {immediate:true})
|
||||
watch(frameRates, values=>{if(!values.includes(parameters.value.fps)){const fallback=capability.value?.defaults.fps;parameters.value.fps=values.includes(fallback)?fallback:values[0]}}, {immediate:true})
|
||||
function addClip(asset:Asset){clips.value.push({key:newRequestId(),asset,start:0,end:asset.duration_seconds});selected.value=clips.value.length-1}
|
||||
function move(index:number,target:number){if(target<0||target>=clips.value.length)return;const [clip]=clips.value.splice(index,1);if(clip)clips.value.splice(target,0,clip);selected.value=target}
|
||||
function remove(index:number){clips.value.splice(index,1);selected.value=Math.min(selected.value,Math.max(0,clips.value.length-1))}
|
||||
function addSubtitle(){subtitles.value.push({start:0,end:Math.min(totalDuration.value||5,5),text:''})}
|
||||
async function submit(){
|
||||
if(busy.value)return
|
||||
if(!capability.value?.available){ElMessage.warning('成片服务尚未就绪');return}
|
||||
if(!clips.value.length){ElMessage.warning('先添加至少一个视频片段');return}
|
||||
if(!isComposeFrameRateAllowed(parameters.value.fps,capability.value)){ElMessage.warning('请选择服务支持的导出帧率');return}
|
||||
for(const clip of clips.value)if(!Number.isFinite(clip.start)||clip.start<0||(clip.end!==null&&(!Number.isFinite(clip.end)||clip.end<=clip.start))){ElMessage.warning('请检查片段入点和出点,出点需要晚于入点');return}
|
||||
for(const subtitle of subtitles.value)if(!subtitle.text.trim()||subtitle.end<=subtitle.start||subtitle.start<0){ElMessage.warning('请补全字幕文字及正确的时间范围');return}
|
||||
busy.value=true
|
||||
try{const input:Record<string,any>={asset_ids:clips.value.map(clip=>clip.asset.id)};if(audio.value)input.audio_asset_id=audio.value.id;const created=await jobs.submit({task_type:'video.compose',input,parameters:{...parameters.value,clips:clips.value.map(clip=>({asset_id:clip.asset.id,start_seconds:clip.start,...(clip.end===null?{}:{end_seconds:clip.end})})),subtitles:subtitles.value.map(row=>({...row,text:row.text.trim()}))}});lastJobId.value=created[0]?.id||null;ElMessage.success('成片合成任务已提交')}
|
||||
catch(error){ElMessage.error(errorMessage(error))}finally{busy.value=false}
|
||||
}
|
||||
async function importClip(){if(typeof route.query.asset!=='string')return;try{const asset=await assets.get(route.query.asset);if(asset.kind==='video')addClip(asset);else ElMessage.warning('请添加视频素材进行片段编排')}catch(error){ElMessage.error(errorMessage(error))}}
|
||||
watch(()=>route.query.asset,importClip);onMounted(importClip)
|
||||
</script>
|
||||
<template>
|
||||
<div class="compose-page"><header class="page-heading split-heading"><div><span class="eyebrow">MAKE YOUR STORY WHOLE</span><h1>让好片段,成为一个故事。</h1><p>调整片段顺序、裁切与人工字幕,用 FFmpeg 完成清晰可控的成片。</p></div><el-button type="primary" :icon="MagicStick" :loading="busy" :disabled="!capability?.available" @click="submit">导出成片 <el-icon><ArrowRight /></el-icon></el-button></header>
|
||||
<div class="compose-layout"><section class="compose-main"><div class="compose-preview"><video v-if="activeClip" :key="activeClip.key" :src="activeClip.asset.preview_url" :poster="activeClip.asset.thumbnail_url||undefined" controls playsinline /><div v-else class="empty-state"><el-icon :size="46"><Film /></el-icon><h3>把你的片段,带到这里</h3><p>从素材库选择视频,或上传已有作品。</p><el-button :icon="Plus" @click="picker=true">添加视频片段</el-button></div></div><div class="timeline-heading"><h2>片段编排 <span>{{ clips.length }} 段 · {{ formatDuration(totalDuration) }}</span></h2><el-button :icon="Plus" @click="picker=true">添加片段</el-button></div><div class="timeline-strip"><article v-for="(clip,index) in clips" :key="clip.key" class="clip-card" :class="{selected:selected===index}" draggable="true" @dragstart="dragged=index" @dragover.prevent @drop.prevent="move(dragged,index)" @click="selected=index"><div class="clip-thumbnail"><img v-if="clip.asset.thumbnail_url" :src="clip.asset.thumbnail_url" :alt="clip.asset.name" /><video v-else :src="clip.asset.preview_url" muted preload="metadata" /><span>{{ String(index+1).padStart(2,'0') }}</span></div><strong>{{ clip.asset.name }}</strong><small>{{ formatDuration((clip.end??clip.asset.duration_seconds??0)-clip.start) }}</small><div class="clip-actions"><el-button text :icon="ArrowUp" :disabled="index===0" aria-label="片段前移" @click.stop="move(index,index-1)"/><el-button text :icon="ArrowDown" :disabled="index===clips.length-1" aria-label="片段后移" @click.stop="move(index,index+1)"/><el-button text type="danger" :icon="Delete" aria-label="移除片段" @click.stop="remove(index)"/></div></article><button class="add-clip-card" @click="picker=true"><el-icon><Plus /></el-icon><span>添加片段</span></button></div><small class="muted">拖动调整顺序,或使用前移 / 后移按钮。当前采用直切拼接。</small>
|
||||
<section v-if="job" class="compose-job surface"><span class="status-pill" :class="job.state">{{ stateLabel(job) }}</span><span>{{ phaseLabel(job) }}</span><button class="text-link" @click="detailId=job.id">查看任务</button><el-button v-for="asset in job.result_assets.filter(item=>item.kind==='video')" :key="asset.id" type="primary" @click="preview=asset">预览成片</el-button></section>
|
||||
</section><aside class="compose-settings surface"><div class="panel-heading"><h2>导出设置</h2><span class="tiny-model">FFmpeg</span></div><div class="parameter-form"><label>输出宽度<el-input-number v-model="parameters.width" :min="capability?.constraints.width?.min||256" :max="capability?.constraints.width?.max||3840" :step="2" /></label><label>输出高度<el-input-number v-model="parameters.height" :min="capability?.constraints.height?.min||256" :max="capability?.constraints.height?.max||2160" :step="2" /></label><label>帧率<el-select v-model="parameters.fps" placeholder="选择导出帧率" aria-label="导出帧率"><el-option v-for="fps in frameRates" :key="fps" :value="fps" :label="`${fps} fps`" /></el-select></label></div><template v-if="activeClip"><h3 class="settings-subheading">当前片段裁切</h3><div class="parameter-form"><label>入点(秒)<el-input-number v-model="activeClip.start" :min="0" :max="activeClip.asset.duration_seconds||86400" :precision="2" :step="0.1" /></label><label>出点(秒)<el-input-number v-model="activeClip.end" :min="0" :max="activeClip.asset.duration_seconds||86400" :precision="2" :step="0.1" /></label></div></template><h3 class="settings-subheading">音轨(可选)</h3><AssetInput v-model="audio" :kinds="['audio']" label="添加音轨" hint="上传或选择你的音频素材" /><h3 class="settings-subheading subtitle-heading">人工字幕<el-button text :icon="Plus" @click="addSubtitle">添加</el-button></h3><div v-for="(row,index) in subtitles" :key="index" class="subtitle-row"><div><el-input-number v-model="row.start" :min="0" :step="0.1" :precision="1" :controls="false" aria-label="字幕开始秒数"/><span>—</span><el-input-number v-model="row.end" :min="0" :step="0.1" :precision="1" :controls="false" aria-label="字幕结束秒数"/><el-button text :icon="Delete" aria-label="删除字幕" @click="subtitles.splice(index,1)"/></div><el-input v-model="row.text" type="textarea" :rows="2" placeholder="字幕文字" /></div><p v-if="!subtitles.length" class="muted small">字幕由你填写,不将分块转写时间冒充逐词对齐。</p><div v-if="!capability?.available" class="notice warning">{{ capability?.description||'正在确认成片服务能力' }}</div></aside></div>
|
||||
<AssetPicker v-model="picker" :kinds="['video']" @select="addClip"/><AssetPreview v-model:asset="preview"/><JobDetail v-model:job-id="detailId"/>
|
||||
</div>
|
||||
</template>
|
||||
13
frontend/src/views/LoginView.vue
Normal file
@ -0,0 +1,13 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { ArrowRight, Lock, User } from '@element-plus/icons-vue'
|
||||
import { useAuthStore } from '../stores/auth'
|
||||
import { errorMessage } from '../api'
|
||||
const auth=useAuthStore(),route=useRoute(),router=useRouter(),username=ref(''),password=ref(''),busy=ref(false),error=ref('')
|
||||
async function login(){if(busy.value)return;if(!username.value.trim()||!password.value){error.value='请输入账号和密码';return}busy.value=true;error.value='';try{await auth.login(username.value.trim(),password.value);const target=route.query.redirect;await router.replace(typeof target==='string'&&target.startsWith('/')&&!target.startsWith('//')?target:'/create/image')}catch(caught){error.value=errorMessage(caught)}finally{busy.value=false}}
|
||||
</script>
|
||||
<template>
|
||||
<main class="login-page"><div class="login-art"><img src="/inspiration/qwen-image.png" alt="本地 Qwen-Image 模型生成的红釉茶壶验收样例"/><div class="login-art-overlay"/><a class="login-brand" href="/"><span class="brand-glyph">V</span><strong>CMVR<span>VISUAL STUDIO</span></strong></a><div class="login-art-copy"><span class="eyebrow">FROM A SPARK TO A SCENE</span><h1>灵感有形,<br/>创作无界。</h1><p>把想法交给画面。<br/>在自己的工作空间,创造下一种可能。</p><span class="sample-label">本地模型验收样例 · Qwen-Image</span></div></div><section class="login-form-section"><div class="login-form-box"><span class="eyebrow">WELCOME TO YOUR STUDIO</span><h2>回到创作的地方。</h2><p>登录你的 CMVR Visual 工作空间</p><el-form @submit.prevent="login" label-position="top"><el-form-item label="账号"><el-input v-model="username" :prefix-icon="User" placeholder="输入你的账号" autocomplete="username" size="large" /></el-form-item><el-form-item label="密码"><el-input v-model="password" :prefix-icon="Lock" type="password" placeholder="输入密码" autocomplete="current-password" show-password size="large" @keyup.enter="login"/></el-form-item><div v-if="error" class="login-error" role="alert">{{ error }}</div><el-button type="primary" size="large" :loading="busy" class="login-submit" native-type="submit">进入工作空间<el-icon><ArrowRight /></el-icon></el-button></el-form><p class="login-help">账号由工作空间管理员创建。<br/>素材与任务仅在登录后的个人空间内展示。</p></div><footer>CMVR VISUAL · LOCAL CREATIVE WORKSPACE</footer></section></main>
|
||||
</template>
|
||||
29
frontend/src/views/TasksView.vue
Normal file
@ -0,0 +1,29 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { RefreshRight, ArrowRight, Close, Clock, Collection, VideoCamera, Picture, Document } from '@element-plus/icons-vue'
|
||||
import { api, errorMessage } from '../api'
|
||||
import { useJobsStore } from '../stores/jobs'
|
||||
import { formatDate, isActive, phaseLabel, stateLabel, taskLabels } from '../format'
|
||||
import type { Job } from '../types'
|
||||
import JobDetail from '../components/JobDetail.vue'
|
||||
const store = useJobsStore(), route = useRoute(), ids = ref<string[]>([]), total = ref(0), page = ref(1), state = ref(''), taskType = ref(''), loading = ref(false), detailId = ref<string | null>(null), pendingId = ref<string | null>(null)
|
||||
const items = computed(() => ids.value.map(id => store.byId[id]).filter((item): item is Job => !!item))
|
||||
let generation = 0, timer: ReturnType<typeof setTimeout> | undefined
|
||||
async function load() { const request = ++generation; loading.value = true; try { const result = await api.jobs({ page: page.value, page_size: 20, task_type: taskType.value, state: state.value }); if (request !== generation) return; store.ingestSnapshot(result.items, result.cursor); ids.value = result.items.map(job => job.id); total.value = result.total } catch (error) { ElMessage.error(errorMessage(error)) } finally { if (request === generation) loading.value = false } }
|
||||
function filter() { page.value = 1; void load() }
|
||||
async function cancel(job: Job) { pendingId.value = job.id; try { await store.cancel(job.id); ElMessage.success('取消请求已提交'); await load() } catch (error) { ElMessage.error(errorMessage(error)) } finally { pendingId.value = null } }
|
||||
async function retry(job: Job) { pendingId.value = job.id; try { const created = await store.retry(job.id); detailId.value = created[0]?.id || null; ElMessage.success('已创建新的生成任务'); await load() } catch (error) { ElMessage.error(errorMessage(error)) } finally { pendingId.value = null } }
|
||||
watch(() => store.cursor, () => { clearTimeout(timer); timer = setTimeout(() => { void load() }, 500) })
|
||||
watch(() => route.query.job, id => { if (typeof id === 'string') detailId.value = id }, { immediate: true })
|
||||
onMounted(load); onBeforeUnmount(() => { generation++; clearTimeout(timer) })
|
||||
</script>
|
||||
<template>
|
||||
<div class="tasks-page"><header class="page-heading split-heading"><div><span class="eyebrow">EVERY IDEA HAS A JOURNEY</span><h1>每次创作,都有迹可循。</h1><p>查看排队、生成与自动让行记录,让长时间创作也保持清晰。</p></div><el-button :icon="RefreshRight" :loading="loading" @click="load">同步任务</el-button></header>
|
||||
<div class="task-policy-note"><span class="live-dot" /> GPU任务串行执行,外部使用优先。让行后保留任务身份,等待空闲算力自动重试。</div>
|
||||
<div class="library-toolbar"><div class="filter-tabs"><button v-for="option in [{value:'',label:'全部任务'},{value:'queued',label:'排队中'},{value:'running',label:'创作中'},{value:'succeeded',label:'已完成'},{value:'failed',label:'失败'}]" :key="option.value" :class="{active:state===option.value}" @click="state=option.value;filter()">{{ option.label }}</button></div><div class="task-filter-selects"><el-select v-model="taskType" placeholder="全部类型" clearable @change="filter"><el-option v-for="(label,key) in taskLabels" :key="key" :label="label" :value="key" /></el-select><el-select v-model="state" placeholder="全部状态" clearable @change="filter"><el-option v-for="(label,key) in {scheduled:'预约中',submitting:'提交中',queued:'排队中',running:'执行中',collecting:'归档中',cancelling:'取消中',succeeded:'已完成',failed:'失败',cancelled:'已取消',timed_out:'已超时'}" :key="key" :label="label" :value="key" /></el-select></div></div>
|
||||
<div class="task-list" v-loading="loading"><article v-for="job in items" :key="job.id" class="task-row"><button class="task-thumb" @click="detailId=job.id"><img v-if="job.result_assets.find(a=>a.kind==='image'||a.thumbnail_url)" :src="job.result_assets.find(a=>a.kind==='image'||a.thumbnail_url)?.thumbnail_url || job.result_assets.find(a=>a.kind==='image'||a.thumbnail_url)?.preview_url" :alt="job.prompt" /><el-icon v-else :size="24"><VideoCamera v-if="job.task_type.includes('video')" /><Picture v-else-if="job.task_type.includes('image')||job.task_type.includes('defect')" /><Document v-else /></el-icon></button><div class="task-main"><div class="task-title-line"><span class="task-type">{{ taskLabels[job.task_type] }}</span><span class="status-pill" :class="job.state">{{ stateLabel(job) }}</span><small v-if="job.attempt_count>1">第 {{ job.attempt_count }} 次尝试</small></div><button class="task-title" @click="detailId=job.id">{{ job.prompt || taskLabels[job.task_type] }}</button><p :class="{'warning-text':job.sync_warning||job.preemptions}">{{ phaseLabel(job) }}</p><small>{{ formatDate(job.created_at) }} <span v-if="job.preemptions"> · 已让行 {{ job.preemptions }} 次</span></small></div><div class="task-row-actions"><el-button v-if="isActive(job)" text :icon="Close" :loading="pendingId===job.id" :disabled="job.cancel_requested" @click="cancel(job)">{{ job.cancel_requested?'正在取消':'取消' }}</el-button><el-button v-else text :icon="RefreshRight" :loading="pendingId===job.id" @click="retry(job)">{{ job.state==='succeeded'?'再生成':'重试' }}</el-button><el-button text :icon="ArrowRight" @click="detailId=job.id">详情</el-button></div></article><div v-if="!loading&&!items.length" class="empty-state full-empty"><el-icon :size="42"><Collection /></el-icon><h3>这里还没有符合条件的任务</h3><p>去工作台提交一次创作,进度和最终结果都会在这里同步。</p><router-link to="/create/image" class="el-button el-button--primary">开始第一项创作</router-link></div></div>
|
||||
<el-pagination v-if="total>20" v-model:current-page="page" :page-size="20" :total="total" layout="total, prev, pager, next" @current-change="load" /><JobDetail v-model:job-id="detailId" />
|
||||
</div>
|
||||
</template>
|
||||
71
frontend/src/views/ToolsView.vue
Normal file
@ -0,0 +1,71 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { ArrowRight, MagicStick, CopyDocument, Document, Headset, DataAnalysis, RefreshRight } from '@element-plus/icons-vue'
|
||||
import { useCapabilitiesStore } from '../stores/capabilities'
|
||||
import { useDraftsStore } from '../stores/drafts'
|
||||
import { useJobsStore } from '../stores/jobs'
|
||||
import { useAssetsStore } from '../stores/assets'
|
||||
import { copyText, formatDate, phaseLabel, stateLabel } from '../format'
|
||||
import { errorMessage } from '../api'
|
||||
import { buildToolRequest } from '../taskForms'
|
||||
import type { Asset, TaskType } from '../types'
|
||||
import AssetInput from '../components/AssetInput.vue'
|
||||
import AssetPreview from '../components/AssetPreview.vue'
|
||||
import JobDetail from '../components/JobDetail.vue'
|
||||
import MathText from '../components/MathText.vue'
|
||||
const route = useRoute(), caps = useCapabilitiesStore(), drafts = useDraftsStore(), jobs = useJobsStore(), assets = useAssetsStore()
|
||||
const audioMode = ref<'transcribe' | 'speech'>('transcribe')
|
||||
const kind = computed(() => route.path === '/math' ? 'math' : route.path === '/analyze' ? 'analyze' : 'audio')
|
||||
const taskType = computed<TaskType>(() => kind.value === 'math' ? 'math.solve' : kind.value === 'analyze' ? 'media.structure' : audioMode.value === 'speech' ? 'audio.speech' : 'audio.transcribe')
|
||||
const capability = computed(() => caps.forTask(taskType.value)), draft = computed(() => drafts.forTask(taskType.value, capability.value?.defaults))
|
||||
const reference = ref<Asset | null>(null), busy = ref(false), selectedId = ref<string | null>(null), detailId = ref<string | null>(null), preview = ref<Asset | null>(null)
|
||||
const history = computed(() => jobs.recent.filter(job => job.task_type === taskType.value).slice(0, 20))
|
||||
const current = computed(() => selectedId.value ? jobs.byId[selectedId.value] : history.value[0])
|
||||
const title = computed(() => kind.value === 'math' ? '让每一步推演,都清晰可见。' : kind.value === 'analyze' ? '读懂画面,也读懂素材。' : '让声音,成为创作的一部分。')
|
||||
const subtitle = computed(() => kind.value === 'math' ? '数学问题交给推理,把精力留给理解与思考。' : kind.value === 'analyze' ? '提取主体、场景和画面文字,把存量素材变成可理解的信息。' : '从音频和视频中整理文字,或使用已配置的真实配音服务。')
|
||||
const textResult = computed(() => current.value?.result?.text ? String(current.value.result.text) : '')
|
||||
const analysis = computed(() => current.value?.result || {})
|
||||
const languages = computed(() => capability.value?.constraints.language?.values || ['zh', 'en', 'auto'])
|
||||
const voices = computed(() => capability.value?.constraints.voice?.values || [])
|
||||
function limit(key: string, edge: string, fallback: number) { return capability.value?.constraints[key]?.[edge] ?? fallback }
|
||||
function renderValue(value: unknown) { return typeof value === 'string' ? value : JSON.stringify(value) }
|
||||
async function submit() {
|
||||
if (busy.value) return
|
||||
if (!capability.value?.available) { ElMessage.warning('此能力尚未配置,请先使用已就绪的功能'); return }
|
||||
if (['math.solve', 'audio.speech'].includes(taskType.value) && !draft.value.prompt.trim()) { ElMessage.warning('请输入需要处理的文字'); return }
|
||||
if (['audio.transcribe', 'media.structure'].includes(taskType.value) && !reference.value) { ElMessage.warning('请先选择或上传素材'); return }
|
||||
if (taskType.value === 'audio.speech' && !draft.value.parameters.voice?.trim()) { ElMessage.warning('请填写真实服务支持的音色名称'); return }
|
||||
busy.value = true
|
||||
try { const created = await jobs.submit(buildToolRequest(taskType.value, draft.value.prompt, draft.value.parameters, reference.value)); selectedId.value = created[0]?.id || null; ElMessage.success('任务已提交,结果将在此同步') }
|
||||
catch (error) { ElMessage.error(errorMessage(error)) } finally { busy.value = false }
|
||||
}
|
||||
async function copy() { if (!textResult.value) return; try { await copyText(textResult.value); ElMessage.success('结果已复制') } catch { ElMessage.warning('请手动选择文本复制') } }
|
||||
async function importAsset() { if (typeof route.query.asset !== 'string') return; try { reference.value = await assets.get(route.query.asset) } catch (error) { ElMessage.error(errorMessage(error)) } }
|
||||
watch(() => kind.value, () => { selectedId.value = null; reference.value = null; if (kind.value !== 'audio') audioMode.value = 'transcribe'; void importAsset() })
|
||||
watch(() => audioMode.value, () => { selectedId.value = null })
|
||||
watch(() => route.query.asset, importAsset)
|
||||
onMounted(() => { void jobs.refresh().catch(() => undefined); void importAsset() })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="tool-page">
|
||||
<header class="page-heading"><span class="eyebrow">{{ kind === 'math' ? 'REASONING SPACE' : kind === 'analyze' ? 'UNDERSTAND YOUR MEDIA' : 'AUDIO WORKSPACE' }}</span><h1>{{ title }}</h1><p>{{ subtitle }}</p></header>
|
||||
<div v-if="kind === 'audio'" class="mode-switch audio-tabs"><button :class="{ active: audioMode === 'transcribe' }" @click="audioMode = 'transcribe'">语音转写</button><button :class="{ active: audioMode === 'speech' }" @click="audioMode = 'speech'">配音生成 <small v-if="!caps.forTask('audio.speech')?.available">待配置</small></button></div>
|
||||
<div class="tool-columns"><section class="tool-input-panel surface"><div class="panel-heading"><h2>{{ kind === 'math' ? '写下你的问题' : kind === 'analyze' ? '添加待解析素材' : audioMode === 'speech' ? '写下配音文本' : '添加声音素材' }}</h2><span class="tiny-model">{{ capability?.model || '本地服务' }}</span></div>
|
||||
<textarea v-if="kind === 'math' || (kind === 'audio' && audioMode === 'speech')" v-model="draft.prompt" class="tool-textarea" :placeholder="kind === 'math' ? '例如:一个圆的半径增加20%,面积增加多少?请说明解题步骤。' : '输入希望转为声音的文字…'" aria-label="任务输入文本" @keydown.ctrl.enter.prevent="submit" />
|
||||
<AssetInput v-else v-model="reference" :kinds="kind === 'analyze' ? ['image', 'video'] : ['audio', 'video']" :label="kind === 'analyze' ? '上传图片或视频' : '上传音频或视频'" :hint="kind === 'analyze' ? '识别主体、场景和画面文字' : '支持从视频中提取音轨后转写'" />
|
||||
<audio v-if="reference && kind === 'audio'" class="source-audio" :src="reference.preview_url" controls />
|
||||
<div v-if="kind === 'math'" class="prompt-suggestions"><button @click="draft.prompt = '一个圆的半径增加20%,面积增加多少?请给出清晰的解题过程。'">比例与面积</button><button @click="draft.prompt = '解方程 x² − 5x + 6 = 0,并验证两个解。'">方程求解</button></div>
|
||||
<div class="tool-parameters parameter-form"><template v-if="kind === 'math'"><label>最大输出长度<el-input-number v-model="draft.parameters.max_tokens" :min="limit('max_tokens','min',128)" :max="limit('max_tokens','max',8192)" :step="128" /></label><small>返回可阅读的解题内容;专业题目请按实际业务需要复核。</small></template><template v-else-if="kind === 'analyze' && reference?.kind !== 'image'"><label>视频采样帧数<el-input-number v-model="draft.parameters.frame_count" :min="limit('frame_count','min',1)" :max="limit('frame_count','max',12)" /></label><small>时间点对应实际采样帧,不等同于完整镜头切分。</small></template><template v-else-if="kind === 'audio' && audioMode === 'transcribe'"><label>转写语言<el-select v-model="draft.parameters.language"><el-option v-for="language in languages" :key="language" :value="language" :label="({zh:'中文',en:'英文',auto:'自动识别'} as Record<string,string>)[language] || language" /></el-select></label><label>音频上限(秒)<el-input-number v-model="draft.parameters.max_audio_seconds" :min="1" :max="1800" :step="30" /></label><small>每30秒分块转写。结果时间为分块边界,不是逐词对齐。</small></template><template v-else-if="kind === 'audio' && audioMode === 'speech'"><label>音色<el-select v-if="voices.length" v-model="draft.parameters.voice"><el-option v-for="voice in voices" :key="voice" :label="voice" :value="voice" /></el-select><el-input v-else v-model="draft.parameters.voice" placeholder="服务端真实音色名称" /></label><label>语速<el-input-number v-model="draft.parameters.speed" :min="limit('speed','min',0.25)" :max="limit('speed','max',4)" :step="0.1" /></label></template></div>
|
||||
<div v-if="!capability?.available" class="notice warning">{{ capability?.description || (audioMode === 'speech' ? '语音生成尚未接入。当前可以使用 Whisper 语音转写。' : '正在确认服务能力,请稍后重试。') }}<el-button text :icon="RefreshRight" @click="caps.load()">刷新能力</el-button></div>
|
||||
<el-button type="primary" class="tool-submit" :icon="MagicStick" :loading="busy" :disabled="!capability?.available" @click="submit">{{ kind === 'math' ? '开始推演' : kind === 'analyze' ? '解析素材' : audioMode === 'speech' ? '生成配音' : '开始转写' }}<el-icon><ArrowRight /></el-icon></el-button>
|
||||
</section><section class="tool-result-panel surface"><div class="panel-heading"><h2>{{ kind === 'math' ? '推演结果' : kind === 'analyze' ? '素材理解' : '处理结果' }}</h2><el-button v-if="textResult" text :icon="CopyDocument" @click="copy">复制</el-button><button v-if="current" class="text-link" @click="detailId = current.id">任务详情</button></div>
|
||||
<template v-if="current"><div class="inline-job-state"><span class="status-pill" :class="current.state">{{ stateLabel(current) }}</span><span>{{ phaseLabel(current) }}</span></div><MathText v-if="textResult" :text="textResult" /><div v-else-if="current.state === 'succeeded' && kind === 'analyze'" class="analysis-result"><h3>画面主体</h3><div class="tag-cloud"><span v-for="(subject,index) in analysis.subjects || []" :key="index">{{ renderValue(subject) }}</span></div><h3>场景描述</h3><p>{{ renderValue(analysis.scene || '未返回场景描述') }}</p><h3>画面文字</h3><p v-for="(line,index) in analysis.ocr || []" :key="index">{{ renderValue(line) }}</p><small v-if="!analysis.ocr?.length" class="muted">未识别到文字</small><details v-if="analysis.frames?.length"><summary>查看逐帧结果({{ analysis.frames.length }} 帧)</summary><pre class="json-output">{{ JSON.stringify(analysis.frames, null, 2) }}</pre></details></div><div v-else-if="!current.result_assets.length" class="empty-state compact"><div v-if="!['failed','cancelled','timed_out'].includes(current.state)" class="generation-orbit" /><p>{{ current.error?.message || '结果会在任务完成后出现在这里' }}</p></div><div v-if="current.result_assets.length" class="tool-output-assets"><div v-for="asset in current.result_assets" :key="asset.id"><audio v-if="asset.kind === 'audio'" :src="asset.preview_url" controls /><button v-else @click="preview = asset">{{ asset.name }} <el-icon><ArrowRight /></el-icon></button><a :href="asset.download_url" :download="asset.name" class="text-link">下载</a></div></div><details v-if="current.result?.segments?.length" class="segments"><summary>查看转写分段</summary><div v-for="(segment,index) in current.result.segments" :key="index"><code>{{ segment.start.toFixed(1) }}–{{ segment.end.toFixed(1) }}s</code><p>{{ segment.text }}</p><small v-if="segment.truncated" class="warning-text">此段输出达到长度上限</small></div></details></template>
|
||||
<div v-else class="empty-state tool-empty"><el-icon :size="38"><Document v-if="kind === 'math'" /><DataAnalysis v-else-if="kind === 'analyze'" /><Headset v-else /></el-icon><h3>给灵感留一个位置</h3><p>提交任务后,这里会同步展示真实处理结果。</p></div>
|
||||
</section></div>
|
||||
<section v-if="history.length" class="tool-history"><div class="section-heading"><h2>最近记录</h2></div><button v-for="job in history" :key="job.id" :class="{ selected: current?.id === job.id }" @click="selectedId = job.id"><span class="status-dot" :class="job.state" /><strong>{{ job.prompt || (kind === 'analyze' ? '素材解析' : '语音任务') }}</strong><span>{{ stateLabel(job) }}</span><small>{{ formatDate(job.created_at) }}</small></button></section>
|
||||
<JobDetail v-model:job-id="detailId" /><AssetPreview v-model:asset="preview" />
|
||||
</div>
|
||||
</template>
|
||||
84
frontend/src/views/WorkbenchView.vue
Normal file
@ -0,0 +1,84 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { ArrowRight, MagicStick, Setting, Clock, Picture, VideoCamera, RefreshRight, Plus } from '@element-plus/icons-vue'
|
||||
import { useCapabilitiesStore } from '../stores/capabilities'
|
||||
import { useDraftsStore } from '../stores/drafts'
|
||||
import { useJobsStore } from '../stores/jobs'
|
||||
import { useAssetsStore } from '../stores/assets'
|
||||
import { errorMessage } from '../api'
|
||||
import { inspirations } from '../inspirations'
|
||||
import type { Asset, TaskType } from '../types'
|
||||
import AssetInput from '../components/AssetInput.vue'
|
||||
import AssetPreview from '../components/AssetPreview.vue'
|
||||
import JobCard from '../components/JobCard.vue'
|
||||
import JobDetail from '../components/JobDetail.vue'
|
||||
const route = useRoute(), router = useRouter(), capabilities = useCapabilitiesStore(), drafts = useDraftsStore(), jobs = useJobsStore(), assets = useAssetsStore()
|
||||
const mode = computed(() => ['image', 'video', 'defect'].includes(String(route.params.mode)) ? String(route.params.mode) : 'image')
|
||||
const taskType = computed<TaskType>(() => mode.value === 'video' ? 'video.generate' : mode.value === 'defect' ? 'defect.generate' : 'image.generate')
|
||||
const capability = computed(() => capabilities.forTask(taskType.value))
|
||||
const draft = computed(() => drafts.forTask(taskType.value, capability.value?.defaults))
|
||||
const reference = computed({ get: () => draft.value.imageAssetId ? assets.byId[draft.value.imageAssetId] || null : null, set: (asset: Asset | null) => { draft.value.imageAssetId = asset?.id || null } })
|
||||
const recentJobs = computed(() => jobs.recent.filter(job => job.task_type === taskType.value).slice(0, 18))
|
||||
const busy = ref(false), importing = ref<string | null>(null), selectedAsset = ref<Asset | null>(null), detailId = ref<string | null>(null), textarea = ref<HTMLTextAreaElement>()
|
||||
const title = computed(() => mode.value === 'video' ? '让想象,开始流动。' : mode.value === 'defect' ? '从细微之处,创造更多可能。' : '下一帧灵感,从这里开始。')
|
||||
const placeholder = computed(() => mode.value === 'video' ? '描述主体的动作、镜头运动与光线。一次简单的运镜,也能带来新的故事。' : mode.value === 'defect' ? '描述想要合成的缺陷,例如:金属表面出现细小划痕,保留原始轮廓…' : '描述你想看见的画面:主体、场景、光线和风格…')
|
||||
function bound(key: string, edge: 'min' | 'max' | 'step', fallback: number) { const value = capability.value?.constraints[key]?.[edge]; return typeof value === 'number' ? value : fallback }
|
||||
function ratio(width: number, height: number) { draft.value.parameters.width = width; draft.value.parameters.height = height }
|
||||
function usePrompt(prompt: string) { draft.value.prompt = prompt; textarea.value?.focus() }
|
||||
async function useSample(sample: typeof inspirations[number]) {
|
||||
importing.value = sample.id
|
||||
try { const response = await fetch(sample.image); if (!response.ok) throw new Error('无法读取示例图片'); const blob = await response.blob(); const asset = await assets.upload(new File([blob], `模型验收样例-${sample.id}.png`, { type: 'image/png' })); await router.push({ path: '/create/video', query: { image: asset.id } }); ElMessage.success('样例已上传到你的素材库,可作为视频首帧') }
|
||||
catch (error) { ElMessage.error(errorMessage(error)) } finally { importing.value = null }
|
||||
}
|
||||
async function submit() {
|
||||
if (busy.value) return
|
||||
if (!capability.value?.available) { ElMessage.warning('当前能力尚未就绪,请稍后重试'); return }
|
||||
if (!draft.value.prompt.trim()) { textarea.value?.focus(); ElMessage.warning('先描述一下你想创作的内容'); return }
|
||||
if (mode.value === 'defect' && !reference.value) { ElMessage.warning('请先添加一张参考图片'); return }
|
||||
const p = draft.value.parameters
|
||||
if (![p.width, p.height, p.num_inference_steps].every(value => Number.isFinite(value) && value > 0)) { ElMessage.warning('请补全尺寸和生成步数'); return }
|
||||
if (capability.value.constraints.max_pixels && p.width * p.height > capability.value.constraints.max_pixels) { ElMessage.warning('当前尺寸超过模型支持的像素上限'); return }
|
||||
busy.value = true
|
||||
try {
|
||||
const input: Record<string, any> = { prompt: draft.value.prompt.trim() }
|
||||
if (draft.value.negative_prompt.trim()) input.negative_prompt = draft.value.negative_prompt.trim()
|
||||
if (reference.value && mode.value !== 'image') input.image_asset_id = reference.value.id
|
||||
const created = await jobs.submit({ task_type: taskType.value, input, parameters: { ...p }, count: mode.value === 'video' ? 1 : draft.value.count, scheduled_at: draft.value.scheduledAt ? new Date(draft.value.scheduledAt).toISOString() : null })
|
||||
ElMessage.success(`已加入 ${created.length} 项创作任务`)
|
||||
} catch (error) { ElMessage.error(errorMessage(error)) } finally { busy.value = false }
|
||||
}
|
||||
async function importReference() {
|
||||
const id = route.query.image
|
||||
if (typeof id === 'string' && mode.value === 'video') {
|
||||
try { const asset = await assets.get(id); if (asset.kind === 'image') reference.value = asset; else ElMessage.warning('视频首帧需要图片素材') }
|
||||
catch (error) { ElMessage.error(errorMessage(error)) }
|
||||
}
|
||||
}
|
||||
watch(() => [mode.value, route.query.image], importReference)
|
||||
onMounted(() => { void jobs.refresh().catch(() => undefined); void importReference() })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="workbench">
|
||||
<div class="workspace-scroll">
|
||||
<div class="workspace-topline"><div class="mode-switch"><router-link to="/create/image">图像生成</router-link><router-link to="/create/video">视频生成</router-link><router-link to="/create/defect">缺陷样本</router-link></div><span class="quiet-note">本地模型 · 你的创作,由你掌控</span></div>
|
||||
<section class="creative-heading"><span class="eyebrow">YOUR NEXT IDEA STARTS HERE</span><h1>{{ title }}</h1><p>{{ mode === 'video' ? '从一句描述或一张首帧开始,把画面交给时间。' : mode === 'defect' ? '用参考轮廓约束结构,探索工业材质与缺陷样本。' : '用文字勾勒,用画面表达。把一闪而过的想法,变成看得见的作品。' }}</p></section>
|
||||
<div v-if="capabilities.error" class="notice warning">{{ capabilities.error }} <el-button text :icon="RefreshRight" @click="capabilities.load()">重新连接</el-button></div>
|
||||
<section v-if="recentJobs.length" class="results-section"><div class="section-heading"><h2>最近创作 <span>{{ recentJobs.length }}</span></h2><router-link to="/tasks">任务中心 <el-icon><ArrowRight /></el-icon></router-link></div><div class="results-grid"><JobCard v-for="job in recentJobs" :key="job.id" :job="job" @open="detailId = $event" @preview="selectedAsset = $event" /></div></section>
|
||||
<section class="inspiration-section"><div class="section-heading"><div><h2>{{ recentJobs.length ? '换一种灵感' : '从真实画面,寻找灵感' }}</h2><p>以下为本地模型验收样例,不是你的历史任务。</p></div><span class="outline-label">MODEL VERIFIED</span></div><div class="inspiration-grid"><article v-for="(sample, index) in inspirations" :key="sample.id" class="inspiration-card" :class="{ 'wide-sample': index === 0 }"><img :src="sample.image" :alt="sample.title" loading="lazy" /><span class="sample-label">模型验收样例</span><div class="inspiration-gradient"><span>{{ sample.category }} / {{ sample.model }}</span><h3>{{ sample.title }}</h3><div class="inspiration-actions"><button @click="usePrompt(sample.prompt)">使用提示词 <el-icon><ArrowRight /></el-icon></button><button v-if="sample.id !== 'robot'" :disabled="!!importing" @click="useSample(sample)">{{ importing === sample.id ? '正在上传…' : '用于视频首帧' }}</button></div></div></article></div></section>
|
||||
</div>
|
||||
<section class="composer-wrap"><div class="prompt-composer">
|
||||
<AssetInput v-if="mode !== 'image'" v-model="reference" :kinds="['image']" :label="mode === 'video' ? '添加首帧(可选)' : '添加参考图片'" :hint="mode === 'video' ? '文生视频可不添加图片' : '上传图片,用边缘结构约束生成'" />
|
||||
<textarea ref="textarea" v-model="draft.prompt" :placeholder="placeholder" aria-label="创作提示词" @keydown.ctrl.enter.prevent="submit" @keydown.meta.enter.prevent="submit" />
|
||||
<div class="composer-controls"><div class="composer-parameters"><span class="model-chip"><span class="model-mark">M</span>{{ capability?.model || '正在读取模型' }}</span>
|
||||
<el-popover placement="top-start" :width="310" trigger="click"><template #reference><button class="parameter-chip">{{ draft.parameters.width || '—' }} × {{ draft.parameters.height || '—' }}</button></template><div class="parameter-form"><h3>画面尺寸</h3><div v-if="mode !== 'video'" class="ratio-options"><button @click="ratio(1024, 1024)">1:1</button><button @click="ratio(1280, 720)">16:9</button><button @click="ratio(720, 1280)">9:16</button></div><label>宽度<el-input-number v-model="draft.parameters.width" :min="bound('width','min',256)" :max="bound('width','max',2048)" :step="bound('width','step',16)" /></label><label>高度<el-input-number v-model="draft.parameters.height" :min="bound('height','min',256)" :max="bound('height','max',2048)" :step="bound('height','step',16)" /></label></div></el-popover>
|
||||
<span v-if="mode === 'video'" class="parameter-chip">约 5 秒 · 121 帧 · 24 fps</span><el-select v-else v-model="draft.count" class="count-select" aria-label="生成数量"><el-option v-for="count in bound('count','max',4)" :key="count" :value="count" :label="`${count} 张`" /></el-select>
|
||||
<el-popover trigger="click" placement="top" :width="340"><template #reference><button class="parameter-chip"><el-icon><Setting /></el-icon>参数</button></template><div class="parameter-form"><h3>生成参数</h3><label>步数<el-input-number v-model="draft.parameters.num_inference_steps" :min="bound('num_inference_steps','min',1)" :max="bound('num_inference_steps','max',100)" /></label><label v-if="draft.parameters.seed !== undefined">随机种子<el-input-number v-model="draft.parameters.seed" :min="0" :max="4294967295" :controls="false" /></label><label v-if="draft.parameters.guidance_scale !== undefined">引导强度<el-input-number v-model="draft.parameters.guidance_scale" :min="bound('guidance_scale','min',1)" :max="bound('guidance_scale','max',20)" :step="0.5" /></label><template v-if="mode === 'defect'"><label>结构控制强度<el-input-number v-model="draft.parameters.controlnet_conditioning_scale" :min="0" :max="2" :step="0.1" /></label><label>Canny低阈值<el-input-number v-model="draft.parameters.canny_low" :min="0" :max="254" /></label><label>Canny高阈值<el-input-number v-model="draft.parameters.canny_high" :min="1" :max="255" /></label></template><label v-if="mode === 'video'">1080p 画质增强<el-switch v-model="draft.parameters.upscale" /></label><label class="vertical-label">不希望出现的内容<el-input v-model="draft.negative_prompt" type="textarea" :rows="2" placeholder="可选,例如模糊、变形" /></label><small v-if="mode === 'defect'">输出合成图和 Canny 控制图,不提供缺陷真值掩膜。</small><small v-if="mode === 'video'">当前最长约 5 秒,尚未开放视频延长或15秒生成。</small></div></el-popover>
|
||||
<el-popover trigger="click" placement="top" :width="300"><template #reference><button class="parameter-chip" :class="{ highlighted: draft.scheduledAt }"><el-icon><Clock /></el-icon>{{ draft.scheduledAt ? '已预约' : '预约' }}</button></template><div class="parameter-form"><h3>预约创作</h3><el-date-picker v-model="draft.scheduledAt" type="datetime" placeholder="选择开始时间" value-format="YYYY-MM-DDTHH:mm:ss" clearable /><small>按当前浏览器时区选择。到达时间后进入串行队列。</small></div></el-popover>
|
||||
</div><el-button class="generate-button" type="primary" :loading="busy" :disabled="!capability?.available" :icon="MagicStick" @click="submit">{{ draft.scheduledAt ? '预约生成' : '开始生成' }} <el-icon v-if="!busy"><ArrowRight /></el-icon></el-button></div>
|
||||
</div><div class="composer-footnote"><span>{{ capability?.available ? '空闲算力串行执行 · 被占用时自动让行与重试' : capability?.description || '正在连接本地创作服务' }}</span><span>Ctrl + Enter 生成</span></div></section>
|
||||
<AssetPreview v-model:asset="selectedAsset" /><JobDetail v-model:job-id="detailId" />
|
||||
</div>
|
||||
</template>
|
||||
10
frontend/tsconfig.json
Normal file
@ -0,0 +1,10 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022", "module": "ESNext", "moduleResolution": "Bundler",
|
||||
"strict": true, "useDefineForClassFields": true, "jsx": "preserve",
|
||||
"resolveJsonModule": true, "isolatedModules": true, "esModuleInterop": true,
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"], "types": ["vite/client", "node"],
|
||||
"skipLibCheck": true, "noEmit": true
|
||||
},
|
||||
"include": ["src/**/*.ts", "src/**/*.vue", "vite.config.ts"]
|
||||
}
|
||||
16
frontend/vite.config.ts
Normal file
@ -0,0 +1,16 @@
|
||||
import { defineConfig, loadEnv } from 'vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
|
||||
export default defineConfig(({ mode }) => {
|
||||
const env = loadEnv(mode, process.cwd(), '')
|
||||
return {
|
||||
plugins: [vue()],
|
||||
server: {
|
||||
port: 5173,
|
||||
strictPort: true,
|
||||
proxy: { '/api': { target: env.VITE_API_PROXY || 'http://127.0.0.1:8000', changeOrigin: true } },
|
||||
},
|
||||
build: { chunkSizeWarningLimit: 1000 },
|
||||
test: { environment: 'node', include: ['src/**/*.test.ts'] },
|
||||
}
|
||||
})
|
||||
260
qa/browser-audit.cjs
Normal file
@ -0,0 +1,260 @@
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { chromium } = require('C:/Users/Administrator/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/node_modules/playwright-core');
|
||||
|
||||
const root = path.resolve(__dirname, '..');
|
||||
const credentials = Object.fromEntries(fs.readFileSync(path.join(root, '.env.preview'), 'utf8')
|
||||
.split(/\r?\n/).filter(line => /^[A-Z_]+=/.test(line))
|
||||
.map(line => { const split = line.indexOf('='); return [line.slice(0, split), line.slice(split + 1).trim().replace(/^(['"])(.*)\1$/, '$2')]; }));
|
||||
const report = { generated_at: new Date().toISOString(), base_url: process.env.QA_BASE_URL || 'http://127.0.0.1:5173',
|
||||
screenshots: [], pages: [], previews: [], media: [], range_responses: [], navigation_retries: [], page_errors: [], http_errors: [], failures: [] };
|
||||
const destination = path.join(__dirname, 'browser.json');
|
||||
const mathEvidencePath = path.join(__dirname, 'browser-live-math.json');
|
||||
const previousReport = fs.existsSync(mathEvidencePath) ? JSON.parse(fs.readFileSync(mathEvidencePath, 'utf8'))
|
||||
: fs.existsSync(destination) ? JSON.parse(fs.readFileSync(destination, 'utf8')) : {};
|
||||
const sanitize = value => credentials.ADMIN_PASSWORD ? value.replaceAll(credentials.ADMIN_PASSWORD, '[redacted]') : value;
|
||||
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
|
||||
|
||||
async function goto(page, location, waitUntil) {
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
try { await page.goto(location, { waitUntil }); return; }
|
||||
catch (error) {
|
||||
if (attempt >= 3 || !/net::ERR_(CONNECTION_REFUSED|CONNECTION_RESET|EMPTY_RESPONSE)/.test(error.message)) throw error;
|
||||
report.navigation_retries.push({ path: new URL(location).pathname, attempt: attempt + 1 });
|
||||
await delay(1500);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function screenshot(page, name) {
|
||||
const file = `browser-${name}.png`;
|
||||
await page.screenshot({ path: path.join(__dirname, file), fullPage: true });
|
||||
report.screenshots.push(file);
|
||||
}
|
||||
async function layout(page, name) {
|
||||
// Measure resting geometry, not the drawer's 300ms enter transition.
|
||||
await page.waitForFunction(() => [...document.querySelectorAll('.el-drawer')].every(element => {
|
||||
const rect = element.getBoundingClientRect();
|
||||
return !rect.width || !rect.height || (rect.left >= -1 && rect.right <= innerWidth + 1);
|
||||
}), null, { timeout: 1200 }).catch(() => {});
|
||||
const metrics = await page.evaluate(() => ({
|
||||
viewport: innerWidth,
|
||||
document_width: document.documentElement.scrollWidth,
|
||||
primary: getComputedStyle(document.documentElement).getPropertyValue('--el-color-primary').trim(),
|
||||
font_family: getComputedStyle(document.documentElement).fontFamily,
|
||||
chinese_font_loaded: document.fonts.check('14px "Noto Sans SC Variable"', '创作素材任务'),
|
||||
heading: document.querySelector('h1')?.textContent?.trim() || document.querySelector('h2')?.textContent?.trim(),
|
||||
connection: document.querySelector('.connection-status')?.textContent?.trim(),
|
||||
wide_visible_overlays: [...document.querySelectorAll('.el-drawer,.el-dialog')].filter(element => {
|
||||
const rect = element.getBoundingClientRect();
|
||||
return rect.height && rect.width && getComputedStyle(element).visibility !== 'hidden' &&
|
||||
(rect.width > innerWidth + 1 || rect.left < -1 || rect.right > innerWidth + 1);
|
||||
}).map(element => ({ class: element.className, width: element.getBoundingClientRect().width,
|
||||
left: element.getBoundingClientRect().left })),
|
||||
overflowing_containers: [...document.querySelectorAll('.page-content,.tool-page,.tool-columns,.library-page,.tasks-page,.compose-page,.compose-layout')]
|
||||
.filter(element => element.clientWidth && element.scrollWidth > element.clientWidth + 2)
|
||||
.map(element => ({ class: element.className, width: element.clientWidth, content_width: element.scrollWidth })),
|
||||
}));
|
||||
report.pages.push({ name, path: new URL(page.url()).pathname, ...metrics });
|
||||
if (metrics.document_width > metrics.viewport + 1 || metrics.wide_visible_overlays.length || metrics.overflowing_containers.length)
|
||||
report.failures.push({ check: 'horizontal_overflow', page: name, ...metrics });
|
||||
await screenshot(page, name);
|
||||
}
|
||||
async function navigate(page, location) {
|
||||
await goto(page, report.base_url + location, 'domcontentloaded');
|
||||
await page.locator('.app-shell').waitFor({ timeout: 30000 });
|
||||
await page.waitForFunction(() => document.querySelector('.connection-status')?.textContent.includes('实时同步'), { timeout: 30000 });
|
||||
await page.evaluate(() => document.fonts.ready);
|
||||
await delay(450);
|
||||
if (await page.locator('.compose-preview video').count()) {
|
||||
await page.waitForFunction(() => document.querySelector('.compose-preview video')?.readyState >= 2, null, { timeout: 20000 });
|
||||
}
|
||||
}
|
||||
async function login(page, label) {
|
||||
await goto(page, report.base_url + '/login', 'networkidle');
|
||||
await page.evaluate(() => document.fonts.ready);
|
||||
await layout(page, `${label}-login`);
|
||||
await page.getByPlaceholder('输入你的账号').fill(credentials.ADMIN_USERNAME);
|
||||
await page.getByPlaceholder('输入密码', { exact: true }).fill(credentials.ADMIN_PASSWORD);
|
||||
await page.getByRole('button', { name: '进入工作空间' }).click();
|
||||
await page.waitForURL('**/create/image', { timeout: 30000 });
|
||||
await page.locator('.connection-status.live').waitFor({ timeout: 30000 });
|
||||
}
|
||||
async function authenticatedJson(page, url) {
|
||||
const response = await page.request.get(report.base_url + url);
|
||||
if (!response.ok()) throw new Error(`Read-only API check failed: ${new URL(url, report.base_url).pathname} ${response.status()}`);
|
||||
return response.json();
|
||||
}
|
||||
async function preview(page, kind, label) {
|
||||
await navigate(page, '/assets');
|
||||
await page.locator('.filter-tabs button').filter({ hasText: new RegExp(`^${{ image: '图片', video: '视频', audio: '音频' }[kind]}$`) }).click();
|
||||
await page.locator('.library-card').first().waitFor({ timeout: 20000 });
|
||||
await delay(550);
|
||||
await page.locator('.library-media').first().click();
|
||||
await page.locator('.preview-dialog').waitFor({ timeout: 10000 });
|
||||
if (kind === 'image') {
|
||||
await page.locator('.preview-stage img').evaluate(image => image.decode());
|
||||
report.previews.push({ viewport: label, kind, decoded: true });
|
||||
} else {
|
||||
const media = page.locator(`.preview-stage ${kind === 'video' ? 'video' : 'audio'}`);
|
||||
await media.waitFor();
|
||||
const result = await media.evaluate(async element => {
|
||||
if (element.readyState < 1) await new Promise((resolve, reject) => {
|
||||
const timeout = setTimeout(() => reject(new Error('metadata_timeout')), 20000);
|
||||
element.addEventListener('loadedmetadata', () => { clearTimeout(timeout); resolve(); }, { once: true });
|
||||
element.addEventListener('error', () => { clearTimeout(timeout); reject(new Error(`media_error_${element.error?.code}`)); }, { once: true });
|
||||
});
|
||||
element.muted = true;
|
||||
await element.play();
|
||||
const before = element.currentTime;
|
||||
await new Promise(resolve => setTimeout(resolve, 500));
|
||||
const advanced = element.currentTime > before;
|
||||
element.pause();
|
||||
const seekTarget = Math.max(.1, Math.min(element.duration / 2, element.duration - .1));
|
||||
await new Promise((resolve, reject) => {
|
||||
const timeout = setTimeout(() => reject(new Error('seek_timeout')), 10000);
|
||||
element.addEventListener('seeked', () => { clearTimeout(timeout); resolve(); }, { once: true });
|
||||
element.currentTime = seekTarget;
|
||||
});
|
||||
return { duration_seconds: element.duration, playback_advanced: advanced, seek_target: seekTarget,
|
||||
current_time: element.currentTime, error: element.error?.code || null,
|
||||
...(element instanceof HTMLVideoElement ? { width: element.videoWidth, height: element.videoHeight } : {}) };
|
||||
});
|
||||
report.media.push({ viewport: label, kind, ...result });
|
||||
if (!result.playback_advanced || result.error) report.failures.push({ check: 'media_playback', kind, viewport: label });
|
||||
}
|
||||
await layout(page, `${label}-preview-${kind}`);
|
||||
await page.locator('.preview-dialog .el-dialog__headerbtn').click();
|
||||
}
|
||||
function watchPage(page) {
|
||||
page.on('pageerror', error => report.page_errors.push({ message: error.message.slice(0, 500) }));
|
||||
page.on('response', response => {
|
||||
if (response.status() === 206 && new URL(response.url()).pathname.startsWith('/api/assets/'))
|
||||
report.range_responses.push({ path: new URL(response.url()).pathname, status: 206,
|
||||
content_range: response.headers()['content-range'] });
|
||||
if (response.status() >= 400 && !(response.status() === 401 && response.url().includes('/auth/me')))
|
||||
report.http_errors.push({ path: new URL(response.url()).pathname, status: response.status() });
|
||||
});
|
||||
}
|
||||
|
||||
(async () => {
|
||||
const browser = await chromium.launch({ channel: 'chrome', headless: true, args: ['--autoplay-policy=no-user-gesture-required'] });
|
||||
report.browser_version = browser.version();
|
||||
try {
|
||||
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 }, locale: 'zh-CN' });
|
||||
await context.addInitScript(() => {
|
||||
window.__auditSSE = { opens: 0, errors: 0, events: [] };
|
||||
const Native = window.EventSource;
|
||||
window.EventSource = class extends Native {
|
||||
constructor(...args) {
|
||||
super(...args);
|
||||
this.addEventListener('open', () => window.__auditSSE.opens++);
|
||||
this.addEventListener('error', () => window.__auditSSE.errors++);
|
||||
this.addEventListener('job.updated', event => {
|
||||
try { const { job } = JSON.parse(event.data); window.__auditSSE.events.push({ id: job.id, state: job.state, version: job.version }); } catch {}
|
||||
});
|
||||
}
|
||||
};
|
||||
});
|
||||
const page = await context.newPage();
|
||||
watchPage(page);
|
||||
await login(page, 'desktop');
|
||||
const jobs = await authenticatedJson(page, '/api/jobs?page_size=48');
|
||||
const assets = await authenticatedJson(page, '/api/assets?page_size=100');
|
||||
const system = await authenticatedJson(page, '/api/system/status');
|
||||
report.real_data = { jobs: jobs.total, assets: assets.total,
|
||||
environment: system.environment, database_backend: system.database_backend,
|
||||
task_types: [...new Set(jobs.items.map(job => job.task_type))],
|
||||
asset_kinds: [...new Set(assets.items.map(asset => asset.kind))] };
|
||||
const video = assets.items.find(asset => asset.kind === 'video');
|
||||
const image = assets.items.find(asset => asset.kind === 'image');
|
||||
const detail = jobs.items.find(job => job.task_type === 'media.structure') || jobs.items[0];
|
||||
const pages = ['/create/image', '/create/video', '/create/defect', '/audio', '/math', '/analyze', '/compose', '/assets', '/tasks'];
|
||||
for (const label of ['desktop', 'mobile']) {
|
||||
await page.setViewportSize(label === 'desktop' ? { width: 1440, height: 1000 } : { width: 390, height: 844 });
|
||||
if (label === 'mobile') {
|
||||
const loginPage = await context.newPage();
|
||||
await loginPage.setViewportSize({ width: 390, height: 844 });
|
||||
// A separate anonymous context keeps the actual session and private cookies out of output.
|
||||
const anonymous = await browser.newContext({ viewport: { width: 390, height: 844 }, locale: 'zh-CN' });
|
||||
const anonymousPage = await anonymous.newPage();
|
||||
await goto(anonymousPage, report.base_url + '/login', 'networkidle');
|
||||
await anonymousPage.evaluate(() => document.fonts.ready);
|
||||
await layout(anonymousPage, 'mobile-login');
|
||||
await anonymous.close();
|
||||
await loginPage.close();
|
||||
}
|
||||
for (const route of pages) {
|
||||
const location = route === '/compose' && video ? `${route}?asset=${video.id}`
|
||||
: route === '/analyze' && image ? `${route}?asset=${image.id}` : route;
|
||||
await navigate(page, location);
|
||||
await layout(page, `${label}-${route.slice(1).replaceAll('/', '-')}`);
|
||||
if (route === '/audio') {
|
||||
await page.getByRole('button', { name: '配音生成' }).click();
|
||||
await layout(page, `${label}-audio-speech`);
|
||||
await page.locator('.side-nav a[href="/analyze"]').click();
|
||||
await page.locator('.tool-page h1').filter({ hasText: '读懂画面' }).waitFor();
|
||||
report.pages.push({ name: `${label}-speech-to-analyze`, speech_fields_visible: await page.locator('.tool-parameters').getByText('语速', { exact: true }).isVisible() });
|
||||
}
|
||||
}
|
||||
for (const kind of ['image', 'video', 'audio']) await preview(page, kind, label);
|
||||
await navigate(page, `/tasks?job=${detail.id}`);
|
||||
await page.locator('.task-identity').waitFor({ timeout: 15000 });
|
||||
await layout(page, `${label}-task-detail`);
|
||||
await page.locator('.el-drawer:visible .el-drawer__close-btn').click();
|
||||
await page.getByRole('button', { name: '服务状态', exact: true }).click();
|
||||
await layout(page, `${label}-system-status`);
|
||||
await page.locator('.el-drawer:visible .el-drawer__close-btn').click();
|
||||
}
|
||||
// Hide the target only from the recent-list fixture, retaining real server responses.
|
||||
// A real one-item API request must still populate this cold-cache deep link.
|
||||
const coldContext = await browser.newContext({ storageState: await context.storageState(), viewport: { width: 1440, height: 1000 } });
|
||||
const coldPage = await coldContext.newPage();
|
||||
let directDetailRequests = 0;
|
||||
coldPage.on('request', request => { if (new URL(request.url()).pathname === `/api/jobs/${detail.id}`) directDetailRequests++; });
|
||||
await coldPage.route('**/api/jobs?*', async route => {
|
||||
const response = await route.fetch();
|
||||
const data = await response.json();
|
||||
data.items = data.items.filter(job => job.id !== detail.id);
|
||||
await route.fulfill({ response, json: data });
|
||||
});
|
||||
await navigate(coldPage, `/tasks?job=${detail.id}`);
|
||||
await coldPage.locator('.task-identity').waitFor({ timeout: 15000 });
|
||||
report.deep_link = { cold_cache_fixture_excludes_target: true, direct_detail_requests: directDetailRequests,
|
||||
detail_visible: (await coldPage.locator('.task-identity').innerText()).includes(detail.id) };
|
||||
await screenshot(coldPage, 'desktop-cold-task-deep-link');
|
||||
await coldContext.close();
|
||||
await page.setViewportSize({ width: 1440, height: 1000 });
|
||||
await navigate(page, '/math');
|
||||
if (process.env.QA_SKIP_MATH === '1' && previousReport.math && previousReport.sse) {
|
||||
report.sse = { ...previousReport.sse, captured_at: previousReport.generated_at };
|
||||
report.math = { ...previousReport.math, reused_previous_verified_run: true };
|
||||
} else {
|
||||
await page.getByRole('textbox', { name: '任务输入文本' }).fill('只回答算式结果:2 + 3 = ?');
|
||||
await page.locator('.tool-parameters input').fill('512');
|
||||
const createdResponse = page.waitForResponse(response => new URL(response.url()).pathname === '/api/jobs' && response.request().method() === 'POST');
|
||||
await page.getByRole('button', { name: '开始推演' }).click();
|
||||
const response = await createdResponse;
|
||||
if (!response.ok()) throw new Error(`Math submit returned ${response.status()}`);
|
||||
const created = await response.json();
|
||||
const mathId = created.jobs[0].id;
|
||||
await page.waitForFunction(id => window.__auditSSE.events.some(event => event.id === id && event.state === 'succeeded'), mathId, { timeout: 120000 });
|
||||
await page.locator('.tool-result-panel .status-pill.succeeded').waitFor();
|
||||
report.sse = await page.evaluate(id => ({ ...window.__auditSSE, events: window.__auditSSE.events.filter(event => event.id === id) }), mathId);
|
||||
report.math = { id: mathId, max_tokens: 512, ui_result: await page.locator('.tool-result-panel .math-text').innerText() };
|
||||
fs.writeFileSync(mathEvidencePath, JSON.stringify({ generated_at: report.generated_at, sse: report.sse, math: report.math }, null, 2));
|
||||
}
|
||||
await layout(page, 'desktop-math-sse-result');
|
||||
await context.close();
|
||||
} catch (error) {
|
||||
report.failures.push({ check: 'audit_execution', message: sanitize(error.message).slice(0, 500) });
|
||||
process.exitCode = 1;
|
||||
} finally {
|
||||
await browser.close();
|
||||
report.completed_at = new Date().toISOString();
|
||||
fs.writeFileSync(destination, sanitize(JSON.stringify(report, null, 2)));
|
||||
console.log(sanitize(JSON.stringify({ report: destination, screenshots: report.screenshots.length,
|
||||
pages: report.pages.length, media: report.media.length, failures: report.failures,
|
||||
page_errors: report.page_errors, http_errors: report.http_errors, sse: report.sse, math: report.math }, null, 2)));
|
||||
}
|
||||
})();
|
||||
BIN
qa/browser-desktop-analyze.png
Normal file
|
After Width: | Height: | Size: 153 KiB |
BIN
qa/browser-desktop-assets.png
Normal file
|
After Width: | Height: | Size: 409 KiB |
BIN
qa/browser-desktop-audio-speech.png
Normal file
|
After Width: | Height: | Size: 157 KiB |
BIN
qa/browser-desktop-audio.png
Normal file
|
After Width: | Height: | Size: 162 KiB |
BIN
qa/browser-desktop-cold-task-deep-link.png
Normal file
|
After Width: | Height: | Size: 149 KiB |
BIN
qa/browser-desktop-compose.png
Normal file
|
After Width: | Height: | Size: 282 KiB |
BIN
qa/browser-desktop-create-defect.png
Normal file
|
After Width: | Height: | Size: 400 KiB |
BIN
qa/browser-desktop-create-image.png
Normal file
|
After Width: | Height: | Size: 304 KiB |
BIN
qa/browser-desktop-create-video.png
Normal file
|
After Width: | Height: | Size: 294 KiB |
BIN
qa/browser-desktop-login.png
Normal file
|
After Width: | Height: | Size: 591 KiB |
BIN
qa/browser-desktop-math-sse-result.png
Normal file
|
After Width: | Height: | Size: 157 KiB |
BIN
qa/browser-desktop-math.png
Normal file
|
After Width: | Height: | Size: 161 KiB |
BIN
qa/browser-desktop-preview-audio.png
Normal file
|
After Width: | Height: | Size: 92 KiB |
BIN
qa/browser-desktop-preview-image.png
Normal file
|
After Width: | Height: | Size: 374 KiB |
BIN
qa/browser-desktop-preview-video.png
Normal file
|
After Width: | Height: | Size: 267 KiB |