feat: consolidate story studio and editable automatic production
Restructure backend and frontend modules; add story, library, and editor schema migrations. Support editable automatic production, manual confirmation modes, account and user lifecycle management, compact container scrolling, consistent forms, and per-task result previews. Update inference and TTS scheduling, deployment guidance, and regression coverage; remove obsolete standalone pages and temporary acceptance artifacts.
This commit is contained in:
parent
7e28662753
commit
88cf14d794
@ -9,3 +9,8 @@
|
||||
**/*.log
|
||||
**/.inference-key
|
||||
qa
|
||||
.deploy
|
||||
.local
|
||||
.superpowers
|
||||
outputs
|
||||
**/.ruff_cache
|
||||
|
||||
15
.editorconfig
Normal file
15
.editorconfig
Normal file
@ -0,0 +1,15 @@
|
||||
root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
end_of_line = lf
|
||||
insert_final_newline = true
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
trim_trailing_whitespace = true
|
||||
|
||||
[*.py]
|
||||
indent_size = 4
|
||||
|
||||
[*.md]
|
||||
trim_trailing_whitespace = false
|
||||
19
.env.example
19
.env.example
@ -18,6 +18,19 @@ MAX_INTERACTIVE_GPU_JOBS=0
|
||||
MAX_CREATION_COMMANDS_PER_MINUTE=6
|
||||
MAX_OWNER_JOBS=500
|
||||
MAX_GLOBAL_JOBS=2000
|
||||
# Pending story candidates are durable plans; only admitted leaves consume Job slots.
|
||||
MAX_OWNER_STORY_CANDIDATES=4000
|
||||
MAX_GLOBAL_STORY_CANDIDATES=16000
|
||||
# Enable only after validating the identical profile in the inference service.
|
||||
REFERENCE_GENERATION_ENABLED=false
|
||||
REFERENCE_GENERATION_PROFILE=qwen-image-edit-2511-v1
|
||||
REFERENCE_MAX_IMAGES=3
|
||||
# Both business and inference must certify/enable the same video editing profile.
|
||||
VIDEO_EDIT_ENABLED=false
|
||||
VIDEO_EDIT_PROFILE=wan-animate-replace-v1
|
||||
VIDEO_EDIT_MAX_SECONDS=120
|
||||
VIDEO_EDIT_MAX_PEOPLE=12
|
||||
VIDEO_EDIT_MAX_PIXELS=399360
|
||||
MAX_OWNER_RUNS=100
|
||||
MAX_GLOBAL_RUNS=1000
|
||||
MAX_OWNER_BATCHES=20
|
||||
@ -26,5 +39,11 @@ MAX_OWNER_ASSET_BYTES=107374182400
|
||||
MAX_DATA_BYTES=2199023255552
|
||||
MIN_FREE_BYTES=53687091200
|
||||
TTS_API_KEY=
|
||||
# Qwen 按需启动:等待 GPU 交接和冷加载使用独立超时,单位秒。
|
||||
QWEN_TIMEOUT_SECONDS=1800
|
||||
# 配音包含有界排队、CPU冷加载与下载。
|
||||
SPEECH_TIMEOUT_SECONDS=330
|
||||
SPEECH_TOTAL_TIMEOUT_SECONDS=360
|
||||
TTS_QUEUE_TIMEOUT_SECONDS=30
|
||||
WORKSPACE_HOST=/data/llmusers/llmuser/workspace
|
||||
WEB_PORT=18193
|
||||
|
||||
48
.env.local.example
Normal file
48
.env.local.example
Normal file
@ -0,0 +1,48 @@
|
||||
# Windows 本地 Vue + FastAPI;MySQL/模型仍使用既有远端服务。
|
||||
# 复制为私有 .env.local 后填写秘密;不要覆盖已有私有配置或提交它。
|
||||
# KEY=value 为字面值;单引号保留字面内容,双引号使用 JSON 转义;不展开 $变量。
|
||||
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=
|
||||
COOKIE_SECURE=false
|
||||
PUBLIC_ACCESS=false
|
||||
WORKSPACE_ROOT=E:/workspace/hybrid/cmvr-visual/.local/workspace
|
||||
# 服务端 API 停止、当前任务/文件迁移核对完成后,才在本机启用协调器。
|
||||
RUN_COORDINATOR=false
|
||||
# 当前开发机经内网HTTP入口直连;入口保留来源IP限制和API Key验证。
|
||||
INFERENCE_BASE_URL=http://192.168.28.10:18190
|
||||
INFERENCE_REMOTE_FILES=true
|
||||
# Default off for a new installation; API and inference settings must both enable this profile.
|
||||
REFERENCE_GENERATION_ENABLED=false
|
||||
REFERENCE_GENERATION_PROFILE=qwen-image-edit-2511-v1
|
||||
REFERENCE_MAX_IMAGES=3
|
||||
VIDEO_EDIT_ENABLED=false
|
||||
VIDEO_EDIT_PROFILE=wan-animate-replace-v1
|
||||
VIDEO_EDIT_MAX_SECONDS=120
|
||||
VIDEO_EDIT_MAX_PEOPLE=12
|
||||
VIDEO_EDIT_MAX_PIXELS=399360
|
||||
MAX_OWNER_STORY_CANDIDATES=4000
|
||||
MAX_GLOBAL_STORY_CANDIDATES=16000
|
||||
INFERENCE_API_KEY_FILE=E:/workspace/hybrid/cmvr-visual/.local/config/inference.key
|
||||
GPU_STATUS_PATH=
|
||||
GPU_SCHEDULER_PATH=
|
||||
# Provider 从远端能力/状态接口同步策略;首次启动前由运维同步有效策略文件。
|
||||
RUNTIME_POLICY_FILE=E:/workspace/hybrid/cmvr-visual/.local/workspace/config/runtime-policy.json
|
||||
QWEN_BASE_URL=http://192.168.28.10:14081/v1
|
||||
QWEN_MODEL=Qwen/Qwen3.8-27B-FP8
|
||||
QWEN_API_KEY=
|
||||
# 通过内网HTTP入口连接配音;仍需填写原有TTS_API_KEY。
|
||||
TTS_BASE_URL=http://192.168.28.10:18192/v1
|
||||
TTS_MODEL=kokoro-82m
|
||||
TTS_API_KEY=
|
||||
SPEECH_TIMEOUT_SECONDS=330
|
||||
SPEECH_TOTAL_TIMEOUT_SECONDS=360
|
||||
NODE_BIN=E:/developmentTool/nodejs/node.exe
|
||||
FFMPEG_BIN=ffmpeg
|
||||
FFPROBE_BIN=ffprobe
|
||||
4
.gitattributes
vendored
Normal file
4
.gitattributes
vendored
Normal file
@ -0,0 +1,4 @@
|
||||
# Keep formatter output stable on Windows and Linux.
|
||||
* text=auto eol=lf
|
||||
*.bat text eol=crlf
|
||||
*.cmd text eol=crlf
|
||||
7
.gitignore
vendored
7
.gitignore
vendored
@ -1,6 +1,7 @@
|
||||
**/.env
|
||||
**/.env.*
|
||||
!**/.env.example
|
||||
!/.env.local.example
|
||||
!**/.env.test.example
|
||||
**/.venv/
|
||||
**/__pycache__/
|
||||
@ -18,4 +19,8 @@
|
||||
/.deploy/
|
||||
/.cache-models/
|
||||
/.local/
|
||||
/qa/generated/
|
||||
/qa/
|
||||
/outputs/
|
||||
/.superpowers/
|
||||
**/.ruff_cache/
|
||||
.idea/
|
||||
|
||||
11
AGENTS.md
Normal file
11
AGENTS.md
Normal file
@ -0,0 +1,11 @@
|
||||
# 协作约定
|
||||
|
||||
- 用户要求:仅修改和验证工作区;没有用户明确指令,不得自动暂存,也不得执行 Git commit、push、amend、reset 或 revert。已有本地提交先保留。
|
||||
- 保留工作区已有未提交改动,不把结构重构当成重置文件或覆盖其他功能的理由。
|
||||
- 前端和业务后端独立运行;推理服务和共享 Qwen 是外部依赖。普通代码整理不得启动真实模型、停止共享服务或改变 GPU 优先策略。
|
||||
- 结构调整须保持 HTTP/SSE 合同、路由、用户隔离、幂等键、Pinia ID、本地存储键、数据库表及历史迁移兼容。
|
||||
- 关键注释优先使用中文,解释事务、并发、权限、恢复和数据保护的原因;避免逐行翻译代码。
|
||||
- 验证完成后说明修改与检查结果,将代码留在工作区供用户检查。
|
||||
- 测试通过后,立即清理本次生成的临时脚本、截图、测试媒体、日志、隔离数据库、打包文件及代理过程记录,不把验收产物长期留在项目中。
|
||||
- 可重复使用的自动化测试代码和必要的最小夹具属于项目质量保障,应保留;一次性验证脚本与测试生成文件在通过后删除。测试优先使用自动清理的临时目录及隔离数据,避免往真实素材库造测试数据。
|
||||
- 清理只针对已确认的临时内容;保留业务素材、用户要求的成片及音频字幕、运行依赖、私有配置、数据库备份和历史迁移。业务交付文件统一放在 outputs/,长期设计说明放在 docs/design/。
|
||||
99
README.md
99
README.md
@ -5,24 +5,29 @@
|
||||
## 当前交付状态
|
||||
|
||||
- 工程目录:`E:\workspace\hybrid\cmvr-visual`;服务器源码目录:`/workspace/projects/cmvr-visual`。
|
||||
- 已连接用户指定的正式数据库 `192.168.28.10:3306/cmvr-visual`,按要求暂用 root;V2 使用17张 `visual_*` 表及 Alembic 版本表,当前 schema 为003。生产启动只校验,不自动改表。
|
||||
- 默认管理员为 `admin`,初始密码保持用户指定的私有配置;重启不重置已有密码。账号页已支持本人改密、管理员维护用户,以及创建/撤销仅展示一次的机器令牌。普通新密码要求12位以上。
|
||||
- 本机私有 `.env.server` 保存当前服务器配置,`.env.preview` 仅保留旧验收库配置。原独立 MySQL 与样例数据没有自动迁入正式库;秘密不提交Git、不打印到日志、不复制进文档。`.env.example` 不含可用密码。
|
||||
- 网站仅发布服务器 `127.0.0.1:18193`,当前通过受信 SSH 隧道本地访问;不直接向局域网或互联网公开。
|
||||
- 已连接用户指定的 MySQL `192.168.28.10:3306/cmvr-visual`;使用 `visual_*` 表及 Alembic 版本表,当前 schema 为007(2026-11-13完成迁移)。启动只校验结构,不自动改表;数据库账号由私有配置提供。
|
||||
- 可编辑自动成片支持一次自动生成、局部重生成、旁白/字幕编辑和从运行恢复版本。2026-11-13经用户授权,已联合备份、演练恢复并升级实际业务库,重启本机业务API和前端;原有23张表6749条记录及原有字段数据比对一致,新编辑接口鉴权读取通过。真实模型质量和产能仍需单独验收。
|
||||
- 默认管理员为 `admin`,初始密码保持用户指定的私有配置;重启不重置已有密码。头像菜单支持本人修改登录用户名和密码;账户页仅供管理员新增、启停或删除用户。新增用户初始密码允许6–256字符,主动修改密码要求12位以上。
|
||||
- 本机私有 `.env.local` 保存本地真实服务配置,`.env.server` 保存服务器配置,`.env.preview` 仅保留旧验收库配置。原独立 MySQL 与样例数据没有自动迁入正式库;秘密不提交Git、不打印到日志、不复制进文档。`.env.example` 不含可用密码。
|
||||
- 当前开发采用本机 Vue `127.0.0.1:5173` + FastAPI `127.0.0.1:8000`,MySQL 和模型推理保留在远端;服务器网站前后端在本地接管后停止,后续正式发布再启用。
|
||||
|
||||
素材、任务和故事支持数据库逻辑文件夹;创建故事可自动建立同名文件夹,创作时可指定成果位置。素材支持多目录复用、批量整理、删除及发布到共享库。
|
||||
|
||||
入口 `/studio` 为跨镜头锚定故事工作室:统一风格/环境、角色形态和造型、`@`实体绑定、首帧候选确认、视频选片及冻结合成。当前多镜头创作统一从“故事”进入,可选择可编辑自动成片或人工候选确认,在故事内“03 成片”调整时间线并合成。独立“工作流”“批量”“成片”页面已移除;旧链接会转至故事或任务,既有草稿、批次、运行、素材和共享后端API仍保留。使用说明见[锚定工作室操作手册](docs/锚定工作室操作手册_20261111.md)。故事、候选、批准及运行元数据保存在MySQL,素材文件保存在工作空间。
|
||||
|
||||
创作页新增 `/create/image-edit` 与 `/create/video-edit`:按顺序绑定最多三张参考图生成图片;分析源视频,选择一个或多个人物并分别绑定身份图生成替换视频。后者使用独立 Wan2.2-Animate-14B 时序模型,复用现有任务、私有素材和 GPU 优先队列,无新增业务表。开放状态以实际能力和模型验收为准;步骤和部署配置见[图生图与视频人物替换操作手册](docs/图生图与视频人物替换操作手册_20261112.md)。
|
||||
|
||||
执行结果以实际验收记录及接口状态为准。单元测试、模拟上游边界和构建成功分别验证各自范围,不等同于真实模型生成或正式数据库验收。
|
||||
|
||||
本轮交付见 [V2开发与验收记录](docs/V2开发与验收记录_20261110.md):默认规格真实三镜头成片、窗口/队列、迁移恢复及当前公开发布边界均有单独记录。
|
||||
历史兼容:2026-11-11扩展的可变多镜头工作流保留数据与API合同,原独立编辑页不再提供。旧版支持增删/排序、每镜头选用1–15秒、动态音轨字幕范围、JSON导入导出及鲲鹏示例。总时长由镜头选用帧数之和决定,旧三镜头草稿与成片继续兼容;单模型原生视频支持1–15秒参数,默认5秒,实际耗时和资源随帧数增加。
|
||||
|
||||
历史功能基线见 [验收报告](docs/验收报告.md):75项自动化测试、八类真实服务调用及桌面/手机验证。正式库接入后新增初始账号回归,后端52项通过;[实际接入记录](qa/mysql-integration-20261110.json)验证正式库登录、读写与SSE。
|
||||
当前使用说明见[操作手册](docs/操作手册_20261111.md):第0节说明六项能力入口,第4节说明故事自动与人工创作,第7节说明故事内的批量执行模式与日夜节拍,第12节说明可编辑自动成片。故事页可打开在线帮助,网页主手册为 `/help/manual.html`。02分镜内容超出工作区时仅在对应容器内滚动;滚动条悬停或键盘操作时显示,移出后隐藏,触屏可直接滑动。[鲲鹏长视频制作指南](docs/鲲鹏长视频制作指南_20261111.md)中的旧JSON与实测记录保留作历史参考,`frontend/public/examples/kunpeng-storyboard.json`不提供当前故事页直接导入。
|
||||
|
||||
2026-11-11扩展为可变多镜头工作流:增删/排序、每镜头选用1–5秒、动态音轨字幕范围、JSON导入导出及20镜头100秒鲲鹏示例。总时长由镜头选用帧数之和决定,旧三镜头草稿与成片继续兼容;单模型原生视频任务仍约5秒。
|
||||
现有“审核”为本人确认首帧和视频选片;生产节拍统计、严格夜间范围和可选多人审批的缺口及实施路径见[生产流程完善方案](docs/design/2026-11-12-production-workflow-design.md),网页版本为 `/help/production.html`。该方案明确区分已实现功能与待实施内容,不代表新增功能已上线。
|
||||
|
||||
使用说明见[操作手册](docs/操作手册_20261111.md)和[鲲鹏长视频制作指南](docs/鲲鹏长视频制作指南_20261111.md),网站工作流页也提供两份在线帮助。模板位于`frontend/public/examples/kunpeng-storyboard.json`,载入后不会自动生成或保存。
|
||||
手册更新后可运行`python scripts/render_manuals.py`生成HTML,再构建前端发布;45秒配音版模板同目录另有`kunpeng-storyboard-45s.json`。
|
||||
|
||||
本轮部署与真实验证见[2026-11-11开发与验收记录](docs/开发与验收记录_20261111.md)。手册更新后可运行`python scripts/render_manuals.py`生成HTML,再构建前端发布;45秒配音版模板同目录另有`kunpeng-storyboard-45s.json`。
|
||||
|
||||
另有[单镜头超过5秒实测](docs/单镜头超过5秒实测报告_20261111.md):既有环境成功生成241帧、24fps、约10秒的原片和增强版;当前网页仍保留5秒上限,尚未正式开放10秒参数。
|
||||
业务交付的成片、配音、配乐和字幕保存在 `outputs/`;素材库运行数据仍在 `.local/workspace`。测试通过后清理临时验收文件,保留可复用的自动化测试与最小夹具,详见[协作约定](AGENTS.md)。
|
||||
|
||||
批量时段由API与GPU worker共读的`/workspace/projects/llm-services/config/runtime-policy.json`决定。`batch_window_enabled=false`为开发全天模式,`true`恢复北京时间21:00–08:00准入;开启时08:00关闭新镜头/新处理阶段准入,当前阶段自然完成,后续排队。文件热读取,样例见`deploy/runtime-policy.development.json`与`deploy/runtime-policy.production.json`。文件缺失默认启用限制,格式错误关闭新batch准入。`workflow_max_shots`默认120,可配置1–1000,只限制新草稿/运行/编排的准入。
|
||||
|
||||
@ -30,12 +35,14 @@ Wan与其集成增强视为同一镜头。交互创作全天等待空闲资源
|
||||
|
||||
初始额度:每用户未结束叶任务500、全局2000;每用户未结束Run100、Batch20,全局Run1000、Batch200;每批最多100项。创建Job/Run/Batch共用每用户每分钟6次命令额度,内部子步骤不重复扣命令数,原键重放不扣额。所有数字可通过配置调整。
|
||||
|
||||
## 八项能力与实际限制
|
||||
## 模型与媒体能力
|
||||
|
||||
| 任务类型 | 后端 | 实际能力与边界 |
|
||||
| --- | --- | --- |
|
||||
| `image.generate` | 既有 Qwen-Image GPU 队列 | 文本生成图片;默认 1024²、50 步。不提供图像编辑或 LoRA 管理。 |
|
||||
| `video.generate` | 既有 Wan2.2-TI2V-5B,可接 Real-ESRGAN | 文生视频或参考首帧;最多 121 帧、24 fps,约 **5 秒**,可选 1080p 增强。不是 15 秒生成,也不附带声音。 |
|
||||
| `image.reference.generate` | Qwen-Image-Edit-2511 / vLLM-Omni | 创作图生图及故事首帧真实多图参考,普通profile最多3张有序去重图片,支持方/横/竖;两端能力开关一致才开放,不默降文字生成。 |
|
||||
| `video.people.analyze` / `video.replace` | 独立 Wan2.2-Animate-14B / Diffusers,YOLO、ViTPose、SAM2 | 选择多人并分别绑定身份参考图,时序替换后合成同一成片,可保留原音轨;默认120秒、12人和约480p预算,可配置,须双端认证开放。 |
|
||||
| `video.generate` | 既有 Wan2.2-TI2V-5B,可接 Real-ESRGAN | 文生视频或参考首帧;1–15秒、24 fps,最大361帧,默认5秒/121帧,可选1080p增强;视频本身不附带声音。 |
|
||||
| `defect.generate` | SDXL + Canny ControlNet | 根据参考图片边缘约束生成条件样本,输出合成图和控制图;**控制图不是缺陷真值 mask**。 |
|
||||
| `audio.transcribe` | 既有 Whisper large-v3-turbo | 音频或有声视频转写;视频先在 CPU 提取音轨,最长 1800 秒。时间戳是约 30 秒分块边界,不是逐词对齐。 |
|
||||
| `math.solve` | 既有 Qwen 文本 HTTP 服务 | 数学解答文本;没有形式化证明或专业正确率验收承诺。 |
|
||||
@ -43,7 +50,7 @@ Wan与其集成增强视为同一镜头。交互创作全天等待空闲资源
|
||||
| `video.compose` | CPU FFmpeg | 片段排序、裁切、直切拼接、单音轨和人工字幕;片段数量由配置控制,总时长由片段决定,帧率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`,界面不编造百分比。
|
||||
参数约束以登录后的 `/api/capabilities` 及 `/api/stories/capabilities` 为准。生成步数字段为 `num_inference_steps`。普通任务接口的图片和条件样本支持 `count=1..4`,故事候选另支持每镜头1–4个首帧或视频候选,均拆成独立任务,种子按序递增。没有真实生成进度来源时 `progress=null`,界面不编造百分比。
|
||||
|
||||
## 项目分层与通信
|
||||
|
||||
@ -58,7 +65,9 @@ Nginx → FastAPI 业务 API → MySQL visual_* 表
|
||||
└─ CPU FFmpeg / 独立 CPU Kokoro
|
||||
```
|
||||
|
||||
`frontend/` 为界面;`backend/app/` 为账号、素材、任务、工作流和协调器;`backend/alembic/` 为迁移;`inference/` 保存既有唯一GPU服务的版本化源码;`tts/` 为CPU配音;`deploy/`、`compose.yaml` 为部署文件。[API 示例](docs/API-examples.md) 和 [共享契约](docs/api-contract.md) 说明调用方式。
|
||||
`frontend/` 和 `backend/` 是独立工程。前端按 `api/types/domain/services/stores/views/components/styles` 分工;后端按 `api/schemas/core/models/domain/services/adapters` 分层,`app.main:app` 保持稳定入口。模型适配器已按协议、远端文件、GPU、Qwen、语音和成片拆分,媒体处理不再反向依赖整个Provider。
|
||||
|
||||
`backend/alembic/` 为迁移;`inference/` 保存既有GPU队列服务的版本化源码;`tts/` 为CPU配音;`deploy/`、`compose.yaml` 为部署文件。目录、依赖方向、注释约定和检查命令见[工程结构与开发约定](docs/工程结构与开发约定.md)。[API 示例](docs/API-examples.md) 和 [共享契约](docs/api-contract.md) 说明调用方式。用户未明确要求时不创建Git提交或推送,详见[协作约定](AGENTS.md)。
|
||||
|
||||
任务提交是短 HTTP 请求,长任务通过 SSE 单向通知浏览器,不需要双向 WebSocket。事件先和数据库状态一起提交;`Last-Event-ID` 用于重连重放,Cookie 使原生 EventSource 无需把令牌放进 URL。SSE 断开不会取消生成,重连后还会重新获取 HTTP 状态快照。[SSE 标准](https://html.spec.whatwg.org/multipage/server-sent-events.html)
|
||||
|
||||
@ -81,11 +90,48 @@ Nginx → FastAPI 业务 API → MySQL visual_* 表
|
||||
| 模型 API | Docker 网络内 `http://llmuser-workspace:18190` |
|
||||
| 模型认证文件 | `/workspace/projects/llm-services/config/api_key`,仅后端读取 |
|
||||
|
||||
用户只提交素材 ID;服务器校验 owner 后解析共享工作区路径。素材内容、缩略图、Range 请求、任务和 SSE 都经过登录与归属校验,不将素材目录直接挂成公开静态目录。被任务引用的已删除输入仍保留物理文件。账号密码用加盐 scrypt,Cookie 为 HttpOnly;所有写操作除登录外均要求 CSRF 头。
|
||||
用户只提交素材 ID;业务后端校验 owner 后解析素材路径。素材内容、缩略图、Range 请求、任务和 SSE 都经过登录与归属校验,不将素材目录直接挂成公开静态目录。素材仍被任务或工作流使用时拒绝删除;允许删除后同步移除原文件、缩略图和数据库文件记录。共享发布和引用者的私有副本各自独立,删除其中一份不会删除其他副本。账号密码用加盐 scrypt,Cookie 为 HttpOnly;所有写操作除登录外均要求 CSRF 头。
|
||||
|
||||
API 和 TTS 容器不挂GPU、宿主`/proc`或Docker socket,根文件系统只读;API仅挂本应用数据、只读模型认证和调度状态目录。模型权重不随网站镜像打包。`inference/` 的更新部署到既有模型服务路径,保留原队列和监管,不启动第二个GPU worker,不修改共享Qwen容器。
|
||||
|
||||
## 本地开发
|
||||
## Windows 本地开发:连接真实 MySQL 与远端模型
|
||||
|
||||
当前使用 `E:\workspace\hybrid\cmvr-visual`。前端和业务 API 在 Windows 本机运行;MySQL 继续使用既有 `192.168.28.10:3306/cmvr-visual`,模型继续使用既有服务器推理队列,不能同时运行两个连接正式库的业务协调器。服务器网站 API 停止并完成文件/任务迁移核对后,才把本地私有配置中的 `RUN_COORDINATOR` 改成 `true`。正式模式只校验既有表结构,不自动建库、改表或回退 SQLite。
|
||||
|
||||
准备本机 Python 3.11+、Node/pnpm,以及 `ffmpeg`/`ffprobe`。已有虚拟环境、依赖和 `.env.local` 时跳过相应步骤,避免覆盖私有配置:
|
||||
|
||||
```powershell
|
||||
Set-Location E:\workspace\hybrid\cmvr-visual
|
||||
python -m venv backend/.venv
|
||||
& ./backend/.venv/Scripts/python.exe -m pip install -r backend/requirements-dev.txt
|
||||
& E:/developmentTool/nodejs/pnpm.cmd --dir frontend install --frozen-lockfile
|
||||
Copy-Item .env.local.example .env.local
|
||||
# 用本机编辑器填写 .env.local;数据库、账号和模型密钥不要写进命令行历史。
|
||||
```
|
||||
|
||||
`.env.local.example` 仅提供配置项,无有效密码。把既有获准的 MySQL/管理员配置放进被 Git 忽略的 `.env.local`,模型密钥保存在 `.local/config/inference.key`;不要把后端秘密放入 `VITE_*`。启动器只加载 `.env.local`,其内容覆盖当前终端同名环境变量;不执行脚本、不展开变量。单引号是字面值,双引号按 JSON 转义;Windows 路径建议使用 `/`。`NODE_BIN` 可以指定 `node.exe`,也支持 PATH 或本机 `E:/developmentTool/nodejs/node.exe`;缺失依赖会明确报错,不会自动安装。
|
||||
|
||||
当前开发机直接通过内网 HTTP 连接模型 `http://192.168.28.10:18190` 和配音 `http://192.168.28.10:18192/v1`,无需建立模型 SSH 隧道。服务器独立入口限定开发机来源 IP 并保留 API Key 鉴权,配置见 [model-gateway](deploy/model-gateway/README.md)。本地设置 `INFERENCE_REMOTE_FILES=true`,通过认证 HTTP 上传模型输入和下载产物;Windows 本地路径不交给远端模型作为服务器文件路径。`WORKSPACE_ROOT` 使用本机 `.local/workspace`;接管前须同步正式库中既有素材和任务文件。`RUNTIME_POLICY_FILE` 指向已同步的本地策略文件,Provider 从远端能力/状态同步有效策略,保持 API 与推理队列规则一致。
|
||||
|
||||
在项目根目录执行:
|
||||
|
||||
```powershell
|
||||
& ./backend/.venv/Scripts/python.exe scripts/local_dev.py start
|
||||
& ./backend/.venv/Scripts/python.exe scripts/local_dev.py status
|
||||
& ./backend/.venv/Scripts/python.exe scripts/local_dev.py stop
|
||||
```
|
||||
|
||||
访问 `http://127.0.0.1:5173`;Vite 将 `/api` 同源代理到 `127.0.0.1:8000`。启动器在后台隐藏启动单进程 uvicorn 和 Vite,等待实际 HTTP 状态并确认子进程仍存活。`api: ready` 表示本地数据库、协调器和准入检查通过;`upstream_protocol=unavailable` 会单独提示模型连接退化,此时网站可打开,应检查内网 HTTP 入口和上游服务。GPU 忙碌本身不算连接故障。`status` 任一本机服务未就绪时返回非零退出码;完整模型协议状态以 API `/api/ready` 为准。
|
||||
|
||||
日志位于 `.local/logs/api.log` 和 `.local/logs/frontend.log`,进程记录位于 `.local/dev-processes.json`。端口已被占用时启动失败,请先识别占用者;启动器不会抢占或停止无关进程。`stop` 使用 PID、Windows 创建时间和可执行文件身份核对,只停止本次启动器记录的本机进程;API 先执行正常关闭,超过20秒会保留进程和记录供排查。它不会停止 SSH、MySQL、远端模型或服务器网站。既有上游任务不会因停止本机网页而自动取消。
|
||||
|
||||
启动器测试不连接正式 MySQL 或真实模型;API 正常关闭测试使用自动清理的临时 SQLite:
|
||||
|
||||
```powershell
|
||||
& ./backend/.venv/Scripts/python.exe -m unittest discover -s scripts/tests -v
|
||||
```
|
||||
|
||||
## 可选 SQLite 开发预览
|
||||
|
||||
需要 Python 3.11+、Node/pnpm;媒体探测和合成需 `ffmpeg`、`ffprobe` 在 PATH。本地 SQLite 仅是显式开发预览,不是 MySQL 故障后的自动回退。
|
||||
|
||||
@ -93,7 +139,7 @@ PowerShell,在项目根目录执行:
|
||||
|
||||
```powershell
|
||||
python -m venv backend/.venv
|
||||
& ./backend/.venv/Scripts/python.exe -m pip install -r backend/requirements.txt
|
||||
& ./backend/.venv/Scripts/python.exe -m pip install -r backend/requirements-dev.txt
|
||||
New-Item -ItemType Directory -Force .local/workspace | Out-Null
|
||||
$env:CMVR_MODE = 'preview'
|
||||
$env:WORKSPACE_ROOT = (Resolve-Path .local/workspace).Path
|
||||
@ -117,16 +163,19 @@ pnpm dev
|
||||
|
||||
访问 `http://127.0.0.1:5173`。Vite 将 `/api` 同源代理到 `127.0.0.1:8000`。开发进程不会自动加载 `.env`;须显式设置环境或使用受控的环境文件加载方式。首次启动仅在账号不存在时创建管理员,重复启动不会用环境变量重置已有密码。无默认密码、无公开注册。
|
||||
|
||||
上例主动禁用 GPU 入口:Windows 本地文件路径不能作为远端模型的 `/workspace` 路径。真实生成使用下述同机 Docker 部署。数学/视觉、FFmpeg、配音是否可用取决于实际服务和本地程序配置;不会在缺失时生成假结果。
|
||||
上例主动禁用 GPU 入口;它只用于独立 SQLite 预览。需要真实生成时使用上文的本机业务服务 + 远端文件传输配置,或下述正式同机 Docker 部署。数学/视觉、FFmpeg、配音是否可用取决于实际服务和本地程序配置;不会在缺失时生成假结果。
|
||||
|
||||
测试与前端构建:
|
||||
|
||||
```powershell
|
||||
cd backend
|
||||
& ./.venv/Scripts/python.exe -m pytest -q
|
||||
& ./.venv/Scripts/python.exe -m ruff check app tests alembic/env.py
|
||||
& ./.venv/Scripts/python.exe -m ruff format --check app tests alembic/env.py
|
||||
cd ../frontend
|
||||
pnpm test
|
||||
pnpm build
|
||||
pnpm format:check
|
||||
```
|
||||
|
||||
缺少 FFmpeg 时相关媒体集成测试会跳过,Linux 的实际媒体测试应单独执行。不要据 SQLite 测试推断正式 MySQL 已连接。
|
||||
@ -137,7 +186,7 @@ pnpm build
|
||||
|
||||
私有 `.env` 至少配置 `CMVR_MODE=production`、`MYSQL_HOST`、`MYSQL_PORT`、`MYSQL_DATABASE`、`MYSQL_USER`、`MYSQL_PASSWORD` 及管理员初始化信息。推荐这些分离字段,后端用 `URL.create` 处理数据库名与密码特殊字符;不要手工拼接连接串。正式库不可达时启动失败,不会切换 SQLite。
|
||||
|
||||
现有六表先经过精确基线检查再登记001,002增补工作流等表,003增加批次持久hold。生产启动要求003,并检查列、类型、索引和约束;只有显式test/preview模式使用`create_all`。从源码backend目录、已安全加载数据库环境后执行:
|
||||
现有六表先经过精确基线检查再登记001,002增补工作流等表,003增加批次持久hold,004增加私有内容及共享素材支持。当前生产启动要求004,并检查列、类型、索引和约束;只有显式test/preview模式使用`create_all`。从源码backend目录、已安全加载数据库环境后执行:
|
||||
|
||||
```bash
|
||||
# 仅匹配的、尚未版本化的旧六表数据库执行一次:
|
||||
@ -147,7 +196,9 @@ alembic -c alembic.ini upgrade head
|
||||
|
||||
空库直接`upgrade head`。已有003库无需stamp。迁移不提供破坏性downgrade;MySQL DDL可能已提交,失败时保持维护并使用已演练的联合恢复点或修复迁移。
|
||||
|
||||
## Docker Compose 启动
|
||||
## Docker Compose 正式部署(后续启用)
|
||||
|
||||
本节保留正式发布步骤。当前 Windows 本地开发不执行这些命令;服务器网站前后端保持停止,模型服务继续运行。
|
||||
|
||||
运维在宿主源码目录 `/data/llmusers/llmuser/workspace/projects/cmvr-visual` 操作。先将前端构建为 `frontend/dist`,因为前端镜像直接复制该目录:
|
||||
|
||||
@ -199,13 +250,13 @@ docker compose logs --tail=100 api
|
||||
|
||||
## 访问方式与对外安全边界
|
||||
|
||||
当前宿主只监听 `127.0.0.1:18193`。从客户端建立隧道:
|
||||
后续恢复服务器网站部署时,宿主网站只监听 `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` 安全取得,不在控制台回显。
|
||||
使用已有获准的运维 SSH 账号;`root` 仅是当前运维连接示例,命令没有内嵌密码。受限 `llmuser` 的 SSH 转发已禁用,不要为了网站访问放开其隔离规则。上述命令后访问 `http://127.0.0.1:18193`;Windows 本地开发的 `8000` 端口由本机 API 使用,不应再把服务器网站隧道绑定到该端口。默认管理员配置由本机私有 `.env.server` 安全取得,不在控制台回显。
|
||||
|
||||
当前回环 HTTP/SSH 验收使用 `COOKIE_SECURE=false`。互联网或不可信网络访问必须先配置 HTTPS 反代或受信加密隧道,并在 HTTPS 浏览器入口使用 `COOKIE_SECURE=true`。保持前后端同源;Cookie 为 HttpOnly/SameSite,CSRF 校验不得移除,推理密钥不得进入前端变量或 URL。
|
||||
|
||||
@ -247,3 +298,5 @@ docker compose up -d api
|
||||
每张符合条件的空闲GPU同时运行一个任务,最多四卡并行。就绪任务按持久入队顺序派发,完成顺序可不同;独立分镜和批次成员有界补队,合成等待全部选定输出。外部用户占用某张卡时,只让出该卡并重排对应任务。
|
||||
|
||||
工作容器内存上限为384 GiB(内存加swap总上限同为384 GiB);派发同时检查主存和共享内存预算。单卡68 GiB分配预算、8 GiB空闲预留和连续空闲15秒准入保持有效。管理员设置放在推理服务config/settings.json;修改runtime-policy.json仍只控制其已支持的时段/工作流字段。
|
||||
|
||||
2026-11-13按用户要求,共享 `Qwen/Qwen3.8-27B-FP8` 恢复常驻 GPU0,调用地址仍为 `http://192.168.28.10:14081/v1`。GPU0 持续预约给共享模型,媒体任务使用其余符合准入条件的 GPU1–3;停止了调用结束自动卸载模型的网关。运行方式及切换记录见 [Qwen运行说明](docs/Qwen按需运行_20261112.md)。
|
||||
|
||||
@ -23,5 +23,15 @@ QWEN_API_KEY=
|
||||
TTS_BASE_URL=
|
||||
TTS_MODEL=
|
||||
TTS_API_KEY=
|
||||
SPEECH_TIMEOUT_SECONDS=330
|
||||
SPEECH_TOTAL_TIMEOUT_SECONDS=360
|
||||
FFMPEG_BIN=ffmpeg
|
||||
FFPROBE_BIN=ffprobe
|
||||
REFERENCE_GENERATION_ENABLED=false
|
||||
REFERENCE_GENERATION_PROFILE=qwen-image-edit-2511-v1
|
||||
REFERENCE_MAX_IMAGES=3
|
||||
VIDEO_EDIT_ENABLED=false
|
||||
VIDEO_EDIT_PROFILE=wan-animate-replace-v1
|
||||
VIDEO_EDIT_MAX_SECONDS=120
|
||||
VIDEO_EDIT_MAX_PEOPLE=12
|
||||
VIDEO_EDIT_MAX_PIXELS=399360
|
||||
|
||||
@ -1,26 +1,44 @@
|
||||
import asyncio,os
|
||||
import asyncio
|
||||
from alembic import context
|
||||
from sqlalchemy.ext.asyncio import create_async_engine
|
||||
from app.models import Base
|
||||
from app import v2_models
|
||||
from app.config import Settings
|
||||
config=context.config
|
||||
target_metadata=Base.metadata
|
||||
from app.core.config import Settings
|
||||
|
||||
config = context.config
|
||||
target_metadata = Base.metadata
|
||||
|
||||
|
||||
def include_object(obj, name, type_, reflected, compare_to):
|
||||
return name.startswith("visual_") if type_ == "table" else True
|
||||
|
||||
def include_object(obj,name,type_,reflected,compare_to):
|
||||
return name.startswith("visual_") if type_=="table" else True
|
||||
|
||||
def run(connection):
|
||||
context.configure(connection=connection,target_metadata=target_metadata,include_object=include_object,compare_type=True)
|
||||
with context.begin_transaction():context.run_migrations()
|
||||
context.configure(
|
||||
connection=connection,
|
||||
target_metadata=target_metadata,
|
||||
include_object=include_object,
|
||||
compare_type=True,
|
||||
)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
async def online():
|
||||
url=config.attributes.get("url") or Settings.from_env().sqlalchemy_url
|
||||
engine=create_async_engine(url)
|
||||
async with engine.connect() as connection:await connection.run_sync(run)
|
||||
url = config.attributes.get("url") or Settings.from_env().sqlalchemy_url
|
||||
engine = create_async_engine(url)
|
||||
async with engine.connect() as connection:
|
||||
await connection.run_sync(run)
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
context.configure(url=config.get_main_option("sqlalchemy.url"),target_metadata=target_metadata,literal_binds=True,include_object=include_object)
|
||||
with context.begin_transaction():context.run_migrations()
|
||||
else:asyncio.run(online())
|
||||
context.configure(
|
||||
url=config.get_main_option("sqlalchemy.url"),
|
||||
target_metadata=target_metadata,
|
||||
literal_binds=True,
|
||||
include_object=include_object,
|
||||
)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
else:
|
||||
asyncio.run(online())
|
||||
|
||||
63
backend/alembic/versions/005_story_studio.py
Normal file
63
backend/alembic/versions/005_story_studio.py
Normal file
@ -0,0 +1,63 @@
|
||||
"""Append-only story selections and durable candidate plans; no legacy table changes."""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.dialects.mysql import DATETIME
|
||||
|
||||
revision = "005"
|
||||
down_revision = "004"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def referenced_type(bind, name):
|
||||
column = next(c["type"].copy() for c in sa.inspect(bind).get_columns(name) if c["name"] == "id")
|
||||
if bind.dialect.name == "mysql":
|
||||
charset, collation = bind.execute(sa.text("SELECT CHARACTER_SET_NAME,COLLATION_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=:name AND COLUMN_NAME='id'"), {"name": name}).one()
|
||||
column.charset, column.collation = charset, collation
|
||||
return column
|
||||
|
||||
|
||||
def upgrade():
|
||||
bind = op.get_bind()
|
||||
timestamp = sa.DateTime().with_variant(DATETIME(fsp=6), "mysql")
|
||||
metadata = sa.MetaData()
|
||||
uid, did = referenced_type(bind, "visual_users"), referenced_type(bind, "visual_drafts")
|
||||
sa.Table("visual_users", metadata, sa.Column("id", uid.copy(), primary_key=True))
|
||||
sa.Table("visual_drafts", metadata, sa.Column("id", did.copy(), primary_key=True))
|
||||
common = lambda: [
|
||||
sa.Column("id", sa.String(32), primary_key=True),
|
||||
sa.Column("owner_id", uid.copy(), sa.ForeignKey("visual_users.id"), nullable=False, index=True),
|
||||
sa.Column("draft_id", did.copy(), sa.ForeignKey("visual_drafts.id"), nullable=False, index=True),
|
||||
sa.Column("shot_id", sa.String(32), nullable=False, index=True),
|
||||
sa.Column("kind", sa.String(16), nullable=False),
|
||||
sa.Column("context_hash", sa.String(64), nullable=False),
|
||||
sa.Column("version", sa.Integer(), nullable=False),
|
||||
sa.Column("created_at", timestamp, nullable=False),
|
||||
]
|
||||
candidate = sa.Table("visual_shot_candidates", metadata, *common(),
|
||||
sa.Column("source_kind", sa.String(16), nullable=False),
|
||||
sa.Column("job_id", sa.String(32), nullable=True, index=True),
|
||||
sa.Column("asset_id", sa.String(32), nullable=True),
|
||||
sa.Column("asset_sha256", sa.String(64), nullable=True),
|
||||
sa.Column("generation_hash", sa.String(64), nullable=False),
|
||||
sa.Column("created_revision", sa.Integer(), nullable=False),
|
||||
sa.Column("state", sa.String(32), nullable=False),
|
||||
sa.Column("plan_json", sa.JSON(), nullable=False),
|
||||
sa.Column("error_json", sa.JSON(), nullable=True),
|
||||
sa.Column("batch_id", sa.String(32), nullable=True, index=True),
|
||||
sa.Column("deleted_at", timestamp, nullable=True))
|
||||
selection = sa.Table("visual_shot_selections", metadata, *common(),
|
||||
sa.Column("candidate_id", sa.String(32), nullable=True),
|
||||
sa.Column("asset_id", sa.String(32), nullable=True),
|
||||
sa.Column("decision_json", sa.JSON(), nullable=False),
|
||||
sa.UniqueConstraint("draft_id", "shot_id", "kind", "version"))
|
||||
for table in (candidate, selection):
|
||||
table.create(bind, checkfirst=True)
|
||||
existing = {i["name"] for i in sa.inspect(bind).get_indexes(table.name)}
|
||||
for index in table.indexes:
|
||||
if index.name not in existing:
|
||||
index.create(bind, checkfirst=True)
|
||||
|
||||
|
||||
def downgrade():
|
||||
raise RuntimeError("Destructive downgrade unsupported; restore a verified joint checkpoint")
|
||||
67
backend/alembic/versions/006_logical_folders.py
Normal file
67
backend/alembic/versions/006_logical_folders.py
Normal file
@ -0,0 +1,67 @@
|
||||
"""Database-only logical folders; existing business rows and paths stay intact."""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.dialects.mysql import DATETIME
|
||||
|
||||
revision = '006'
|
||||
down_revision = '005'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def referenced_type(bind, name):
|
||||
column = next(c['type'].copy() for c in sa.inspect(bind).get_columns(name) if c['name'] == 'id')
|
||||
if bind.dialect.name == 'mysql':
|
||||
charset, collation = bind.execute(sa.text("SELECT CHARACTER_SET_NAME,COLLATION_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=:name AND COLUMN_NAME='id'"), {'name': name}).one()
|
||||
column.charset, column.collation = charset, collation
|
||||
return column
|
||||
|
||||
|
||||
def upgrade():
|
||||
bind = op.get_bind()
|
||||
uid = referenced_type(bind, 'visual_users')
|
||||
aid = referenced_type(bind, 'visual_assets')
|
||||
# 新目录 ID 继承用户 ID 的字符集/排序规则;所有引用使用反射类型。
|
||||
fid = uid.copy()
|
||||
timestamp = sa.DateTime().with_variant(DATETIME(fsp=6), 'mysql')
|
||||
metadata = sa.MetaData()
|
||||
sa.Table('visual_users', metadata, sa.Column('id', uid.copy(), primary_key=True))
|
||||
sa.Table('visual_assets', metadata, sa.Column('id', aid.copy(), primary_key=True))
|
||||
folders = sa.Table('visual_folders', metadata,
|
||||
sa.Column('id', fid.copy(), primary_key=True),
|
||||
sa.Column('owner_id', uid.copy(), sa.ForeignKey('visual_users.id'), nullable=False, index=True),
|
||||
sa.Column('name', sa.String(255), nullable=False),
|
||||
sa.Column('parent_id', fid.copy(), sa.ForeignKey('visual_folders.id', ondelete='CASCADE'), nullable=True, index=True),
|
||||
sa.Column('parent_key', sa.String(32), nullable=False, server_default=''),
|
||||
sa.Column('created_at', timestamp, nullable=False),
|
||||
sa.Column('updated_at', timestamp, nullable=False),
|
||||
sa.UniqueConstraint('owner_id', 'parent_key', 'name', name='uq_visual_folders_sibling'))
|
||||
links = sa.Table('visual_asset_folders', metadata,
|
||||
sa.Column('asset_id', aid.copy(), sa.ForeignKey('visual_assets.id', ondelete='CASCADE'), primary_key=True),
|
||||
sa.Column('folder_id', fid.copy(), sa.ForeignKey('visual_folders.id', ondelete='CASCADE'), primary_key=True, index=True))
|
||||
for table in (folders, links):
|
||||
table.create(bind, checkfirst=True)
|
||||
existing = {i['name'] for i in sa.inspect(bind).get_indexes(table.name)}
|
||||
for index in table.indexes:
|
||||
if index.name not in existing:
|
||||
index.create(bind, checkfirst=True)
|
||||
# SQLite 用 batch 新增外键;MySQL 保留原表与历史数据,使用原生 ALTER。
|
||||
for table_name in ('visual_jobs', 'visual_drafts', 'visual_workflow_runs'):
|
||||
fields = ['folder_id'] + ([] if table_name == 'visual_drafts' else ['output_folder_id'])
|
||||
inspector = sa.inspect(bind)
|
||||
columns = {c['name'] for c in inspector.get_columns(table_name)}
|
||||
fks = {tuple(f['constrained_columns']) for f in inspector.get_foreign_keys(table_name)}
|
||||
indexes = {i['name'] for i in inspector.get_indexes(table_name)}
|
||||
with op.batch_alter_table(table_name) as batch:
|
||||
for field in fields:
|
||||
if field not in columns:
|
||||
batch.add_column(sa.Column(field, fid.copy(), nullable=True))
|
||||
if (field,) not in fks:
|
||||
batch.create_foreign_key(f'fk_{table_name}_{field}', 'visual_folders', [field], ['id'], ondelete='SET NULL')
|
||||
index = f'ix_{table_name}_{field}'
|
||||
if index not in indexes:
|
||||
batch.create_index(index, [field])
|
||||
|
||||
|
||||
def downgrade():
|
||||
raise RuntimeError('Destructive downgrade unsupported; restore a verified joint checkpoint')
|
||||
32
backend/alembic/versions/007_editable_automation.py
Normal file
32
backend/alembic/versions/007_editable_automation.py
Normal file
@ -0,0 +1,32 @@
|
||||
"""可恢复自动成片;仅追加字段,历史运行保留 legacy 语义。"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
revision = '007'
|
||||
down_revision = '006'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
columns = {
|
||||
'visual_drafts': [sa.Column('editor_manifest', sa.JSON(), nullable=True)],
|
||||
'visual_workflow_runs': [
|
||||
sa.Column('run_kind', sa.String(32), nullable=False, server_default='legacy'),
|
||||
sa.Column('output_goal', sa.String(16), nullable=False, server_default='film'),
|
||||
sa.Column('base_run_id', sa.String(32), nullable=True),
|
||||
sa.Column('source_draft_version', sa.Integer(), nullable=True),
|
||||
sa.Column('plan_snapshot', sa.JSON(), nullable=True),
|
||||
sa.Column('result_manifest', sa.JSON(), nullable=True),
|
||||
sa.Column('apply_state', sa.String(16), nullable=True)],
|
||||
'visual_workflow_steps': [sa.Column(name, sa.JSON(), nullable=True) for name in ('recipe_json','resolved_input_json','result_json')],
|
||||
}
|
||||
bind = op.get_bind()
|
||||
for table, fields in columns.items():
|
||||
existing = {c['name'] for c in sa.inspect(bind).get_columns(table)}
|
||||
for field in fields:
|
||||
if field.name not in existing:
|
||||
op.add_column(table, field)
|
||||
|
||||
|
||||
def downgrade():
|
||||
raise RuntimeError('Destructive downgrade unsupported; restore a verified joint checkpoint')
|
||||
0
backend/app/adapters/__init__.py
Normal file
0
backend/app/adapters/__init__.py
Normal file
681
backend/app/adapters/media.py
Normal file
681
backend/app/adapters/media.py
Normal file
@ -0,0 +1,681 @@
|
||||
"""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
|
||||
|
||||
|
||||
from app.domain.errors import MediaError
|
||||
from app.domain.execution import CpuResult
|
||||
from app.adapters.storage import file_thread
|
||||
|
||||
|
||||
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
|
||||
|
||||
# 超限或取消后也要排空管道,否则子进程退出后 transport 仍可能被满管道占住。
|
||||
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]:
|
||||
"""只管理本次 FFmpeg/ffprobe 子进程,取消时执行 TERM/KILL/wait。
|
||||
|
||||
读取期间就限制管道大小,避免任意诊断输出耗尽内存;不会停止共享模型服务。
|
||||
"""
|
||||
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]:
|
||||
# 限制输入协议与容器,排除播放列表、网络协议和嵌套文件列表。
|
||||
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 file_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)
|
||||
|
||||
|
||||
async def inspect_video_track(path: Path, settings) -> dict:
|
||||
"""Count decoded video frames; container or audio duration cannot mask a short source."""
|
||||
from fractions import Fraction
|
||||
|
||||
source = confined(path, settings)
|
||||
raw = await run_process(
|
||||
[
|
||||
settings.ffprobe_bin,
|
||||
"-v",
|
||||
"error",
|
||||
*input_options(),
|
||||
"-select_streams",
|
||||
"v:0",
|
||||
"-count_frames",
|
||||
"-show_entries",
|
||||
"stream=width,height,avg_frame_rate,nb_read_frames,duration,time_base:format=duration",
|
||||
"-of",
|
||||
"json",
|
||||
str(source),
|
||||
],
|
||||
timeout=120,
|
||||
max_output=256 * 1024,
|
||||
)
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
stream = data["streams"][0]
|
||||
frames = int(stream["nb_read_frames"])
|
||||
fps = Fraction(stream["avg_frame_rate"])
|
||||
width, height = int(stream["width"]), int(stream["height"])
|
||||
if frames <= 0 or fps <= 0 or width <= 0 or height <= 0 or width * height > 40000000:
|
||||
raise ValueError
|
||||
return {
|
||||
"frames": frames,
|
||||
"fps": float(fps),
|
||||
"width": width,
|
||||
"height": height,
|
||||
"duration": float(data["format"]["duration"]),
|
||||
"time_base": stream.get("time_base"),
|
||||
}
|
||||
except (KeyError, IndexError, TypeError, ValueError, ZeroDivisionError):
|
||||
raise MediaError("invalid_media", "Video frame decoding failed.") from None
|
||||
|
||||
|
||||
async def compose_workflow(plan, work_dir, control=None, *, settings, sources, audio=None):
|
||||
"""Render a frozen multi-shot timeline from internal resolved asset paths."""
|
||||
if len(sources) != len(plan.spec["shots"]):
|
||||
raise MediaError("invalid_timeline", "Source videos differ from the frozen shot count.")
|
||||
story_clips = getattr(plan, "clips", None)
|
||||
shot_frames = (
|
||||
tuple(c["duration_frames"] for c in story_clips)
|
||||
if story_clips
|
||||
else plan.shot_frames or (plan.clip_frames,) * len(sources)
|
||||
)
|
||||
starts = tuple(c["start_frame"] for c in story_clips) if story_clips else (0,) * len(sources)
|
||||
duration = plan.frames / plan.fps
|
||||
duration_text = f"{duration:.9f}".rstrip("0").rstrip(".")
|
||||
sources = [confined(p, settings) for p in sources]
|
||||
work = Path(work_dir).resolve()
|
||||
if not work.is_relative_to(Path(settings.workspace_root).resolve()):
|
||||
raise MediaError("invalid_asset", "Invalid work directory.")
|
||||
width, height = plan.canvas
|
||||
expected = (
|
||||
None
|
||||
if story_clips
|
||||
else (
|
||||
plan.generation_parameters["upscale_width"],
|
||||
plan.generation_parameters["upscale_height"],
|
||||
)
|
||||
)
|
||||
for index, (source, frames, start) in enumerate(zip(sources, shot_frames, starts)):
|
||||
info = await inspect_video_track(source, settings)
|
||||
if info["frames"] < frames + start:
|
||||
raise MediaError(
|
||||
"short_source",
|
||||
f"Each source needs at least {frames} decoded video frames for its selected duration.",
|
||||
)
|
||||
dimensions = (
|
||||
(story_clips[index]["width"], story_clips[index]["height"]) if story_clips else expected
|
||||
)
|
||||
if story_clips and (
|
||||
("fps" in story_clips[index] and story_clips[index]["fps"] != info["fps"])
|
||||
or (
|
||||
"source_frames" in story_clips[index]
|
||||
and story_clips[index]["source_frames"] != info["frames"]
|
||||
)
|
||||
):
|
||||
raise MediaError(
|
||||
"invalid_video_profile", "Source facts differ from frozen decoded video."
|
||||
)
|
||||
if info["fps"] != 24 or (info["width"], info["height"]) != dimensions:
|
||||
raise MediaError(
|
||||
"invalid_video_profile", "Source video differs from frozen enhanced profile."
|
||||
)
|
||||
audio_spec = plan.spec["render"]["audio"]
|
||||
if bool(audio_spec) != bool(audio):
|
||||
raise MediaError("invalid_timeline", "Audio source does not match timeline.")
|
||||
if audio:
|
||||
audio = confined(audio, settings)
|
||||
info = await inspect_media(audio, settings)
|
||||
if info["kind"] != "audio" or audio_spec["source_end_ms"] > round(
|
||||
info["duration_seconds"] * 1000
|
||||
):
|
||||
raise MediaError("invalid_timeline", "Audio cut exceeds decoded source.")
|
||||
work.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
async def checkpoint():
|
||||
if control is not None:
|
||||
result = control() if callable(control) else control.checkpoint()
|
||||
if hasattr(result, "__await__"):
|
||||
await result
|
||||
|
||||
parts = []
|
||||
for index, (source, frames, start) in enumerate(zip(sources, shot_frames, starts)):
|
||||
await checkpoint()
|
||||
target = work / f"shot-{index}.mp4"
|
||||
fit = plan.spec["render"]["fit"]
|
||||
canvas = f"scale={width}:{height}:force_original_aspect_ratio=" + (
|
||||
"decrease" if fit == "contain" else "increase"
|
||||
)
|
||||
canvas += (
|
||||
f",pad={width}:{height}:(ow-iw)/2:(oh-ih)/2"
|
||||
if fit == "contain"
|
||||
else f",crop={width}:{height}"
|
||||
)
|
||||
vf = (
|
||||
f"trim=start_frame={start}:end_frame={start + frames},setpts=PTS-STARTPTS,"
|
||||
+ canvas
|
||||
+ ",setsar=1"
|
||||
)
|
||||
await run_process(
|
||||
[
|
||||
settings.ffmpeg_bin,
|
||||
"-v",
|
||||
"error",
|
||||
"-nostdin",
|
||||
*input_options(),
|
||||
"-i",
|
||||
str(source),
|
||||
"-map",
|
||||
"0:v:0",
|
||||
"-an",
|
||||
"-vf",
|
||||
vf,
|
||||
"-r",
|
||||
"24",
|
||||
"-frames:v",
|
||||
str(frames),
|
||||
"-c:v",
|
||||
"libx264",
|
||||
"-preset",
|
||||
"veryfast",
|
||||
"-crf",
|
||||
"20",
|
||||
"-pix_fmt",
|
||||
"yuv420p",
|
||||
"-threads",
|
||||
"2",
|
||||
"-fs",
|
||||
str(settings.max_output_bytes),
|
||||
str(target),
|
||||
],
|
||||
timeout=600,
|
||||
)
|
||||
parts.append(target)
|
||||
if sum(p.stat().st_size for p in parts) >= settings.max_output_bytes:
|
||||
raise MediaError("output_too_large", "Intermediate media exceeds size budget.")
|
||||
listing = work / "concat.txt"
|
||||
listing.write_text("".join(f"file '{p.name}'\n" for p in parts), encoding="utf-8")
|
||||
target = work / "workflow.mp4"
|
||||
command = [
|
||||
settings.ffmpeg_bin,
|
||||
"-v",
|
||||
"error",
|
||||
"-nostdin",
|
||||
"-f",
|
||||
"concat",
|
||||
"-safe",
|
||||
"1",
|
||||
"-i",
|
||||
listing.name,
|
||||
]
|
||||
if audio:
|
||||
command += [*input_options(), "-i", str(audio)]
|
||||
else:
|
||||
command += ["-f", "lavfi", "-i", "anullsrc=channel_layout=stereo:sample_rate=48000"]
|
||||
filters = []
|
||||
# Windows 未安装 Noto 时 FFmpeg 会静默回退至西文字体,必须选用已有中文字库。
|
||||
subtitle_font = "Microsoft YaHei" if os.name == "nt" else "Noto Sans CJK SC"
|
||||
for index, cue in enumerate(plan.spec["render"]["subtitles"]):
|
||||
name = f"cue-{index:04d}.txt"
|
||||
(work / name).write_text(cue["text"], encoding="utf-8")
|
||||
filters.append(
|
||||
f"drawtext=font='{subtitle_font}':textfile={name}:expansion=none:fontcolor=white:fontsize=48:borderw=3:x=(w-tw)/2:y=h-th-60:enable='gte(n,{cue['start_frame']})*lt(n,{cue['end_frame']})'"
|
||||
)
|
||||
if audio:
|
||||
start, end = audio_spec["source_start_ms"] / 1000, audio_spec["source_end_ms"] / 1000
|
||||
delay = audio_spec["offset_frame"] * 1000 / 24
|
||||
af = f"atrim=start={start:.3f}:end={end:.3f},asetpts=PTS-STARTPTS,adelay={delay:.9f}:all=1,apad,atrim=duration={duration_text}"
|
||||
else:
|
||||
af = f"atrim=duration={duration_text}"
|
||||
command += ["-map", "0:v:0", "-map", "1:a:0"]
|
||||
if filters:
|
||||
command += ["-vf", ",".join(filters)]
|
||||
command += [
|
||||
"-af",
|
||||
af,
|
||||
"-frames:v",
|
||||
str(plan.frames),
|
||||
"-r",
|
||||
"24",
|
||||
"-c:v",
|
||||
"libx264",
|
||||
"-preset",
|
||||
"veryfast",
|
||||
"-crf",
|
||||
"20",
|
||||
"-pix_fmt",
|
||||
"yuv420p",
|
||||
"-c:a",
|
||||
"aac",
|
||||
"-ar",
|
||||
"48000",
|
||||
"-ac",
|
||||
"2",
|
||||
"-threads",
|
||||
"2",
|
||||
"-movflags",
|
||||
"+faststart",
|
||||
"-fs",
|
||||
str(settings.max_output_bytes),
|
||||
str(target),
|
||||
]
|
||||
await checkpoint()
|
||||
await run_process(command, timeout=min(3600, max(600, duration * 5)), cwd=work)
|
||||
info = await inspect_video_track(target, settings)
|
||||
if (
|
||||
info["frames"] != plan.frames
|
||||
or info["fps"] != 24
|
||||
or (info["width"], info["height"]) != plan.canvas
|
||||
or abs(info["duration"] - duration) > 0.10
|
||||
or target.stat().st_size >= settings.max_output_bytes
|
||||
):
|
||||
raise MediaError(
|
||||
"composition_incomplete",
|
||||
"Final video differs from the frozen frame count, profile or duration.",
|
||||
)
|
||||
result = {
|
||||
"frames": plan.frames,
|
||||
"fps": 24,
|
||||
"duration_seconds": duration,
|
||||
"width": width,
|
||||
"height": height,
|
||||
"clip_count": len(sources),
|
||||
"subtitle_count": len(filters),
|
||||
}
|
||||
return CpuResult(
|
||||
[target],
|
||||
result,
|
||||
{"provider": "ffmpeg-cpu", "profile": plan.spec["profile"], "template_version": "plain-v1"},
|
||||
)
|
||||
|
||||
|
||||
async def compose_story(plan, work_dir, control=None, *, settings, sources, audio=None):
|
||||
"""v3 专用计划,保持独立验证,不经过旧 compile_timeline。"""
|
||||
from app.domain.stories import StoryRenderPlan
|
||||
from dataclasses import replace
|
||||
import hashlib
|
||||
|
||||
recovered_clips = []
|
||||
|
||||
if not isinstance(plan, StoryRenderPlan):
|
||||
raise MediaError("invalid_timeline", "需要冻结的故事合成计划")
|
||||
for source, clip in zip(sources, plan.clips):
|
||||
source = confined(source, settings)
|
||||
|
||||
def checksum():
|
||||
h = hashlib.sha256()
|
||||
with source.open("rb") as stream:
|
||||
while chunk := stream.read(1024 * 1024):
|
||||
h.update(chunk)
|
||||
return h.hexdigest()
|
||||
|
||||
if await asyncio.to_thread(checksum) != clip["sha256"]:
|
||||
raise MediaError("dependency_changed", "冻结视频 SHA 不匹配")
|
||||
# 旧自动快照缺少解码尺寸;只在原字节SHA确认后补齐执行副本,不重写历史冻结输入。
|
||||
recovered = dict(clip)
|
||||
if "width" not in clip or "height" not in clip:
|
||||
info = await inspect_video_track(source, settings)
|
||||
for key in ("width", "height"):
|
||||
if key not in recovered:
|
||||
recovered[key] = info[key]
|
||||
recovered_clips.append(recovered)
|
||||
plan = replace(plan, clips=tuple(recovered_clips))
|
||||
return await compose_workflow(
|
||||
plan, work_dir, control, settings=settings, sources=sources, audio=audio
|
||||
)
|
||||
|
||||
|
||||
async def inspect_video_timeline(path: Path, settings) -> float:
|
||||
"""用真实视频帧的时间戳计时;容器时长可能被更长的音轨撑大。"""
|
||||
from fractions import Fraction
|
||||
from statistics import median
|
||||
|
||||
source = confined(path, settings)
|
||||
raw = await run_process(
|
||||
[
|
||||
settings.ffprobe_bin,
|
||||
"-v",
|
||||
"error",
|
||||
*input_options(),
|
||||
"-select_streams",
|
||||
"v:0",
|
||||
"-show_frames",
|
||||
"-show_entries",
|
||||
"frame=best_effort_timestamp_time,duration_time,pkt_duration_time:stream=avg_frame_rate",
|
||||
"-of",
|
||||
"json",
|
||||
str(source),
|
||||
],
|
||||
timeout=120,
|
||||
max_output=16 * 1024 * 1024,
|
||||
)
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
frames = data["frames"]
|
||||
timestamps = [float(frame["best_effort_timestamp_time"]) for frame in frames]
|
||||
if not timestamps or any(not math.isfinite(t) for t in timestamps):
|
||||
raise ValueError
|
||||
gaps = [b - a for a, b in zip(timestamps, timestamps[1:])]
|
||||
if any(gap <= 0 for gap in gaps):
|
||||
raise ValueError
|
||||
last = frames[-1]
|
||||
duration = float(last.get("duration_time", last.get("pkt_duration_time", 0)))
|
||||
if not math.isfinite(duration) or duration <= 0:
|
||||
duration = (
|
||||
median(gaps) if gaps else 1 / float(Fraction(data["streams"][0]["avg_frame_rate"]))
|
||||
)
|
||||
total = timestamps[-1] + duration - timestamps[0]
|
||||
if not math.isfinite(total) or total <= 0:
|
||||
raise ValueError
|
||||
return total
|
||||
except (KeyError, IndexError, TypeError, ValueError, ZeroDivisionError):
|
||||
raise MediaError("invalid_media", "视频时间轴无法解码。") from None
|
||||
1
backend/app/adapters/provider/__init__.py
Normal file
1
backend/app/adapters/provider/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
"""已部署推理服务与 CPU 媒体适配;公共入口为 client。"""
|
||||
154
backend/app/adapters/provider/client.py
Normal file
154
backend/app/adapters/provider/client.py
Normal file
@ -0,0 +1,154 @@
|
||||
"""推理适配公共门面:无数据库依赖,HTTP 客户端可替换。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import httpx
|
||||
|
||||
from app.domain.errors import MediaError as ProviderError
|
||||
from app.domain.execution import CpuResult, current_phase_callback, enter_phase
|
||||
from .contracts import capabilities, validate_arguments
|
||||
from . import composition, cpu, files, gpu, qwen, runtime, speech, transport
|
||||
|
||||
__all__ = [
|
||||
"Provider",
|
||||
"capabilities",
|
||||
"validate_arguments",
|
||||
"ProviderError",
|
||||
"CpuResult",
|
||||
"current_phase_callback",
|
||||
"enter_phase",
|
||||
]
|
||||
|
||||
|
||||
class Provider:
|
||||
def __init__(self, settings):
|
||||
self.settings = settings
|
||||
self._runtime_lock = asyncio.Lock()
|
||||
# 组合模块每次读取此属性,替换客户端后不会继续使用旧连接。
|
||||
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"):
|
||||
return transport._headers(self, family)
|
||||
|
||||
@staticmethod
|
||||
def _http_error(status):
|
||||
return transport._http_error(status)
|
||||
|
||||
async def _json(self, method, url, *, payload=None, headers=None, timeout=None):
|
||||
return await transport._json(
|
||||
self, method, url, payload=payload, headers=headers, timeout=timeout
|
||||
)
|
||||
|
||||
async def health(self):
|
||||
return await runtime.health(self)
|
||||
|
||||
@staticmethod
|
||||
def _runtime_value(value):
|
||||
return runtime._runtime_value(value)
|
||||
|
||||
async def runtime_status(self):
|
||||
return await runtime.runtime_status(self)
|
||||
|
||||
def _mirror_runtime_policy(self, policy):
|
||||
return runtime._mirror_runtime_policy(self, policy)
|
||||
|
||||
async def scheduler_status(self):
|
||||
return await runtime.scheduler_status(self)
|
||||
|
||||
def _work(self, path):
|
||||
return files._work(self, path)
|
||||
|
||||
def _asset(self, asset_id, assets):
|
||||
return files._asset(self, asset_id, assets)
|
||||
|
||||
async def _upload_input(self, source):
|
||||
return await files._upload_input(self, source)
|
||||
|
||||
async def _download_url(
|
||||
self, url, destination, headers, *, payload=None, timeout=None, total_timeout=None
|
||||
):
|
||||
return await files._download_url(
|
||||
self,
|
||||
url,
|
||||
destination,
|
||||
headers,
|
||||
payload=payload,
|
||||
timeout=timeout,
|
||||
total_timeout=total_timeout,
|
||||
)
|
||||
|
||||
async def speech_health(self):
|
||||
return await speech.health(self)
|
||||
|
||||
async def download(self, upstream_id, index, destination):
|
||||
return await files.download(self, upstream_id, index, destination)
|
||||
|
||||
@staticmethod
|
||||
def _json_file(work, name, value):
|
||||
return files._json_file(work, name, value)
|
||||
|
||||
async def prepare_gpu_payload(
|
||||
self, task_type, inputs, parameters, assets, work_dir, *, analysis_binding=None
|
||||
):
|
||||
return await gpu.prepare_gpu_payload(
|
||||
self, task_type, inputs, parameters, assets, work_dir, analysis_binding=analysis_binding
|
||||
)
|
||||
|
||||
async def submit(self, payload, idempotency_key):
|
||||
return await gpu.submit(self, payload, idempotency_key)
|
||||
|
||||
@staticmethod
|
||||
def _job_id(value):
|
||||
return gpu._job_id(value)
|
||||
|
||||
@staticmethod
|
||||
def _sanitize_job(value):
|
||||
return gpu._sanitize_job(value)
|
||||
|
||||
async def query(self, upstream_id):
|
||||
return await gpu.query(self, upstream_id)
|
||||
|
||||
async def upstream_capabilities(self):
|
||||
return await gpu.upstream_capabilities(self)
|
||||
|
||||
async def control(
|
||||
self,
|
||||
upstream_id,
|
||||
desired_state,
|
||||
command_id,
|
||||
expected_version=None,
|
||||
expected_execution_id=None,
|
||||
):
|
||||
return await gpu.control(
|
||||
self, upstream_id, desired_state, command_id, expected_version, expected_execution_id
|
||||
)
|
||||
|
||||
async def cancel(self, upstream_id):
|
||||
return await gpu.cancel(self, upstream_id)
|
||||
|
||||
async def _chat(self, messages, *, max_tokens=2048, thinking=False):
|
||||
return await qwen._chat(self, messages, max_tokens=max_tokens, thinking=thinking)
|
||||
|
||||
async def _image_uri(self, source):
|
||||
return await qwen._image_uri(self, source)
|
||||
|
||||
async def _structure(self, inputs, p, assets, work):
|
||||
return await qwen._structure(self, inputs, p, assets, work)
|
||||
|
||||
async def _speech(self, inputs, p, work):
|
||||
return await speech._speech(self, inputs, p, work)
|
||||
|
||||
async def _compose(self, inputs, p, assets, work):
|
||||
return await composition._compose(self, inputs, p, assets, work)
|
||||
|
||||
async def run_cpu(self, task_type, inputs, parameters, assets, work_dir):
|
||||
return await cpu.run_cpu(self, task_type, inputs, parameters, assets, work_dir)
|
||||
258
backend/app/adapters/provider/composition.py
Normal file
258
backend/app/adapters/provider/composition.py
Normal file
@ -0,0 +1,258 @@
|
||||
"""固定 FFmpeg 参数的素材编排适配。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import html
|
||||
import re
|
||||
|
||||
from app.adapters.media import input_options, inspect_media, run_process
|
||||
from app.domain.execution import CpuResult
|
||||
from app.domain.errors import MediaError as ProviderError
|
||||
from .contracts import _invalid, _keys, _int, _float, _string
|
||||
from .contracts import validate_arguments
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .client import Provider
|
||||
|
||||
|
||||
async def _compose(provider: Provider, inputs, p, assets, work):
|
||||
if "story_spec" in p:
|
||||
from app.domain.stories import compile_story_render
|
||||
from app.adapters.media import compose_story
|
||||
|
||||
validate_arguments("video.compose", inputs, p, provider.settings)
|
||||
plan = compile_story_render(p["story_spec"], p["render_inputs"])
|
||||
audio_id = inputs.get("audio_asset_id")
|
||||
frozen_audio = p["render_inputs"].get("audio")
|
||||
if frozen_audio:
|
||||
import hashlib
|
||||
|
||||
def digest_file(path):
|
||||
h = hashlib.sha256()
|
||||
with path.open("rb") as stream:
|
||||
while chunk := stream.read(1024 * 1024):
|
||||
h.update(chunk)
|
||||
return h.hexdigest()
|
||||
|
||||
# 音轨与视频都校验已冻结字节,不能在等待合成期间替换源文件。
|
||||
if (
|
||||
await asyncio.to_thread(digest_file, provider._asset(audio_id, assets))
|
||||
!= frozen_audio["sha256"]
|
||||
):
|
||||
raise _invalid("Frozen story audio SHA differs.")
|
||||
return await compose_story(
|
||||
plan,
|
||||
work,
|
||||
settings=provider.settings,
|
||||
sources=[provider._asset(c["asset_id"], assets) for c in plan.clips],
|
||||
audio=provider._asset(audio_id, assets) if audio_id else None,
|
||||
)
|
||||
if "workflow_spec" in p:
|
||||
from app.domain.timeline import compile_timeline
|
||||
from app.adapters.media import compose_workflow
|
||||
|
||||
validate_arguments("video.compose", inputs, p, provider.settings)
|
||||
audio_id = inputs.get("audio_asset_id")
|
||||
audio = provider._asset(audio_id, assets) if audio_id else None
|
||||
owned = {audio_id: await inspect_media(audio, provider.settings)} if audio else {}
|
||||
try:
|
||||
plan = compile_timeline(p["workflow_spec"], owned)
|
||||
except ValueError:
|
||||
raise _invalid("Invalid workflow audio timeline.") from None
|
||||
return await compose_workflow(
|
||||
plan,
|
||||
work,
|
||||
settings=provider.settings,
|
||||
sources=[provider._asset(c["asset_id"], assets) for c in p["clips"]],
|
||||
audio=audio,
|
||||
)
|
||||
_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) <= 1000:
|
||||
raise _invalid("请选择1至1000个视频片段。")
|
||||
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, 86400)
|
||||
end = clip.get("end_seconds")
|
||||
if end is not None and _float(end, 0, 86400) <= start:
|
||||
raise _invalid("片段结束时间必须大于开始时间。")
|
||||
normalized.append((provider._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 = provider._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, 86400 * 1000),
|
||||
_float(cue.get("end"), 0, 86400 * 1000),
|
||||
)
|
||||
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, provider.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"] + 0.05 or end - start < 0.05:
|
||||
raise _invalid("裁剪范围超出视频实际时长。")
|
||||
total += end - start
|
||||
parts.append((source, start, end - start, info.get("has_audio", False)))
|
||||
if any(end > total + 0.05 for _, end, _ in cues):
|
||||
raise _invalid("字幕超出成片时长。")
|
||||
if audio and (await inspect_media(audio, provider.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 = [
|
||||
provider.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(provider.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) >= provider.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 = [
|
||||
provider.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(provider.settings.max_output_bytes),
|
||||
str(target),
|
||||
]
|
||||
await run_process(command, timeout=min(600, max(60, total * 5)), cwd=work)
|
||||
info = await inspect_media(target, provider.settings)
|
||||
if (
|
||||
abs(info["duration_seconds"] - total) > max(0.2, 2 / fps)
|
||||
or target.stat().st_size >= provider.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 = provider._json_file(work, "composition.json", result)
|
||||
return CpuResult(
|
||||
[target, manifest],
|
||||
result,
|
||||
{"provider": "ffmpeg-cpu", "audio": "uploaded" if audio else "original-or-silence"},
|
||||
)
|
||||
560
backend/app/adapters/provider/contracts.py
Normal file
560
backend/app/adapters/provider/contracts.py
Normal file
@ -0,0 +1,560 @@
|
||||
"""能力声明、默认值与提交参数校验,不执行模型任务。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import re
|
||||
|
||||
from app.domain.errors import MediaError as ProviderError
|
||||
from app.domain.tasks import GPU_TYPES as GPU_TASKS
|
||||
|
||||
|
||||
LANGUAGES = ["zh", "en", "ja", "ko", "de", "fr", "es", "ru", "ar", "pt", "it", "auto"]
|
||||
REFERENCE_PROFILES = {
|
||||
"qwen-image-edit-2511-v1": ("Qwen-Image-Edit-2511", 3),
|
||||
"qwen-image-edit-2509-v1": ("Qwen-Image-Edit-2509", 3),
|
||||
"qwen-image-edit-2511-experimental-4-v1": ("Qwen-Image-Edit-2511", 4),
|
||||
}
|
||||
|
||||
|
||||
def reference_capability(settings):
|
||||
profile = getattr(settings, "reference_generation_profile", "qwen-image-edit-2511-v1")
|
||||
model, maximum = REFERENCE_PROFILES.get(profile, ("Unrecognized edit profile", 0))
|
||||
maximum = min(maximum, getattr(settings, "reference_max_images", 3))
|
||||
return {
|
||||
"profile": profile,
|
||||
"model": model,
|
||||
"max_reference_images": maximum,
|
||||
"available": bool(
|
||||
maximum
|
||||
and getattr(settings, "reference_generation_enabled", False)
|
||||
and getattr(settings, "inference_base_url", "")
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
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]:
|
||||
from app.core.runtime_policy import read_runtime_policy
|
||||
|
||||
compose_limit = read_runtime_policy(settings)["workflow_max_shots"]
|
||||
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": 361, "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)
|
||||
)
|
||||
reference = reference_capability(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,
|
||||
)
|
||||
|
||||
from app.domain.video_editing import video_capability, video_defaults as edit_defaults
|
||||
|
||||
edit = video_capability(settings)
|
||||
story_tasks = [
|
||||
*[
|
||||
item(
|
||||
task,
|
||||
label,
|
||||
edit["model"],
|
||||
edit["available"],
|
||||
["video"],
|
||||
edit_defaults(task, settings),
|
||||
{k: edit[k] for k in ("max_seconds", "max_people", "max_pixels", "fps")},
|
||||
edit["reason"] or "按视频实例选择多人替换,保留未选人物与背景。",
|
||||
)
|
||||
for task, label in (
|
||||
("video.people.analyze", "识别视频人物"),
|
||||
("video.replace", "视频多人替换"),
|
||||
)
|
||||
],
|
||||
item(
|
||||
"image.reference.generate",
|
||||
"多图锚定首帧",
|
||||
reference["model"],
|
||||
reference["available"],
|
||||
["text", "images"],
|
||||
{
|
||||
"profile": reference["profile"],
|
||||
"width": 1280,
|
||||
"height": 704,
|
||||
"num_inference_steps": 40,
|
||||
"seed": 42,
|
||||
"guidance_scale": 1.0,
|
||||
"true_cfg_scale": 4.0,
|
||||
"max_sequence_length": 1024,
|
||||
},
|
||||
{
|
||||
"max_reference_images": reference["max_reference_images"],
|
||||
"sizes": [[1280, 704], [704, 1280], [1024, 1024]],
|
||||
"count": {"min": 1, "max": 4},
|
||||
"max_sequence_length": {"min": 1, "max": 1024},
|
||||
"num_inference_steps": {"min": 1, "max": 100},
|
||||
"guidance_scale": {"min": 1, "max": 20},
|
||||
"true_cfg_scale": {"min": 1, "max": 20},
|
||||
"seed": {"min": 0, "max": 2**32 - 1},
|
||||
},
|
||||
"按顺序使用全部真实参考图片;需完成服务端认证,缺图不会降级文生图。",
|
||||
),
|
||||
item(
|
||||
"image.prepare_frame",
|
||||
"首帧规范化",
|
||||
"Pillow CPU",
|
||||
True,
|
||||
["image"],
|
||||
{"width": 1280, "height": 704, "fit": "contain"},
|
||||
{
|
||||
"width": {"min": 256, "max": 2048, "step": 16},
|
||||
"height": {"min": 256, "max": 2048, "step": 16},
|
||||
"fit": {"values": ["contain", "cover"]},
|
||||
},
|
||||
"生成独立RGB PNG,按指定尺寸留边或居中裁剪,不覆盖原素材。",
|
||||
),
|
||||
]
|
||||
# 旧快速创作依赖首项为文生图,新增内部阶段追加在原能力之后。
|
||||
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,
|
||||
"单镜头最多361帧、24fps,约15秒无声视频;默认约5秒,可选1080p增强。",
|
||||
),
|
||||
item(
|
||||
"defect.generate",
|
||||
"条件样本生成",
|
||||
"SDXL + Canny ControlNet",
|
||||
configured,
|
||||
["text", "image"],
|
||||
dict(
|
||||
image_defaults,
|
||||
guidance_scale=7.5,
|
||||
controlnet_conditioning_scale=0.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": compose_limit},
|
||||
"source_duration_seconds": {"min": 0.05, "max": 86400},
|
||||
},
|
||||
"按顺序裁剪拼接片段,支持上传音轨和人工字幕;无热度预测。",
|
||||
),
|
||||
item(
|
||||
"audio.speech",
|
||||
"中文配音",
|
||||
getattr(settings, "tts_model", "") or "尚未配置",
|
||||
speech,
|
||||
["text"],
|
||||
{"voice": (_voices(settings) or [""])[0], "speed": 1.0},
|
||||
{
|
||||
"voice": {"values": _voices(settings)},
|
||||
"speed": {"min": 0.5, "max": 2},
|
||||
"text": {"max": 2000},
|
||||
},
|
||||
"仅在配置真实语音服务后可用;输出 WAV,不提供音乐生成。",
|
||||
),
|
||||
item(
|
||||
"text.script.generate",
|
||||
"镜头旁白文案",
|
||||
getattr(settings, "qwen_model", ""),
|
||||
qwen,
|
||||
["text"],
|
||||
{},
|
||||
{"max_shots": 1000},
|
||||
"按稳定镜头ID生成可编辑的简短旁白。",
|
||||
),
|
||||
item(
|
||||
"audio.assemble",
|
||||
"旁白音轨装配",
|
||||
"FFmpeg",
|
||||
True,
|
||||
["audio"],
|
||||
{"fps": 24},
|
||||
{"max_segments": 1000},
|
||||
"将已选用配音段按24fps位置装配为单音轨。",
|
||||
),
|
||||
*story_tasks,
|
||||
]
|
||||
|
||||
|
||||
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 {"text.script.generate", "audio.assemble"}:
|
||||
from .editor_media import validate
|
||||
|
||||
validate(task_type, inputs, parameters)
|
||||
return
|
||||
if task_type == "image.prepare_frame":
|
||||
_keys(inputs, {"image_asset_id"})
|
||||
_keys(p, {"width", "height", "fit"})
|
||||
_string(inputs.get("image_asset_id"), 64)
|
||||
for name in ("width", "height"):
|
||||
_int(p.get(name, 1280 if name == "width" else 704), 256, 2048, 16)
|
||||
if p.get("fit", "contain") not in {"contain", "cover"}:
|
||||
raise _invalid("首帧适配方式无效。")
|
||||
return
|
||||
if task_type in {"video.people.analyze", "video.replace"}:
|
||||
from app.domain.video_editing import validate_video_arguments
|
||||
|
||||
validate_video_arguments(task_type, inputs, p, settings)
|
||||
return
|
||||
if task_type == "image.reference.generate":
|
||||
reference = reference_capability(settings)
|
||||
if not reference["available"]:
|
||||
raise ProviderError("capability_unavailable", "多图参考生成尚未通过认证或未启用。")
|
||||
_keys(inputs, {"prompt", "negative_prompt", "reference_asset_ids"})
|
||||
_string(inputs.get("prompt"))
|
||||
_string(inputs.get("negative_prompt", ""), required=False)
|
||||
defaults = next(
|
||||
i["defaults"] for i in capabilities(settings) if i["task_type"] == task_type
|
||||
)
|
||||
_keys(p, set(defaults))
|
||||
p = {**defaults, **p}
|
||||
if p["profile"] != reference["profile"]:
|
||||
raise _invalid("参考生成必须使用已配置且认证的模型版本。")
|
||||
ids = inputs.get("reference_asset_ids")
|
||||
if not isinstance(ids, list) or not 1 <= len(ids) <= reference["max_reference_images"]:
|
||||
raise _invalid("参考图片数量超出已认证范围。")
|
||||
if any(not isinstance(v, str) for v in ids) or len(set(ids)) != len(ids):
|
||||
raise _invalid("参考图片不能重复。")
|
||||
for asset_id in ids:
|
||||
_string(asset_id, 64)
|
||||
if (p["width"], p["height"]) not in {(1280, 704), (704, 1280), (1024, 1024)}:
|
||||
raise _invalid("参考图仅支持1280×704、704×1280或1024×1024。")
|
||||
_int(p["num_inference_steps"], 1, 100)
|
||||
_int(p["seed"], 0, 2**32 - 1)
|
||||
_int(p["max_sequence_length"], 1, 1024)
|
||||
_float(p["guidance_scale"], 1, 20)
|
||||
_float(p["true_cfg_scale"], 1, 20)
|
||||
return
|
||||
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, 361)
|
||||
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", "model"})
|
||||
if p.get("model", getattr(settings, "tts_model", "")) != getattr(settings, "tts_model", ""):
|
||||
raise ProviderError("capability_changed", "配音模型配置已变化,请重新生成执行计划")
|
||||
_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), 0.5, 2)
|
||||
return
|
||||
if task_type == "video.compose":
|
||||
if "story_spec" in p:
|
||||
from app.domain.stories import compile_story_render
|
||||
|
||||
_keys(inputs, {"asset_ids", "audio_asset_id"})
|
||||
_keys(p, {"story_spec", "render_inputs", "clips"})
|
||||
try:
|
||||
plan = compile_story_render(p["story_spec"], p["render_inputs"])
|
||||
except (ValueError, KeyError, TypeError):
|
||||
raise _invalid("Invalid frozen story timeline.") from None
|
||||
if inputs.get("asset_ids") != [c["asset_id"] for c in plan.clips] or p.get("clips") != [
|
||||
{"asset_id": c["asset_id"]} for c in plan.clips
|
||||
]:
|
||||
raise _invalid("Story clip order differs.")
|
||||
audio = plan.spec["render"]["audio"]
|
||||
if inputs.get("audio_asset_id") != (audio["asset_id"] if audio else None):
|
||||
raise _invalid("Story audio differs.")
|
||||
return
|
||||
if "workflow_spec" in p:
|
||||
from app.domain.timeline import WorkflowSpec
|
||||
|
||||
_keys(inputs, {"asset_ids", "audio_asset_id"})
|
||||
_keys(p, {"workflow_spec", "clips"})
|
||||
try:
|
||||
spec = WorkflowSpec.model_validate(p["workflow_spec"])
|
||||
except ValueError:
|
||||
raise _invalid("Invalid frozen workflow timeline.") from None
|
||||
clips = p.get("clips")
|
||||
if not isinstance(clips, list) or len(clips) != len(spec.shots):
|
||||
raise _invalid("Workflow clips must match the frozen shot count.")
|
||||
for clip in clips:
|
||||
_keys(clip, {"asset_id"})
|
||||
_string(clip.get("asset_id"), 64)
|
||||
if inputs.get("asset_ids") != [c["asset_id"] for c in clips]:
|
||||
raise _invalid("Workflow clip order differs.")
|
||||
if inputs.get("audio_asset_id") != (
|
||||
spec.render.audio.asset_id if spec.render.audio else None
|
||||
):
|
||||
raise _invalid("Workflow audio differs.")
|
||||
return
|
||||
_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) <= 1000:
|
||||
raise _invalid("请选择1至1000个视频片段,并遵守当前配置的资源上限。")
|
||||
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, 86400)
|
||||
if (
|
||||
clip.get("end_seconds") is not None
|
||||
and _float(clip["end_seconds"], 0, 86400) <= 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, 86400 * 1000),
|
||||
_float(cue.get("end"), 0, 86400 * 1000),
|
||||
)
|
||||
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("不支持此任务类型。")
|
||||
121
backend/app/adapters/provider/cpu.py
Normal file
121
backend/app/adapters/provider/cpu.py
Normal file
@ -0,0 +1,121 @@
|
||||
"""CPU 与共享 HTTP 任务入口和资源阶段切换。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import uuid
|
||||
|
||||
from PIL import Image, ImageOps, UnidentifiedImageError
|
||||
|
||||
from app.domain.execution import CpuResult, enter_phase
|
||||
from app.adapters.storage import file_thread
|
||||
from app.domain.errors import MediaError as ProviderError
|
||||
from .contracts import _invalid, _keys, _int, _string
|
||||
from .contracts import validate_arguments
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .client import Provider
|
||||
|
||||
|
||||
async def run_cpu(provider: Provider, task_type, inputs, parameters, assets, work_dir):
|
||||
work = provider._work(work_dir)
|
||||
validate_arguments(task_type, inputs, parameters, provider.settings)
|
||||
try:
|
||||
if task_type == "image.prepare_frame":
|
||||
await enter_phase("prepare_frame", "cpu_media")
|
||||
source = provider._asset(inputs["image_asset_id"], assets)
|
||||
width, height = parameters.get("width", 1280), parameters.get("height", 704)
|
||||
fit = parameters.get("fit", "contain")
|
||||
target = work / ("frame-" + uuid.uuid4().hex + ".png")
|
||||
|
||||
def normalize():
|
||||
temporary = target.with_suffix(".tmp.png")
|
||||
try:
|
||||
with Image.open(source) as original:
|
||||
original.load()
|
||||
image = ImageOps.exif_transpose(original).convert("RGBA")
|
||||
background = Image.new("RGBA", image.size, (0, 0, 0, 255))
|
||||
background.alpha_composite(image)
|
||||
image = background.convert("RGB")
|
||||
if fit == "cover":
|
||||
image = ImageOps.fit(
|
||||
image, (width, height), method=Image.Resampling.LANCZOS
|
||||
)
|
||||
else:
|
||||
image = ImageOps.pad(
|
||||
image,
|
||||
(width, height),
|
||||
method=Image.Resampling.LANCZOS,
|
||||
color="black",
|
||||
)
|
||||
image.save(temporary, format="PNG")
|
||||
os.replace(temporary, target)
|
||||
except (UnidentifiedImageError, Image.DecompressionBombError, ValueError):
|
||||
raise _invalid("首帧素材必须是可解码的安全图片。") from None
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
|
||||
await file_thread(normalize)
|
||||
details = {
|
||||
"width": width,
|
||||
"height": height,
|
||||
"fit": fit,
|
||||
"image_asset_id": inputs["image_asset_id"],
|
||||
}
|
||||
return CpuResult(
|
||||
[target], details, {"provider": "pillow", "stage": "prepare_frame", **details}
|
||||
)
|
||||
if task_type == "math.solve":
|
||||
await enter_phase("solve", "qwen_http")
|
||||
_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 provider._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, provider._json_file(work, "answer.json", result)],
|
||||
result,
|
||||
{
|
||||
"provider": "qwen",
|
||||
"model": provider.settings.qwen_model,
|
||||
"formal_verification": False,
|
||||
},
|
||||
)
|
||||
if task_type == "media.structure":
|
||||
return await provider._structure(inputs, parameters, assets, work)
|
||||
if task_type == "text.script.generate":
|
||||
from .editor_media import script
|
||||
|
||||
await enter_phase("script", "qwen_http")
|
||||
return await script(provider, inputs, parameters, work)
|
||||
if task_type == "audio.assemble":
|
||||
from .editor_media import assemble
|
||||
|
||||
await enter_phase("assemble", "cpu_media")
|
||||
return await assemble(provider, inputs, parameters, assets, work)
|
||||
if task_type == "video.compose":
|
||||
await enter_phase("compose", "cpu_media")
|
||||
return await provider._compose(inputs, parameters, assets, work)
|
||||
if task_type == "audio.speech":
|
||||
await enter_phase("speech", "cpu_media")
|
||||
return await provider._speech(inputs, parameters, work)
|
||||
raise _invalid("不支持此CPU任务类型。")
|
||||
except OSError:
|
||||
raise ProviderError("output_unavailable", "任务文件处理失败。", True) from None
|
||||
210
backend/app/adapters/provider/editor_media.py
Normal file
210
backend/app/adapters/provider/editor_media.py
Normal file
@ -0,0 +1,210 @@
|
||||
"""自动文案和单音轨装配;模型只通过已有Qwen HTTP边界调用。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import uuid
|
||||
import wave
|
||||
|
||||
from app.adapters.media import input_options, run_process
|
||||
from app.adapters.storage import file_thread
|
||||
from app.domain.execution import CpuResult
|
||||
from app.domain.errors import MediaError
|
||||
from app.domain.timeline import Subtitle
|
||||
from .contracts import _invalid, _int, _keys, _string
|
||||
|
||||
|
||||
def validate(task_type, inputs, parameters):
|
||||
if task_type == "text.script.generate":
|
||||
_keys(inputs, {"shots", "context"})
|
||||
_keys(parameters, {"model"})
|
||||
if "model" in parameters:
|
||||
_string(parameters["model"], 256)
|
||||
shots = inputs.get("shots")
|
||||
if not isinstance(shots, list) or not 1 <= len(shots) <= 1000:
|
||||
raise _invalid("文案需要1–1000个镜头")
|
||||
ids = []
|
||||
for shot in shots:
|
||||
_keys(shot, {"shot_id", "name", "visual_prompt", "motion_prompt", "duration_frames"})
|
||||
sid = shot.get("shot_id")
|
||||
if not isinstance(sid, str) or not re.fullmatch("[a-f0-9]{32}", sid):
|
||||
raise _invalid("镜头ID无效")
|
||||
ids.append(sid)
|
||||
for field in ("name", "visual_prompt", "motion_prompt"):
|
||||
_string(shot.get(field, ""), 8000, required=False)
|
||||
_int(shot.get("duration_frames", 120), 24, 360)
|
||||
if len(ids) != len(set(ids)):
|
||||
raise _invalid("文案镜头ID不能重复")
|
||||
if "context" in inputs and not isinstance(inputs["context"], dict):
|
||||
raise _invalid("故事设定无效")
|
||||
if len(json.dumps(inputs, ensure_ascii=False)) > 200000:
|
||||
raise _invalid("文案输入过长,请减少镜头或描述")
|
||||
elif task_type == "audio.assemble":
|
||||
_keys(inputs, {"segments", "total_frames"})
|
||||
_keys(parameters, {"fps"})
|
||||
if parameters.get("fps", 24) != 24:
|
||||
raise _invalid("音轨装配仅支持24fps")
|
||||
_int(inputs.get("total_frames"), 1, 360000)
|
||||
segments = inputs.get("segments")
|
||||
if not isinstance(segments, list) or not 1 <= len(segments) <= 1000:
|
||||
raise _invalid("音轨需要1–1000个片段")
|
||||
for segment in segments:
|
||||
_keys(segment, {"asset_id", "offset_frame"})
|
||||
asset_id = _string(segment.get("asset_id"), 64)
|
||||
if not re.fullmatch("[A-Za-z0-9_.-]+", asset_id):
|
||||
raise _invalid("音轨只接受素材编号")
|
||||
_int(segment.get("offset_frame"), 0, inputs["total_frames"] - 1)
|
||||
|
||||
|
||||
async def script(provider, inputs, parameters, work):
|
||||
validate("text.script.generate", inputs, parameters)
|
||||
if parameters.get("model", provider.settings.qwen_model) != provider.settings.qwen_model:
|
||||
raise MediaError("capability_changed", "文案模型配置已变化,请重新生成执行计划")
|
||||
# 大故事按有界小组调用,避免一次输出截断;已返回组只有在整个步骤成功后发布。
|
||||
segments = []
|
||||
for index in range(0, len(inputs["shots"]), 8):
|
||||
shots = inputs["shots"][index : index + 8]
|
||||
content = await provider._chat(
|
||||
[
|
||||
{
|
||||
"role": "system",
|
||||
"content": '根据故事和镜头生成简短中文旁白。只返回JSON对象,格式为{"segments":[{"shot_id":"原ID","text":"旁白"}]}。每镜头恰好一条,ID原样返回。旁白字数必须适合给定duration_frames/24秒,建议每秒不超过3个汉字。不要把运镜、参数或提示词写入旁白,不要输出Markdown。',
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": json.dumps(
|
||||
{"context": inputs.get("context", {}), "shots": shots}, ensure_ascii=False
|
||||
),
|
||||
},
|
||||
],
|
||||
max_tokens=4096,
|
||||
thinking=False,
|
||||
)
|
||||
try:
|
||||
text = content.strip()
|
||||
if text.startswith("```"):
|
||||
text = re.sub(r"^```(?:json)?\s*|\s*```$", "", text)
|
||||
value = json.loads(text)
|
||||
_keys(value, {"segments"})
|
||||
rows = value["segments"]
|
||||
if not isinstance(rows, list) or len(rows) != len(shots):
|
||||
raise ValueError
|
||||
by_id = {}
|
||||
for row in rows:
|
||||
_keys(row, {"shot_id", "text"})
|
||||
if row["shot_id"] in by_id:
|
||||
raise ValueError
|
||||
Subtitle(start_frame=0, end_frame=24, text=row["text"])
|
||||
if len(row["text"]) > 2000:
|
||||
raise ValueError
|
||||
by_id[row["shot_id"]] = row
|
||||
if set(by_id) != {s["shot_id"] for s in shots}:
|
||||
raise ValueError
|
||||
segments.extend(by_id[s["shot_id"]] for s in shots)
|
||||
except (ValueError, TypeError, KeyError, MediaError) as exc:
|
||||
raise MediaError(
|
||||
"invalid_script", "文案服务返回了无效、缺失或不匹配的镜头内容"
|
||||
) from exc
|
||||
result = {"segments": segments}
|
||||
path = provider._json_file(work, "script.json", result)
|
||||
return CpuResult(
|
||||
[path],
|
||||
result,
|
||||
{"provider": "qwen", "model": provider.settings.qwen_model, "recipe": "shot-script-v1"},
|
||||
)
|
||||
|
||||
|
||||
async def assemble(provider, inputs, parameters, assets, work):
|
||||
validate("audio.assemble", inputs, parameters)
|
||||
total_samples = inputs["total_frames"] * 2000
|
||||
if total_samples * 4 + 44 > provider.settings.max_output_bytes:
|
||||
raise MediaError("output_too_large", "装配音轨超出输出大小限制")
|
||||
normalized, positions = [], []
|
||||
target = work / ("narration-" + uuid.uuid4().hex + ".wav")
|
||||
temporary = target.with_suffix(".part.wav")
|
||||
try:
|
||||
for segment in sorted(inputs["segments"], key=lambda s: s["offset_frame"]):
|
||||
source = provider._asset(segment["asset_id"], assets)
|
||||
start = segment["offset_frame"] * 2000
|
||||
path = work / ("segment-" + uuid.uuid4().hex + ".wav")
|
||||
normalized.append(path)
|
||||
await run_process(
|
||||
[
|
||||
provider.settings.ffmpeg_bin,
|
||||
"-v",
|
||||
"error",
|
||||
"-nostdin",
|
||||
*input_options(),
|
||||
"-i",
|
||||
str(source),
|
||||
"-vn",
|
||||
"-t",
|
||||
str((total_samples - start + 2000) / 48000),
|
||||
"-ar",
|
||||
"48000",
|
||||
"-ac",
|
||||
"2",
|
||||
"-c:a",
|
||||
"pcm_s16le",
|
||||
"-y",
|
||||
str(path),
|
||||
],
|
||||
timeout=300,
|
||||
)
|
||||
with wave.open(str(path), "rb") as audio:
|
||||
count = audio.getnframes()
|
||||
if (
|
||||
count <= 0
|
||||
or start + count > total_samples
|
||||
or (positions and start < positions[-1]["end_sample"])
|
||||
):
|
||||
raise MediaError("invalid_timeline", "配音片段重叠或超出成片,原音频已保留")
|
||||
positions.append(
|
||||
{
|
||||
**segment,
|
||||
"start_sample": start,
|
||||
"end_sample": start + count,
|
||||
"sample_count": count,
|
||||
}
|
||||
)
|
||||
|
||||
def write_track():
|
||||
cursor = 0
|
||||
silence = bytes(65536)
|
||||
with wave.open(str(temporary), "wb") as output:
|
||||
output.setparams((2, 2, 48000, 0, "NONE", "not compressed"))
|
||||
|
||||
def pad(count):
|
||||
remaining = count * 4
|
||||
while remaining:
|
||||
chunk = silence[: min(remaining, len(silence))]
|
||||
output.writeframesraw(chunk)
|
||||
remaining -= len(chunk)
|
||||
|
||||
for path, position in zip(normalized, positions, strict=True):
|
||||
pad(position["start_sample"] - cursor)
|
||||
with wave.open(str(path), "rb") as source:
|
||||
while chunk := source.readframes(16384):
|
||||
output.writeframesraw(chunk)
|
||||
cursor = position["end_sample"]
|
||||
pad(total_samples - cursor)
|
||||
os.replace(temporary, target)
|
||||
|
||||
await file_thread(write_track)
|
||||
result = {
|
||||
"segments": positions,
|
||||
"sample_rate": 48000,
|
||||
"sample_count": total_samples,
|
||||
"total_frames": inputs["total_frames"],
|
||||
}
|
||||
return CpuResult(
|
||||
[target, provider._json_file(work, "narration.json", result)],
|
||||
result,
|
||||
{"provider": "ffmpeg-cpu", "recipe": "narration-assemble-v1"},
|
||||
)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
for path in normalized:
|
||||
path.unlink(missing_ok=True)
|
||||
227
backend/app/adapters/provider/files.py
Normal file
227
backend/app/adapters/provider/files.py
Normal file
@ -0,0 +1,227 @@
|
||||
"""受限工作目录与远程输入输出字节校验。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import PurePosixPath
|
||||
import stat
|
||||
import uuid
|
||||
|
||||
import httpx
|
||||
|
||||
from app.adapters.media import confined
|
||||
from app.domain.errors import MediaError as ProviderError
|
||||
from .contracts import _invalid, _int
|
||||
from .transport import _url
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .client import Provider
|
||||
|
||||
|
||||
_REMOTE_INPUT_SUFFIXES = {
|
||||
".png",
|
||||
".jpg",
|
||||
".jpeg",
|
||||
".webp",
|
||||
".bmp",
|
||||
".wav",
|
||||
".mp3",
|
||||
".flac",
|
||||
".m4a",
|
||||
".ogg",
|
||||
".aac",
|
||||
".mp4",
|
||||
".webm",
|
||||
".mov",
|
||||
}
|
||||
_REMOTE_INPUT_LIMIT = 512 * 1024 * 1024
|
||||
|
||||
|
||||
def _work(provider: Provider, path):
|
||||
work = confined(path, provider.settings, exists=False, root=provider.settings.job_work_root)
|
||||
if not work.is_dir():
|
||||
raise _invalid("任务工作目录不可用。")
|
||||
return work
|
||||
|
||||
|
||||
def _asset(provider: Provider, asset_id, assets):
|
||||
# assets 由上游按用户权限解析;这里只接受映射内 ID,不能把输入当作路径。
|
||||
if not isinstance(asset_id, str) or asset_id not in assets:
|
||||
raise _invalid("请选择可访问的素材。")
|
||||
return confined(assets[asset_id], provider.settings)
|
||||
|
||||
|
||||
async def _upload_input(provider: Provider, source):
|
||||
source = confined(source, provider.settings)
|
||||
suffix = source.suffix.lower()
|
||||
if suffix == ".jfif":
|
||||
# 参考图已按内容解码校验;JFIF使用JPEG编码,远端沿用标准.jpg名称。
|
||||
# 只规范传输文件名,原素材字节、摘要和本地存储位置保持不变。
|
||||
suffix = ".jpg"
|
||||
if suffix not in _REMOTE_INPUT_SUFFIXES:
|
||||
raise _invalid("模型输入文件类型不受支持。")
|
||||
limit = min(
|
||||
_REMOTE_INPUT_LIMIT,
|
||||
int(getattr(provider.settings, "max_upload_bytes", _REMOTE_INPUT_LIMIT)),
|
||||
)
|
||||
try:
|
||||
with source.open("rb") as stream:
|
||||
# 同一描述符完成摘要与上传,回执必须匹配字节数、摘要和目标名。
|
||||
info = os.fstat(stream.fileno())
|
||||
if not stat.S_ISREG(info.st_mode) or info.st_size <= 0:
|
||||
raise _invalid("模型输入文件为空或不可读取。")
|
||||
if info.st_size > limit:
|
||||
raise ProviderError("input_too_large", "模型输入文件超出大小限制。")
|
||||
digest, size = hashlib.sha256(), 0
|
||||
while chunk := await asyncio.to_thread(stream.read, 1024 * 1024):
|
||||
size += len(chunk)
|
||||
if size > limit or size > info.st_size:
|
||||
raise ProviderError("input_too_large", "模型输入文件超出大小限制。")
|
||||
digest.update(chunk)
|
||||
if size != info.st_size:
|
||||
raise ProviderError("invalid_asset", "模型输入文件在读取时发生变化。", True)
|
||||
digest = digest.hexdigest()
|
||||
name = digest + suffix
|
||||
stream.seek(0)
|
||||
|
||||
async def chunks():
|
||||
count = 0
|
||||
while data := await asyncio.to_thread(stream.read, 1024 * 1024):
|
||||
count += len(data)
|
||||
if count > size:
|
||||
raise ProviderError("invalid_asset", "模型输入文件在读取时发生变化。", True)
|
||||
yield data
|
||||
if count != size:
|
||||
raise ProviderError("invalid_asset", "模型输入文件在读取时发生变化。", True)
|
||||
|
||||
headers = {
|
||||
**provider._headers(),
|
||||
"Content-Type": "application/octet-stream",
|
||||
"Content-Length": str(size),
|
||||
}
|
||||
async with asyncio.timeout(
|
||||
max(30, min(600, float(provider.settings.request_timeout_seconds) * 4))
|
||||
):
|
||||
async with provider.client.stream(
|
||||
"POST",
|
||||
_url(provider.settings.inference_base_url, "/inputs/" + name),
|
||||
headers=headers,
|
||||
content=chunks(),
|
||||
) as response:
|
||||
if not 200 <= response.status_code < 300:
|
||||
raise provider._http_error(response.status_code)
|
||||
parts, count = [], 0
|
||||
async for chunk in response.aiter_bytes():
|
||||
count += len(chunk)
|
||||
if count > 16384:
|
||||
raise ValueError
|
||||
parts.append(chunk)
|
||||
receipt = json.loads(b"".join(parts))
|
||||
path = receipt["path"]
|
||||
candidate = PurePosixPath(path)
|
||||
if (
|
||||
not isinstance(path, str)
|
||||
or not path.startswith("/")
|
||||
or path.startswith("//")
|
||||
or "\\" in path
|
||||
or ":" in path
|
||||
or "\x00" in path
|
||||
or not candidate.is_absolute()
|
||||
or str(candidate) != path
|
||||
or any(part in {".", ".."} for part in candidate.parts)
|
||||
or candidate.name != name
|
||||
or candidate.parent.parts[-2:] != ("inputs", "llm-services")
|
||||
or receipt["sha256"] != digest
|
||||
or type(receipt["size_bytes"]) is not int
|
||||
or receipt["size_bytes"] != size
|
||||
):
|
||||
raise ValueError
|
||||
return path
|
||||
except (httpx.HTTPError, asyncio.TimeoutError):
|
||||
raise ProviderError(
|
||||
"upstream_unavailable", "模型输入文件传输失败,请稍后重试。", True
|
||||
) from None
|
||||
except OSError:
|
||||
raise ProviderError("invalid_asset", "模型输入文件不存在或不可读取。", True) from None
|
||||
except (ValueError, TypeError, KeyError, UnicodeError, RecursionError):
|
||||
raise ProviderError(
|
||||
"invalid_upstream_response", "模型服务返回了无效文件接收结果。", True
|
||||
) from None
|
||||
|
||||
|
||||
async def _download_url(
|
||||
provider: Provider, url, destination, headers, *, payload=None, timeout=None, total_timeout=None
|
||||
):
|
||||
target = confined(destination, provider.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(
|
||||
total_timeout
|
||||
if total_timeout is not None
|
||||
else max(30, min(600, float(provider.settings.request_timeout_seconds) * 4))
|
||||
):
|
||||
options = {} if timeout is None else {"timeout": timeout}
|
||||
async with provider.client.stream(
|
||||
"POST" if payload is not None else "GET",
|
||||
url,
|
||||
headers=headers,
|
||||
json=payload,
|
||||
**options,
|
||||
) as response:
|
||||
if not 200 <= response.status_code < 300:
|
||||
raise provider._http_error(response.status_code)
|
||||
limit = int(provider.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(provider: Provider, upstream_id, index, destination):
|
||||
_int(index, 0, 1000)
|
||||
await provider._download_url(
|
||||
_url(
|
||||
provider.settings.inference_base_url,
|
||||
"/jobs/" + provider._job_id(upstream_id) + "/outputs/" + str(index),
|
||||
),
|
||||
destination,
|
||||
provider._headers(),
|
||||
)
|
||||
|
||||
|
||||
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
|
||||
292
backend/app/adapters/provider/gpu.py
Normal file
292
backend/app/adapters/provider/gpu.py
Normal file
@ -0,0 +1,292 @@
|
||||
"""GPU 任务准备、幂等提交与远端控制。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from app.adapters.media import input_options, inspect_media, run_process
|
||||
from app.domain.execution import enter_phase
|
||||
from app.domain.errors import MediaError as ProviderError
|
||||
from .contracts import _invalid, _keys, _int, _float, _string
|
||||
from .contracts import GPU_TASKS, LANGUAGES, capabilities, validate_arguments
|
||||
from .transport import _url
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .client import Provider
|
||||
|
||||
|
||||
async def prepare_gpu_payload(
|
||||
provider: Provider, task_type, inputs, parameters, assets, work_dir, *, analysis_binding=None
|
||||
):
|
||||
validate_arguments(task_type, inputs, parameters, provider.settings)
|
||||
work = provider._work(work_dir)
|
||||
if task_type not in GPU_TASKS:
|
||||
raise _invalid("不支持此模型任务类型。")
|
||||
if task_type in {"video.people.analyze", "video.replace"}:
|
||||
from .video_editing import prepare_video
|
||||
|
||||
return await prepare_video(
|
||||
provider, task_type, inputs, parameters, assets, analysis_binding
|
||||
)
|
||||
if task_type == "image.reference.generate":
|
||||
defaults = next(
|
||||
item["defaults"]
|
||||
for item in capabilities(provider.settings)
|
||||
if item["task_type"] == task_type
|
||||
)
|
||||
upstream = (await provider.upstream_capabilities()).get("reference_generation", {})
|
||||
maximum = upstream.get("max_reference_images")
|
||||
if (
|
||||
upstream.get("available") is not True
|
||||
or upstream.get("profile") != defaults["profile"]
|
||||
or type(maximum) is not int
|
||||
or maximum < 1
|
||||
):
|
||||
raise ProviderError("capability_unavailable", "上游多图生成尚未认证或模型版本不匹配。")
|
||||
if len(inputs["reference_asset_ids"]) > maximum:
|
||||
raise _invalid("参考图片数量超出上游已认证范围。")
|
||||
# 先逐张解码确认全部可用,再上传;不能在中途缺图时退回文生图。
|
||||
paths = []
|
||||
for asset_id in inputs["reference_asset_ids"]:
|
||||
source = provider._asset(asset_id, assets)
|
||||
if (await inspect_media(source, provider.settings))["kind"] != "image":
|
||||
raise _invalid("全部参考素材必须是有效图片。")
|
||||
paths.append(str(source))
|
||||
if getattr(provider.settings, "inference_remote_files", False):
|
||||
paths = [await provider._upload_input(Path(path)) for path in paths]
|
||||
return {
|
||||
"task_type": task_type,
|
||||
"input": {
|
||||
"prompt": inputs["prompt"],
|
||||
"negative_prompt": inputs.get("negative_prompt", ""),
|
||||
"image_paths": paths,
|
||||
},
|
||||
"parameters": {**defaults, **parameters},
|
||||
"timeout_seconds": 3600,
|
||||
}
|
||||
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(provider.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 = provider._asset(asset_id, assets)
|
||||
info = await inspect_media(source, provider.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":
|
||||
await enter_phase("extract_audio", "cpu_media")
|
||||
target = work / "asr-input.wav"
|
||||
temporary = work / ("asr-" + uuid.uuid4().hex + ".wav")
|
||||
try:
|
||||
await run_process(
|
||||
[
|
||||
provider.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
|
||||
await enter_phase("transcribe", "new_gpu")
|
||||
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 = provider._asset(inputs["image_asset_id"], assets)
|
||||
if (await inspect_media(source, provider.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, 361)
|
||||
if (
|
||||
normalized["num_frames"] % 4 != 1
|
||||
or type(normalized["fps"]) is not int
|
||||
or normalized["fps"] != 24
|
||||
):
|
||||
raise _invalid("视频仅支持4n+1帧、最多361帧和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)
|
||||
if getattr(provider.settings, "inference_remote_files", False):
|
||||
for key in ("image_path", "audio_path"):
|
||||
if key in out:
|
||||
out[key] = await provider._upload_input(Path(out[key]))
|
||||
return {"task_type": task_type, "input": out, "parameters": normalized, "timeout_seconds": 3600}
|
||||
|
||||
|
||||
async def submit(provider: Provider, payload, idempotency_key):
|
||||
# 响应丢失后的恢复必须使用相同请求体与幂等键,不能隐式创建第二个模型任务。
|
||||
_string(idempotency_key, 128)
|
||||
if any(not 33 <= ord(char) <= 126 for char in idempotency_key):
|
||||
raise _invalid("幂等请求标识无效。")
|
||||
return provider._sanitize_job(
|
||||
await provider._json(
|
||||
"POST",
|
||||
_url(provider.settings.inference_base_url, "/jobs"),
|
||||
payload=payload,
|
||||
headers={**provider._headers(), "Idempotency-Key": idempotency_key},
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _job_id(value):
|
||||
if not isinstance(value, str) or re.fullmatch(r"[0-9a-f]{32}", value) is None:
|
||||
raise _invalid("模型任务标识无效。")
|
||||
return value
|
||||
|
||||
|
||||
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(provider: Provider, upstream_id):
|
||||
return provider._sanitize_job(
|
||||
await provider._json(
|
||||
"GET",
|
||||
_url(provider.settings.inference_base_url, "/jobs/" + provider._job_id(upstream_id)),
|
||||
headers=provider._headers(),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
async def upstream_capabilities(provider: Provider):
|
||||
cached = getattr(provider, "_capabilities_cache", None)
|
||||
if cached and time.monotonic() - cached[0] < 30:
|
||||
return json.loads(json.dumps(cached[1]))
|
||||
value = await provider._json(
|
||||
"GET",
|
||||
_url(provider.settings.inference_base_url, "/capabilities"),
|
||||
headers=provider._headers(),
|
||||
)
|
||||
features = value.get("features", {})
|
||||
value["admission_policy"] = bool(
|
||||
value.get("admission_policy")
|
||||
or (features.get("scheduling") and features.get("admission_pause"))
|
||||
)
|
||||
provider._capabilities_cache = (time.monotonic(), value)
|
||||
return json.loads(json.dumps(value))
|
||||
|
||||
|
||||
async def control(
|
||||
provider: Provider,
|
||||
upstream_id,
|
||||
desired_state,
|
||||
command_id,
|
||||
expected_version=None,
|
||||
expected_execution_id=None,
|
||||
):
|
||||
if desired_state not in {"run", "pause", "cancel"}:
|
||||
raise _invalid("Invalid control intention.")
|
||||
_string(command_id, 128)
|
||||
payload = {"desired_state": desired_state, "command_id": command_id}
|
||||
if expected_version is not None:
|
||||
payload["expected_version"] = _int(expected_version, 0, 2**63 - 1)
|
||||
if expected_execution_id is not None:
|
||||
payload["expected_execution_id"] = _string(expected_execution_id, 64)
|
||||
return provider._sanitize_job(
|
||||
await provider._json(
|
||||
"PUT",
|
||||
_url(
|
||||
provider.settings.inference_base_url,
|
||||
"/jobs/" + provider._job_id(upstream_id) + "/control",
|
||||
),
|
||||
payload=payload,
|
||||
headers=provider._headers(),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
async def cancel(provider: Provider, upstream_id):
|
||||
return provider._sanitize_job(
|
||||
await provider._json(
|
||||
"POST",
|
||||
_url(
|
||||
provider.settings.inference_base_url,
|
||||
"/jobs/" + provider._job_id(upstream_id) + "/cancel",
|
||||
),
|
||||
headers=provider._headers(),
|
||||
)
|
||||
)
|
||||
199
backend/app/adapters/provider/qwen.py
Normal file
199
backend/app/adapters/provider/qwen.py
Normal file
@ -0,0 +1,199 @@
|
||||
"""共享 Qwen 的文本、图片与视频抽帧理解适配。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
from io import BytesIO
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
|
||||
from PIL import Image, ImageOps
|
||||
|
||||
from app.adapters.media import input_options, inspect_media, run_process
|
||||
from app.domain.execution import CpuResult, enter_phase
|
||||
from app.domain.errors import MediaError as ProviderError
|
||||
from .contracts import _invalid, _keys, _int, _string
|
||||
from .transport import _url
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .client import Provider
|
||||
|
||||
|
||||
async def _chat(provider: Provider, messages, *, max_tokens=2048, thinking=False):
|
||||
# 取消只影响当前等待;常驻网关负责并发引用计数、排空和模型释放。
|
||||
if not provider.settings.qwen_model:
|
||||
raise ProviderError("capability_unavailable", "文本与视觉服务尚未配置。")
|
||||
value = await provider._json(
|
||||
"POST",
|
||||
_url(provider.settings.qwen_base_url, "/chat/completions"),
|
||||
headers=provider._headers("qwen"),
|
||||
timeout=getattr(provider.settings, "qwen_timeout_seconds", 1800.0),
|
||||
payload={
|
||||
"model": provider.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
|
||||
|
||||
|
||||
async def _image_uri(provider: Provider, 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(provider: Provider, 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 = provider._asset(asset_id, assets)
|
||||
info = await inspect_media(source, provider.settings)
|
||||
if info["kind"] not in {"image", "video"}:
|
||||
raise _invalid("素材理解支持图片或视频。")
|
||||
samples, outputs = [(0.0, source)], []
|
||||
if info["kind"] == "video":
|
||||
await enter_phase("sample_frames", "cpu_media")
|
||||
samples = []
|
||||
for index in range(count):
|
||||
timestamp = (index + 0.5) * info["duration_seconds"] / count
|
||||
frame = work / f"frame-{index:03d}.jpg"
|
||||
# 只使用固定滤镜与数值时间,不允许用户输入 FFmpeg 滤镜或协议。
|
||||
_, diagnostics = await run_process(
|
||||
[
|
||||
provider.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 -0.1 <= actual_time <= info["duration_seconds"] + 0.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 index, (timestamp, frame) in enumerate(samples):
|
||||
image_uri = await provider._image_uri(frame)
|
||||
await enter_phase(f"describe_frame_{index}", "qwen_http")
|
||||
text = await provider._chat(
|
||||
[
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{"type": "image_url", "image_url": {"url": image_uri}},
|
||||
{"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(provider._json_file(work, "structure.json", result))
|
||||
return CpuResult(
|
||||
outputs,
|
||||
result,
|
||||
{
|
||||
"provider": "qwen",
|
||||
"model": provider.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),
|
||||
},
|
||||
)
|
||||
313
backend/app/adapters/provider/runtime.py
Normal file
313
backend/app/adapters/provider/runtime.py
Normal file
@ -0,0 +1,313 @@
|
||||
"""运行状态白名单、短缓存与远程调度策略镜像。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from app.adapters.media import confined
|
||||
from app.domain.errors import MediaError as ProviderError
|
||||
from .contracts import _int, _float
|
||||
from .transport import _url
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .client import Provider
|
||||
|
||||
|
||||
_UUID = re.compile(r"GPU-[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}\Z")
|
||||
|
||||
|
||||
async def health(provider: Provider):
|
||||
try:
|
||||
value = await provider._json(
|
||||
"GET",
|
||||
_url(provider.settings.inference_base_url, "/health"),
|
||||
headers=provider._headers(),
|
||||
)
|
||||
return value.get("status") == "ok"
|
||||
except ProviderError:
|
||||
return False
|
||||
|
||||
|
||||
def _runtime_value(value):
|
||||
"""Validate and whitelist operator telemetry before retaining it locally."""
|
||||
try:
|
||||
if type(value["schema_version"]) is not int or value["schema_version"] != 1:
|
||||
raise ValueError
|
||||
policy = value["runtime_policy"]
|
||||
if type(policy["batch_window_enabled"]) is not bool:
|
||||
raise ValueError
|
||||
shots = _int(policy["workflow_max_shots"], 1, 1000)
|
||||
error = policy.get("configuration_error")
|
||||
if error not in {None, "runtime_policy_invalid", "runtime_policy_unavailable"}:
|
||||
raise ValueError
|
||||
policy = {
|
||||
"batch_window_enabled": policy["batch_window_enabled"],
|
||||
"workflow_max_shots": shots,
|
||||
"configuration_error": error,
|
||||
}
|
||||
monitor = value["monitor"]
|
||||
if type(monitor["schema_version"]) is not int or monitor["schema_version"] != 1:
|
||||
raise ValueError
|
||||
if monitor.get("error") is not None:
|
||||
monitor = {
|
||||
"schema_version": 1,
|
||||
"generated_at": None,
|
||||
"error": "gpu_monitor_unavailable",
|
||||
"gpus": [],
|
||||
}
|
||||
else:
|
||||
now = time.time()
|
||||
stamp = _float(monitor["generated_at"], 0, now + 1)
|
||||
entries = monitor["gpus"]
|
||||
if not isinstance(entries, list) or len(entries) > 1024:
|
||||
raise ValueError
|
||||
gpus, seen_indexes, seen_uuids = [], set(), set()
|
||||
for row in entries:
|
||||
index, gpu_uuid = _int(row["index"], 0, 1024), row["uuid"]
|
||||
if (
|
||||
not isinstance(gpu_uuid, str)
|
||||
or not _UUID.fullmatch(gpu_uuid)
|
||||
or index in seen_indexes
|
||||
or gpu_uuid.lower() in seen_uuids
|
||||
):
|
||||
raise ValueError
|
||||
seen_indexes.add(index)
|
||||
seen_uuids.add(gpu_uuid.lower())
|
||||
total = _float(row["total_gib"], 0.001, 100000)
|
||||
free = _float(row["free_gib"], 0, total)
|
||||
idle = row.get("idle_since")
|
||||
if idle is not None:
|
||||
idle = _float(idle, 0, now + 1)
|
||||
if type(row["external_busy"]) is not bool or type(row["own_busy"]) is not bool:
|
||||
raise ValueError
|
||||
gpus.append(
|
||||
{
|
||||
"index": index,
|
||||
"uuid": gpu_uuid,
|
||||
"total_gib": total,
|
||||
"free_gib": free,
|
||||
"idle_since": idle,
|
||||
"external_busy": row["external_busy"],
|
||||
"own_busy": row["own_busy"],
|
||||
}
|
||||
)
|
||||
monitor = {"schema_version": 1, "generated_at": stamp, "error": None, "gpus": gpus}
|
||||
scheduler = value.get("scheduler")
|
||||
if scheduler is not None:
|
||||
if not isinstance(scheduler, dict):
|
||||
raise ValueError
|
||||
if type(scheduler.get("schema_version")) is not int or scheduler[
|
||||
"schema_version"
|
||||
] not in {1, 2}:
|
||||
raise ValueError
|
||||
# 只保留摘要所需的租约与计数,不暴露任务 ID、进程或诊断路径。
|
||||
clean = {
|
||||
key: scheduler[key]
|
||||
for key in ("schema_version", "updated_at", "state", "queued_count")
|
||||
if key in scheduler
|
||||
}
|
||||
if clean.get("state") not in {"idle", "waiting", "running", "blocked", "leased"}:
|
||||
raise ValueError
|
||||
clean["updated_at"] = _float(scheduler["updated_at"], 0, time.time() + 1)
|
||||
if "queued_count" in clean and clean["queued_count"] is not None:
|
||||
clean["queued_count"] = _int(clean["queued_count"], 0, 10000000)
|
||||
clean["reason"] = (
|
||||
"memory" if "memory" in str(scheduler.get("reason", "")).lower() else None
|
||||
)
|
||||
if scheduler.get("schema_version") == 2:
|
||||
rows = scheduler.get("active_jobs", [])
|
||||
if not isinstance(rows, list) or len(rows) > 1024:
|
||||
raise ValueError
|
||||
active = []
|
||||
for row in rows:
|
||||
index, gpu_uuid = _int(row["gpu_index"], 0, 1024), row["gpu_uuid"]
|
||||
if not isinstance(gpu_uuid, str) or not _UUID.fullmatch(gpu_uuid):
|
||||
raise ValueError
|
||||
state, stage = row.get("state"), row.get("stage")
|
||||
if state not in {"running", "launching", "preempting", "blocked"}:
|
||||
raise ValueError
|
||||
stage = (
|
||||
stage
|
||||
if stage
|
||||
in {"launching", "executing", "cleanup", "model", "upscale", "collecting"}
|
||||
else None
|
||||
)
|
||||
active.append(
|
||||
{"gpu_index": index, "gpu_uuid": gpu_uuid, "state": state, "stage": stage}
|
||||
)
|
||||
clean["active_jobs"] = active
|
||||
elif scheduler.get("state") == "leased":
|
||||
lease = scheduler.get("lease") or {}
|
||||
index, gpu_uuid = _int(lease["index"], 0, 1024), lease["uuid"]
|
||||
if not isinstance(gpu_uuid, str) or not _UUID.fullmatch(gpu_uuid):
|
||||
raise ValueError
|
||||
clean["lease"] = {"index": index, "uuid": gpu_uuid}
|
||||
scheduler = clean
|
||||
return {
|
||||
"schema_version": 1,
|
||||
"monitor": monitor,
|
||||
"scheduler": scheduler,
|
||||
"runtime_policy": policy,
|
||||
}
|
||||
except (ValueError, TypeError, KeyError, AttributeError, ProviderError, OverflowError):
|
||||
raise ProviderError(
|
||||
"invalid_upstream_response", "模型服务返回了无效运行状态。", True
|
||||
) from None
|
||||
|
||||
|
||||
async def runtime_status(provider: Provider):
|
||||
cached = getattr(provider, "_runtime_cache", None)
|
||||
if cached and time.monotonic() - cached[0] < 1:
|
||||
return json.loads(json.dumps(cached[1]))
|
||||
async with provider._runtime_lock:
|
||||
cached = getattr(provider, "_runtime_cache", None)
|
||||
if cached and time.monotonic() - cached[0] < 1:
|
||||
return json.loads(json.dumps(cached[1]))
|
||||
try:
|
||||
value = await provider._json(
|
||||
"GET",
|
||||
_url(provider.settings.inference_base_url, "/runtime/status"),
|
||||
headers=provider._headers(),
|
||||
)
|
||||
result = provider._runtime_value(value)
|
||||
provider._mirror_runtime_policy(result["runtime_policy"])
|
||||
observed = time.monotonic()
|
||||
if getattr(provider.settings, "inference_remote_files", False):
|
||||
provider.settings._remote_policy_error = result["runtime_policy"][
|
||||
"configuration_error"
|
||||
]
|
||||
if provider.settings._remote_policy_error is None:
|
||||
provider.settings._remote_policy_observed_at = observed
|
||||
provider._runtime_cache = (observed, result)
|
||||
return json.loads(json.dumps(result))
|
||||
except (ProviderError, asyncio.CancelledError) as exc:
|
||||
if getattr(provider.settings, "inference_remote_files", False):
|
||||
provider.settings._remote_policy_error = (
|
||||
"runtime_policy_invalid"
|
||||
if isinstance(exc, ProviderError) and exc.code == "invalid_upstream_response"
|
||||
else "runtime_policy_unavailable"
|
||||
)
|
||||
raise
|
||||
|
||||
|
||||
def _mirror_runtime_policy(provider: Provider, policy):
|
||||
if (
|
||||
not getattr(provider.settings, "inference_remote_files", False)
|
||||
or policy["configuration_error"] is not None
|
||||
):
|
||||
return
|
||||
path = confined(
|
||||
getattr(provider.settings, "runtime_policy_file", None), provider.settings, exists=False
|
||||
)
|
||||
payload = {
|
||||
"schema_version": 1,
|
||||
"batch_window_enabled": policy["batch_window_enabled"],
|
||||
"workflow_max_shots": policy["workflow_max_shots"],
|
||||
}
|
||||
temporary = path.with_name(path.name + ".part-" + uuid.uuid4().hex)
|
||||
try:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
if path.stat().st_size <= 65536 and json.loads(path.read_bytes()) == payload:
|
||||
return
|
||||
except (OSError, ValueError, UnicodeError):
|
||||
pass
|
||||
with temporary.open("xb") as handle:
|
||||
handle.write(json.dumps(payload, allow_nan=False).encode("utf-8"))
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
os.replace(temporary, path)
|
||||
except OSError:
|
||||
raise ProviderError("provider_not_configured", "无法同步模型服务运行策略。", True) from None
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
|
||||
|
||||
async def scheduler_status(provider: Provider):
|
||||
unavailable = {
|
||||
"available": False,
|
||||
"state": "unavailable",
|
||||
"reason": "GPU状态暂时不可用。",
|
||||
"gpus": [],
|
||||
"updated_at": None,
|
||||
}
|
||||
try:
|
||||
remote = bool(getattr(provider.settings, "inference_remote_files", False))
|
||||
if remote:
|
||||
runtime = await provider.runtime_status()
|
||||
data, scheduler = runtime["monitor"], runtime["scheduler"]
|
||||
else:
|
||||
path = Path(provider.settings.gpu_status_path)
|
||||
if path.stat().st_size > 1024 * 1024:
|
||||
return unavailable
|
||||
data = json.loads(path.read_bytes())
|
||||
scheduler = None
|
||||
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"], 0.001, 100000)
|
||||
free = _float(gpu["free_gib"], 0, total)
|
||||
if remote:
|
||||
external, own = gpu["external_busy"], gpu["own_busy"]
|
||||
else:
|
||||
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)
|
||||
eligible = not busy and free >= 76 and idle is not None and now - idle >= 15
|
||||
gpus.append(
|
||||
{
|
||||
"index": index,
|
||||
"name": f"GPU {index}",
|
||||
"busy": busy,
|
||||
"eligible": eligible,
|
||||
"free_gib": free,
|
||||
"_uuid": gpu["uuid"],
|
||||
"_own": bool(own),
|
||||
"state": "external"
|
||||
if external
|
||||
else "running"
|
||||
if own
|
||||
else "ready"
|
||||
if eligible
|
||||
else "waiting",
|
||||
"stage": None,
|
||||
}
|
||||
)
|
||||
if not remote:
|
||||
try:
|
||||
scheduler_path = Path(provider.settings.gpu_scheduler_path)
|
||||
if scheduler_path.stat().st_size <= 1024 * 1024:
|
||||
scheduler = json.loads(scheduler_path.read_bytes())
|
||||
except (OSError, ValueError, TypeError, AttributeError):
|
||||
pass
|
||||
from app.domain.gpu_summary import summarize
|
||||
|
||||
return summarize(gpus, scheduler, now, generated)
|
||||
except (OSError, ValueError, TypeError, KeyError, AttributeError, ProviderError, OverflowError):
|
||||
return unavailable
|
||||
103
backend/app/adapters/provider/speech.py
Normal file
103
backend/app/adapters/provider/speech.py
Normal file
@ -0,0 +1,103 @@
|
||||
"""已配置真实 TTS 服务的 WAV 输出适配。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import wave
|
||||
|
||||
from app.adapters.media import inspect_media
|
||||
from app.domain.execution import CpuResult
|
||||
from app.domain.errors import MediaError as ProviderError
|
||||
from .contracts import _invalid, _keys, _float, _string, _voices
|
||||
from .transport import _url
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .client import Provider
|
||||
|
||||
|
||||
async def _speech(provider: Provider, inputs, p, work):
|
||||
if (
|
||||
not provider.settings.tts_base_url
|
||||
or not provider.settings.tts_model
|
||||
or not _voices(provider.settings)
|
||||
):
|
||||
raise ProviderError("capability_unavailable", "中文配音服务尚未配置。")
|
||||
_keys(inputs, {"prompt"})
|
||||
_keys(p, {"voice", "speed", "model"})
|
||||
model = p.get("model", provider.settings.tts_model)
|
||||
if model != provider.settings.tts_model:
|
||||
raise ProviderError("capability_changed", "配音模型配置已变化,请重新生成执行计划")
|
||||
text = _string(inputs.get("prompt"), 2000)
|
||||
voice = p.get("voice", _voices(provider.settings)[0])
|
||||
if voice not in _voices(provider.settings):
|
||||
raise _invalid("请选择已配置的中文音色。")
|
||||
speed = _float(p.get("speed", 1.0), 0.5, 2)
|
||||
target = work / "speech.wav"
|
||||
await provider._download_url(
|
||||
_url(provider.settings.tts_base_url, "/audio/speech"),
|
||||
target,
|
||||
provider._headers("tts"),
|
||||
timeout=getattr(provider.settings, "speech_timeout_seconds", 330.0),
|
||||
total_timeout=getattr(provider.settings, "speech_total_timeout_seconds", 360.0),
|
||||
payload={
|
||||
"model": model,
|
||||
"input": text,
|
||||
"voice": voice,
|
||||
"speed": speed,
|
||||
"response_format": "wav",
|
||||
},
|
||||
)
|
||||
info = await inspect_media(target, provider.settings)
|
||||
if info["kind"] != "audio" or info["mime_type"] != "audio/wav":
|
||||
target.unlink(missing_ok=True)
|
||||
raise ProviderError("invalid_speech_response", "配音服务未返回有效的 WAV 音频。", True)
|
||||
# 时间线用48kHz整数采样,避免5.02秒被round成5秒后错误准入视频生成。
|
||||
try:
|
||||
with wave.open(str(target), "rb") as source:
|
||||
samples = (
|
||||
source.getnframes() * 48000 + source.getframerate() - 1
|
||||
) // source.getframerate()
|
||||
except (wave.Error, EOFError):
|
||||
samples = math.ceil(info["duration_seconds"] * 48000)
|
||||
return CpuResult(
|
||||
[target],
|
||||
{
|
||||
"text": text,
|
||||
"voice": voice,
|
||||
"duration_seconds": info["duration_seconds"],
|
||||
"sample_count": samples,
|
||||
"sample_rate": 48000,
|
||||
},
|
||||
{"provider": "openai-compatible-tts", "model": model, "speed": speed},
|
||||
)
|
||||
|
||||
|
||||
async def health(provider: Provider):
|
||||
configured = bool(
|
||||
provider.settings.tts_base_url
|
||||
and provider.settings.tts_model
|
||||
and _voices(provider.settings)
|
||||
)
|
||||
result = {
|
||||
"configured": configured,
|
||||
"reachable": False,
|
||||
"model": provider.settings.tts_model,
|
||||
"validation": "requires_deployment_acceptance",
|
||||
}
|
||||
if not configured:
|
||||
return result
|
||||
try:
|
||||
base = provider.settings.tts_base_url.rstrip("/").removesuffix("/v1")
|
||||
value = await provider._json(
|
||||
"GET", _url(base, "/health"), headers=provider._headers("tts"), timeout=5
|
||||
)
|
||||
result["reachable"] = (
|
||||
value.get("status") == "ok"
|
||||
and value.get("model") == provider.settings.tts_model
|
||||
and set(_voices(provider.settings)).issubset(value.get("voices", []))
|
||||
)
|
||||
except (ProviderError, TypeError, ValueError):
|
||||
pass
|
||||
return result
|
||||
109
backend/app/adapters/provider/transport.py
Normal file
109
backend/app/adapters/provider/transport.py
Normal file
@ -0,0 +1,109 @@
|
||||
"""受限 HTTP 与按服务隔离的认证。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import stat
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
import httpx
|
||||
|
||||
from app.domain.errors import MediaError as ProviderError
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .client import Provider
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
def _headers(provider: Provider, family="inference"):
|
||||
# 各服务只读自己的认证信息,Qwen/TTS 不继承 GPU 推理服务的密钥。
|
||||
key = getattr(provider.settings, family + "_api_key", "") or ""
|
||||
if family == "inference" and getattr(provider.settings, "inference_api_key_file", None):
|
||||
key = _read_key(provider.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 {}
|
||||
|
||||
|
||||
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(provider: Provider, method, url, *, payload=None, headers=None, timeout=None):
|
||||
seconds = float(provider.settings.request_timeout_seconds if timeout is None else timeout)
|
||||
options = {} if timeout is None else {"timeout": httpx.Timeout(seconds)}
|
||||
try:
|
||||
async with asyncio.timeout(seconds + 1):
|
||||
async with provider.client.stream(
|
||||
method, url, json=payload, headers=headers, **options
|
||||
) as response:
|
||||
if not 200 <= response.status_code < 300:
|
||||
raise provider._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
|
||||
74
backend/app/adapters/provider/video_editing.py
Normal file
74
backend/app/adapters/provider/video_editing.py
Normal file
@ -0,0 +1,74 @@
|
||||
"""可信分析绑定到真实输入字节,再送入现有监管队列。"""
|
||||
|
||||
import asyncio
|
||||
from app.adapters.media import inspect_media, inspect_video_timeline
|
||||
from app.services.artifacts import digest_file
|
||||
from app.domain.errors import MediaError
|
||||
from app.domain.video_editing import video_capability, video_defaults
|
||||
|
||||
|
||||
async def prepare_video(provider, task, inputs, parameters, assets, binding):
|
||||
local = video_capability(provider.settings)
|
||||
remote = (await provider.upstream_capabilities()).get("video_edit", {})
|
||||
p = video_defaults(task, provider.settings) | parameters
|
||||
if (
|
||||
remote.get("available") is not True
|
||||
or remote.get("profile") != p["profile"]
|
||||
or remote.get("fps") != 24
|
||||
):
|
||||
raise MediaError("capability_unavailable", "上游视频编辑未认证或模型版本不匹配。")
|
||||
source = provider._asset(inputs["video_asset_id"], assets)
|
||||
info = await inspect_media(source, provider.settings)
|
||||
duration = await inspect_video_timeline(source, provider.settings)
|
||||
if (
|
||||
info["kind"] != "video"
|
||||
or duration > min(local["max_seconds"], remote.get("max_seconds", 0)) + 0.001
|
||||
or p["max_pixels"] > remote.get("max_pixels", 0)
|
||||
):
|
||||
raise MediaError("invalid_input", "视频类型、时长或规格超出已认证范围。")
|
||||
digest = await asyncio.to_thread(digest_file, source)
|
||||
paths = []
|
||||
if task == "video.replace":
|
||||
if (
|
||||
not isinstance(binding, dict)
|
||||
or binding.get("source_sha256") != digest
|
||||
or binding.get("profile") != p["profile"]
|
||||
):
|
||||
raise MediaError("analysis_source_mismatch", "源视频字节与冻结分析不匹配。")
|
||||
if len(inputs["replacements"]) > remote.get("max_people", 0):
|
||||
raise MediaError("invalid_input", "人物数量超出上游范围。")
|
||||
for row in inputs["replacements"]:
|
||||
image = provider._asset(row["reference_asset_id"], assets)
|
||||
if (await inspect_media(image, provider.settings))["kind"] != "image":
|
||||
raise MediaError("invalid_input", "人物参考素材必须是有效图片。")
|
||||
if await asyncio.to_thread(digest_file, image) != binding.get(
|
||||
"reference_sha256", {}
|
||||
).get(row["reference_asset_id"]):
|
||||
raise MediaError("invalid_asset", "参考图片字节与冻结映射不一致。")
|
||||
paths.append(image)
|
||||
|
||||
# 全部输入完成校验后才上传;原片不改写,映射保序且包含所有所选人物。
|
||||
async def path(value):
|
||||
return (
|
||||
await provider._upload_input(value)
|
||||
if provider.settings.inference_remote_files
|
||||
else str(value)
|
||||
)
|
||||
|
||||
out = {"video_path": await path(source)}
|
||||
if task == "video.replace":
|
||||
out.update(
|
||||
analysis_id=binding["analysis_id"],
|
||||
analysis_token=binding["analysis_token"],
|
||||
prompt=inputs.get("prompt", ""),
|
||||
negative_prompt=inputs.get("negative_prompt", ""),
|
||||
replacements=[
|
||||
{
|
||||
"person_id": row["person_id"],
|
||||
"image_path": await path(image),
|
||||
"prompt": row.get("prompt", ""),
|
||||
}
|
||||
for row, image in zip(inputs["replacements"], paths, strict=True)
|
||||
],
|
||||
)
|
||||
return {"task_type": task, "input": out, "parameters": p, "timeout_seconds": 86400}
|
||||
45
backend/app/adapters/storage.py
Normal file
45
backend/app/adapters/storage.py
Normal file
@ -0,0 +1,45 @@
|
||||
import asyncio
|
||||
import os, stat
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
async def file_thread(operation, *args, **kwargs):
|
||||
"""取消等待不会停止系统线程;真实文件操作结束后才能释放执行/上传保护。"""
|
||||
worker = asyncio.create_task(asyncio.to_thread(operation, *args, **kwargs))
|
||||
try:
|
||||
return await asyncio.shield(worker)
|
||||
except asyncio.CancelledError:
|
||||
# 多次cancel也不能让底层线程失去跟踪;只等待本次本地文件操作。
|
||||
while not worker.done():
|
||||
try:
|
||||
await asyncio.shield(worker)
|
||||
except asyncio.CancelledError:
|
||||
continue
|
||||
except Exception:
|
||||
break
|
||||
if not worker.cancelled():
|
||||
worker.exception()
|
||||
raise
|
||||
|
||||
|
||||
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
|
||||
@ -1,68 +0,0 @@
|
||||
"""Durable clock-anomaly gate, applied only to new batch phases."""
|
||||
from datetime import datetime, timezone, timedelta
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import time
|
||||
import uuid
|
||||
|
||||
SHANGHAI=timezone(timedelta(hours=8))
|
||||
|
||||
class AdmissionClock:
|
||||
def __init__(self,path):
|
||||
self.path=Path(path)
|
||||
self.watermark=0.0
|
||||
self.closed_through=''
|
||||
self.reason=None
|
||||
self.valid=True
|
||||
if self.path.exists():
|
||||
try:
|
||||
data=json.loads(self.path.read_text(encoding='utf-8'))
|
||||
self.watermark=float(data['max_seen'])
|
||||
self.closed_through=data['closed_through']
|
||||
if not math.isfinite(self.watermark) or not 0<=self.watermark<=253402300799:
|
||||
raise ValueError('Invalid timestamp')
|
||||
datetime.fromisoformat(self.closed_through)
|
||||
except (ValueError,KeyError,TypeError,OSError):
|
||||
self.valid=False
|
||||
|
||||
def observe(self,now=None):
|
||||
if not self.valid:
|
||||
self.reason='clock_state_invalid'
|
||||
return False
|
||||
try:
|
||||
now=time.time() if now is None else float(now)
|
||||
if not math.isfinite(now):raise ValueError()
|
||||
local=datetime.fromtimestamp(now,timezone.utc).astimezone(SHANGHAI)
|
||||
except (ValueError,TypeError,OverflowError,OSError):
|
||||
self.reason='clock_invalid'
|
||||
return False
|
||||
closed=(local.date() if local.hour>=8 else local.date()-timedelta(days=1)).isoformat()
|
||||
next_closed=max(self.closed_through,closed)
|
||||
next_watermark=max(self.watermark,now)
|
||||
if int(next_watermark)>int(self.watermark) or next_closed!=self.closed_through:
|
||||
temporary=self.path.with_name(self.path.name+'.'+uuid.uuid4().hex+'.tmp')
|
||||
try:
|
||||
self.path.parent.mkdir(parents=True,exist_ok=True)
|
||||
with temporary.open('x',encoding='utf-8') as stream:
|
||||
json.dump({'max_seen':next_watermark,'closed_through':next_closed},stream)
|
||||
stream.flush();os.fsync(stream.fileno())
|
||||
os.replace(temporary,self.path)
|
||||
self.watermark,self.closed_through=next_watermark,next_closed
|
||||
except OSError:
|
||||
self.reason='clock_state_unwritable'
|
||||
return False
|
||||
finally:
|
||||
try:temporary.unlink(missing_ok=True)
|
||||
except OSError:pass
|
||||
if now<self.watermark-5:
|
||||
self.reason='clock_rollback'
|
||||
return False
|
||||
if local.hour>=21 or local.hour<8:
|
||||
window_end=local.date()+timedelta(days=1) if local.hour>=21 else local.date()
|
||||
if window_end.isoformat()<=self.closed_through:
|
||||
self.reason='window_already_closed'
|
||||
return False
|
||||
self.reason=None
|
||||
return True
|
||||
0
backend/app/api/__init__.py
Normal file
0
backend/app/api/__init__.py
Normal file
100
backend/app/api/dependencies.py
Normal file
100
backend/app/api/dependencies.py
Normal file
@ -0,0 +1,100 @@
|
||||
import hmac
|
||||
from fastapi import Depends, Request
|
||||
from sqlalchemy import select
|
||||
from app.models import Session, User, utcnow, ApiToken
|
||||
from app.core.errors import fail
|
||||
from app.core.security import Actor, COOKIE, token_hash
|
||||
|
||||
|
||||
async def current_actor(request: Request):
|
||||
authorization = request.headers.get("Authorization", "")
|
||||
if authorization.startswith("Bearer "):
|
||||
return await bearer_actor(request, authorization[7:])
|
||||
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,
|
||||
must_change_password=user.must_change_password,
|
||||
)
|
||||
|
||||
|
||||
async def csrf_actor(request: Request, actor: Actor = Depends(current_actor)):
|
||||
if actor.auth_kind == "bearer":
|
||||
if request.headers.get("sec-fetch-site") or request.cookies.get(COOKIE):
|
||||
fail(403, "machine_token_only", "Use session authentication in browsers")
|
||||
return 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
|
||||
|
||||
|
||||
async def bearer_actor(request, token):
|
||||
async with request.app.state.db.session() as session:
|
||||
row = await session.scalar(
|
||||
select(ApiToken).where(
|
||||
ApiToken.token_hash == token_hash(token), ApiToken.revoked_at.is_(None)
|
||||
)
|
||||
)
|
||||
if not row or (row.expires_at and row.expires_at <= utcnow()):
|
||||
fail(401, "token_expired", "Token unavailable")
|
||||
user = await session.get(User, row.owner_id)
|
||||
if not user or user.disabled:
|
||||
fail(401, "token_expired", "Token unavailable")
|
||||
path = request.url.path.removeprefix("/api/").split("/")[0]
|
||||
if path == "submissions":
|
||||
operation = request.query_params.get("operation", "")
|
||||
path = (
|
||||
"assets"
|
||||
if operation in {"assets.publish", "shared.import"}
|
||||
else "workflows"
|
||||
if operation.startswith("workflow")
|
||||
or operation.startswith("story.")
|
||||
or operation.startswith("editor.")
|
||||
else "batches"
|
||||
if operation.startswith("batch")
|
||||
else "jobs"
|
||||
)
|
||||
scope = {
|
||||
"workflow-runs": "workflows",
|
||||
"stories": "workflows",
|
||||
"editors": "workflows",
|
||||
"shared-assets": "assets",
|
||||
}.get(path, path) + (":read" if request.method in {"GET", "HEAD"} else ":write")
|
||||
if scope not in row.scopes:
|
||||
fail(403, "scope_required", "Token scope required: " + scope)
|
||||
return Actor(
|
||||
user.id,
|
||||
user.username,
|
||||
user.display_name,
|
||||
"user",
|
||||
"",
|
||||
row.token_hash,
|
||||
"bearer",
|
||||
row.scopes,
|
||||
user.must_change_password,
|
||||
)
|
||||
0
backend/app/api/middleware/__init__.py
Normal file
0
backend/app/api/middleware/__init__.py
Normal file
116
backend/app/api/middleware/upload_guard.py
Normal file
116
backend/app/api/middleware/upload_guard.py
Normal file
@ -0,0 +1,116 @@
|
||||
"""Authenticate and bound uploads before multipart parsing creates spool files."""
|
||||
|
||||
import asyncio
|
||||
import tempfile
|
||||
from fastapi import HTTPException
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import JSONResponse
|
||||
from app.api.dependencies import current_actor, csrf_actor
|
||||
from app.services.quotas import check_storage_budget
|
||||
|
||||
|
||||
class UploadGuard:
|
||||
def __init__(self, app):
|
||||
self.app = app
|
||||
self.slots = asyncio.Semaphore(2)
|
||||
self.lock = asyncio.Lock()
|
||||
self.reserved = {}
|
||||
self.global_reserved = 0
|
||||
|
||||
async def __call__(self, scope, receive, send):
|
||||
if (
|
||||
scope["type"] != "http"
|
||||
or scope["method"] != "POST"
|
||||
or scope["path"].rstrip("/") != "/api/assets"
|
||||
):
|
||||
return await self.app(scope, receive, send)
|
||||
request = Request(scope)
|
||||
settings = request.app.state.settings
|
||||
|
||||
async def reject(status, code, message):
|
||||
await JSONResponse({"detail": {"code": code, "message": message}}, status_code=status)(
|
||||
scope, receive, send
|
||||
)
|
||||
|
||||
try:
|
||||
actor = await current_actor(request)
|
||||
await csrf_actor(request, actor)
|
||||
except HTTPException as exc:
|
||||
return await JSONResponse({"detail": exc.detail}, status_code=exc.status_code)(
|
||||
scope, receive, send
|
||||
)
|
||||
limit = settings.max_upload_bytes + 1024 * 1024 # bounded multipart overhead
|
||||
length = request.headers.get("content-length")
|
||||
try:
|
||||
expected = int(length) if length is not None else limit
|
||||
if expected < 0:
|
||||
raise ValueError()
|
||||
except ValueError:
|
||||
return await reject(400, "invalid_content_length", "上传长度无效")
|
||||
if expected > limit:
|
||||
return await reject(413, "upload_too_large", "上传超过文件大小限制")
|
||||
if self.slots.locked():
|
||||
return await reject(429, "upload_busy", "同时上传数量已满,请稍后重试")
|
||||
await self.slots.acquire()
|
||||
reservation = expected * 2 # raw body plus multipart spool during parsing
|
||||
reserved = False
|
||||
try:
|
||||
async with self.lock:
|
||||
async with request.app.state.db.session() as session:
|
||||
await check_storage_budget(
|
||||
session,
|
||||
settings,
|
||||
actor.id,
|
||||
incoming_bytes=self.reserved.get(actor.id, 0) + expected,
|
||||
global_incoming_bytes=self.global_reserved + reservation,
|
||||
)
|
||||
self.reserved[actor.id] = self.reserved.get(actor.id, 0) + expected
|
||||
self.global_reserved += reservation
|
||||
reserved = True
|
||||
temporary = (settings.asset_root.parent / "tmp").resolve()
|
||||
if not temporary.is_relative_to(settings.workspace_root):
|
||||
return await reject(503, "upload_storage_unavailable", "上传暂存目录不可用")
|
||||
temporary.mkdir(parents=True, exist_ok=True)
|
||||
with tempfile.TemporaryFile(dir=temporary) as body:
|
||||
total = 0
|
||||
while True:
|
||||
message = await receive()
|
||||
if message["type"] == "http.disconnect":
|
||||
return await reject(499, "upload_disconnected", "上传连接已断开")
|
||||
if message["type"] != "http.request":
|
||||
continue
|
||||
chunk = message.get("body", b"")
|
||||
total += len(chunk)
|
||||
if total > limit or (length is not None and total > expected):
|
||||
return await reject(413, "upload_too_large", "上传超过文件大小限制")
|
||||
await asyncio.to_thread(body.write, chunk)
|
||||
if not message.get("more_body", False):
|
||||
break
|
||||
if length is not None and total != expected:
|
||||
return await reject(400, "invalid_content_length", "上传数据长度不匹配")
|
||||
await asyncio.to_thread(body.seek, 0)
|
||||
remaining = total
|
||||
completed = False
|
||||
|
||||
async def replay():
|
||||
nonlocal remaining, completed
|
||||
if completed:
|
||||
return await receive()
|
||||
chunk = await asyncio.to_thread(body.read, min(1024 * 1024, remaining))
|
||||
remaining -= len(chunk)
|
||||
completed = remaining == 0
|
||||
return {"type": "http.request", "body": chunk, "more_body": not completed}
|
||||
|
||||
await self.app(scope, replay, send)
|
||||
except HTTPException as exc:
|
||||
await JSONResponse({"detail": exc.detail}, status_code=exc.status_code)(
|
||||
scope, receive, send
|
||||
)
|
||||
finally:
|
||||
if reserved:
|
||||
async with self.lock:
|
||||
self.reserved[actor.id] -= expected
|
||||
self.global_reserved -= reservation
|
||||
if self.reserved[actor.id] == 0:
|
||||
self.reserved.pop(actor.id)
|
||||
self.slots.release()
|
||||
64
backend/app/api/responses.py
Normal file
64
backend/app/api/responses.py
Normal file
@ -0,0 +1,64 @@
|
||||
import os, re
|
||||
from urllib.parse import quote
|
||||
from fastapi import Response
|
||||
from fastapi.responses import StreamingResponse
|
||||
from starlette.background import BackgroundTask
|
||||
from app.adapters.storage import safe_file
|
||||
from app.core.errors import fail
|
||||
|
||||
|
||||
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),
|
||||
)
|
||||
38
backend/app/api/router.py
Normal file
38
backend/app/api/router.py
Normal file
@ -0,0 +1,38 @@
|
||||
"""统一挂载 /api,子路由保留原有路径与注册顺序。"""
|
||||
|
||||
from fastapi import APIRouter
|
||||
from app.api.routes import (
|
||||
editors,
|
||||
folders,
|
||||
auth,
|
||||
assets,
|
||||
shared_assets,
|
||||
jobs,
|
||||
events,
|
||||
submissions,
|
||||
tokens,
|
||||
workflows,
|
||||
batches,
|
||||
system,
|
||||
stories,
|
||||
)
|
||||
|
||||
router = APIRouter()
|
||||
for child in (
|
||||
editors.router,
|
||||
folders.router,
|
||||
auth.router,
|
||||
assets.router,
|
||||
shared_assets.router,
|
||||
shared_assets.publish_router,
|
||||
jobs.router,
|
||||
events.router,
|
||||
submissions.router,
|
||||
tokens.router,
|
||||
workflows.router,
|
||||
workflows.runs_router,
|
||||
batches.router,
|
||||
system.router,
|
||||
stories.router,
|
||||
):
|
||||
router.include_router(child)
|
||||
0
backend/app/api/routes/__init__.py
Normal file
0
backend/app/api/routes/__init__.py
Normal file
104
backend/app/api/routes/assets.py
Normal file
104
backend/app/api/routes/assets.py
Normal file
@ -0,0 +1,104 @@
|
||||
from app.services.assets import owned_asset
|
||||
|
||||
|
||||
from fastapi import APIRouter, Depends, File, Form, Request, UploadFile
|
||||
|
||||
|
||||
from app.core.security import Actor
|
||||
from app.api.dependencies import csrf_actor, current_actor
|
||||
|
||||
|
||||
from app.core.errors import fail
|
||||
|
||||
|
||||
from app.schemas.assets import AssetPatch
|
||||
from app.services import assets as service
|
||||
from app.api.responses import file_response
|
||||
|
||||
router = APIRouter(prefix="/assets", tags=["assets"])
|
||||
|
||||
|
||||
@router.post("", status_code=201)
|
||||
async def upload(
|
||||
request: Request,
|
||||
file: UploadFile = File(),
|
||||
name: str | None = Form(default=None),
|
||||
folder_id: str | None = Form(default=None),
|
||||
actor: Actor = Depends(csrf_actor),
|
||||
):
|
||||
return await service.upload(
|
||||
runtime=request.app.state,
|
||||
file=file,
|
||||
name=name,
|
||||
folder_id=folder_id,
|
||||
actor=actor,
|
||||
content_length=request.headers.get("content-length", "0"),
|
||||
)
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_assets(
|
||||
request: Request,
|
||||
page: int = 1,
|
||||
page_size: int = 24,
|
||||
folder_id: str = "",
|
||||
kind: str = "",
|
||||
q: str = "",
|
||||
tag: str = "",
|
||||
favorite: bool | None = None,
|
||||
origin: str = "",
|
||||
actor: Actor = Depends(current_actor),
|
||||
):
|
||||
return await service.list_assets(
|
||||
runtime=request.app.state,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
folder_id=folder_id,
|
||||
kind=kind,
|
||||
q=q,
|
||||
tag=tag,
|
||||
favorite=favorite,
|
||||
origin=origin,
|
||||
actor=actor,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{asset_id}")
|
||||
async def get_asset(asset_id: str, request: Request, actor: Actor = Depends(current_actor)):
|
||||
return await service.get_asset(asset_id=asset_id, runtime=request.app.state, actor=actor)
|
||||
|
||||
|
||||
@router.patch("/{asset_id}")
|
||||
async def patch_asset(
|
||||
asset_id: str, body: AssetPatch, request: Request, actor: Actor = Depends(csrf_actor)
|
||||
):
|
||||
return await service.patch_asset(
|
||||
asset_id=asset_id, body=body, runtime=request.app.state, actor=actor
|
||||
)
|
||||
|
||||
|
||||
@router.delete("/{asset_id}", status_code=204)
|
||||
async def delete_asset(asset_id: str, request: Request, actor: Actor = Depends(csrf_actor)):
|
||||
return await service.delete_asset(asset_id=asset_id, runtime=request.app.state, actor=actor)
|
||||
|
||||
|
||||
@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
|
||||
)
|
||||
81
backend/app/api/routes/auth.py
Normal file
81
backend/app/api/routes/auth.py
Normal file
@ -0,0 +1,81 @@
|
||||
from fastapi import APIRouter, Depends, Request, Response
|
||||
from app.schemas.auth import Login, CreateUser, UserPatch, PasswordChange, UsernameChange
|
||||
from app.api.dependencies import current_actor, csrf_actor
|
||||
from app.core.security import Actor, COOKIE
|
||||
from app.services import auth as service
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||
|
||||
|
||||
@router.post("/login")
|
||||
async def login(body: Login, request: Request, response: Response):
|
||||
result, token = await service.login(body=body, runtime=request.app.state)
|
||||
settings = request.app.state.settings
|
||||
response.set_cookie(
|
||||
COOKIE,
|
||||
token,
|
||||
httponly=True,
|
||||
secure=settings.cookie_secure,
|
||||
samesite="lax",
|
||||
max_age=settings.session_hours * 3600,
|
||||
path="/",
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
@router.get("/me")
|
||||
async def me(actor: Actor = Depends(current_actor)):
|
||||
return await service.me(actor=actor)
|
||||
|
||||
|
||||
@router.post("/logout", status_code=204)
|
||||
async def logout(request: Request, actor: Actor = Depends(csrf_actor)):
|
||||
await service.logout(runtime=request.app.state, actor=actor)
|
||||
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)):
|
||||
return await service.create_user(body=body, runtime=request.app.state, actor=actor)
|
||||
|
||||
|
||||
@router.get("/users")
|
||||
async def list_users(
|
||||
request: Request, page: int = 1, page_size: int = 24, actor: Actor = Depends(current_actor)
|
||||
):
|
||||
return await service.list_users(
|
||||
runtime=request.app.state, page=page, page_size=page_size, actor=actor
|
||||
)
|
||||
|
||||
|
||||
@router.patch("/users/{user_id}")
|
||||
async def patch_user(
|
||||
user_id: str, body: UserPatch, request: Request, actor: Actor = Depends(csrf_actor)
|
||||
):
|
||||
return await service.patch_user(
|
||||
user_id=user_id, body=body, runtime=request.app.state, actor=actor
|
||||
)
|
||||
|
||||
|
||||
@router.post("/password")
|
||||
async def change_password(
|
||||
body: PasswordChange, request: Request, actor: Actor = Depends(csrf_actor)
|
||||
):
|
||||
return await service.change_password(body=body, runtime=request.app.state, actor=actor)
|
||||
|
||||
|
||||
@router.post("/username")
|
||||
async def change_username(
|
||||
body: UsernameChange, request: Request, actor: Actor = Depends(csrf_actor)
|
||||
):
|
||||
return await service.change_username(body=body, runtime=request.app.state, actor=actor)
|
||||
|
||||
|
||||
@router.delete("/users/{user_id}", status_code=204)
|
||||
async def delete_user(user_id: str, request: Request, actor: Actor = Depends(csrf_actor)):
|
||||
from app.services.user_deletion import delete_user as delete_account
|
||||
|
||||
await delete_account(user_id=user_id, runtime=request.app.state, actor=actor)
|
||||
return Response(status_code=204)
|
||||
62
backend/app/api/routes/batches.py
Normal file
62
backend/app/api/routes/batches.py
Normal file
@ -0,0 +1,62 @@
|
||||
from fastapi import APIRouter, Depends, Header, Request
|
||||
|
||||
|
||||
from app.core.security import Actor
|
||||
from app.api.dependencies import csrf_actor, current_actor
|
||||
|
||||
|
||||
from app.schemas.batches import BatchCreate, BatchControl
|
||||
from app.services import batches as service
|
||||
|
||||
router = APIRouter(prefix="/batches", tags=["batches"])
|
||||
|
||||
|
||||
@router.post("", status_code=202)
|
||||
async def post_batch(
|
||||
body: BatchCreate,
|
||||
request: Request,
|
||||
idempotency_key: str | None = Header(None),
|
||||
actor: Actor = Depends(csrf_actor),
|
||||
):
|
||||
return await service.post_batch(
|
||||
body=body, runtime=request.app.state, idempotency_key=idempotency_key, actor=actor
|
||||
)
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_batches(
|
||||
request: Request, page: int = 1, page_size: int = 24, actor: Actor = Depends(current_actor)
|
||||
):
|
||||
return await service.list_batches(
|
||||
runtime=request.app.state, page=page, page_size=page_size, actor=actor
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{id}")
|
||||
async def get_batch(id: str, request: Request, actor: Actor = Depends(current_actor)):
|
||||
return await service.get_batch(id=id, runtime=request.app.state, actor=actor)
|
||||
|
||||
|
||||
@router.delete("/{id}")
|
||||
async def delete_batch(
|
||||
id: str,
|
||||
request: Request,
|
||||
if_match: str | None = Header(None),
|
||||
actor: Actor = Depends(csrf_actor),
|
||||
):
|
||||
return await service.delete_batch(
|
||||
id=id, runtime=request.app.state, if_match=if_match, actor=actor
|
||||
)
|
||||
|
||||
|
||||
@router.post("/{id}/control")
|
||||
async def batch_control(
|
||||
id: str,
|
||||
body: BatchControl,
|
||||
request: Request,
|
||||
idempotency_key: str | None = Header(None),
|
||||
actor: Actor = Depends(csrf_actor),
|
||||
):
|
||||
return await service.batch_control(
|
||||
id=id, body=body, runtime=request.app.state, idempotency_key=idempotency_key, actor=actor
|
||||
)
|
||||
78
backend/app/api/routes/editors.py
Normal file
78
backend/app/api/routes/editors.py
Normal file
@ -0,0 +1,78 @@
|
||||
from fastapi import APIRouter, Depends, Header, Request
|
||||
from app.api.dependencies import csrf_actor, current_actor
|
||||
from app.core.security import Actor
|
||||
from app.schemas.editors import SaveEditor, RestoreEditor, PlanEditor, StartEditor, EditorMode
|
||||
from app.services import editors as service
|
||||
|
||||
router = APIRouter(prefix="/editors", tags=["editors"])
|
||||
|
||||
|
||||
@router.get("/{draft_id}")
|
||||
async def get(draft_id: str, request: Request, actor: Actor = Depends(current_actor)):
|
||||
return await service.get_editor(request.app.state, actor, draft_id)
|
||||
|
||||
|
||||
@router.post("/{draft_id}/save")
|
||||
async def save(
|
||||
draft_id: str,
|
||||
body: SaveEditor,
|
||||
request: Request,
|
||||
idempotency_key: str | None = Header(None),
|
||||
actor: Actor = Depends(csrf_actor),
|
||||
):
|
||||
return await service.save_editor(request.app.state, actor, draft_id, body, idempotency_key)
|
||||
|
||||
|
||||
@router.post("/{draft_id}/from-run")
|
||||
async def restore(
|
||||
draft_id: str,
|
||||
body: RestoreEditor,
|
||||
request: Request,
|
||||
idempotency_key: str | None = Header(None),
|
||||
actor: Actor = Depends(csrf_actor),
|
||||
):
|
||||
return await service.from_run(request.app.state, actor, draft_id, body, idempotency_key)
|
||||
|
||||
|
||||
@router.post("/{draft_id}/plan")
|
||||
async def plan(
|
||||
draft_id: str, body: PlanEditor, request: Request, actor: Actor = Depends(csrf_actor)
|
||||
):
|
||||
return await service.plan_editor_request(request.app.state, actor, draft_id, body)
|
||||
|
||||
|
||||
@router.post("/{draft_id}/runs", status_code=202)
|
||||
async def start(
|
||||
draft_id: str,
|
||||
body: StartEditor,
|
||||
request: Request,
|
||||
idempotency_key: str | None = Header(None),
|
||||
actor: Actor = Depends(csrf_actor),
|
||||
):
|
||||
return await service.start_editor_request(
|
||||
request.app.state, actor, draft_id, body, idempotency_key
|
||||
)
|
||||
|
||||
|
||||
@router.post("/{draft_id}/apply")
|
||||
async def apply(
|
||||
draft_id: str,
|
||||
body: RestoreEditor,
|
||||
request: Request,
|
||||
idempotency_key: str | None = Header(None),
|
||||
actor: Actor = Depends(csrf_actor),
|
||||
):
|
||||
return await service.apply_editor(request.app.state, actor, draft_id, body, idempotency_key)
|
||||
|
||||
|
||||
@router.post("/{draft_id}/mode")
|
||||
async def change_mode(
|
||||
draft_id: str,
|
||||
body: EditorMode,
|
||||
request: Request,
|
||||
idempotency_key: str | None = Header(None),
|
||||
actor: Actor = Depends(csrf_actor),
|
||||
):
|
||||
from app.services.editor_modes import change_mode
|
||||
|
||||
return await change_mode(request.app.state, actor, draft_id, body, idempotency_key)
|
||||
78
backend/app/api/routes/events.py
Normal file
78
backend/app/api/routes/events.py
Normal file
@ -0,0 +1,78 @@
|
||||
import asyncio
|
||||
|
||||
import json
|
||||
|
||||
import time
|
||||
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
|
||||
from fastapi.responses import StreamingResponse
|
||||
|
||||
from sqlalchemy import func, select
|
||||
|
||||
from app.core.security import Actor, COOKIE
|
||||
from app.api.dependencies import current_actor
|
||||
|
||||
|
||||
from app.core.errors import fail
|
||||
|
||||
from app.models import Event
|
||||
|
||||
from app.services.events import event_batch, session_is_active
|
||||
|
||||
router = APIRouter(tags=["events"])
|
||||
|
||||
|
||||
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
|
||||
)
|
||||
minimum = (
|
||||
await session.scalar(select(func.min(Event.id)).where(Event.owner_id == owner_id)) or 0
|
||||
)
|
||||
if after > maximum or (after > 0 and minimum > 0 and after < minimum - 1):
|
||||
yield f"id: {maximum}\nevent: reset\ndata: {{}}\n\n"
|
||||
after = maximum
|
||||
while not await request.is_disconnected():
|
||||
if getattr(request.app.state, "draining", False):
|
||||
return
|
||||
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(0.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.headers.get("Authorization")
|
||||
if actor.auth_kind == "bearer"
|
||||
else request.cookies.get(COOKIE),
|
||||
cursor,
|
||||
),
|
||||
media_type="text/event-stream",
|
||||
headers={"Cache-Control": "no-cache, no-transform", "X-Accel-Buffering": "no"},
|
||||
)
|
||||
37
backend/app/api/routes/folders.py
Normal file
37
backend/app/api/routes/folders.py
Normal file
@ -0,0 +1,37 @@
|
||||
from fastapi import APIRouter, Depends, Request, Response
|
||||
from app.api.dependencies import current_actor, csrf_actor
|
||||
from app.core.security import Actor
|
||||
from app.schemas.folders import FolderCreate, FolderPatch, FolderAssign
|
||||
from app.services import folders as service
|
||||
|
||||
router = APIRouter(prefix="/folders", tags=["folders"])
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_folders(request: Request, actor: Actor = Depends(current_actor)):
|
||||
return await service.list_folders(runtime=request.app.state, actor=actor)
|
||||
|
||||
|
||||
@router.post("", status_code=201)
|
||||
async def create(body: FolderCreate, request: Request, actor: Actor = Depends(csrf_actor)):
|
||||
return await service.create(runtime=request.app.state, actor=actor, body=body)
|
||||
|
||||
|
||||
@router.post("/assign")
|
||||
async def assign(body: FolderAssign, request: Request, actor: Actor = Depends(csrf_actor)):
|
||||
return await service.assign(runtime=request.app.state, actor=actor, body=body)
|
||||
|
||||
|
||||
@router.patch("/{folder_id}")
|
||||
async def patch(
|
||||
folder_id: str, body: FolderPatch, request: Request, actor: Actor = Depends(csrf_actor)
|
||||
):
|
||||
return await service.patch(
|
||||
runtime=request.app.state, actor=actor, folder_id=folder_id, body=body
|
||||
)
|
||||
|
||||
|
||||
@router.delete("/{folder_id}", status_code=204)
|
||||
async def remove(folder_id: str, request: Request, actor: Actor = Depends(csrf_actor)):
|
||||
await service.remove(runtime=request.app.state, actor=actor, folder_id=folder_id)
|
||||
return Response(status_code=204)
|
||||
80
backend/app/api/routes/jobs.py
Normal file
80
backend/app/api/routes/jobs.py
Normal file
@ -0,0 +1,80 @@
|
||||
from fastapi import APIRouter, Depends, Header, Request
|
||||
|
||||
|
||||
from app.core.security import Actor
|
||||
from app.api.dependencies import csrf_actor, current_actor
|
||||
|
||||
|
||||
from app.schemas.jobs import Submit
|
||||
from app.services import jobs as service
|
||||
|
||||
router = APIRouter(prefix="/jobs", tags=["jobs"])
|
||||
|
||||
|
||||
@router.post("", status_code=202)
|
||||
async def submit(
|
||||
body: Submit,
|
||||
request: Request,
|
||||
idempotency_key: str | None = Header(default=None),
|
||||
actor: Actor = Depends(csrf_actor),
|
||||
):
|
||||
return await service.submit(
|
||||
body=body, runtime=request.app.state, idempotency_key=idempotency_key, actor=actor
|
||||
)
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_jobs(
|
||||
request: Request,
|
||||
page: int = 1,
|
||||
page_size: int = 24,
|
||||
folder_id: str = "",
|
||||
task_type: str = "",
|
||||
state: str = "",
|
||||
root_only: bool = False,
|
||||
actor: Actor = Depends(current_actor),
|
||||
):
|
||||
return await service.list_jobs(
|
||||
runtime=request.app.state,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
folder_id=folder_id,
|
||||
task_type=task_type,
|
||||
state=state,
|
||||
root_only=root_only,
|
||||
actor=actor,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{job_id}")
|
||||
async def get_job(job_id: str, request: Request, actor: Actor = Depends(current_actor)):
|
||||
return await service.get_job(job_id=job_id, runtime=request.app.state, actor=actor)
|
||||
|
||||
|
||||
@router.delete("/{job_id}")
|
||||
async def delete_job(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
if_match: str | None = Header(default=None),
|
||||
actor: Actor = Depends(csrf_actor),
|
||||
):
|
||||
return await service.delete_job(
|
||||
job_id=job_id, runtime=request.app.state, if_match=if_match, actor=actor
|
||||
)
|
||||
|
||||
|
||||
@router.post("/{job_id}/cancel")
|
||||
async def cancel(job_id: str, request: Request, actor: Actor = Depends(csrf_actor)):
|
||||
return await service.cancel(job_id=job_id, runtime=request.app.state, actor=actor)
|
||||
|
||||
|
||||
@router.post("/{job_id}/retry", status_code=202)
|
||||
async def retry(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
idempotency_key: str | None = Header(default=None),
|
||||
actor: Actor = Depends(csrf_actor),
|
||||
):
|
||||
return await service.retry(
|
||||
job_id=job_id, runtime=request.app.state, idempotency_key=idempotency_key, actor=actor
|
||||
)
|
||||
121
backend/app/api/routes/shared_assets.py
Normal file
121
backend/app/api/routes/shared_assets.py
Normal file
@ -0,0 +1,121 @@
|
||||
from app.services.shared_assets import available_shared
|
||||
|
||||
|
||||
from fastapi import APIRouter, Body, Depends, Header, Request
|
||||
|
||||
|
||||
from app.api.responses import file_response
|
||||
from app.core.security import Actor
|
||||
from app.api.dependencies import csrf_actor, current_actor
|
||||
|
||||
|
||||
from app.core.errors import fail
|
||||
|
||||
|
||||
from app.schemas.shared_assets import EmptyPayload
|
||||
from app.schemas.assets import SharedImport
|
||||
from app.services import shared_assets as service
|
||||
|
||||
router = APIRouter(prefix="/shared-assets", tags=["shared-assets"])
|
||||
|
||||
|
||||
publish_router = APIRouter(prefix="/assets", tags=["shared-assets"])
|
||||
|
||||
|
||||
@publish_router.post("/{asset_id}/publish", status_code=201)
|
||||
async def publish_asset(
|
||||
asset_id: str,
|
||||
request: Request,
|
||||
body: EmptyPayload | None = Body(default=None),
|
||||
idempotency_key: str | None = Header(default=None),
|
||||
actor: Actor = Depends(csrf_actor),
|
||||
):
|
||||
return await service.publish_asset(
|
||||
asset_id=asset_id,
|
||||
runtime=request.app.state,
|
||||
body=body,
|
||||
idempotency_key=idempotency_key,
|
||||
actor=actor,
|
||||
)
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_shared_assets(
|
||||
request: Request,
|
||||
q: str = "",
|
||||
kind: str = "",
|
||||
tag: str = "",
|
||||
mine: bool = False,
|
||||
page: int = 1,
|
||||
page_size: int = 24,
|
||||
actor: Actor = Depends(current_actor),
|
||||
):
|
||||
return await service.list_shared_assets(
|
||||
runtime=request.app.state,
|
||||
q=q,
|
||||
kind=kind,
|
||||
tag=tag,
|
||||
mine=mine,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
actor=actor,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{shared_id}")
|
||||
async def get_shared_asset(shared_id: str, request: Request, actor: Actor = Depends(current_actor)):
|
||||
return await service.get_shared_asset(
|
||||
shared_id=shared_id, runtime=request.app.state, actor=actor
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{shared_id}/content")
|
||||
async def shared_content(
|
||||
shared_id: str, request: Request, download: bool = False, actor: Actor = Depends(current_actor)
|
||||
):
|
||||
async with request.app.state.db.session() as session:
|
||||
_, asset, _ = await available_shared(session, shared_id)
|
||||
return file_response(
|
||||
request.app.state.settings,
|
||||
asset,
|
||||
asset.storage_key,
|
||||
request.headers.get("range"),
|
||||
download,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{shared_id}/thumbnail")
|
||||
async def shared_thumbnail(shared_id: str, request: Request, actor: Actor = Depends(current_actor)):
|
||||
async with request.app.state.db.session() as session:
|
||||
_, asset, _ = await available_shared(session, shared_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
|
||||
)
|
||||
|
||||
|
||||
@router.post("/{shared_id}/import", status_code=201)
|
||||
async def import_shared_asset(
|
||||
shared_id: str,
|
||||
request: Request,
|
||||
body: SharedImport | None = Body(default=None),
|
||||
idempotency_key: str | None = Header(default=None),
|
||||
actor: Actor = Depends(csrf_actor),
|
||||
):
|
||||
return await service.import_shared_asset(
|
||||
shared_id=shared_id,
|
||||
runtime=request.app.state,
|
||||
body=body,
|
||||
idempotency_key=idempotency_key,
|
||||
actor=actor,
|
||||
)
|
||||
|
||||
|
||||
@router.delete("/{shared_id}", status_code=204)
|
||||
async def withdraw_shared_asset(
|
||||
shared_id: str, request: Request, actor: Actor = Depends(csrf_actor)
|
||||
):
|
||||
return await service.withdraw_shared_asset(
|
||||
shared_id=shared_id, runtime=request.app.state, actor=actor
|
||||
)
|
||||
180
backend/app/api/routes/stories.py
Normal file
180
backend/app/api/routes/stories.py
Normal file
@ -0,0 +1,180 @@
|
||||
from fastapi import APIRouter, Depends, Header, Request
|
||||
from app.api.dependencies import csrf_actor, current_actor
|
||||
from app.schemas.stories import (
|
||||
StoryCreate,
|
||||
StoryPatch,
|
||||
CandidateCreate,
|
||||
CandidateBatch,
|
||||
SelectionCreate,
|
||||
SelectionClear,
|
||||
RenderCreate,
|
||||
Version,
|
||||
)
|
||||
from app.services.stories import api as service
|
||||
from app.services.stories.candidates import capabilities
|
||||
|
||||
router = APIRouter(prefix="/stories", tags=["stories"])
|
||||
|
||||
|
||||
@router.get("/capabilities")
|
||||
async def get_capabilities(request: Request, actor=Depends(current_actor)):
|
||||
return await capabilities(request.app.state)
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def listing(
|
||||
request: Request,
|
||||
page: int = 1,
|
||||
page_size: int = 24,
|
||||
folder_id: str = "",
|
||||
actor=Depends(current_actor),
|
||||
):
|
||||
return await service.listing(request.app.state, actor, page, page_size, folder_id)
|
||||
|
||||
|
||||
@router.post("", status_code=201)
|
||||
async def create(body: StoryCreate, request: Request, actor=Depends(csrf_actor)):
|
||||
return await service.create(request.app.state, actor, body)
|
||||
|
||||
|
||||
@router.get("/{id}")
|
||||
async def get(id: str, request: Request, actor=Depends(current_actor)):
|
||||
return await service.get(request.app.state, actor, id)
|
||||
|
||||
|
||||
@router.patch("/{id}")
|
||||
async def patch(
|
||||
id: str,
|
||||
body: StoryPatch,
|
||||
request: Request,
|
||||
if_match: str | None = Header(None),
|
||||
actor=Depends(csrf_actor),
|
||||
):
|
||||
return await service.patch(request.app.state, actor, id, body, if_match)
|
||||
|
||||
|
||||
@router.delete("/{id}")
|
||||
async def delete_story(
|
||||
id: str, request: Request, if_match: str | None = Header(None), actor=Depends(csrf_actor)
|
||||
):
|
||||
from app.services.stories.deletion import delete_story as remove
|
||||
|
||||
return await remove(request.app.state, actor, id, if_match)
|
||||
|
||||
|
||||
@router.get("/{id}/preview")
|
||||
async def preview(id: str, request: Request, actor=Depends(current_actor)):
|
||||
return await service.get(request.app.state, actor, id, "preview")
|
||||
|
||||
|
||||
@router.get("/{id}/readiness")
|
||||
async def readiness(id: str, request: Request, actor=Depends(current_actor)):
|
||||
return await service.get(request.app.state, actor, id, "readiness")
|
||||
|
||||
|
||||
@router.get("/{id}/candidates")
|
||||
async def candidates(
|
||||
id: str,
|
||||
request: Request,
|
||||
shot_id: str | None = None,
|
||||
kind: str | None = None,
|
||||
page: int = 1,
|
||||
page_size: int = 24,
|
||||
actor=Depends(current_actor),
|
||||
):
|
||||
return await service.candidates_list(
|
||||
request.app.state, actor, id, shot_id, kind, page, page_size
|
||||
)
|
||||
|
||||
|
||||
@router.post("/{id}/candidates", status_code=202)
|
||||
async def create_candidates(
|
||||
id: str,
|
||||
body: CandidateCreate,
|
||||
request: Request,
|
||||
idempotency_key: str | None = Header(None),
|
||||
actor=Depends(csrf_actor),
|
||||
):
|
||||
return await service.create_candidates(request.app.state, actor, id, body, idempotency_key)
|
||||
|
||||
|
||||
@router.post("/{id}/candidate-batches", status_code=202)
|
||||
async def create_batch(
|
||||
id: str,
|
||||
body: CandidateBatch,
|
||||
request: Request,
|
||||
idempotency_key: str | None = Header(None),
|
||||
actor=Depends(csrf_actor),
|
||||
):
|
||||
return await service.create_candidates(
|
||||
request.app.state, actor, id, body, idempotency_key, batch=True
|
||||
)
|
||||
|
||||
|
||||
@router.post("/{id}/candidates/{candidate_id}/retry", status_code=202)
|
||||
async def retry(
|
||||
id: str,
|
||||
candidate_id: str,
|
||||
body: Version,
|
||||
request: Request,
|
||||
idempotency_key: str | None = Header(None),
|
||||
actor=Depends(csrf_actor),
|
||||
):
|
||||
return await service.create_candidates(
|
||||
request.app.state, actor, id, body, idempotency_key, retry_id=candidate_id
|
||||
)
|
||||
|
||||
|
||||
@router.delete("/{id}/candidates/{candidate_id}")
|
||||
async def delete_candidate(
|
||||
id: str,
|
||||
candidate_id: str,
|
||||
request: Request,
|
||||
if_match: str | None = Header(None),
|
||||
actor=Depends(csrf_actor),
|
||||
):
|
||||
from app.services.stories.deletion import delete_candidate as remove
|
||||
|
||||
return await remove(request.app.state, actor, id, candidate_id, if_match)
|
||||
|
||||
|
||||
@router.post("/{id}/selections")
|
||||
async def selection(
|
||||
id: str,
|
||||
body: SelectionCreate,
|
||||
request: Request,
|
||||
idempotency_key: str | None = Header(None),
|
||||
actor=Depends(csrf_actor),
|
||||
):
|
||||
return await service.select_candidate(request.app.state, actor, id, body, idempotency_key)
|
||||
|
||||
|
||||
@router.post("/{id}/selections/clear")
|
||||
async def clear(
|
||||
id: str,
|
||||
body: SelectionClear,
|
||||
request: Request,
|
||||
idempotency_key: str | None = Header(None),
|
||||
actor=Depends(csrf_actor),
|
||||
):
|
||||
return await service.select_candidate(
|
||||
request.app.state, actor, id, body, idempotency_key, clear=True
|
||||
)
|
||||
|
||||
|
||||
@router.post("/{id}/renders", status_code=202)
|
||||
async def render(
|
||||
id: str,
|
||||
body: RenderCreate,
|
||||
request: Request,
|
||||
idempotency_key: str | None = Header(None),
|
||||
actor=Depends(csrf_actor),
|
||||
):
|
||||
return await service.render(request.app.state, actor, id, body, idempotency_key)
|
||||
|
||||
|
||||
@router.get("/{id}/runs")
|
||||
async def runs(
|
||||
id: str, request: Request, page: int = 1, page_size: int = 24, actor=Depends(current_actor)
|
||||
):
|
||||
return await service.runs(request.app.state, actor, id, page, page_size)
|
||||
19
backend/app/api/routes/submissions.py
Normal file
19
backend/app/api/routes/submissions.py
Normal file
@ -0,0 +1,19 @@
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
|
||||
|
||||
from app.core.security import Actor
|
||||
from app.api.dependencies import current_actor
|
||||
|
||||
|
||||
from app.services import submissions as service
|
||||
|
||||
router = APIRouter(prefix="/submissions", tags=["submissions"])
|
||||
|
||||
|
||||
@router.get("/{key}")
|
||||
async def recover(
|
||||
key: str, request: Request, operation: str, actor: Actor = Depends(current_actor)
|
||||
):
|
||||
return await service.recover(
|
||||
key=key, runtime=request.app.state, operation=operation, actor=actor
|
||||
)
|
||||
36
backend/app/api/routes/system.py
Normal file
36
backend/app/api/routes/system.py
Normal file
@ -0,0 +1,36 @@
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from app.api.dependencies import current_actor
|
||||
from app.services import system as service
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
async def health(request: Request):
|
||||
return await service.health(request.app.state)
|
||||
|
||||
|
||||
@router.get("/live")
|
||||
async def live():
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.get("/ready")
|
||||
async def ready(request: Request):
|
||||
checks = await service.readiness(request.app.state)
|
||||
healthy = all(checks.values())
|
||||
return JSONResponse(
|
||||
status_code=200 if healthy else 503,
|
||||
content={"status": "ready" if healthy else "not_ready", "checks": checks},
|
||||
)
|
||||
|
||||
|
||||
@router.get("/capabilities", dependencies=[Depends(current_actor)])
|
||||
async def capabilities(request: Request):
|
||||
return await service.capabilities(request.app.state)
|
||||
|
||||
|
||||
@router.get("/system/status", dependencies=[Depends(current_actor)])
|
||||
async def status(request: Request):
|
||||
return await service.status(request.app.state)
|
||||
26
backend/app/api/routes/tokens.py
Normal file
26
backend/app/api/routes/tokens.py
Normal file
@ -0,0 +1,26 @@
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
|
||||
|
||||
from app.core.security import Actor
|
||||
from app.api.dependencies import current_actor, csrf_actor
|
||||
|
||||
|
||||
from app.schemas.tokens import TokenInput
|
||||
from app.services import tokens as service
|
||||
|
||||
router = APIRouter(prefix="/auth/tokens", tags=["tokens"])
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_tokens(request: Request, actor: Actor = Depends(current_actor)):
|
||||
return await service.list_tokens(runtime=request.app.state, actor=actor)
|
||||
|
||||
|
||||
@router.post("", status_code=201)
|
||||
async def create_token(body: TokenInput, request: Request, actor: Actor = Depends(csrf_actor)):
|
||||
return await service.create_token(body=body, runtime=request.app.state, actor=actor)
|
||||
|
||||
|
||||
@router.delete("/{token_id}", status_code=204)
|
||||
async def revoke(token_id: str, request: Request, actor: Actor = Depends(csrf_actor)):
|
||||
return await service.revoke(token_id=token_id, runtime=request.app.state, actor=actor)
|
||||
163
backend/app/api/routes/workflows.py
Normal file
163
backend/app/api/routes/workflows.py
Normal file
@ -0,0 +1,163 @@
|
||||
from fastapi import APIRouter, Depends, Header, Request
|
||||
|
||||
|
||||
from app.core.security import Actor
|
||||
from app.api.dependencies import csrf_actor, current_actor
|
||||
|
||||
|
||||
from app.schemas.workflows import DraftCreate, DraftPatch, RunCreate, Control, Retry
|
||||
from app.services import workflows as service
|
||||
|
||||
router = APIRouter(prefix="/workflows", tags=["workflows"])
|
||||
|
||||
|
||||
runs_router = APIRouter(prefix="/workflow-runs", tags=["workflows"])
|
||||
|
||||
|
||||
@router.post("", status_code=201)
|
||||
async def post_draft(body: DraftCreate, request: Request, actor: Actor = Depends(csrf_actor)):
|
||||
return await service.post_draft(body=body, runtime=request.app.state, actor=actor)
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_drafts(
|
||||
request: Request,
|
||||
page: int = 1,
|
||||
page_size: int = 24,
|
||||
folder_id: str = "",
|
||||
actor: Actor = Depends(current_actor),
|
||||
):
|
||||
return await service.list_drafts(
|
||||
runtime=request.app.state, page=page, page_size=page_size, actor=actor, folder_id=folder_id
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{id}")
|
||||
async def get_draft(id: str, request: Request, actor: Actor = Depends(current_actor)):
|
||||
return await service.get_draft(id=id, runtime=request.app.state, actor=actor)
|
||||
|
||||
|
||||
@router.delete("/{id}")
|
||||
async def delete_draft(
|
||||
id: str,
|
||||
request: Request,
|
||||
if_match: str | None = Header(None),
|
||||
actor: Actor = Depends(csrf_actor),
|
||||
):
|
||||
return await service.delete_draft(
|
||||
id=id, runtime=request.app.state, if_match=if_match, actor=actor
|
||||
)
|
||||
|
||||
|
||||
@router.patch("/{id}")
|
||||
async def patch_draft(
|
||||
id: str,
|
||||
body: DraftPatch,
|
||||
request: Request,
|
||||
if_match: str | None = Header(None),
|
||||
actor: Actor = Depends(csrf_actor),
|
||||
):
|
||||
return await service.patch_draft(
|
||||
id=id, body=body, runtime=request.app.state, if_match=if_match, actor=actor
|
||||
)
|
||||
|
||||
|
||||
@router.post("/{id}/runs", status_code=202)
|
||||
async def post_run(
|
||||
id: str,
|
||||
body: RunCreate,
|
||||
request: Request,
|
||||
idempotency_key: str | None = Header(None),
|
||||
actor: Actor = Depends(csrf_actor),
|
||||
):
|
||||
return await service.post_run(
|
||||
id=id, body=body, runtime=request.app.state, idempotency_key=idempotency_key, actor=actor
|
||||
)
|
||||
|
||||
|
||||
@runs_router.get("")
|
||||
async def list_runs(
|
||||
request: Request,
|
||||
page: int = 1,
|
||||
page_size: int = 24,
|
||||
folder_id: str = "",
|
||||
actor: Actor = Depends(current_actor),
|
||||
):
|
||||
return await service.list_runs(
|
||||
runtime=request.app.state, page=page, page_size=page_size, actor=actor, folder_id=folder_id
|
||||
)
|
||||
|
||||
|
||||
@runs_router.get("/{id}")
|
||||
async def get_run(id: str, request: Request, actor: Actor = Depends(current_actor)):
|
||||
return await service.get_run(id=id, runtime=request.app.state, actor=actor)
|
||||
|
||||
|
||||
@runs_router.delete("/{id}")
|
||||
async def delete_run(
|
||||
id: str,
|
||||
request: Request,
|
||||
if_match: str | None = Header(None),
|
||||
actor: Actor = Depends(csrf_actor),
|
||||
):
|
||||
return await service.delete_run(
|
||||
id=id, runtime=request.app.state, if_match=if_match, actor=actor
|
||||
)
|
||||
|
||||
|
||||
@runs_router.post("/{id}/steps/{key}/retry", status_code=202)
|
||||
async def retry_step(
|
||||
id: str,
|
||||
key: str,
|
||||
body: Retry,
|
||||
request: Request,
|
||||
idempotency_key: str | None = Header(None),
|
||||
actor: Actor = Depends(csrf_actor),
|
||||
):
|
||||
return await service.retry_step(
|
||||
id=id,
|
||||
key=key,
|
||||
body=body,
|
||||
runtime=request.app.state,
|
||||
idempotency_key=idempotency_key,
|
||||
actor=actor,
|
||||
)
|
||||
|
||||
|
||||
@runs_router.post("/{id}/cancel")
|
||||
async def cancel_run(
|
||||
id: str,
|
||||
body: Control,
|
||||
request: Request,
|
||||
idempotency_key: str | None = Header(None),
|
||||
actor: Actor = Depends(csrf_actor),
|
||||
):
|
||||
return await service.cancel_run(
|
||||
id=id, body=body, runtime=request.app.state, idempotency_key=idempotency_key, actor=actor
|
||||
)
|
||||
|
||||
|
||||
@runs_router.post("/{id}/pause")
|
||||
async def pause_run(
|
||||
id: str,
|
||||
body: Control,
|
||||
request: Request,
|
||||
idempotency_key: str | None = Header(None),
|
||||
actor: Actor = Depends(csrf_actor),
|
||||
):
|
||||
return await service.pause_run(
|
||||
id=id, body=body, runtime=request.app.state, idempotency_key=idempotency_key, actor=actor
|
||||
)
|
||||
|
||||
|
||||
@runs_router.post("/{id}/resume")
|
||||
async def resume_run(
|
||||
id: str,
|
||||
body: Control,
|
||||
request: Request,
|
||||
idempotency_key: str | None = Header(None),
|
||||
actor: Actor = Depends(csrf_actor),
|
||||
):
|
||||
return await service.resume_run(
|
||||
id=id, body=body, runtime=request.app.state, idempotency_key=idempotency_key, actor=actor
|
||||
)
|
||||
@ -1,43 +0,0 @@
|
||||
"""Atomic durable manifests. Paths and bytes are validated before result recovery."""
|
||||
import hashlib,json,os
|
||||
from pathlib import Path
|
||||
from .assets import confined,safe_file
|
||||
|
||||
def digest_file(path):
|
||||
digest=hashlib.sha256()
|
||||
with Path(path).open("rb") as stream:
|
||||
while chunk:=stream.read(1024*1024):digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
def write_manifest(root,directory,execution_id,fence_token,outputs,result,metadata):
|
||||
directory=confined(root,directory,exists=True)
|
||||
entries=[]
|
||||
for output in outputs:
|
||||
path=confined(root,output,exists=True)
|
||||
with safe_file(root,path): pass
|
||||
entries.append({"path":path.relative_to(root).as_posix(),"size":path.stat().st_size,"sha256":digest_file(path)})
|
||||
manifest={"schema":1,"execution_id":execution_id,"fence_token":fence_token,"outputs":entries,"result":result,"metadata":metadata}
|
||||
target=directory/"result-manifest.json"
|
||||
temporary=target.with_suffix(".tmp")
|
||||
with temporary.open("w",encoding="utf-8") as stream:
|
||||
json.dump(manifest,stream,ensure_ascii=False,allow_nan=False);stream.flush();os.fsync(stream.fileno())
|
||||
os.replace(temporary,target)
|
||||
return manifest
|
||||
|
||||
def verify_manifest(root,manifest):
|
||||
if manifest.get("schema")!=1 or not manifest.get("outputs"):raise ValueError("Invalid manifest")
|
||||
paths=[]
|
||||
for entry in manifest["outputs"]:
|
||||
if Path(entry["path"]).is_absolute():raise ValueError("Manifest path must be relative")
|
||||
path=confined(root,entry["path"],exists=True)
|
||||
with safe_file(root,path):pass
|
||||
if path.stat().st_size!=entry["size"] or digest_file(path)!=entry["sha256"]:raise ValueError("Artifact hash mismatch")
|
||||
paths.append(str(path))
|
||||
return paths
|
||||
|
||||
def reconcile_artifacts(root):
|
||||
verified=[];invalid=[]
|
||||
for path in Path(root).rglob("result-manifest.json"):
|
||||
try: verify_manifest(root,json.loads(path.read_text(encoding="utf-8")));verified.append(str(path))
|
||||
except (OSError,ValueError,KeyError):invalid.append(str(path))
|
||||
return {"verified":verified,"invalid":invalid,"deleted":[]}
|
||||
@ -1,338 +0,0 @@
|
||||
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 delete, func, select, update
|
||||
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.library_scope == "private", Asset.ready.is_(True))
|
||||
if not include_deleted:
|
||||
query = query.where(Asset.deleted_at.is_(None))
|
||||
asset = await session.scalar(query.with_for_update())
|
||||
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,
|
||||
Job.deleted_at.is_(None)))
|
||||
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 validate_workflow_output(job, source, settings):
|
||||
if job.run_id and job.step_key != "compose" and job.task_type == "video.generate":
|
||||
from .media import inspect_video_track
|
||||
source_frames = job.parameters.get('num_frames',121)
|
||||
if not isinstance(source_frames,int) or isinstance(source_frames,bool):
|
||||
raise ValueError("Workflow shot does not meet frozen decoded video specification")
|
||||
required = max(120,source_frames-1)
|
||||
track = await inspect_video_track(source,settings)
|
||||
if track['frames']<required or track['fps']!=24 or (track['width'],track['height'])!=(job.parameters.get('upscale_width'),job.parameters.get('upscale_height')):
|
||||
raise ValueError("Workflow shot does not meet frozen decoded video specification")
|
||||
|
||||
|
||||
async def import_output(db, settings, job, source, index, *, execution_fence=None):
|
||||
async with db.session() as session:
|
||||
current = await session.scalar(select(Job).where(Job.id == job.id, Job.owner_id == job.owner_id,
|
||||
Job.deleted_at.is_(None)))
|
||||
if current is None:
|
||||
raise ValueError("Archived job cannot import output")
|
||||
job = current
|
||||
existing = await session.scalar(select(Asset).where(Asset.source_job_id == job.id,
|
||||
Asset.source_output_index == index))
|
||||
if existing:
|
||||
if execution_fence:
|
||||
from .v2_models import AssetReference
|
||||
binding=await session.scalar(select(AssetReference.id).where(AssetReference.asset_id==existing.id,AssetReference.ref_kind=="execution",AssetReference.ref_id==execution_fence["execution_id"]))
|
||||
if not binding:raise ValueError("Output belongs to a different execution")
|
||||
if existing:
|
||||
from .artifacts import digest_file
|
||||
path=confined(settings.asset_root,existing.storage_key,exists=True)
|
||||
with safe_file(settings.asset_root,path):pass
|
||||
if path.stat().st_size!=existing.size_bytes or digest_file(path)!=existing.sha256:
|
||||
raise ValueError("Imported artifact is missing or corrupt")
|
||||
await validate_workflow_output(job,path,settings)
|
||||
return existing
|
||||
asset_id = new_id()
|
||||
source = confined(settings.job_work_root, source, exists=True)
|
||||
if source.stat().st_size>settings.max_output_bytes:
|
||||
raise ValueError("Output exceeds reserved asset limit; retained for operator reconciliation")
|
||||
await validate_workflow_output(job,source,settings)
|
||||
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:
|
||||
current = await session.scalar(select(Job).where(Job.id == job.id, Job.owner_id == job.owner_id,
|
||||
Job.deleted_at.is_(None)))
|
||||
if current is None:
|
||||
raise ValueError("Archived job cannot import output")
|
||||
if execution_fence:
|
||||
from .executions import gpu_publication_matches
|
||||
current=await session.get(Job,job.id)
|
||||
if not await gpu_publication_matches(session,current,execution_fence):raise ValueError("Stale GPU result import")
|
||||
from .quotas import enforce_owner_asset_budget
|
||||
await enforce_owner_asset_budget(session,settings,job.owner_id,asset.size_bytes)
|
||||
session.add(asset)
|
||||
await session.flush()
|
||||
if execution_fence:
|
||||
from .v2_models import AssetReference
|
||||
session.add(AssetReference(owner_id=job.owner_id,asset_id=asset.id,ref_kind="execution",ref_id=execution_fence["execution_id"]))
|
||||
await session.commit()
|
||||
return asset
|
||||
except BaseException:
|
||||
# Commit may have succeeded despite lost ACK; retain for reconciliation.
|
||||
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
|
||||
from .maintenance import require_writable
|
||||
from .quotas import check_storage_budget
|
||||
require_writable(settings)
|
||||
async with request.app.state.db.session() as session:
|
||||
await check_storage_budget(session,settings,actor.id,min(max(0,int(request.headers.get("content-length","0"))) if request.headers.get("content-length","0").isdigit() else settings.max_upload_bytes,settings.max_upload_bytes))
|
||||
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
|
||||
commit_started = False
|
||||
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:
|
||||
from .quotas import enforce_owner_asset_budget
|
||||
await enforce_owner_asset_budget(session,settings,actor.id,asset.size_bytes)
|
||||
session.add(asset)
|
||||
await session.flush()
|
||||
commit_started = True
|
||||
emit_asset(session, actor.id, "asset.created", {"asset": asset_dto(asset)})
|
||||
await session.commit()
|
||||
return asset_dto(asset)
|
||||
except BaseException as exc:
|
||||
if not commit_started:
|
||||
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 = "", favorite: bool | None = None, origin: 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.library_scope == "private",
|
||||
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))
|
||||
from .v2_models import AssetTag
|
||||
if favorite is not None:query=query.where(Asset.favorite==favorite)
|
||||
if origin:query=query.where(Asset.origin==origin)
|
||||
if tag:query=query.where(Asset.id.in_(select(AssetTag.asset_id).where(AssetTag.owner_id==actor.id,AssetTag.tag==tag)))
|
||||
total=await session.scalar(select(func.count()).select_from(query.subquery()))
|
||||
rows=(await session.scalars(query.order_by(Asset.created_at.desc(),Asset.id.desc()).offset((page-1)*page_size).limit(page_size))).all()
|
||||
return {"items":[asset_dto(a) for a in rows],"total":total,"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))
|
||||
from .v2_models import AssetTag
|
||||
await session.execute(delete(AssetTag).where(AssetTag.asset_id==asset.id))
|
||||
session.add_all(AssetTag(owner_id=actor.id,asset_id=asset.id,tag=tag) for tag in asset.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, include_deleted=True)
|
||||
from .asset_deletion import remove_asset
|
||||
from .v2_models import Submission
|
||||
await remove_asset(session, request.app.state.settings, asset)
|
||||
# Match the deleted result only: a publication's private source may be
|
||||
# deleted while its independent shared snapshot remains available.
|
||||
await session.execute(update(Submission).where(
|
||||
Submission.owner_id == actor.id, Submission.status != "purged",
|
||||
Submission.resource_json["asset_id"].as_string() == asset.id).values(status="purged"))
|
||||
emit_asset(session, actor.id, "asset.deleted", {"id": asset.id})
|
||||
await touch_source_job(session, asset)
|
||||
await session.commit()
|
||||
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)
|
||||
@ -1,239 +0,0 @@
|
||||
import asyncio
|
||||
from dataclasses import dataclass, field
|
||||
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, func
|
||||
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, "disabled": user.disabled, "must_change_password": user.must_change_password}
|
||||
|
||||
|
||||
@dataclass
|
||||
class Actor:
|
||||
id: str
|
||||
username: str
|
||||
display_name: str
|
||||
role: str
|
||||
csrf_token: str
|
||||
token_hash: str
|
||||
auth_kind: str = "session"
|
||||
scopes: list[str] = field(default_factory=list)
|
||||
must_change_password: bool = False
|
||||
|
||||
|
||||
async def current_actor(request: Request):
|
||||
authorization = request.headers.get("Authorization", "")
|
||||
if authorization.startswith("Bearer "):
|
||||
from .tokens import bearer_actor
|
||||
return await bearer_actor(request, authorization[7:])
|
||||
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, must_change_password=user.must_change_password)
|
||||
|
||||
|
||||
async def csrf_actor(request: Request, actor: Actor = Depends(current_actor)):
|
||||
if actor.auth_kind == "bearer":
|
||||
if request.headers.get("sec-fetch-site") or request.cookies.get(COOKIE):
|
||||
fail(403, "machine_token_only", "Use session authentication in browsers")
|
||||
return 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", must_change_password=True, 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, "must_change_password": actor.must_change_password},
|
||||
"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" or actor.auth_kind != "session":
|
||||
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)
|
||||
|
||||
|
||||
class UserPatch(BaseModel):
|
||||
display_name: str | None = Field(default=None,min_length=1,max_length=80)
|
||||
disabled: bool | None = None
|
||||
|
||||
class PasswordChange(BaseModel):
|
||||
current_password: str = Field(max_length=256)
|
||||
new_password: str = Field(max_length=256)
|
||||
|
||||
@router.get("/users")
|
||||
async def list_users(request:Request,page:int=1,page_size:int=24,actor:Actor=Depends(current_actor)):
|
||||
if actor.role!="admin" or actor.auth_kind!="session": fail(403,"admin_required","Administrator session required")
|
||||
if page<1 or not 1<=page_size<=100: fail(422,"invalid_page","Invalid page")
|
||||
async with request.app.state.db.session() as session:
|
||||
total=await session.scalar(select(func.count()).select_from(User))
|
||||
rows=(await session.scalars(select(User).order_by(User.created_at,User.id).offset((page-1)*page_size).limit(page_size))).all()
|
||||
return {"items":[user_dto(u) for u in rows],"total":total,"page":page,"page_size":page_size}
|
||||
|
||||
@router.patch("/users/{user_id}")
|
||||
async def patch_user(user_id:str,body:UserPatch,request:Request,actor:Actor=Depends(csrf_actor)):
|
||||
if actor.role!="admin" or actor.auth_kind!="session": fail(403,"admin_required","Administrator session required")
|
||||
from .models import Job
|
||||
from .events import emit_job
|
||||
async with request.app.state.db.session() as session:
|
||||
user=await session.get(User,user_id)
|
||||
if not user: fail(404,"user_not_found","User not found")
|
||||
if body.disabled and user.role=="admin" and not user.disabled:
|
||||
count=await session.scalar(select(func.count()).select_from(User).where(User.role=="admin",User.disabled.is_(False)))
|
||||
if count<=1: fail(409,"last_admin","Cannot disable the last administrator")
|
||||
if body.display_name is not None: user.display_name=body.display_name.strip() or user.display_name
|
||||
if body.disabled is not None:
|
||||
user.disabled=body.disabled
|
||||
if body.disabled:
|
||||
await session.execute(delete(Session).where(Session.user_id==user_id))
|
||||
from .v2_models import ApiToken
|
||||
from sqlalchemy import update
|
||||
await session.execute(update(ApiToken).where(ApiToken.owner_id==user_id,ApiToken.revoked_at.is_(None)).values(revoked_at=utcnow()))
|
||||
from .v2_models import WorkflowRun,Batch
|
||||
runs=(await session.scalars(select(WorkflowRun).where(WorkflowRun.owner_id==user_id,WorkflowRun.state.notin_(["succeeded","failed","cancelled"])))).all()
|
||||
from .workflows import emit_run
|
||||
from .batches import emit_batch
|
||||
for run in runs:
|
||||
if "admin_suspend" not in (run.hold_reasons or []):
|
||||
run.hold_reasons=list(set((run.hold_reasons or [])+["admin_suspend"]))
|
||||
await emit_run(session,run)
|
||||
batches=(await session.scalars(select(Batch).where(Batch.owner_id==user_id,Batch.state.notin_(["succeeded","cancelled","completed_with_errors"])))).all()
|
||||
for batch in batches:
|
||||
if "admin_suspend" not in (batch.hold_reasons or []):
|
||||
batch.hold_reasons=list(set((batch.hold_reasons or [])+["admin_suspend"]))
|
||||
await emit_batch(session,batch)
|
||||
rows=(await session.scalars(select(Job).where(Job.owner_id==user_id,Job.state.notin_(["succeeded","failed","cancelled","timed_out"])))).all()
|
||||
for job in rows:
|
||||
job.hold_reasons=list(set((job.hold_reasons or [])+["admin_suspend"]))
|
||||
await emit_job(session,job)
|
||||
await session.commit()
|
||||
return user_dto(user)
|
||||
|
||||
@router.post("/password")
|
||||
async def change_password(body:PasswordChange,request:Request,actor:Actor=Depends(csrf_actor)):
|
||||
if actor.auth_kind!="session": fail(403,"session_required","Session required")
|
||||
validate_password(body.new_password)
|
||||
async with request.app.state.db.session() as session:
|
||||
user=await session.get(User,actor.id)
|
||||
if not await asyncio.to_thread(verify_password,body.current_password,user.password_hash): fail(403,"invalid_password","Current password is incorrect")
|
||||
user.password_hash=await asyncio.to_thread(hash_password,body.new_password)
|
||||
user.must_change_password=False
|
||||
await session.execute(delete(Session).where(Session.user_id==actor.id))
|
||||
await session.commit()
|
||||
return {"requires_relogin":True}
|
||||
@ -1,202 +0,0 @@
|
||||
"""Persistent mixed workflow/job batches with independently eligible members."""
|
||||
from typing import Literal
|
||||
from fastapi import APIRouter, Depends, Header, Request, HTTPException
|
||||
from pydantic import Field
|
||||
from sqlalchemy import select
|
||||
from .auth import Actor, csrf_actor, current_actor
|
||||
from .dto import iso
|
||||
from .errors import fail
|
||||
from .events import emit_asset, emit_job
|
||||
from .jobs import Submit, create_jobs, validate_submission, TERMINAL
|
||||
from .models import Job, utcnow
|
||||
from .submissions import accept_submission
|
||||
from .timeline import Strict
|
||||
from .v2_models import Batch, BatchItem, WorkflowDraft, WorkflowRun, Execution
|
||||
from .workflows import owned, cursor, create_run, control_run, page_rows, wake, RUN_TERMINAL, check_batch_capability, emit_run
|
||||
|
||||
router=APIRouter(prefix='/batches',tags=['batches'])
|
||||
class BatchWorkflow(Strict):
|
||||
kind:Literal['workflow']
|
||||
draft_id:str
|
||||
draft_revision:int=Field(ge=1)
|
||||
expected_version:int=Field(ge=1)
|
||||
class BatchJob(Strict):
|
||||
kind:Literal['job']
|
||||
task_type:str
|
||||
input:dict=Field(default_factory=dict)
|
||||
parameters:dict=Field(default_factory=dict)
|
||||
count:int=Field(default=1,ge=1,le=4)
|
||||
class BatchCreate(Strict):
|
||||
name:str=Field(default='夜间批次',min_length=1,max_length=255)
|
||||
items:list[BatchWorkflow|BatchJob]=Field(min_length=1,max_length=100)
|
||||
class BatchControl(Strict):
|
||||
desired_state:Literal['run','pause','cancel']
|
||||
expected_version:int|None=Field(default=None,ge=1)
|
||||
|
||||
def batch_dto(b,items):
|
||||
return dict(id=b.id,name=b.name,state=b.state,desired_state=b.desired_state,hold_reasons=b.hold_reasons or [],version=b.version,created_at=iso(b.created_at),finished_at=iso(b.finished_at),total_items=len(items),completed_items=sum(i.state=='succeeded' for i in items),current_item_index=next((i.item_index for i in items if i.state=='running'),None),active_item_indices=[i.item_index for i in items if i.state in {'running','cleanup_pending'}],active_item_count=sum(i.state in {'running','cleanup_pending'} for i in items))
|
||||
async def snapshot_batch(s,owner,id):
|
||||
b=await owned(s,Batch,id,owner)
|
||||
items=(await s.scalars(select(BatchItem).where(BatchItem.batch_id==b.id).order_by(BatchItem.item_index))).all()
|
||||
return {'batch':batch_dto(b,items),'items':[{k:getattr(i,k) for k in ('id','batch_id','item_index','target_kind','target_id','state','spec_json')} for i in items],'cursor':await cursor(s,owner)}
|
||||
async def emit_batch(s,b):
|
||||
if b.deleted_at is not None:return
|
||||
b.version+=1;snap=await snapshot_batch(s,b.owner_id,b.id);emit_asset(s,b.owner_id,'batch.updated',{'batch':snap['batch'],'items':snap['items']})
|
||||
|
||||
async def active_member(s,items):
|
||||
eligible=[i for i in items if i.state not in {'succeeded','cancelled','failed','timed_out','blocked'}]
|
||||
# A retry joins behind the member already admitted. Its batch_wait hold
|
||||
# survives ticks until that member drains, including a queued child.
|
||||
for item in eligible:
|
||||
if item.target_kind=='run':
|
||||
target=await s.get(WorkflowRun,item.target_id)
|
||||
if target and target.deleted_at is None and 'batch_wait' not in (target.hold_reasons or []):return item
|
||||
else:
|
||||
# target_id is only the group's representative. It may already
|
||||
# be cancelled while a different job in the member is draining.
|
||||
jobs=(await s.scalars(select(Job).where(Job.batch_id==item.batch_id,Job.batch_item_index==item.item_index,Job.state.not_in(TERMINAL)))).all()
|
||||
if any('batch_wait' not in (j.hold_reasons or []) for j in jobs):return item
|
||||
return eligible[0] if eligible else None
|
||||
|
||||
def member_holds(holds,b,waiting):
|
||||
holds=set(holds or [])|set(b.hold_reasons or [])
|
||||
if b.desired_state=='pause':holds.add('batch_pause')
|
||||
else:holds.discard('batch_pause')
|
||||
if waiting:holds.add('batch_wait')
|
||||
else:holds.discard('batch_wait')
|
||||
return holds
|
||||
|
||||
async def run_member_holds(s,r):
|
||||
b=await s.get(Batch,r.batch_id)
|
||||
if b is None or b.deleted_at is not None:return set(r.hold_reasons or [])|{'batch_wait'}
|
||||
return member_holds(r.hold_reasons,b,False)
|
||||
|
||||
async def advance_batches(s,settings):
|
||||
batches=(await s.scalars(select(Batch).where(Batch.deleted_at.is_(None),Batch.state.not_in({'succeeded','cancelled','completed_with_errors'})).order_by(Batch.created_at,Batch.id).with_for_update())).all()
|
||||
for b in batches:
|
||||
items=(await s.scalars(select(BatchItem).where(BatchItem.batch_id==b.id).order_by(BatchItem.item_index))).all()
|
||||
before=(b.state,tuple(i.state for i in items))
|
||||
for item in items:
|
||||
if item.target_kind=='run':
|
||||
target=await s.get(WorkflowRun,item.target_id);item.state=target.state
|
||||
else:
|
||||
jobs=(await s.scalars(select(Job).where(Job.batch_id==b.id,Job.batch_item_index==item.item_index))).all()
|
||||
if all(j.state in TERMINAL for j in jobs):item.state='succeeded' if all(j.state=='succeeded' for j in jobs) else 'cancelled' if all(j.state=='cancelled' for j in jobs) else 'failed'
|
||||
elif any(j.state in {'running','collecting','cancelling'} for j in jobs):item.state='running'
|
||||
else:item.state='queued'
|
||||
if item.state in {'failed','cancelled','timed_out','blocked'}:
|
||||
target_jobs=select(Job.id).where(Job.run_id==item.target_id) if item.target_kind=='run' else select(Job.id).where(Job.batch_id==b.id,Job.batch_item_index==item.item_index)
|
||||
pending=await s.scalar(select(Execution.id).where(Execution.job_id.in_(target_jobs),Execution.state.not_in({'exited','results_ready'})))
|
||||
if pending:item.state='cleanup_pending'
|
||||
active=await active_member(s,items)
|
||||
for item in items:
|
||||
if item.target_kind=='run':
|
||||
target=await s.get(WorkflowRun,item.target_id)
|
||||
holds=sorted(member_holds(target.hold_reasons,b,False))
|
||||
if target.hold_reasons!=holds:
|
||||
target.hold_reasons=holds;await emit_run(s,target)
|
||||
jobs=(await s.scalars(select(Job).where(Job.run_id==item.target_id,Job.state.not_in(TERMINAL)))).all()
|
||||
else:
|
||||
jobs=(await s.scalars(select(Job).where(Job.batch_id==b.id,Job.batch_item_index==item.item_index,Job.state.not_in(TERMINAL)))).all()
|
||||
for j in jobs:
|
||||
holds=member_holds(j.hold_reasons,b,False)
|
||||
if item.target_kind=='run':
|
||||
# Parent admission pressure must not stop accepted children
|
||||
# from completing and freeing the very quota it waits for.
|
||||
holds-= {'quota','storage'}
|
||||
holds|=set(target.hold_reasons or [])-{'quota','storage'}
|
||||
holds=sorted(holds)
|
||||
if j.hold_reasons!=holds:
|
||||
j.hold_reasons=holds;await emit_job(s,j)
|
||||
if all(i.state in RUN_TERMINAL|{'timed_out'} for i in items):
|
||||
b.state='cancelled' if b.desired_state=='cancel' else 'succeeded' if all(i.state=='succeeded' for i in items) else 'completed_with_errors';b.finished_at=utcnow()
|
||||
elif b.desired_state=='cancel':b.state='cancelling'
|
||||
elif b.desired_state=='pause' or b.hold_reasons:b.state='paused'
|
||||
elif not active:b.state='blocked'
|
||||
else:b.state='running'
|
||||
if before!=(b.state,tuple(i.state for i in items)):await emit_batch(s,b)
|
||||
|
||||
@router.post('',status_code=202)
|
||||
async def post_batch(body:BatchCreate,request:Request,idempotency_key:str|None=Header(None),actor:Actor=Depends(csrf_actor)):
|
||||
from .maintenance import require_writable
|
||||
require_writable(request.app.state.settings)
|
||||
capability_error=None
|
||||
try:await check_batch_capability(request,[i.task_type if i.kind=='job' else 'video.generate' for i in body.items])
|
||||
except HTTPException as exc:capability_error=exc
|
||||
async with request.app.state.db.session() as s:
|
||||
sub=await accept_submission(s,actor.id,'batch.create',idempotency_key,2,body.model_dump(mode='json'))
|
||||
if sub.resource_json:b=await owned(s,Batch,sub.resource_json['batch_id'],actor.id)
|
||||
else:
|
||||
if capability_error:raise capability_error
|
||||
from .quotas import reserve_budget,check_parent_capacity
|
||||
await reserve_budget(s,actor.id,'batch.create',units=0,settings=request.app.state.settings)
|
||||
await check_parent_capacity(s,request.app.state.settings,actor.id,'batch')
|
||||
b=Batch(owner_id=actor.id,name=body.name,spec_snapshot=body.model_dump(mode='json'));s.add(b);await s.flush()
|
||||
frozen_drafts={}
|
||||
for item in body.items:
|
||||
if item.kind=='workflow':
|
||||
d=await owned(s,WorkflowDraft,item.draft_id,actor.id)
|
||||
if d.version!=item.expected_version or d.revision!=item.draft_revision:fail(409,'draft_version_conflict','Draft version conflict.')
|
||||
frozen_drafts[d.id]=d
|
||||
for idx,item in enumerate(body.items):
|
||||
if item.kind=='workflow':
|
||||
r=await create_run(s,actor.id,item.draft_id,frozen_drafts[item.draft_id].version,item.draft_revision,'batch',batch_id=b.id,batch_item_index=idx,settings=request.app.state.settings)
|
||||
kind,target='run',r.id
|
||||
else:
|
||||
jobs=await create_jobs(s,Submit(task_type=item.task_type,input=item.input,parameters=item.parameters,count=item.count,execution_mode='batch'),actor,request.app.state.settings,key=f'batch:{b.id}:{idx}',internal=True)
|
||||
for j in jobs:
|
||||
j.batch_id=b.id;j.batch_item_index=idx
|
||||
await emit_job(s,j)
|
||||
kind,target='job',jobs[0].id
|
||||
s.add(BatchItem(batch_id=b.id,item_index=idx,target_kind=kind,target_id=target,spec_json=item.model_dump(mode='json')))
|
||||
sub.resource_json={'batch_id':b.id};await emit_batch(s,b)
|
||||
await s.commit();snap=await snapshot_batch(s,actor.id,b.id)
|
||||
wake(request);return snap
|
||||
|
||||
@router.get('')
|
||||
async def list_batches(request:Request,page:int=1,page_size:int=24,actor:Actor=Depends(current_actor)):
|
||||
async with request.app.state.db.session() as s:
|
||||
rows,data=await page_rows(s,Batch,actor,page,page_size);return {**data,'items':[(await snapshot_batch(s,actor.id,b.id))['batch'] for b in rows]}
|
||||
@router.get('/{id}')
|
||||
async def get_batch(id:str,request:Request,actor:Actor=Depends(current_actor)):
|
||||
async with request.app.state.db.session() as s:return await snapshot_batch(s,actor.id,id)
|
||||
@router.delete('/{id}')
|
||||
async def delete_batch(id:str,request:Request,if_match:str|None=Header(None),actor:Actor=Depends(csrf_actor)):
|
||||
from .deletions import archive_records
|
||||
async with request.app.state.db.session() as s:
|
||||
result=await archive_records(s,Batch,id,actor.id,if_match)
|
||||
await s.commit()
|
||||
return result
|
||||
@router.post('/{id}/control')
|
||||
async def batch_control(id:str,body:BatchControl,request:Request,idempotency_key:str|None=Header(None),actor:Actor=Depends(csrf_actor)):
|
||||
async with request.app.state.db.session() as s:
|
||||
sub=await accept_submission(s,actor.id,'batch.control',idempotency_key,2,{'batch_id':id,**body.model_dump()})
|
||||
b=await owned(s,Batch,id,actor.id)
|
||||
if not sub.resource_json:
|
||||
if body.expected_version is not None and b.version!=body.expected_version:fail(409,'batch_version_conflict','批次版本冲突')
|
||||
if b.state not in {'succeeded','cancelled','completed_with_errors'}:
|
||||
if b.desired_state=='cancel' and body.desired_state!='cancel':fail(409,'batch_cancelled','取消不可逆')
|
||||
b.desired_state=body.desired_state
|
||||
runs=(await s.scalars(select(WorkflowRun).where(WorkflowRun.batch_id==b.id))).all()
|
||||
for r in runs:
|
||||
if body.desired_state=='cancel':await control_run(s,r,'cancel')
|
||||
else:
|
||||
holds=set(r.hold_reasons or [])
|
||||
if body.desired_state=='pause':holds.add('batch_pause')
|
||||
else:holds.discard('batch_pause')
|
||||
r.hold_reasons=sorted(holds)
|
||||
jobs=(await s.scalars(select(Job).where(Job.batch_id==b.id,Job.state.not_in(TERMINAL)))).all()
|
||||
for j in jobs:
|
||||
holds=set(j.hold_reasons or [])
|
||||
if body.desired_state=='pause':holds.add('batch_pause')
|
||||
else:holds.discard('batch_pause')
|
||||
j.hold_reasons=sorted(holds)
|
||||
if body.desired_state=='cancel':
|
||||
j.desired_state='cancel';j.cancel_requested=True
|
||||
if not j.upstream_id and not j.upstream_payload and j.phase not in {'cpu_running','preparing'}:j.state='cancelled';j.phase='cancelled';j.finished_at=utcnow()
|
||||
elif j.state!='collecting':j.state='cancelling';j.phase='cancellation_pending'
|
||||
await emit_job(s,j)
|
||||
await advance_batches(s,request.app.state.settings);await emit_batch(s,b)
|
||||
sub.resource_json={'batch_id':id}
|
||||
await s.commit();snap=await snapshot_batch(s,actor.id,id)
|
||||
wake(request);return snap
|
||||
106
backend/app/bootstrap.py
Normal file
106
backend/app/bootstrap.py
Normal file
@ -0,0 +1,106 @@
|
||||
"""应用组装边界:仅在 lifespan 中创建外部资源,退出时按顺序回收。"""
|
||||
|
||||
from contextlib import asynccontextmanager
|
||||
import logging
|
||||
from fastapi import FastAPI
|
||||
from fastapi.responses import JSONResponse
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from app.api.router import router as api_router
|
||||
from app.core.config import Settings
|
||||
from app.core.database import Database
|
||||
from app.services.auth import bootstrap_admin
|
||||
from app.services.orchestration.coordinator import Coordinator
|
||||
|
||||
|
||||
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 app.adapters.provider.client import Provider
|
||||
|
||||
live_provider = Provider(configuration)
|
||||
app.state.provider = live_provider
|
||||
coordinator = Coordinator(configuration, db, live_provider)
|
||||
app.state.coordinator = coordinator
|
||||
app.state.draining = False
|
||||
|
||||
async def after_tick():
|
||||
from app.services.orchestration.workflow_engine import advance_workflows
|
||||
|
||||
await advance_workflows(db, configuration, live_provider)
|
||||
|
||||
coordinator.after_tick = after_tick
|
||||
try:
|
||||
await db.initialize()
|
||||
await bootstrap_admin(db, configuration)
|
||||
from app.core.public_preflight import require_public_ready
|
||||
|
||||
await require_public_ready(db, configuration)
|
||||
if configuration.run_coordinator:
|
||||
await coordinator.start()
|
||||
yield
|
||||
finally:
|
||||
app.state.draining = True
|
||||
await coordinator.close()
|
||||
await live_provider.aclose()
|
||||
await db.close()
|
||||
|
||||
app = FastAPI(title="CMVR Visual", lifespan=lifespan)
|
||||
from app.api.middleware.upload_guard import UploadGuard
|
||||
|
||||
app.add_middleware(UploadGuard)
|
||||
|
||||
@app.middleware("http")
|
||||
async def maintenance_writes(request, call_next):
|
||||
from app.core.maintenance import maintenance_active
|
||||
|
||||
configuration = getattr(request.app.state, "settings", None)
|
||||
if (
|
||||
configuration
|
||||
and request.method in {"POST", "PUT", "PATCH", "DELETE"}
|
||||
and request.url.path.startswith("/api/")
|
||||
and (request.url.path not in {"/api/auth/login", "/api/auth/logout"})
|
||||
and maintenance_active(configuration)
|
||||
):
|
||||
return JSONResponse(
|
||||
status_code=503,
|
||||
content={
|
||||
"detail": {
|
||||
"code": "maintenance",
|
||||
"message": "系统维护中,任务和草稿已保留,请稍后重试",
|
||||
}
|
||||
},
|
||||
)
|
||||
return await call_next(request)
|
||||
|
||||
@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": "服务处理失败,请联系管理员"}},
|
||||
)
|
||||
|
||||
app.include_router(api_router, prefix="/api")
|
||||
return app
|
||||
@ -1,127 +0,0 @@
|
||||
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
|
||||
public_access: bool = False
|
||||
# Zero disables this optional per-owner unfinished interactive GPU job cap.
|
||||
max_interactive_gpu_jobs: int = 0
|
||||
max_creation_commands_per_minute: int = 6
|
||||
max_owner_asset_bytes: int = 100 * 1024**3
|
||||
max_data_bytes: int = 2 * 1024**4
|
||||
min_free_bytes: int = 50 * 1024**3
|
||||
max_owner_jobs: int = 500
|
||||
max_global_jobs: int = 2000
|
||||
max_owner_runs: int = 100
|
||||
max_global_runs: int = 1000
|
||||
max_owner_batches: int = 20
|
||||
max_global_batches: int = 200
|
||||
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")
|
||||
runtime_policy_file: Path | None = Path("/workspace/projects/llm-services/config/runtime-policy.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")
|
||||
if self.max_interactive_gpu_jobs < 0:
|
||||
raise ValueError("MAX_INTERACTIVE_GPU_JOBS must be non-negative; 0 disables the limit")
|
||||
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", "runtime_policy_file"):
|
||||
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
|
||||
if env.get("RUNTIME_POLICY_FILE"):
|
||||
values["runtime_policy_file"] = Path(env["RUNTIME_POLICY_FILE"])
|
||||
for field in ("mysql_port", "session_hours", "max_upload_bytes", "max_output_bytes", "max_owner_jobs", "max_global_jobs", "max_interactive_gpu_jobs", "max_creation_commands_per_minute", "max_owner_asset_bytes", "max_data_bytes", "min_free_bytes", "max_owner_runs", "max_global_runs", "max_owner_batches", "max_global_batches"):
|
||||
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", "public_access"):
|
||||
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)
|
||||
@ -1,703 +0,0 @@
|
||||
import asyncio
|
||||
from datetime import timedelta
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
from pathlib import Path
|
||||
import re
|
||||
from filelock import FileLock
|
||||
from sqlalchemy import case, or_, select
|
||||
from .assets import confined, import_output, safe_file, validate_workflow_output
|
||||
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, User, utcnow
|
||||
|
||||
LOG = logging.getLogger(__name__)
|
||||
GPU_FENCE_UNSET = object()
|
||||
|
||||
|
||||
class PhaseDeferred(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class Coordinator:
|
||||
def __init__(self, settings, db, provider):
|
||||
self.settings, self.db, self.provider = settings, db, provider
|
||||
self._task = None
|
||||
self._cpu = {}
|
||||
self._preparing = {}
|
||||
self._collecting = {}
|
||||
# Bound pending coroutines independently of their current phase/slot.
|
||||
# A Qwen quarantine must leave capacity for unrelated media work.
|
||||
self._cpu_initial_pool = {}
|
||||
self._pools = {name:asyncio.Semaphore(1) for name in ("new_gpu","cpu_media","qwen_http")}
|
||||
self._held_pool = {}
|
||||
self._blocked_pools = set()
|
||||
from .admission_clock import AdmissionClock
|
||||
self._admission_clock=AdmissionClock(settings.state_root / "admission-clock.json")
|
||||
self._control_sent = {}
|
||||
self._run_lock = asyncio.Lock()
|
||||
self._wake = asyncio.Event()
|
||||
self._file_lock = FileLock(str(settings.state_root / "coordinator.lock"))
|
||||
self._closing = False
|
||||
self.after_tick = None
|
||||
self.last_tick_success = None
|
||||
self._cancel_sent = set()
|
||||
self._uncertain_cpu = set()
|
||||
|
||||
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.deleted_at.is_(None), Job.state.notin_(TERMINAL),
|
||||
Job.task_type.notin_(GPU_TYPES), Job.state.in_(["running","cancelling"])))).all()
|
||||
from .v2_models import Execution
|
||||
from .artifacts import verify_manifest
|
||||
for job in rows:
|
||||
execution = await session.get(Execution,job.current_execution_id) if job.current_execution_id else None
|
||||
manifest = execution.manifest_json if execution else None
|
||||
if not manifest:
|
||||
candidates = sorted((self.settings.job_work_root / job.id).glob("attempt-*/result-manifest.json"))
|
||||
for candidate in reversed(candidates):
|
||||
try:
|
||||
found=json.loads(candidate.read_text(encoding="utf-8"))
|
||||
if found.get("execution_id")==job.current_execution_id:
|
||||
manifest=found;break
|
||||
except (ValueError,OSError):pass
|
||||
if manifest and execution:
|
||||
try:
|
||||
paths=verify_manifest(self.settings.job_work_root,manifest)
|
||||
if manifest.get("fence_token")!=execution.fence_token:raise ValueError("Fence mismatch")
|
||||
job.upstream_result={"cpu_outputs":paths,"cpu_result":manifest["result"],"metadata":manifest["metadata"]}
|
||||
job.state,job.phase="collecting","importing_outputs"
|
||||
execution.manifest_json=manifest;execution.state="results_ready"
|
||||
await emit_job(session,job)
|
||||
continue
|
||||
except (ValueError,OSError,KeyError):pass
|
||||
if execution and (execution.resource_pool == "qwen_http" or job.task_type=="audio.speech"):
|
||||
self._blocked_pools.add(execution.resource_pool)
|
||||
execution.state="unknown"
|
||||
job.state = "cancelled" if job.cancel_requested else "needs_attention"
|
||||
job.phase, job.finished_at = job.state, utcnow()
|
||||
job.error_json = {"code": "worker_interrupted", "message": "服务重启中断了此任务,可手动重试", "retriable": True}
|
||||
await emit_job(session, job)
|
||||
blocked=(await session.scalars(select(Execution).where(Execution.resource_pool.in_(["qwen_http","cpu_media"]),Execution.state=="unknown"))).all()
|
||||
self._blocked_pools.update(execution.resource_pool for execution in blocked)
|
||||
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)
|
||||
background=[*self._cpu.values(),*self._preparing.values(),*self._collecting.values()]
|
||||
for task in background:task.cancel()
|
||||
await asyncio.gather(*background, return_exceptions=True)
|
||||
if self._file_lock.is_locked:
|
||||
self._file_lock.release()
|
||||
|
||||
async def _loop(self):
|
||||
while True:
|
||||
try:
|
||||
await self.run_once()
|
||||
self.last_tick_success=time.monotonic()
|
||||
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, remote_observation=None, **changes):
|
||||
async with self.db.session() as session:
|
||||
job = await session.get(Job, job_id)
|
||||
if job is None or job.deleted_at is not None or job.state in TERMINAL:
|
||||
return job
|
||||
execution_changed=False
|
||||
if remote_observation is not None:
|
||||
from .executions import observe_gpu_execution,gpu_result_fence
|
||||
from .v2_models import Execution
|
||||
previous_execution_id=job.current_execution_id
|
||||
accepted,execution=await observe_gpu_execution(session,job,remote_observation)
|
||||
if not accepted:return job
|
||||
execution_changed=job.current_execution_id!=previous_execution_id or any(isinstance(row,Execution) and session.is_modified(row) for row in session.dirty)
|
||||
if remote_observation["state"]=="succeeded" and execution:
|
||||
changes["upstream_result"]={**(changes.get("upstream_result") or {}),"_visual_execution":gpu_result_fence(execution)}
|
||||
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 = execution_changed
|
||||
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,
|
||||
Asset.library_scope == 'private', Asset.ready.is_(True), Asset.deleted_at.is_(None)))).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)
|
||||
if job is None or job.deleted_at is not None:return
|
||||
from .v2_models import Execution
|
||||
async with self.db.session() as session:
|
||||
job = await session.get(Job, job_id)
|
||||
if job is None or job.deleted_at is not None:return
|
||||
execution=await session.get(Execution,job.current_execution_id) if job.current_execution_id else None
|
||||
if execution:
|
||||
unknown=(execution.resource_pool=="qwen_http" or job.task_type=="audio.speech") and getattr(exc,"retriable",False)
|
||||
execution.state="unknown" if unknown else "exited"
|
||||
execution.finished_at=utcnow()
|
||||
if unknown:self._blocked_pools.add(execution.resource_pool)
|
||||
await session.commit()
|
||||
if execution and execution.state=="unknown":
|
||||
await self._update(job_id,state="needs_attention",phase="remote_outcome_unknown",error_json={"code":"remote_outcome_unknown","message":"Remote request completion is unconfirmed","retriable":False})
|
||||
return
|
||||
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, *, gpu_fence=GPU_FENCE_UNSET):
|
||||
async with self.db.session() as session:
|
||||
job = await session.get(Job, job_id)
|
||||
if job is None or job.deleted_at is not None or job.state in TERMINAL:
|
||||
return
|
||||
if gpu_fence is not GPU_FENCE_UNSET:
|
||||
from .executions import gpu_publication_matches
|
||||
if not await gpu_publication_matches(session,job,gpu_fence):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,
|
||||
Asset.owner_id == job.owner_id, Asset.library_scope == 'private', Asset.deleted_at.is_(None))
|
||||
.order_by(Asset.source_output_index))).all()
|
||||
if not outputs:
|
||||
raise ValueError("Completed job has no imported artifacts")
|
||||
for asset in outputs:
|
||||
if gpu_fence is not GPU_FENCE_UNSET and gpu_fence:
|
||||
from .v2_models import AssetReference
|
||||
binding=await session.scalar(select(AssetReference.id).where(AssetReference.asset_id==asset.id,AssetReference.ref_kind=="execution",AssetReference.ref_id==gpu_fence["execution_id"]))
|
||||
if not binding:raise ValueError("Output belongs to a different execution")
|
||||
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()
|
||||
|
||||
def _clock_allows(self,job):
|
||||
if job.execution_mode!="batch":return True
|
||||
return self._batch_clock_allows()
|
||||
|
||||
def _batch_clock_allows(self):
|
||||
from .runtime_policy import read_runtime_policy
|
||||
from .resource_policy import execution_policy
|
||||
policy=read_runtime_policy(self.settings)
|
||||
if policy["configuration_error"]:return False
|
||||
if not policy["batch_window_enabled"]:return True
|
||||
return execution_policy()["batch_open"] and self._admission_clock.observe()
|
||||
|
||||
async def run_once(self, *, force=False):
|
||||
from .runtime_policy import read_runtime_policy
|
||||
policy=read_runtime_policy(self.settings)
|
||||
if policy["batch_window_enabled"] and not policy["configuration_error"]:
|
||||
self._admission_clock.observe()
|
||||
async with self._run_lock:
|
||||
for job_id, task in list(self._cpu.items()):
|
||||
if task.done():
|
||||
self._cpu.pop(job_id)
|
||||
self._cpu_initial_pool.pop(job_id, None)
|
||||
await asyncio.gather(task, return_exceptions=True)
|
||||
for pending in (self._preparing,self._collecting):
|
||||
for jid,task in list(pending.items()):
|
||||
if task.done():
|
||||
pending.pop(jid)
|
||||
await asyncio.gather(task,return_exceptions=True)
|
||||
async with self.db.session() as session:
|
||||
query = select(Job).where(Job.deleted_at.is_(None), 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())
|
||||
# New dispatch FIFO is separate from observation/retry backoff.
|
||||
fresh=select(Job).join(User,User.id==Job.owner_id).where(User.disabled.is_(False),Job.deleted_at.is_(None),Job.state.notin_(TERMINAL),
|
||||
Job.task_type.in_(GPU_TYPES),Job.upstream_id.is_(None),
|
||||
Job.desired_state=="run",or_(Job.hold_reasons==[],Job.hold_reasons==["window"]),
|
||||
Job.state.in_(["submitting","queued","scheduled"]),
|
||||
(or_(Job.sync_failures==0,Job.next_action_at<=utcnow()) if not force else True),
|
||||
or_(Job.scheduled_at.is_(None),Job.scheduled_at<=utcnow()))
|
||||
if not self._batch_clock_allows():fresh=fresh.where(Job.execution_mode!="batch")
|
||||
ready=list((await session.scalars(fresh.order_by(Job.created_at,Job.batch_index,Job.id).limit(25))).all())
|
||||
ready_ids={j.id for j in ready}
|
||||
jobs=ready+[j for j in jobs if j.id not in ready_ids]
|
||||
# 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]
|
||||
from .resource_policy import admits
|
||||
# Media preparation is bounded independently of the dispatch loop.
|
||||
for job in jobs:
|
||||
if job.task_type not in GPU_TYPES or job.upstream_id or job.upstream_payload is not None or job.state in {"collecting","needs_attention","paused","pausing"} or job.cancel_requested:continue
|
||||
if job.scheduled_at and job.scheduled_at>utcnow():continue
|
||||
if not admits(job,settings=self.settings) or not self._clock_allows(job) or not await self._owner_enabled(job.owner_id):continue
|
||||
from .maintenance import maintenance_active
|
||||
if maintenance_active(self.settings):continue
|
||||
if job.id not in self._preparing and len(self._preparing)<4:
|
||||
self._preparing[job.id]=asyncio.create_task(self._gpu(job,prepare_only=True),name=f"prepare-{job.id}")
|
||||
if self._preparing:
|
||||
await asyncio.wait(list(self._preparing.values()),timeout=.1)
|
||||
# Preparation candidates are not the submission queue. Re-read
|
||||
# persisted ready payloads after bounded preparation, including
|
||||
# payloads beyond a prefix of unfinished media jobs.
|
||||
async with self.db.session() as session:
|
||||
ready=list((await session.scalars(fresh.where(Job.upstream_payload.is_not(None)).order_by(Job.created_at,Job.batch_index,Job.id).limit(25))).all())
|
||||
ready=[j for j in ready if j.id not in self._preparing or self._preparing[j.id].done()]
|
||||
ready_ids={j.id for j in ready}
|
||||
jobs=ready+[j for j in jobs if j.id not in ready_ids]
|
||||
if cpu is not None:jobs=[cpu]+[j for j in jobs if j.id!=cpu.id]
|
||||
for job in jobs:
|
||||
job=await self._job(job.id)
|
||||
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
|
||||
from .maintenance import maintenance_active
|
||||
holds=set(job.hold_reasons or [])
|
||||
if maintenance_active(self.settings):holds.add('maintenance')
|
||||
else:holds.discard('maintenance')
|
||||
if holds!=set(job.hold_reasons or []):
|
||||
job=await self._update(job.id,hold_reasons=sorted(holds))
|
||||
if job.id in self._cpu:
|
||||
if job.cancel_requested and job.state != "collecting":
|
||||
held=self._held_pool.get(job.id)
|
||||
draining_http=held=="qwen_http" or (job.task_type=="audio.speech" and held=="cpu_media")
|
||||
if not draining_http:self._cpu[job.id].cancel()
|
||||
continue
|
||||
if job.id in self._uncertain_cpu:
|
||||
await self._update(job.id,state="needs_attention",phase="outcome_unknown")
|
||||
continue
|
||||
if job.state == "needs_attention" or (job.state in {"paused","pausing"} and not job.upstream_id):continue
|
||||
# Query existing upstream IDs and collect artifacts at all hours.
|
||||
# Admission only protects NEW computational phases.
|
||||
from .maintenance import maintenance_active
|
||||
if job.state != "collecting" and not job.upstream_id and not job.cancel_requested and (not admits(job,settings=self.settings) or not self._clock_allows(job) or maintenance_active(self.settings) or not await self._owner_enabled(job.owner_id)):
|
||||
continue
|
||||
if job.id in self._collecting:continue
|
||||
# A persisted payload is not dispatchable until preparation's
|
||||
# final cancellation check has finished. Otherwise it could
|
||||
# locally cancel while a concurrent POST loses its remote ID.
|
||||
if job.id in self._preparing and not self._preparing[job.id].done():continue
|
||||
if job.task_type in GPU_TYPES:
|
||||
if job.state=="collecting":
|
||||
if len(self._collecting)<2:self._collecting[job.id]=asyncio.create_task(self._gpu(job),name=f"collect-{job.id}")
|
||||
elif job.upstream_id or job.upstream_payload is not None or job.cancel_requested:
|
||||
# Observation overflow is a polling cursor, never a
|
||||
# second submit queue. Only the FIFO prefix dispatches.
|
||||
if not job.upstream_id and not job.cancel_requested and job.id not in ready_ids:continue
|
||||
await self._gpu(job)
|
||||
elif job.state == "collecting":
|
||||
if len(self._collecting)<2:
|
||||
self._collecting[job.id]=asyncio.create_task(self._collect_cpu_background(job),name=f"collect-{job.id}")
|
||||
elif job.state in {"submitting","queued","scheduled","cancelling"}:
|
||||
from .resource_policy import resource_plan
|
||||
initial_pool = resource_plan(job.task_type)[0][1]
|
||||
if sum(pool == initial_pool for pool in self._cpu_initial_pool.values()) < 25:
|
||||
# This membership stays fixed when the provider moves
|
||||
# phases; only _held_pool follows active resource slots.
|
||||
self._cpu_initial_pool[job.id] = initial_pool
|
||||
self._cpu[job.id] = asyncio.create_task(self._run_cpu(job), name=f"cpu-job-{job.id}")
|
||||
|
||||
if self._collecting:
|
||||
await asyncio.wait(list(self._collecting.values()),timeout=.1)
|
||||
if self.after_tick is not None:
|
||||
await self.after_tick()
|
||||
|
||||
async def _collect_cpu_background(self,job):
|
||||
try:await self._collect_cpu(job)
|
||||
except Exception as exc:await self._warning(job.id,exc)
|
||||
|
||||
async def _gpu(self, job, *, prepare_only=False):
|
||||
try:
|
||||
job = await self._job(job.id)
|
||||
if job is None or job.deleted_at is not None or job.state in TERMINAL:return
|
||||
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)
|
||||
from .providers import current_phase_callback
|
||||
async def prepare_phase(key,pool):
|
||||
from .resource_policy import admits
|
||||
current=await self._job(job.id)
|
||||
if not admits(current,settings=self.settings):raise PhaseDeferred()
|
||||
await self._enter_phase(job.id,key,pool,nonblocking=True)
|
||||
token=current_phase_callback.set(prepare_phase)
|
||||
try:
|
||||
payload = await self.provider.prepare_gpu_payload(job.task_type, job.input_json, job.parameters,
|
||||
await self._assets(job), work)
|
||||
finally:
|
||||
current_phase_callback.reset(token)
|
||||
held=self._held_pool.pop(job.id,None)
|
||||
if held:self._pools[held].release()
|
||||
payload["scheduling"] = {"execution_mode": job.execution_mode, "principal_id": job.owner_id,
|
||||
"policy_version": job.policy_version,
|
||||
**{key:getattr(job,key) for key in ("batch_id","run_id","step_key") if getattr(job,key)}}
|
||||
# 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
|
||||
if prepare_only:return
|
||||
from .resource_policy import admits
|
||||
if not job.cancel_requested and (not admits(job,settings=self.settings) or not self._clock_allows(job) or not await self._owner_enabled(job.owner_id)):return
|
||||
if job.execution_mode == "batch":
|
||||
capabilities = await self.provider.upstream_capabilities() if hasattr(self.provider,"upstream_capabilities") else {}
|
||||
if capabilities.get("protocol_version",0)<2 or not capabilities.get("admission_policy",False):
|
||||
await self._update(job.id,sync_warning="Batch requires upstream scheduling protocol v2")
|
||||
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:
|
||||
controls = {"manual","batch_pause","admin_suspend","batch_wait","maintenance"}
|
||||
desired = "pause" if job.desired_state == "pause" or controls.intersection(job.hold_reasons or []) else "run"
|
||||
if job.cancel_requested and job.id not in self._cancel_sent:
|
||||
remote = await self.provider.cancel(job.upstream_id)
|
||||
self._cancel_sent.add(job.id)
|
||||
elif not job.cancel_requested and hasattr(self.provider,"control") and self._control_sent.get(job.id)!=desired:
|
||||
remote = await self.provider.control(job.upstream_id,desired,"cmvr:"+job.id+":"+str(job.version)+":"+desired)
|
||||
self._control_sent[job.id]=desired
|
||||
else:
|
||||
remote = 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, defer_collection=True)
|
||||
except PhaseDeferred:
|
||||
await self._update(job.id,state="submitting",phase="waiting_phase")
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
if getattr(exc,"code",None) in {"quota_exceeded","storage_insufficient"}:
|
||||
await self._failure(job.id,exc)
|
||||
elif 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, *, defer_collection=False):
|
||||
state = remote.get("state")
|
||||
if state not in {"queued", "running", "paused", "pausing", "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, remote_observation=remote, **changes)
|
||||
if job.state == "collecting":
|
||||
if defer_collection:
|
||||
if job.id not in self._collecting and len(self._collecting)<2:
|
||||
self._collecting[job.id]=asyncio.create_task(self._gpu(job),name=f"collect-{job.id}")
|
||||
else:
|
||||
await self._collect_gpu(job)
|
||||
|
||||
async def _collect_gpu(self, job):
|
||||
fence=(job.upstream_result or {}).get("_visual_execution")
|
||||
from .executions import gpu_publication_matches
|
||||
async with self.db.session() as session:
|
||||
current=await session.get(Job,job.id)
|
||||
if not await gpu_publication_matches(session,current,fence):raise ValueError("Stale GPU execution result")
|
||||
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 = []
|
||||
selected_indices = None
|
||||
if job.run_id and job.task_type == "video.generate" and job.step_key != "compose":
|
||||
selected_indices = (job.upstream_result.get("metadata") or {}).get("final_output_indices")
|
||||
if (not isinstance(selected_indices, list) or not selected_indices or
|
||||
any(type(i) is not int or i < 0 or i >= len(outputs) for i in selected_indices)):
|
||||
raise ValueError("Workflow requires explicit final enhanced output indices from upstream")
|
||||
for index, output in enumerate(outputs):
|
||||
if selected_indices is not None and index not in selected_indices:
|
||||
continue
|
||||
async with self.db.session() as session:
|
||||
existing = await session.scalar(select(Asset).where(Asset.source_job_id == job.id,
|
||||
Asset.owner_id == job.owner_id,
|
||||
Asset.library_scope == 'private',
|
||||
Asset.source_output_index == index))
|
||||
if existing:
|
||||
if fence:
|
||||
from .v2_models import AssetReference
|
||||
async with self.db.session() as session:
|
||||
binding=await session.scalar(select(AssetReference.id).where(AssetReference.asset_id==existing.id,AssetReference.ref_kind=="execution",AssetReference.ref_id==fence["execution_id"]))
|
||||
if not binding:raise ValueError("Output belongs to a different execution")
|
||||
from .artifacts import digest_file
|
||||
path=confined(self.settings.asset_root,existing.storage_key,exists=True)
|
||||
if path.stat().st_size!=existing.size_bytes or digest_file(path)!=existing.sha256:
|
||||
raise ValueError("Imported artifact is missing or corrupt")
|
||||
await validate_workflow_output(job,path,self.settings)
|
||||
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, execution_fence=fence))
|
||||
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, gpu_fence=fence)
|
||||
|
||||
async def _owner_enabled(self,owner_id):
|
||||
async with self.db.session() as session:
|
||||
owner=await session.get(User,owner_id)
|
||||
return owner is not None and not owner.disabled
|
||||
|
||||
async def _enter_phase(self, job_id, phase_key, pool, *, nonblocking=False):
|
||||
previous=self._held_pool.pop(job_id,None)
|
||||
if previous:self._pools[previous].release()
|
||||
from .resource_policy import admits
|
||||
from .maintenance import maintenance_active
|
||||
while True:
|
||||
job=await self._job(job_id)
|
||||
if job is None or job.deleted_at is not None or job.state in TERMINAL:raise asyncio.CancelledError()
|
||||
if job.cancel_requested:raise asyncio.CancelledError()
|
||||
if admits(job,settings=self.settings) and self._clock_allows(job) and pool not in self._blocked_pools and not maintenance_active(self.settings) and await self._owner_enabled(job.owner_id):break
|
||||
if nonblocking:raise PhaseDeferred()
|
||||
await self._update(job_id,phase="waiting_phase:"+phase_key)
|
||||
await asyncio.sleep(min(1,self.settings.poll_seconds))
|
||||
if nonblocking and self._pools[pool].locked():raise PhaseDeferred()
|
||||
await self._pools[pool].acquire()
|
||||
# Recheck after waiting for the slot; no closed-window compute starts.
|
||||
job=await self._job(job_id)
|
||||
if job.deleted_at is not None or job.state in TERMINAL or job.cancel_requested or not admits(job,settings=self.settings) or not self._clock_allows(job) or pool in self._blocked_pools or maintenance_active(self.settings) or not await self._owner_enabled(job.owner_id):
|
||||
self._pools[pool].release()
|
||||
if nonblocking:raise PhaseDeferred()
|
||||
return await self._enter_phase(job_id,phase_key,pool)
|
||||
self._held_pool[job_id]=pool
|
||||
async with self.db.session() as session:
|
||||
current=await session.get(Job,job_id)
|
||||
if current.current_execution_id:
|
||||
from .v2_models import Execution
|
||||
from .executions import begin_execution
|
||||
active=await session.get(Execution,current.current_execution_id)
|
||||
if active and (active.phase_key!=phase_key or active.resource_pool!=pool):
|
||||
active.state="exited";active.finished_at=utcnow()
|
||||
await begin_execution(session,job_id,phase_key,pool)
|
||||
await session.commit()
|
||||
await self._update(job_id,phase="cpu_running")
|
||||
|
||||
async def _run_cpu(self, job):
|
||||
phase_token=None
|
||||
try:
|
||||
job = await self._job(job.id)
|
||||
if job is None or job.deleted_at is not None:return
|
||||
if job.cancel_requested:
|
||||
await self._update(job.id, state="cancelled", phase="cancelled", finished_at=utcnow())
|
||||
return
|
||||
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)
|
||||
from .executions import begin_execution
|
||||
from .resource_policy import resource_plan
|
||||
from .providers import current_phase_callback
|
||||
phase_token=current_phase_callback.set(lambda phase,pool:self._enter_phase(job.id,phase,pool))
|
||||
initial_pool=resource_plan(job.task_type)[0][1]
|
||||
await self._enter_phase(job.id,"execute",initial_pool)
|
||||
job = await self._update(job.id, state="running", phase="cpu_running", started_at=utcnow(),
|
||||
attempt_count=job.attempt_count + 1)
|
||||
if job.cancel_requested or job.state in TERMINAL:
|
||||
if job.state not in TERMINAL:
|
||||
await self._update(job.id,state="cancelled",phase="cancelled",finished_at=utcnow())
|
||||
return
|
||||
async with self.db.session() as session:
|
||||
execution = await begin_execution(session,job.id,resource_pool=resource_plan(job.task_type)[0][1])
|
||||
await session.commit()
|
||||
result = await self.provider.run_cpu(job.task_type, job.input_json, job.parameters, await self._assets(job), work)
|
||||
# A successful HTTP response proves this request ended. Explicit
|
||||
# cancellation drains shared calls, then discards their response.
|
||||
from .v2_models import Execution
|
||||
async with self.db.session() as session:
|
||||
current=await session.get(Job,job.id)
|
||||
if current.cancel_requested:
|
||||
execution=await session.get(Execution,current.current_execution_id)
|
||||
if execution:execution.state="exited";execution.finished_at=utcnow()
|
||||
current.state,current.phase,current.finished_at="cancelled","cancelled",utcnow()
|
||||
current.result_json=None;current.error_json=None
|
||||
await emit_job(session,current)
|
||||
await session.commit()
|
||||
return
|
||||
from .artifacts import write_manifest
|
||||
from .v2_models import Execution
|
||||
async with self.db.session() as session:
|
||||
current=await session.get(Job,job.id)
|
||||
execution=await session.get(Execution,current.current_execution_id)
|
||||
manifest=write_manifest(self.settings.job_work_root,work,execution.id,execution.fence_token,result.outputs,result.result,result.metadata)
|
||||
from .executions import accept_manifest
|
||||
async with self.db.session() as session:
|
||||
if not await accept_manifest(session,execution.id,execution.fence_token,manifest):
|
||||
current=await session.get(Job,job.id)
|
||||
if current.cancel_requested:
|
||||
execution.state="exited";execution.finished_at=utcnow()
|
||||
current.state,current.phase,current.finished_at="cancelled","cancelled",utcnow()
|
||||
current.result_json=None;current.error_json=None
|
||||
await emit_job(session,current)
|
||||
await session.commit()
|
||||
return
|
||||
await session.commit()
|
||||
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:
|
||||
held=self._held_pool.get(job.id)
|
||||
current=await self._job(job.id)
|
||||
if self._closing and not current.cancel_requested and current.current_execution_id is None:
|
||||
# A pool/window waiter never allocated a provider execution.
|
||||
# Keep its accepted identity queued across an API restart.
|
||||
await self._update(job.id,state='queued',phase='waiting_for_resource',
|
||||
started_at=None,finished_at=None,error_json=None)
|
||||
return
|
||||
unknown=held=="qwen_http" or (job.task_type=="audio.speech" and held=="cpu_media")
|
||||
if unknown:self._blocked_pools.add(held)
|
||||
from .v2_models import Execution
|
||||
async with self.db.session() as session:
|
||||
current=await session.get(Job,job.id)
|
||||
active=await session.get(Execution,current.current_execution_id) if current.current_execution_id else None
|
||||
if active and active.state not in {"results_ready","exited"}:
|
||||
active.state="unknown" if unknown else "exited"
|
||||
active.finished_at=utcnow()
|
||||
await session.commit()
|
||||
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" and getattr(exc,"code",None) not in {"quota_exceeded","storage_insufficient"}:
|
||||
await self._warning(job.id, exc)
|
||||
else:
|
||||
LOG.exception("CPU job %s failed", job.id)
|
||||
try:
|
||||
await self._failure(job.id, exc)
|
||||
except Exception:
|
||||
self._uncertain_cpu.add(job.id)
|
||||
LOG.exception("CPU outcome uncertain; execution is quarantined")
|
||||
|
||||
finally:
|
||||
previous=self._held_pool.pop(job.id,None)
|
||||
if previous:self._pools[previous].release()
|
||||
if phase_token is not None:
|
||||
from .providers import current_phase_callback
|
||||
current_phase_callback.reset(phase_token)
|
||||
|
||||
async def _collect_cpu(self, job):
|
||||
job = await self._job(job.id)
|
||||
if job is None or job.deleted_at is not None or job.state in TERMINAL:return
|
||||
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", {})))
|
||||
0
backend/app/core/__init__.py
Normal file
0
backend/app/core/__init__.py
Normal file
269
backend/app/core/config.py
Normal file
269
backend/app/core/config.py
Normal file
@ -0,0 +1,269 @@
|
||||
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
|
||||
public_access: bool = False
|
||||
# Zero disables this optional per-owner unfinished interactive GPU job cap.
|
||||
max_interactive_gpu_jobs: int = 0
|
||||
max_creation_commands_per_minute: int = 6
|
||||
max_owner_asset_bytes: int = 100 * 1024**3
|
||||
max_data_bytes: int = 2 * 1024**4
|
||||
min_free_bytes: int = 50 * 1024**3
|
||||
max_owner_jobs: int = 500
|
||||
max_global_jobs: int = 2000
|
||||
# 等待补队的持久候选与活动Job独立限额,默认容纳1000镜头各4个候选。
|
||||
max_owner_story_candidates: int = 4000
|
||||
max_global_story_candidates: int = 16000
|
||||
max_owner_runs: int = 100
|
||||
max_global_runs: int = 1000
|
||||
max_owner_batches: int = 20
|
||||
max_global_batches: int = 200
|
||||
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_remote_files: bool = False
|
||||
# 真实多图通道尚未完成资源、抢占及质量认证,默认关闭。
|
||||
reference_generation_enabled: bool = False
|
||||
reference_generation_profile: str = "qwen-image-edit-2511-v1"
|
||||
reference_max_images: int = 3
|
||||
video_edit_enabled: bool = False
|
||||
video_edit_profile: str = "wan-animate-replace-v1"
|
||||
video_edit_max_seconds: int = 120
|
||||
video_edit_max_people: int = 12
|
||||
video_edit_max_pixels: int = 399360
|
||||
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"
|
||||
)
|
||||
runtime_policy_file: Path | None = Path(
|
||||
"/workspace/projects/llm-services/config/runtime-policy.json"
|
||||
)
|
||||
qwen_base_url: str = "http://192.168.28.10:14081/v1"
|
||||
qwen_model: str = "Qwen/Qwen3.8-27B-FP8"
|
||||
qwen_api_key: str = ""
|
||||
# 包含 GPU 交接和冷加载;普通模型控制接口仍使用原来的短超时。
|
||||
qwen_timeout_seconds: float = 1800.0
|
||||
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")
|
||||
speech_timeout_seconds: float = 330.0
|
||||
speech_total_timeout_seconds: float = 360.0
|
||||
|
||||
def __post_init__(self):
|
||||
import math
|
||||
|
||||
if (
|
||||
not math.isfinite(self.speech_timeout_seconds)
|
||||
or not math.isfinite(self.speech_total_timeout_seconds)
|
||||
or self.speech_timeout_seconds <= 0
|
||||
or self.speech_total_timeout_seconds < self.speech_timeout_seconds
|
||||
):
|
||||
raise ValueError("Speech timeouts must be finite, positive and ordered")
|
||||
if self.mode not in {"production", "preview", "test"}:
|
||||
raise ValueError("CMVR_MODE must be production, preview or test")
|
||||
if self.max_interactive_gpu_jobs < 0:
|
||||
raise ValueError("MAX_INTERACTIVE_GPU_JOBS must be non-negative; 0 disables the limit")
|
||||
if any(
|
||||
type(value) is not int or value < 0
|
||||
for value in (self.max_owner_story_candidates, self.max_global_story_candidates)
|
||||
):
|
||||
raise ValueError("Story candidate plan limits must be non-negative integers")
|
||||
if self.video_edit_profile != "wan-animate-replace-v1":
|
||||
raise ValueError("Unsupported VIDEO_EDIT_PROFILE")
|
||||
if any(
|
||||
type(v) is not int or v < 1
|
||||
for v in (self.video_edit_max_seconds, self.video_edit_max_people)
|
||||
):
|
||||
raise ValueError("Video edit limits must be positive integers")
|
||||
if type(self.video_edit_max_pixels) is not int or self.video_edit_max_pixels not in {
|
||||
399360,
|
||||
921600,
|
||||
}:
|
||||
raise ValueError("VIDEO_EDIT_MAX_PIXELS must be a certified 480p/720p budget")
|
||||
profiles = {
|
||||
"qwen-image-edit-2511-v1",
|
||||
"qwen-image-edit-2509-v1",
|
||||
"qwen-image-edit-2511-experimental-4-v1",
|
||||
}
|
||||
if self.reference_generation_profile not in profiles:
|
||||
raise ValueError("Unsupported REFERENCE_GENERATION_PROFILE")
|
||||
maximum = 4 if "experimental-4" in self.reference_generation_profile else 3
|
||||
if (
|
||||
type(self.reference_max_images) is not int
|
||||
or not 1 <= self.reference_max_images <= maximum
|
||||
):
|
||||
raise ValueError("REFERENCE_MAX_IMAGES exceeds the selected profile")
|
||||
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",
|
||||
"runtime_policy_file",
|
||||
):
|
||||
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",
|
||||
"reference_generation_profile",
|
||||
"video_edit_profile",
|
||||
"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
|
||||
if env.get("RUNTIME_POLICY_FILE"):
|
||||
values["runtime_policy_file"] = Path(env["RUNTIME_POLICY_FILE"])
|
||||
for field in (
|
||||
"mysql_port",
|
||||
"session_hours",
|
||||
"max_upload_bytes",
|
||||
"max_output_bytes",
|
||||
"max_owner_jobs",
|
||||
"max_global_jobs",
|
||||
"max_owner_story_candidates",
|
||||
"max_global_story_candidates",
|
||||
"max_interactive_gpu_jobs",
|
||||
"reference_max_images",
|
||||
"video_edit_max_seconds",
|
||||
"video_edit_max_people",
|
||||
"video_edit_max_pixels",
|
||||
"max_creation_commands_per_minute",
|
||||
"max_owner_asset_bytes",
|
||||
"max_data_bytes",
|
||||
"min_free_bytes",
|
||||
"max_owner_runs",
|
||||
"max_global_runs",
|
||||
"max_owner_batches",
|
||||
"max_global_batches",
|
||||
):
|
||||
if field.upper() in env:
|
||||
values[field] = int(env[field.upper()])
|
||||
for field in (
|
||||
"poll_seconds",
|
||||
"event_heartbeat_seconds",
|
||||
"request_timeout_seconds",
|
||||
"qwen_timeout_seconds",
|
||||
"speech_timeout_seconds",
|
||||
"speech_total_timeout_seconds",
|
||||
):
|
||||
if field.upper() in env:
|
||||
values[field] = float(env[field.upper()])
|
||||
for field in (
|
||||
"cookie_secure",
|
||||
"run_coordinator",
|
||||
"public_access",
|
||||
"inference_remote_files",
|
||||
"reference_generation_enabled",
|
||||
"video_edit_enabled",
|
||||
):
|
||||
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)
|
||||
@ -2,8 +2,7 @@ from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
|
||||
from sqlalchemy import event
|
||||
import asyncio
|
||||
from contextlib import asynccontextmanager
|
||||
from .models import Base
|
||||
from . import v2_models
|
||||
from app.models import Base
|
||||
|
||||
|
||||
class Database:
|
||||
@ -11,15 +10,16 @@ class Database:
|
||||
self.mode = settings.mode
|
||||
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.
|
||||
# 单 API 进程内串行提交短事务,确保 SSE 游标顺序与提交顺序一致;GPU 并行不等于增加 API workers。
|
||||
self._unit_lock = asyncio.Lock()
|
||||
|
||||
@asynccontextmanager
|
||||
@ -33,8 +33,9 @@ class Database:
|
||||
if self.mode in {"test", "preview"}:
|
||||
await connection.run_sync(Base.metadata.create_all)
|
||||
else:
|
||||
from .schema import check_schema_revision
|
||||
await connection.run_sync(check_schema_revision, {"004"})
|
||||
from app.core.schema import check_schema_revision
|
||||
|
||||
await connection.run_sync(check_schema_revision, {"007"})
|
||||
|
||||
async def close(self):
|
||||
await self.engine.dispose()
|
||||
13
backend/app/core/maintenance.py
Normal file
13
backend/app/core/maintenance.py
Normal file
@ -0,0 +1,13 @@
|
||||
"""Server-owned admission switch. Reads, synchronization and archival continue."""
|
||||
|
||||
from pathlib import Path
|
||||
from app.core.errors import fail
|
||||
|
||||
|
||||
def maintenance_active(settings):
|
||||
return (Path(settings.state_root) / "maintenance").exists()
|
||||
|
||||
|
||||
def require_writable(settings):
|
||||
if maintenance_active(settings):
|
||||
fail(503, "maintenance", "Service is in maintenance mode")
|
||||
@ -1,8 +1,9 @@
|
||||
"""Fail closed when the operator explicitly enables Internet access."""
|
||||
|
||||
import asyncio
|
||||
from sqlalchemy import select
|
||||
from .auth import verify_password
|
||||
from .models import User
|
||||
from app.core.security import verify_password
|
||||
from app.models import User
|
||||
|
||||
|
||||
async def require_public_ready(db, settings):
|
||||
@ -10,11 +11,14 @@ async def require_public_ready(db, settings):
|
||||
return
|
||||
if not settings.cookie_secure:
|
||||
raise ValueError("PUBLIC_ACCESS requires COOKIE_SECURE and HTTPS")
|
||||
if (settings.sqlalchemy_url.username or '').lower()=='root':
|
||||
if (settings.sqlalchemy_url.username or "").lower() == "root":
|
||||
raise ValueError("PUBLIC_ACCESS requires a dedicated MySQL application user")
|
||||
async with db.session() as session:
|
||||
admins = (await session.scalars(select(User).where(
|
||||
User.role == "admin", User.disabled.is_(False)))).all()
|
||||
admins = (
|
||||
await session.scalars(
|
||||
select(User).where(User.role == "admin", User.disabled.is_(False))
|
||||
)
|
||||
).all()
|
||||
if not admins:
|
||||
raise ValueError("Public access requires an enabled administrator")
|
||||
initial_passwords = {"123456"}
|
||||
@ -25,4 +29,6 @@ async def require_public_ready(db, settings):
|
||||
for password in initial_passwords:
|
||||
unchanged |= await asyncio.to_thread(verify_password, password, user.password_hash)
|
||||
if unchanged:
|
||||
raise ValueError("Change the initial administrator password in private mode before PUBLIC_ACCESS")
|
||||
raise ValueError(
|
||||
"Change the initial administrator password in private mode before PUBLIC_ACCESS"
|
||||
)
|
||||
@ -1,11 +1,13 @@
|
||||
"""Hot-read, operator-owned policy. Client job data never selects this file."""
|
||||
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
import time
|
||||
|
||||
|
||||
def read_runtime_policy(settings=None):
|
||||
result = {"batch_window_enabled": True, "workflow_max_shots": 120,
|
||||
"configuration_error": None}
|
||||
def _read_file_policy(settings=None):
|
||||
result = {"batch_window_enabled": True, "workflow_max_shots": 120, "configuration_error": None}
|
||||
path = getattr(settings, "runtime_policy_file", None)
|
||||
if path is None:
|
||||
return result
|
||||
@ -21,7 +23,10 @@ def read_runtime_policy(settings=None):
|
||||
raise ValueError("Policy too large")
|
||||
value = json.loads(raw.decode("utf-8"))
|
||||
if not isinstance(value, dict) or set(value) - {
|
||||
"schema_version", "batch_window_enabled", "workflow_max_shots"}:
|
||||
"schema_version",
|
||||
"batch_window_enabled",
|
||||
"workflow_max_shots",
|
||||
}:
|
||||
raise ValueError("Unknown policy fields")
|
||||
if type(value.get("schema_version")) is not int or value["schema_version"] != 1:
|
||||
raise ValueError("Unsupported schema")
|
||||
@ -32,5 +37,31 @@ def read_runtime_policy(settings=None):
|
||||
raise ValueError("Invalid shot limit")
|
||||
except (ValueError, TypeError, UnicodeError):
|
||||
return {**result, "configuration_error": "runtime_policy_invalid"}
|
||||
return {"batch_window_enabled": value["batch_window_enabled"],
|
||||
"workflow_max_shots": max_shots, "configuration_error": None}
|
||||
return {
|
||||
"batch_window_enabled": value["batch_window_enabled"],
|
||||
"workflow_max_shots": max_shots,
|
||||
"configuration_error": None,
|
||||
}
|
||||
|
||||
|
||||
def read_runtime_policy(settings=None):
|
||||
policy = _read_file_policy(settings)
|
||||
if not getattr(settings, "inference_remote_files", False):
|
||||
return policy
|
||||
error = getattr(settings, "_remote_policy_error", None)
|
||||
observed = getattr(settings, "_remote_policy_observed_at", None)
|
||||
if error is not None:
|
||||
error = (
|
||||
"runtime_policy_invalid"
|
||||
if error == "runtime_policy_invalid"
|
||||
else "runtime_policy_unavailable"
|
||||
)
|
||||
elif (
|
||||
type(observed) not in (int, float)
|
||||
or not math.isfinite(observed)
|
||||
or not 0 <= time.monotonic() - observed <= 5
|
||||
):
|
||||
error = "runtime_policy_unavailable"
|
||||
if error:
|
||||
return {**policy, "configuration_error": error}
|
||||
return policy
|
||||
119
backend/app/core/schema.py
Normal file
119
backend/app/core/schema.py
Normal file
@ -0,0 +1,119 @@
|
||||
from dataclasses import dataclass, field
|
||||
from sqlalchemy import inspect, text, Boolean, String, Text
|
||||
from sqlalchemy.dialects.mysql import TINYINT
|
||||
|
||||
|
||||
@dataclass
|
||||
class SchemaDiff:
|
||||
differences: list[str] = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def matches(self):
|
||||
return not self.differences
|
||||
|
||||
|
||||
def compatible_type(expected, observed, dialect):
|
||||
# Reflection includes inherited database collation; generic VARCHAR does not
|
||||
# assert one. Explicit model collation/charset still remains a hard contract.
|
||||
if isinstance(expected, Boolean) and dialect.name == "mysql":
|
||||
return (
|
||||
isinstance(observed, Boolean)
|
||||
or isinstance(observed, TINYINT)
|
||||
and observed.display_width == 1
|
||||
)
|
||||
if isinstance(expected, String) and isinstance(observed, String):
|
||||
if isinstance(expected, Text) != isinstance(observed, Text):
|
||||
return False
|
||||
if expected.length != observed.length:
|
||||
return False
|
||||
for option in ("collation", "charset"):
|
||||
desired = getattr(expected, option, None)
|
||||
if desired is not None and desired != getattr(observed, option, None):
|
||||
return False
|
||||
return True
|
||||
return expected.compile(dialect=dialect).upper() == observed.compile(dialect=dialect).upper()
|
||||
|
||||
|
||||
def schema_preflight(connection, metadata):
|
||||
inspector = inspect(connection)
|
||||
diff = SchemaDiff()
|
||||
tables = set(inspector.get_table_names())
|
||||
for table in metadata.sorted_tables:
|
||||
if table.name not in tables:
|
||||
diff.differences.append("Missing table: " + table.name)
|
||||
continue
|
||||
if connection.dialect.name == "mysql":
|
||||
options = inspector.get_table_options(table.name)
|
||||
charset = (
|
||||
options.get("mysql_default charset")
|
||||
or options.get("mysql_default_charset")
|
||||
or options.get("mysql_charset")
|
||||
)
|
||||
if charset and charset != "utf8mb4":
|
||||
diff.differences.append("Unexpected charset: " + table.name)
|
||||
actual = {c["name"]: c for c in inspector.get_columns(table.name)}
|
||||
if set(actual) != set(table.columns.keys()):
|
||||
diff.differences.append("Unexpected/missing columns: " + table.name)
|
||||
if tuple(inspector.get_pk_constraint(table.name)["constrained_columns"]) != tuple(
|
||||
c.name for c in table.primary_key.columns
|
||||
):
|
||||
diff.differences.append("Primary key: " + table.name)
|
||||
for col in table.columns:
|
||||
current = actual.get(col.name)
|
||||
if not current:
|
||||
diff.differences.append(f"Missing column: {table.name}.{col.name}")
|
||||
continue
|
||||
expected = col.type.compile(dialect=connection.dialect)
|
||||
observed = current["type"].compile(dialect=connection.dialect)
|
||||
if not compatible_type(col.type, current["type"], connection.dialect):
|
||||
diff.differences.append(
|
||||
f"Column type: {table.name}.{col.name}: {observed} != {expected}"
|
||||
)
|
||||
if not col.primary_key and col.nullable != current["nullable"]:
|
||||
diff.differences.append(f"Nullability: {table.name}.{col.name}")
|
||||
expected_fks = {
|
||||
(
|
||||
tuple(fk.parent.name for fk in constraint.elements),
|
||||
constraint.elements[0].column.table.name,
|
||||
tuple(fk.column.name for fk in constraint.elements),
|
||||
)
|
||||
for constraint in table.foreign_key_constraints
|
||||
}
|
||||
actual_fks = {
|
||||
(tuple(fk["constrained_columns"]), fk["referred_table"], tuple(fk["referred_columns"]))
|
||||
for fk in inspector.get_foreign_keys(table.name)
|
||||
}
|
||||
if not expected_fks <= actual_fks:
|
||||
diff.differences.append("Missing foreign key: " + table.name)
|
||||
expected_unique = {
|
||||
tuple(c.name for c in constraint.columns)
|
||||
for constraint in table.constraints
|
||||
if constraint.__class__.__name__ == "UniqueConstraint"
|
||||
}
|
||||
observed_unique = {
|
||||
tuple(c["column_names"]) for c in inspector.get_unique_constraints(table.name)
|
||||
}
|
||||
observed_unique |= {
|
||||
tuple(c["column_names"]) for c in inspector.get_indexes(table.name) if c.get("unique")
|
||||
}
|
||||
if not expected_unique <= observed_unique:
|
||||
diff.differences.append("Missing unique constraint: " + table.name)
|
||||
expected_indexes = {tuple(c.name for c in index.columns) for index in table.indexes}
|
||||
observed_indexes = {tuple(c["column_names"]) for c in inspector.get_indexes(table.name)}
|
||||
if not expected_indexes <= observed_indexes:
|
||||
diff.differences.append("Missing index: " + table.name)
|
||||
return diff
|
||||
|
||||
|
||||
def check_schema_revision(connection, supported):
|
||||
inspector = inspect(connection)
|
||||
if "alembic_version" not in inspector.get_table_names():
|
||||
raise RuntimeError("Schema is unversioned; preflight and explicit migration required")
|
||||
revisions = set(connection.execute(text("SELECT version_num FROM alembic_version")).scalars())
|
||||
if len(revisions) != 1 or not revisions <= supported:
|
||||
raise RuntimeError("Unsupported schema revision")
|
||||
from app.models import Base
|
||||
|
||||
diff = schema_preflight(connection, Base.metadata)
|
||||
if not diff.matches:
|
||||
raise RuntimeError("Schema drift: " + "; ".join(diff.differences))
|
||||
55
backend/app/core/security.py
Normal file
55
backend/app/core/security.py
Normal file
@ -0,0 +1,55 @@
|
||||
from dataclasses import dataclass, field
|
||||
import hashlib, hmac, secrets
|
||||
from app.core.errors import fail
|
||||
|
||||
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 个字符")
|
||||
|
||||
|
||||
@dataclass
|
||||
class Actor:
|
||||
id: str
|
||||
username: str
|
||||
display_name: str
|
||||
role: str
|
||||
csrf_token: str
|
||||
token_hash: str
|
||||
auth_kind: str = "session"
|
||||
scopes: list[str] = field(default_factory=list)
|
||||
must_change_password: bool = False
|
||||
@ -1,116 +0,0 @@
|
||||
"""Transactional archival of owner records; execution and asset audit rows survive."""
|
||||
from sqlalchemy import delete, or_, select
|
||||
|
||||
from .errors import fail
|
||||
from .events import emit_asset
|
||||
from .models import Job, JobAsset, utcnow
|
||||
from .v2_models import AssetReference, Batch, Execution, Submission, WorkflowDraft, WorkflowRun, WorkflowStep
|
||||
|
||||
JOB_TERMINAL = {'succeeded', 'failed', 'cancelled', 'timed_out'}
|
||||
RUN_TERMINAL = {'succeeded', 'failed', 'cancelled'}
|
||||
BATCH_TERMINAL = {'succeeded', 'cancelled', 'completed_with_errors'}
|
||||
MODEL_KEYS = {Job: 'job_ids', WorkflowRun: 'run_ids', WorkflowDraft: 'draft_ids', Batch: 'batch_ids'}
|
||||
EVENT_NAMES = {Job: 'job.deleted', WorkflowRun: 'workflow.deleted', WorkflowDraft: 'draft.deleted', Batch: 'batch.deleted'}
|
||||
|
||||
|
||||
async def archive_records(session, model, record_id, owner_id, if_match=None):
|
||||
"""Validate the complete tree before changing anything in the caller's unit."""
|
||||
root = await session.scalar(select(model).where(model.id == record_id,
|
||||
model.owner_id == owner_id).with_for_update())
|
||||
if root is None:
|
||||
fail(404, 'resource_not_found', '记录不存在')
|
||||
groups = {Job: [], WorkflowRun: [], WorkflowDraft: [], Batch: []}
|
||||
groups[model] = [root]
|
||||
if model is WorkflowDraft:
|
||||
groups[WorkflowRun] = list((await session.scalars(select(WorkflowRun).where(
|
||||
WorkflowRun.owner_id == owner_id, WorkflowRun.draft_id == root.id)
|
||||
.order_by(WorkflowRun.created_at, WorkflowRun.id).with_for_update())).all())
|
||||
elif model is Batch:
|
||||
groups[WorkflowRun] = list((await session.scalars(select(WorkflowRun).where(
|
||||
WorkflowRun.owner_id == owner_id, WorkflowRun.batch_id == root.id)
|
||||
.order_by(WorkflowRun.created_at, WorkflowRun.id).with_for_update())).all())
|
||||
run_ids = [run.id for run in groups[WorkflowRun]]
|
||||
if model is not Job:
|
||||
child_filter = Job.run_id.in_(run_ids)
|
||||
if model is Batch:
|
||||
child_filter = or_(child_filter, Job.batch_id == root.id)
|
||||
groups[Job] = list((await session.scalars(select(Job).where(Job.owner_id == owner_id,
|
||||
child_filter).order_by(Job.created_at, Job.id).with_for_update())).all())
|
||||
result = {'deleted': {MODEL_KEYS[kind]: [row.id for row in rows] for kind, rows in groups.items()}}
|
||||
if root.deleted_at is not None:
|
||||
return result
|
||||
if if_match is not None and if_match.strip('"') != str(root.version):
|
||||
fail(409, 'version_conflict', '记录已更新,请刷新后重试删除')
|
||||
if model is Job and (root.run_id or root.batch_id):
|
||||
fail(409, 'parent_control_required', '请在所属工作流或批次中删除此任务')
|
||||
if model is WorkflowRun and root.batch_id:
|
||||
fail(409, 'parent_control_required', '请删除所属批次')
|
||||
if model is WorkflowDraft:
|
||||
batch_ids = {run.batch_id for run in groups[WorkflowRun] if run.batch_id and run.deleted_at is None}
|
||||
if batch_ids and await session.scalar(select(Batch.id).where(Batch.id.in_(batch_ids),
|
||||
Batch.owner_id == owner_id, Batch.deleted_at.is_(None)).limit(1)):
|
||||
fail(409, 'parent_control_required', '草稿仍有关联批次,请先删除所属批次')
|
||||
for kind, terminal in ((Job, JOB_TERMINAL), (WorkflowRun, RUN_TERMINAL), (Batch, BATCH_TERMINAL)):
|
||||
if any(row.deleted_at is None and row.state not in terminal for row in groups[kind]):
|
||||
fail(409, 'deletion_requires_terminal', '请先取消活动任务,等待执行结束后再删除')
|
||||
job_ids = [job.id for job in groups[Job]]
|
||||
executions = list((await session.scalars(select(Execution).where(Execution.job_id.in_(job_ids))
|
||||
.with_for_update())).all()) if job_ids else []
|
||||
if any(execution.state not in {'exited', 'results_ready'} for execution in executions):
|
||||
fail(409, 'cleanup_pending', '执行尚未确认清理,请等待清理完成后再删除')
|
||||
if job_ids:
|
||||
in_use = await session.scalar(select(WorkflowRun.id).join(WorkflowStep,
|
||||
WorkflowStep.run_id == WorkflowRun.id).where(WorkflowRun.deleted_at.is_(None),
|
||||
WorkflowRun.id.not_in(run_ids), WorkflowStep.selected_job_id.in_(job_ids)).limit(1))
|
||||
if in_use:
|
||||
fail(409, 'resource_in_use', '任务产物仍被其他工作流运行复用,请先删除该运行')
|
||||
now = utcnow()
|
||||
for kind in (Job, WorkflowRun, WorkflowDraft, Batch):
|
||||
for row in groups[kind]:
|
||||
if row.deleted_at is not None:
|
||||
continue
|
||||
row.deleted_at = now
|
||||
row.version += 1
|
||||
emit_asset(session, owner_id, EVENT_NAMES[kind], {'id': row.id, 'version': row.version})
|
||||
# A draft survives deletion of its last/current run or enclosing batch.
|
||||
if run_ids:
|
||||
drafts = (await session.scalars(select(WorkflowDraft).where(WorkflowDraft.owner_id == owner_id,
|
||||
WorkflowDraft.current_run_id.in_(run_ids), WorkflowDraft.deleted_at.is_(None)).with_for_update())).all()
|
||||
from .workflows import draft_dto
|
||||
for draft in drafts:
|
||||
draft.current_run_id = None
|
||||
draft.version += 1
|
||||
draft.updated_at = now
|
||||
emit_asset(session, owner_id, 'draft.updated', {'draft': draft_dto(draft)})
|
||||
for draft in groups[WorkflowDraft]:
|
||||
draft.current_run_id = None
|
||||
draft.updated_at = now
|
||||
if job_ids:
|
||||
await session.execute(delete(JobAsset).where(JobAsset.job_id.in_(job_ids)))
|
||||
refs = []
|
||||
if run_ids:
|
||||
refs.append((AssetReference.ref_kind == 'run') & AssetReference.ref_id.in_(run_ids))
|
||||
if groups[WorkflowDraft]:
|
||||
refs.append((AssetReference.ref_kind == 'draft') & AssetReference.ref_id.in_([d.id for d in groups[WorkflowDraft]]))
|
||||
if executions:
|
||||
refs.append((AssetReference.ref_kind == 'execution') & AssetReference.ref_id.in_([e.id for e in executions]))
|
||||
if refs:
|
||||
await session.execute(delete(AssetReference).where(AssetReference.owner_id == owner_id, or_(*refs)))
|
||||
archived_ids = {row.id for rows in groups.values() for row in rows}
|
||||
submissions = (await session.scalars(select(Submission).where(Submission.owner_id == owner_id,
|
||||
Submission.status != 'purged').with_for_update())).all()
|
||||
for submission in submissions:
|
||||
if references_any(submission.resource_json, archived_ids):
|
||||
submission.status = 'purged'
|
||||
await session.flush()
|
||||
return result
|
||||
|
||||
|
||||
def references_any(value, ids):
|
||||
if isinstance(value, str):
|
||||
return value in ids
|
||||
if isinstance(value, dict):
|
||||
return any(references_any(item, ids) for item in value.values())
|
||||
if isinstance(value, list):
|
||||
return any(references_any(item, ids) for item in value)
|
||||
return False
|
||||
0
backend/app/domain/__init__.py
Normal file
0
backend/app/domain/__init__.py
Normal file
165
backend/app/domain/editors.py
Normal file
165
backend/app/domain/editors.py
Normal file
@ -0,0 +1,165 @@
|
||||
"""编辑真源转换和时间冲突报告,不访问数据库。"""
|
||||
|
||||
from copy import deepcopy
|
||||
import re
|
||||
import uuid
|
||||
from pydantic import ValidationError
|
||||
from app.schemas.editors import EditorManifest
|
||||
from app.domain.timeline import WorkflowSpec
|
||||
from app.domain.stories import StorySpecV3
|
||||
from app.core.errors import fail
|
||||
|
||||
|
||||
def validate_manifest(manifest):
|
||||
try:
|
||||
m = EditorManifest.model_validate(manifest).model_dump(mode="json")
|
||||
raw = deepcopy(m["spec"])
|
||||
raw.pop("compiled", None)
|
||||
raw.setdefault("render", {}).update(audio=None, subtitles=[], total_frames=None)
|
||||
model = StorySpecV3 if m["source_kind"] == "story" else WorkflowSpec
|
||||
m["spec"] = model.model_validate(raw).model_dump(mode="json")
|
||||
ids = m["shot_ids"]
|
||||
if (
|
||||
len(ids) != len(m["spec"]["shots"])
|
||||
or len(set(ids)) != len(ids)
|
||||
or any(not re.fullmatch("[0-9a-f]{32}", i) for i in ids)
|
||||
):
|
||||
raise ValueError("shot_ids must match ordered shots")
|
||||
if m["source_kind"] == "story" and ids != [s["id"] for s in m["spec"]["shots"]]:
|
||||
raise ValueError("story shot_ids mismatch")
|
||||
for group in (m["audio"]["segments"], m["captions"]["cues"]):
|
||||
if len({x["id"] for x in group}) != len(group):
|
||||
raise ValueError("duplicate stable id")
|
||||
valid_keys = {f"{kind}:{id}" for kind in ("frame", "video") for id in ids}
|
||||
valid_keys.update("audio:" + x["id"] for x in m["audio"]["segments"])
|
||||
if set(m["bindings"]) - valid_keys:
|
||||
raise ValueError("unknown binding key")
|
||||
for key, b in m["bindings"].items():
|
||||
if (
|
||||
b["kind"]
|
||||
!= {"frame": "image", "video": "video", "audio": "audio"}[key.split(":")[0]]
|
||||
):
|
||||
raise ValueError("wrong binding kind")
|
||||
return m
|
||||
except (ValidationError, ValueError, TypeError, KeyError) as exc:
|
||||
fail(422, "invalid_editor_manifest", str(exc))
|
||||
|
||||
|
||||
def manifest_from_draft(draft):
|
||||
if draft.editor_manifest:
|
||||
return deepcopy(draft.editor_manifest)
|
||||
spec = deepcopy(draft.spec)
|
||||
spec.pop("compiled", None)
|
||||
spec.pop("render_inputs", None)
|
||||
story = draft.kind == "story_v3"
|
||||
ids = [
|
||||
s["id"] if story else uuid.uuid5(uuid.NAMESPACE_URL, f"editor:{draft.id}:{s['key']}").hex
|
||||
for s in spec["shots"]
|
||||
]
|
||||
old = spec.get("render", {})
|
||||
audio = {
|
||||
"mode": "manual_track" if old.get("audio") else "silent",
|
||||
"voice": "",
|
||||
"speed": 1.0,
|
||||
"track": old.get("audio"),
|
||||
"segments": [
|
||||
{
|
||||
"id": uuid.uuid5(uuid.NAMESPACE_URL, f"segment:{draft.id}:{id}").hex,
|
||||
"shot_id": id,
|
||||
"text": "",
|
||||
}
|
||||
for id in ids
|
||||
],
|
||||
}
|
||||
cues = [
|
||||
dict(
|
||||
id=uuid.uuid5(uuid.NAMESPACE_URL, f"cue:{draft.id}:{i}").hex,
|
||||
anchor="absolute",
|
||||
text_override=True,
|
||||
timing_override=True,
|
||||
**c,
|
||||
)
|
||||
for i, c in enumerate(old.get("subtitles", []))
|
||||
]
|
||||
return validate_manifest(
|
||||
dict(
|
||||
schema_version=1,
|
||||
source_kind="story" if story else "workflow",
|
||||
spec=spec,
|
||||
shot_ids=ids,
|
||||
bindings={},
|
||||
audio=audio,
|
||||
captions={"mode": "manual" if cues else "none", "cues": cues},
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def editor_issues(manifest):
|
||||
m = manifest
|
||||
shots = {
|
||||
id: s.get("edit", {}).get("duration_frames", s.get("duration_frames", 120))
|
||||
for id, s in zip(m["shot_ids"], m["spec"]["shots"])
|
||||
}
|
||||
total = sum(shots.values())
|
||||
segments = {s["id"]: s for s in m["audio"]["segments"]}
|
||||
issues = []
|
||||
|
||||
def issue(code, id, message):
|
||||
issues.append(dict(code=code, unit_id=id, message=message))
|
||||
|
||||
for s in segments.values():
|
||||
if s["shot_id"] not in shots:
|
||||
issue("orphan_audio_segment", s["id"], "配音段引用的镜头不存在")
|
||||
for c in m["captions"]["cues"]:
|
||||
limit = total
|
||||
if c["anchor"] == "shot":
|
||||
limit = shots.get(c["shot_id"])
|
||||
elif c["anchor"] == "audio_segment":
|
||||
segment = segments.get(c["segment_id"])
|
||||
limit = shots.get(segment["shot_id"]) if segment else None
|
||||
if limit is None:
|
||||
issue("orphan_caption_anchor", c["id"], "字幕锚点不存在")
|
||||
elif c["start_frame"] < 0 or c["end_frame"] <= c["start_frame"] or c["end_frame"] > limit:
|
||||
issue("invalid_timeline", c["id"], "字幕时间超出锚点范围")
|
||||
a = m["audio"].get("track")
|
||||
if m["audio"]["mode"] == "manual_track":
|
||||
if not a:
|
||||
issue("missing_audio_track", "audio", "请选择音轨")
|
||||
elif a["offset_frame"] + (a["source_end_ms"] - a["source_start_ms"]) * 24 / 1000 > total:
|
||||
issue("invalid_timeline", "audio", "音轨超出成片范围")
|
||||
return issues
|
||||
|
||||
|
||||
def collect_manifest_asset_ids(manifest):
|
||||
result = set()
|
||||
|
||||
def visit(value):
|
||||
if isinstance(value, dict):
|
||||
for k, v in value.items():
|
||||
if k.endswith("asset_id") and isinstance(v, str):
|
||||
result.add(v)
|
||||
elif k.endswith("asset_ids") and isinstance(v, list):
|
||||
result.update(v)
|
||||
else:
|
||||
visit(v)
|
||||
elif isinstance(value, list):
|
||||
for item in value:
|
||||
visit(item)
|
||||
|
||||
visit(manifest)
|
||||
return result
|
||||
|
||||
|
||||
def editing_mode(draft):
|
||||
return (
|
||||
(draft.editor_manifest or {}).get("editing_mode", "auto")
|
||||
if draft.editor_manifest
|
||||
else "manual"
|
||||
)
|
||||
|
||||
|
||||
def is_editor_auto(draft):
|
||||
return bool(draft.editor_manifest) and editing_mode(draft) == "auto"
|
||||
|
||||
|
||||
MODE_CAPABILITIES = {"mode_switch": True, "manual": True, "auto": True, "name_edit": True}
|
||||
7
backend/app/domain/errors.py
Normal file
7
backend/app/domain/errors.py
Normal file
@ -0,0 +1,7 @@
|
||||
"""领域任务错误,不依赖 HTTP、数据库或具体模型。"""
|
||||
|
||||
|
||||
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
|
||||
27
backend/app/domain/execution.py
Normal file
27
backend/app/domain/execution.py
Normal file
@ -0,0 +1,27 @@
|
||||
"""执行结果与任务阶段上下文,不引入 HTTP、数据库或适配器。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from contextvars import ContextVar
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Awaitable, Callable
|
||||
|
||||
PhaseCallback = Callable[[str, str], Awaitable[None]]
|
||||
# ContextVar 按 asyncio 任务隔离;共享同一对象让媒体与 HTTP 阶段使用同一准入边界。
|
||||
current_phase_callback: ContextVar[PhaseCallback | None] = ContextVar(
|
||||
"current_phase_callback", default=None
|
||||
)
|
||||
|
||||
|
||||
async def enter_phase(phase_key: str, resource_pool: str) -> None:
|
||||
callback = current_phase_callback.get()
|
||||
if callback is not None:
|
||||
await callback(phase_key, resource_pool)
|
||||
|
||||
|
||||
@dataclass
|
||||
class CpuResult:
|
||||
outputs: list[Path]
|
||||
result: dict
|
||||
metadata: dict
|
||||
102
backend/app/domain/gpu_summary.py
Normal file
102
backend/app/domain/gpu_summary.py
Normal file
@ -0,0 +1,102 @@
|
||||
"""Public GPU summary. Never expose scheduler job IDs or host PID details."""
|
||||
|
||||
import math
|
||||
from datetime import datetime, timezone
|
||||
|
||||
|
||||
def summarize(gpus, scheduler, now, generated):
|
||||
active, queued = [], None
|
||||
try:
|
||||
stamp = scheduler["updated_at"]
|
||||
if (
|
||||
type(stamp) not in (int, float)
|
||||
or not math.isfinite(stamp)
|
||||
or not now - 5 <= stamp <= now + 1
|
||||
):
|
||||
raise ValueError("Stale scheduler")
|
||||
if scheduler.get("schema_version") == 2:
|
||||
entries = scheduler.get("active_jobs", [])
|
||||
if not isinstance(entries, list) or len(entries) > len(gpus):
|
||||
raise ValueError("Invalid active list")
|
||||
indexes = set()
|
||||
for entry in entries:
|
||||
index = entry["gpu_index"]
|
||||
if (
|
||||
type(index) is not int
|
||||
or index in indexes
|
||||
or not any(
|
||||
row["index"] == index and row["_uuid"] == entry["gpu_uuid"] for row in gpus
|
||||
)
|
||||
):
|
||||
raise ValueError("Invalid lease")
|
||||
indexes.add(index)
|
||||
count = scheduler.get("queued_count")
|
||||
if count is not None and (type(count) is not int or not 0 <= count <= 10000000):
|
||||
raise ValueError("Invalid queue count")
|
||||
active, queued = entries, count
|
||||
elif scheduler.get("state") == "leased":
|
||||
lease = scheduler.get("lease") or {}
|
||||
active = [
|
||||
{"gpu_index": lease.get("index"), "gpu_uuid": lease.get("uuid"), "state": "running"}
|
||||
]
|
||||
except (KeyError, TypeError, ValueError):
|
||||
scheduler, active, queued = None, [], None
|
||||
active_indexes = set()
|
||||
for entry in active:
|
||||
gpu = next(
|
||||
(
|
||||
row
|
||||
for row in gpus
|
||||
if row["index"] == entry.get("gpu_index") and row["_uuid"] == entry.get("gpu_uuid")
|
||||
),
|
||||
None,
|
||||
)
|
||||
if gpu is None:
|
||||
continue
|
||||
active_indexes.add(gpu["index"])
|
||||
state = entry.get("state")
|
||||
gpu.update(
|
||||
busy=True,
|
||||
eligible=False,
|
||||
state=state if state in {"preempting", "blocked", "launching"} else "running",
|
||||
stage=entry.get("stage")
|
||||
if entry.get("stage")
|
||||
in {"launching", "executing", "cleanup", "model", "upscale", "collecting"}
|
||||
else None,
|
||||
)
|
||||
running = sum(row["index"] in active_indexes or row["_own"] for row in gpus)
|
||||
available = sum(row["eligible"] for row in gpus)
|
||||
state = "running" if running else "ready" if available else "waiting"
|
||||
reason = (
|
||||
f"正在运行{running}个GPU任务,{available}张卡可接新任务。"
|
||||
if running
|
||||
else None
|
||||
if available
|
||||
else "等待可用GPU,外部任务优先。"
|
||||
)
|
||||
dispatch_blocked = bool(scheduler and scheduler.get("state") == "blocked")
|
||||
if dispatch_blocked:
|
||||
reason = "执行器需要管理员检查,新任务暂停派发。"
|
||||
if not running:
|
||||
state = "blocked"
|
||||
available = 0
|
||||
for gpu in gpus:
|
||||
gpu["eligible"] = False
|
||||
if gpu["state"] == "ready":
|
||||
gpu["state"] = "waiting"
|
||||
elif scheduler and "memory" in str(scheduler.get("reason", "")).lower():
|
||||
reason = "共享内存不足,任务按入队顺序等待资源。"
|
||||
for gpu in gpus:
|
||||
gpu.pop("_uuid")
|
||||
gpu.pop("_own")
|
||||
return {
|
||||
"available": True,
|
||||
"state": state,
|
||||
"reason": reason,
|
||||
"gpus": gpus,
|
||||
"running_count": running,
|
||||
"available_count": available,
|
||||
"queued_count": queued,
|
||||
"dispatch_blocked": dispatch_blocked,
|
||||
"updated_at": datetime.fromtimestamp(generated, timezone.utc).isoformat(),
|
||||
}
|
||||
341
backend/app/domain/stories.py
Normal file
341
backend/app/domain/stories.py
Normal file
@ -0,0 +1,341 @@
|
||||
"""独立 v3 故事模型及确定性编译,不读数据库或调用语言模型。"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
import hashlib
|
||||
import json
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import Field, model_validator
|
||||
from app.domain.timeline import Strict, Render, MAX_WORKFLOW_SHOTS
|
||||
|
||||
ID = r"^[0-9a-f]{32}$"
|
||||
|
||||
|
||||
def digest(value):
|
||||
return hashlib.sha256(
|
||||
json.dumps(
|
||||
value, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False
|
||||
).encode()
|
||||
).hexdigest()
|
||||
|
||||
|
||||
class Context(Strict):
|
||||
era: str = ""
|
||||
style: str = ""
|
||||
palette: str = ""
|
||||
lighting: str = ""
|
||||
negative_prompt: str = ""
|
||||
|
||||
|
||||
class Variant(Strict):
|
||||
id: str = Field(pattern=ID)
|
||||
name: str = ""
|
||||
description: str = ""
|
||||
reference_asset_ids: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class Entity(Variant):
|
||||
kind: Literal["person", "creature", "prop"] = "person"
|
||||
forms: list[Variant] = Field(default_factory=list)
|
||||
appearances: list[Variant] = Field(default_factory=list)
|
||||
|
||||
|
||||
class Scene(Variant):
|
||||
location: str = ""
|
||||
time: str = ""
|
||||
weather: str = ""
|
||||
lighting: str = ""
|
||||
|
||||
|
||||
class Cast(Strict):
|
||||
id: str = Field(pattern=ID)
|
||||
entity_id: str = Field(pattern=ID)
|
||||
form_id: str | None = Field(default=None, pattern=ID)
|
||||
appearance_id: str | None = Field(default=None, pattern=ID)
|
||||
position: str = ""
|
||||
action: str = ""
|
||||
|
||||
|
||||
class Overrides(Strict):
|
||||
time: str | None = None
|
||||
weather: str | None = None
|
||||
lighting: str | None = None
|
||||
palette: str | None = None
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def no_null(cls, value):
|
||||
if isinstance(value, dict) and any(v is None for v in value.values()):
|
||||
raise ValueError("override must be a string; remove key to inherit")
|
||||
return value
|
||||
|
||||
def model_dump(self, **kwargs):
|
||||
return super().model_dump(exclude_unset=True, **kwargs)
|
||||
|
||||
|
||||
class FrameParameters(Strict):
|
||||
seed: int = Field(default=42, ge=0, le=2**32 - 1)
|
||||
|
||||
|
||||
class VideoParameters(FrameParameters):
|
||||
source_seconds: int = Field(default=5, ge=1, le=15)
|
||||
num_inference_steps: int = Field(default=50, ge=1, le=100)
|
||||
guidance_scale: float = Field(default=5.0, ge=1, le=20, allow_inf_nan=False)
|
||||
upscale: bool = True
|
||||
|
||||
|
||||
class Edit(Strict):
|
||||
start_frame: int = Field(default=0, ge=0)
|
||||
duration_frames: int = Field(default=120, ge=24, le=360)
|
||||
|
||||
|
||||
class StoryShot(Strict):
|
||||
id: str = Field(pattern=ID)
|
||||
name: str = ""
|
||||
scene_id: str | None = Field(default=None, pattern=ID)
|
||||
cast: list[Cast] = Field(default_factory=list)
|
||||
visual_prompt: str = Field(default="", max_length=8000)
|
||||
motion_prompt: str = Field(default="", max_length=8000)
|
||||
overrides: Overrides = Field(default_factory=Overrides)
|
||||
frame_parameters: FrameParameters = Field(default_factory=FrameParameters)
|
||||
video_parameters: VideoParameters = Field(default_factory=VideoParameters)
|
||||
edit: Edit = Field(default_factory=Edit)
|
||||
|
||||
|
||||
class StorySpecV3(Strict):
|
||||
schema_version: Literal[3] = 3
|
||||
profile: Literal["landscape_1080_v1", "portrait_1080_v1"] = "landscape_1080_v1"
|
||||
context: Context = Field(default_factory=Context)
|
||||
scenes: list[Scene] = Field(default_factory=list)
|
||||
entities: list[Entity] = Field(default_factory=list)
|
||||
shots: list[StoryShot] = Field(min_length=1, max_length=MAX_WORKFLOW_SHOTS)
|
||||
render: Render = Field(default_factory=Render)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def consistent(self):
|
||||
all_ids = []
|
||||
for collection in (self.scenes, self.entities, self.shots):
|
||||
all_ids.extend(x.id for x in collection)
|
||||
for entity in self.entities:
|
||||
all_ids.extend(x.id for x in entity.forms + entity.appearances)
|
||||
for shot in self.shots:
|
||||
all_ids.extend(x.id for x in shot.cast)
|
||||
if len(set(all_ids)) != len(all_ids):
|
||||
raise ValueError("duplicate stable id")
|
||||
scenes = {x.id for x in self.scenes}
|
||||
entities = {x.id: x for x in self.entities}
|
||||
for shot in self.shots:
|
||||
if shot.scene_id and shot.scene_id not in scenes:
|
||||
raise ValueError("scene reference missing")
|
||||
for cast in shot.cast:
|
||||
entity = entities.get(cast.entity_id)
|
||||
if (
|
||||
entity is None
|
||||
or (cast.form_id and cast.form_id not in {x.id for x in entity.forms})
|
||||
or (
|
||||
cast.appearance_id
|
||||
and cast.appearance_id not in {x.id for x in entity.appearances}
|
||||
)
|
||||
):
|
||||
raise ValueError("entity/form/appearance reference missing")
|
||||
# 生成源长度不代表人工素材长度;实际选用范围由候选来源与媒体帧数校验。
|
||||
frames = sum(s.edit.duration_frames for s in self.shots)
|
||||
if self.render.total_frames is not None and self.render.total_frames != frames:
|
||||
raise ValueError("total_frames differs from edits")
|
||||
self.render.total_frames = frames
|
||||
if any(s.end_frame > frames for s in self.render.subtitles):
|
||||
raise ValueError("subtitle exceeds canvas")
|
||||
audio = self.render.audio
|
||||
if audio and (
|
||||
audio.offset_frame >= frames
|
||||
or (audio.source_end_ms - audio.source_start_ms) * 24
|
||||
> (frames - audio.offset_frame) * 1000
|
||||
):
|
||||
raise ValueError("audio exceeds canvas")
|
||||
return self
|
||||
|
||||
def model_dump(self, **kwargs):
|
||||
data = super().model_dump(**kwargs)
|
||||
for shot, model in zip(data["shots"], self.shots):
|
||||
shot["overrides"] = model.overrides.model_dump()
|
||||
return data
|
||||
|
||||
|
||||
def ordered_reference_ids(references):
|
||||
"""编号与模型输入共享同一首次去重顺序,角色清单自身不去重。"""
|
||||
return list(dict.fromkeys(ref["asset_id"] for ref in references))
|
||||
|
||||
|
||||
def reference_binding_suffix(references):
|
||||
if not references:
|
||||
return ""
|
||||
lines = []
|
||||
for index, asset_id in enumerate(ordered_reference_ids(references), 1):
|
||||
labels = list(
|
||||
dict.fromkeys(
|
||||
(ref["role"], ref["label"]) for ref in references if ref["asset_id"] == asset_id
|
||||
)
|
||||
)
|
||||
bindings = "; ".join(
|
||||
f"{role} {json.dumps(label, ensure_ascii=False)}" for role, label in labels
|
||||
)
|
||||
lines.append(f"Picture {index}: {bindings}.")
|
||||
return (
|
||||
"\n\nReference image bindings (Picture numbers follow the attached image order):\n"
|
||||
+ "\n".join(lines)
|
||||
+ "\nUse scene references for the setting and background. Use entity, form and appearance references only for their named subject; preserve its identity, selected form and costume. Compose one frame according to the shot description; do not draw the Picture labels."
|
||||
)
|
||||
|
||||
|
||||
def text_frame_prompt(compiled_shot):
|
||||
"""显式文生图不声称已附图,只移除编译器确定追加的映射后缀。"""
|
||||
return compiled_shot["frame_prompt"].removesuffix(
|
||||
reference_binding_suffix(compiled_shot["references"])
|
||||
)
|
||||
|
||||
|
||||
def compile_story(spec, assets):
|
||||
spec = spec if isinstance(spec, StorySpecV3) else StorySpecV3.model_validate(spec)
|
||||
scenes, entities = {s.id: s for s in spec.scenes}, {e.id: e for e in spec.entities}
|
||||
results = []
|
||||
for shot in spec.shots:
|
||||
scene = scenes.get(shot.scene_id)
|
||||
effective = spec.context.model_dump()
|
||||
if scene:
|
||||
effective.update(
|
||||
{k: getattr(scene, k) for k in ("time", "weather", "lighting") if getattr(scene, k)}
|
||||
)
|
||||
effective.update(shot.overrides.model_dump())
|
||||
parts = [f"{k}: {v}" for k, v in effective.items() if v and k != "negative_prompt"]
|
||||
bound_parts = list(parts)
|
||||
aliases = {}
|
||||
for cast in shot.cast:
|
||||
if cast.entity_id not in aliases:
|
||||
entity = entities[cast.entity_id]
|
||||
kind = {"person": "Character", "creature": "Creature", "prop": "Prop"}[entity.kind]
|
||||
aliases[entity.id] = f"{kind} {len(aliases) + 1} / {entity.name or entity.kind}"
|
||||
bound_items = set()
|
||||
refs = []
|
||||
errors = []
|
||||
|
||||
def include(item, role, label):
|
||||
parts.extend(v for v in (item.name, item.description) if v)
|
||||
if (role, item.id) not in bound_items:
|
||||
bound_items.add((role, item.id))
|
||||
description = f": {item.description}" if item.description else ""
|
||||
bound_parts.append(f"{role} {json.dumps(label, ensure_ascii=False)}{description}")
|
||||
for asset_id in item.reference_asset_ids:
|
||||
asset = assets.get(asset_id)
|
||||
sha = (
|
||||
asset.get("sha256")
|
||||
if isinstance(asset, dict)
|
||||
else getattr(asset, "sha256", None)
|
||||
)
|
||||
refs.append({"asset_id": asset_id, "sha256": sha, "role": role, "label": label})
|
||||
if not sha:
|
||||
errors.append(
|
||||
{
|
||||
"code": "reference_unavailable",
|
||||
"message": "参考素材不存在或不可访问",
|
||||
"asset_id": asset_id,
|
||||
}
|
||||
)
|
||||
|
||||
if scene:
|
||||
scene_alias = f"Scene 1 / {scene.name or 'unnamed scene'}"
|
||||
include(scene, "scene", scene_alias)
|
||||
if scene.location:
|
||||
parts.append(scene.location)
|
||||
bound_parts.append(
|
||||
f"{json.dumps(scene_alias, ensure_ascii=False)} location: {scene.location}"
|
||||
)
|
||||
for cast in shot.cast:
|
||||
entity = entities[cast.entity_id]
|
||||
alias = aliases[entity.id]
|
||||
include(entity, "entity", alias)
|
||||
for key, role in (("form_id", "form"), ("appearance_id", "appearance")):
|
||||
selected = getattr(cast, key)
|
||||
if selected:
|
||||
variant = next(
|
||||
v
|
||||
for v in getattr(entity, "forms" if role == "form" else "appearances")
|
||||
if v.id == selected
|
||||
)
|
||||
include(
|
||||
variant,
|
||||
role,
|
||||
f"{alias} / {variant.name or role}",
|
||||
)
|
||||
parts.extend(v for v in (cast.position, cast.action) if v)
|
||||
for key in ("position", "action"):
|
||||
if value := getattr(cast, key):
|
||||
bound_parts.append(f"{json.dumps(alias, ensure_ascii=False)} {key}: {value}")
|
||||
parts.append(shot.visual_prompt)
|
||||
bound_parts.append(shot.visual_prompt)
|
||||
if refs:
|
||||
bound_parts.insert(
|
||||
0,
|
||||
"Use the following subject aliases to bind descriptions and spatial relations; do not draw these alias labels or numbers as text.",
|
||||
)
|
||||
prompt = "\n".join(
|
||||
p for p in (bound_parts if refs else parts) if p
|
||||
) + reference_binding_suffix(refs)
|
||||
if not prompt.strip():
|
||||
errors.append({"code": "prompt_required", "message": "请输入镜头画面描述"})
|
||||
if len(prompt) > 8000:
|
||||
errors.append({"code": "prompt_too_long", "message": "编译提示词超过8000字符"})
|
||||
visual = {
|
||||
"prompt": prompt,
|
||||
"settings": effective,
|
||||
"references": refs,
|
||||
"profile": spec.profile,
|
||||
}
|
||||
results.append(
|
||||
{
|
||||
"shot_id": shot.id,
|
||||
"context_hash": digest(visual),
|
||||
"frame_prompt": prompt,
|
||||
"motion_prompt": shot.motion_prompt,
|
||||
"references": refs,
|
||||
"effective_settings": effective,
|
||||
"errors": errors,
|
||||
}
|
||||
)
|
||||
return {"shots": results, "errors": []}
|
||||
|
||||
|
||||
def canvas(profile):
|
||||
return (1080, 1920) if profile == "portrait_1080_v1" else (1920, 1080)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StoryRenderPlan:
|
||||
spec: dict
|
||||
canvas: tuple
|
||||
frames: int
|
||||
clips: tuple
|
||||
fps: int = 24
|
||||
|
||||
|
||||
def compile_story_render(spec, render_inputs):
|
||||
model = StorySpecV3.model_validate(spec)
|
||||
clips = render_inputs["clips"]
|
||||
if (
|
||||
len(clips) != len(model.shots)
|
||||
or render_inputs.get("fps") != 24
|
||||
or render_inputs.get("canvas") != list(canvas(model.profile))
|
||||
):
|
||||
raise ValueError("invalid story render inputs")
|
||||
for shot, clip in zip(model.shots, clips):
|
||||
if (
|
||||
shot.id != clip["shot_id"]
|
||||
or shot.edit.start_frame != clip["start_frame"]
|
||||
or shot.edit.duration_frames != clip["duration_frames"]
|
||||
):
|
||||
raise ValueError("frozen trim differs from spec")
|
||||
return StoryRenderPlan(
|
||||
model.model_dump(mode="json"),
|
||||
canvas(model.profile),
|
||||
model.render.total_frames,
|
||||
tuple(clips),
|
||||
)
|
||||
22
backend/app/domain/tasks.py
Normal file
22
backend/app/domain/tasks.py
Normal file
@ -0,0 +1,22 @@
|
||||
"""任务分类与完成态;不读取配置、不访问数据库或模型。"""
|
||||
|
||||
GPU_TYPES = {
|
||||
"image.generate",
|
||||
"image.reference.generate",
|
||||
"video.generate",
|
||||
"video.people.analyze",
|
||||
"video.replace",
|
||||
"defect.generate",
|
||||
"audio.transcribe",
|
||||
}
|
||||
CPU_TYPES = {
|
||||
"image.prepare_frame",
|
||||
"math.solve",
|
||||
"media.structure",
|
||||
"video.compose",
|
||||
"audio.speech",
|
||||
"text.script.generate",
|
||||
"audio.assemble",
|
||||
}
|
||||
TERMINAL = {"succeeded", "failed", "cancelled", "timed_out"}
|
||||
RUN_TERMINAL = {"succeeded", "cancelled", "failed"}
|
||||
196
backend/app/domain/timeline.py
Normal file
196
backend/app/domain/timeline.py
Normal file
@ -0,0 +1,196 @@
|
||||
"""Versioned short-clip story contract. Public fields contain no executable paths."""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Literal
|
||||
import re
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_serializer, model_validator
|
||||
|
||||
DEFAULT_CLIP_FRAMES = 120
|
||||
MAX_CLIP_FRAMES = 360
|
||||
DEFAULT_SOURCE_FRAMES = 121
|
||||
MAX_SOURCE_FRAMES = 361
|
||||
MAX_WORKFLOW_SHOTS = 1000
|
||||
MAX_TIMELINE_FRAMES = MAX_WORKFLOW_SHOTS * MAX_CLIP_FRAMES
|
||||
|
||||
|
||||
class Strict(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", strict=True)
|
||||
|
||||
|
||||
class ShotParameters(Strict):
|
||||
seed: int = Field(default=42, ge=0, le=2**32 - 1)
|
||||
|
||||
|
||||
class Shot(Strict):
|
||||
key: str = Field(pattern=r"^shot_[1-9][0-9]{0,3}$")
|
||||
prompt: str = Field(min_length=1, max_length=8000)
|
||||
duration_frames: int = Field(default=DEFAULT_CLIP_FRAMES, ge=24, le=MAX_CLIP_FRAMES)
|
||||
image_asset_id: str | None = Field(default=None, min_length=1, max_length=64)
|
||||
parameters: ShotParameters = Field(default_factory=ShotParameters)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def prompt_required(self):
|
||||
if not self.prompt.strip():
|
||||
raise ValueError("prompt_required")
|
||||
return self
|
||||
|
||||
|
||||
class Subtitle(Strict):
|
||||
start_frame: int = Field(ge=0)
|
||||
end_frame: int = Field(gt=0)
|
||||
text: str = Field(min_length=1, max_length=2000)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def safe(self):
|
||||
if (
|
||||
self.end_frame <= self.start_frame
|
||||
or not self.text.strip()
|
||||
or re.search(r"[\\{}\x00-\x1f\x7f]", self.text)
|
||||
):
|
||||
raise ValueError("invalid_timeline: subtitle")
|
||||
return self
|
||||
|
||||
|
||||
class Audio(Strict):
|
||||
asset_id: str = Field(min_length=1, max_length=64)
|
||||
source_start_ms: int = Field(ge=0)
|
||||
source_end_ms: int = Field(gt=0)
|
||||
offset_frame: int = Field(default=0, ge=0)
|
||||
short_policy: Literal["silence"] = "silence"
|
||||
|
||||
@model_validator(mode="after")
|
||||
def fits(self):
|
||||
if self.source_end_ms <= self.source_start_ms:
|
||||
raise ValueError("invalid_timeline: invalid audio selection")
|
||||
return self
|
||||
|
||||
|
||||
class Render(Strict):
|
||||
fps: Literal[24] = 24
|
||||
total_frames: int | None = Field(default=None, ge=1, le=MAX_TIMELINE_FRAMES)
|
||||
fit: Literal["contain", "cover"] = "contain"
|
||||
audio: Audio | None = None
|
||||
subtitles: list[Subtitle] = Field(default_factory=list, max_length=1000)
|
||||
template_version: Literal["plain-v1"] = "plain-v1"
|
||||
|
||||
|
||||
class WorkflowSpec(Strict):
|
||||
schema_version: Literal[1, 2] = 1
|
||||
shots: list[Shot] = Field(min_length=1, max_length=MAX_WORKFLOW_SHOTS)
|
||||
profile: Literal["landscape_1080_v1", "portrait_1080_v1"] = "landscape_1080_v1"
|
||||
render: Render = Field(default_factory=Render)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def ordered_timeline(self):
|
||||
if self.schema_version == 1 and (
|
||||
len(self.shots) != 3 or any("duration_frames" in s.model_fields_set for s in self.shots)
|
||||
):
|
||||
raise ValueError("schema_version 1 requires three full-length shots")
|
||||
if [s.key for s in self.shots] != [f"shot_{i}" for i in range(1, len(self.shots) + 1)]:
|
||||
raise ValueError("exact ordered sequential shot keys required")
|
||||
frames = sum(s.duration_frames for s in self.shots)
|
||||
if frames > MAX_TIMELINE_FRAMES:
|
||||
raise ValueError("invalid_timeline: total frames exceed maximum story length")
|
||||
if self.render.total_frames is not None and self.render.total_frames != frames:
|
||||
raise ValueError("invalid_timeline: total_frames differs from shots")
|
||||
self.render.total_frames = frames
|
||||
if any(c.end_frame > frames for c in self.render.subtitles):
|
||||
raise ValueError("invalid_timeline: subtitle exceeds canvas")
|
||||
audio = self.render.audio
|
||||
if audio and (
|
||||
audio.offset_frame >= frames
|
||||
or (audio.source_end_ms - audio.source_start_ms) * 24
|
||||
> (frames - audio.offset_frame) * 1000
|
||||
):
|
||||
raise ValueError("invalid_timeline: audio exceeds canvas")
|
||||
return self
|
||||
|
||||
@model_serializer(mode="wrap")
|
||||
def legacy_compatible_dump(self, handler):
|
||||
data = handler(self)
|
||||
if self.schema_version == 1:
|
||||
for shot in data["shots"]:
|
||||
shot.pop("duration_frames", None)
|
||||
return data
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TimelinePlan:
|
||||
spec: dict
|
||||
generation_parameters: dict
|
||||
canvas: tuple[int, int]
|
||||
frames: int = 360
|
||||
clip_frames: int = 120
|
||||
fps: int = 24
|
||||
shot_frames: tuple[int, ...] = ()
|
||||
shot_generation_parameters: dict[str, dict] = field(default_factory=dict)
|
||||
|
||||
|
||||
def ordered_step_keys(snapshot):
|
||||
"""The frozen shot array is authoritative, including shot_10 and later."""
|
||||
if snapshot.get("schema_version") == 3:
|
||||
return ["compose"]
|
||||
return [shot["key"] for shot in snapshot["shots"]] + ["compose"]
|
||||
|
||||
|
||||
def generation_parameters_for_shot(snapshot, key):
|
||||
"""只读取已冻结源参数;仅旧快照完全缺少 map 时回退,不能从当前草稿重算。"""
|
||||
compiled = snapshot["compiled"]
|
||||
if "shot_generation_parameters" not in compiled:
|
||||
return compiled["generation_parameters"]
|
||||
parameters = compiled["shot_generation_parameters"]
|
||||
if (
|
||||
not isinstance(parameters, dict)
|
||||
or key not in parameters
|
||||
or not isinstance(parameters[key], dict)
|
||||
or "num_frames" not in parameters[key]
|
||||
):
|
||||
raise ValueError("Frozen shot generation parameters are incomplete")
|
||||
return parameters[key]
|
||||
|
||||
|
||||
def compile_timeline(spec, owned_assets) -> TimelinePlan:
|
||||
spec = spec if isinstance(spec, WorkflowSpec) else WorkflowSpec.model_validate(spec)
|
||||
audio = spec.render.audio
|
||||
if audio:
|
||||
asset = owned_assets.get(audio.asset_id)
|
||||
|
||||
def field(name):
|
||||
return asset.get(name) if isinstance(asset, dict) else getattr(asset, name, None)
|
||||
|
||||
if (
|
||||
asset is None
|
||||
or field("kind") != "audio"
|
||||
or field("duration_seconds") is None
|
||||
or audio.source_end_ms > round(field("duration_seconds") * 1000)
|
||||
):
|
||||
raise ValueError("invalid_timeline: audio source cut exceeds source")
|
||||
portrait = spec.profile == "portrait_1080_v1"
|
||||
parameters = dict(
|
||||
width=704 if portrait else 1280,
|
||||
height=1280 if portrait else 704,
|
||||
num_frames=DEFAULT_SOURCE_FRAMES,
|
||||
fps=24,
|
||||
upscale=True,
|
||||
upscale_width=1056 if portrait else 1920,
|
||||
upscale_height=1920 if portrait else 1056,
|
||||
num_inference_steps=50,
|
||||
guidance_scale=5.0,
|
||||
tile_size=128,
|
||||
)
|
||||
# 原生源长按每个镜头独立取 4n+1;短片保持 121 帧,使旧的 trim-only 复用哈希不变。
|
||||
per_shot = {
|
||||
shot.key: {
|
||||
**parameters,
|
||||
"num_frames": max(DEFAULT_SOURCE_FRAMES, 4 * ((shot.duration_frames + 3) // 4) + 1),
|
||||
}
|
||||
for shot in spec.shots
|
||||
}
|
||||
return TimelinePlan(
|
||||
spec.model_dump(mode="json"),
|
||||
parameters,
|
||||
(1080, 1920) if portrait else (1920, 1080),
|
||||
frames=spec.render.total_frames,
|
||||
shot_frames=tuple(s.duration_frames for s in spec.shots),
|
||||
shot_generation_parameters=per_shot,
|
||||
)
|
||||
188
backend/app/domain/video_editing.py
Normal file
188
backend/app/domain/video_editing.py
Normal file
@ -0,0 +1,188 @@
|
||||
"""视频编辑的纯参数与公开分析合同;不接受客户端路径或遮罩。"""
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator
|
||||
from app.domain.errors import MediaError
|
||||
|
||||
PROFILE = "wan-animate-replace-v1"
|
||||
TASKS = {"video.people.analyze", "video.replace"}
|
||||
|
||||
|
||||
def video_capability(settings):
|
||||
available = bool(getattr(settings, "video_edit_enabled", False) and settings.inference_base_url)
|
||||
return {
|
||||
"available": available,
|
||||
"profile": getattr(settings, "video_edit_profile", PROFILE),
|
||||
"model": "Wan2.2-Animate-14B",
|
||||
"max_seconds": getattr(settings, "video_edit_max_seconds", 120),
|
||||
"max_people": getattr(settings, "video_edit_max_people", 12),
|
||||
"max_pixels": getattr(settings, "video_edit_max_pixels", 399360),
|
||||
"fps": 24,
|
||||
"reason": None if available else "视频编辑尚未启用或未完成模型认证。",
|
||||
}
|
||||
|
||||
|
||||
def video_defaults(task, settings):
|
||||
value = {
|
||||
"profile": getattr(settings, "video_edit_profile", PROFILE),
|
||||
"max_pixels": 399360,
|
||||
"fps": 24,
|
||||
}
|
||||
if task == "video.replace":
|
||||
value.update(
|
||||
num_inference_steps=20,
|
||||
guidance_scale=1.0,
|
||||
seed=42,
|
||||
preserve_audio=True,
|
||||
mask_expand_pixels=8,
|
||||
mask_feather_pixels=4,
|
||||
)
|
||||
return value
|
||||
|
||||
|
||||
def invalid(message="视频编辑输入或参数无效。"):
|
||||
return MediaError("invalid_input", message)
|
||||
|
||||
|
||||
def validate_video_arguments(task, inputs, parameters, settings):
|
||||
# 参数校验也用于Provider;服务器绑定通过单独参数传递,不能混入浏览器input。
|
||||
if not video_capability(settings)["available"]:
|
||||
raise MediaError("capability_unavailable", "视频编辑尚未启用或未认证。")
|
||||
allowed = {"video_asset_id"}
|
||||
if task == "video.replace":
|
||||
allowed |= {"analysis_job_id", "prompt", "negative_prompt", "replacements"}
|
||||
if not isinstance(inputs, dict) or set(inputs) - allowed:
|
||||
raise invalid()
|
||||
for key in ("video_asset_id", "analysis_job_id"):
|
||||
if (key == "video_asset_id" or task == "video.replace") and (
|
||||
not isinstance(inputs.get(key), str) or not 1 <= len(inputs[key]) <= 64
|
||||
):
|
||||
raise invalid()
|
||||
defaults = video_defaults(task, settings)
|
||||
if not isinstance(parameters, dict) or set(parameters) - set(defaults):
|
||||
raise invalid()
|
||||
p = defaults | parameters
|
||||
if (
|
||||
p["profile"] != getattr(settings, "video_edit_profile", PROFILE)
|
||||
or type(p["fps"]) is not int
|
||||
or p["fps"] != 24
|
||||
or type(p["max_pixels"]) is not int
|
||||
or p["max_pixels"] not in {399360, 921600}
|
||||
or p["max_pixels"] > video_capability(settings)["max_pixels"]
|
||||
):
|
||||
raise invalid()
|
||||
if task == "video.people.analyze":
|
||||
return p
|
||||
for key in ("prompt", "negative_prompt"):
|
||||
if not isinstance(inputs.get(key, ""), str) or len(inputs.get(key, "")) > 8000:
|
||||
raise invalid()
|
||||
if not inputs.get("prompt", "").strip():
|
||||
raise invalid("请输入全局提示词。")
|
||||
rows = inputs.get("replacements")
|
||||
if not isinstance(rows, list) or not 1 <= len(rows) <= getattr(
|
||||
settings, "video_edit_max_people", 12
|
||||
):
|
||||
raise invalid("请选择预算范围内的人物。")
|
||||
seen = set()
|
||||
for row in rows:
|
||||
if not isinstance(row, dict) or set(row) - {"person_id", "reference_asset_id", "prompt"}:
|
||||
raise invalid()
|
||||
for key in ("person_id", "reference_asset_id"):
|
||||
if not isinstance(row.get(key), str) or not 1 <= len(row[key]) <= 64:
|
||||
raise invalid()
|
||||
if row["person_id"] in seen:
|
||||
raise invalid("同一人物不能重复替换。")
|
||||
seen.add(row["person_id"])
|
||||
if not isinstance(row.get("prompt", ""), str) or len(row.get("prompt", "")) > 8000:
|
||||
raise invalid()
|
||||
for key, low, high in (
|
||||
("num_inference_steps", 1, 100),
|
||||
("seed", 0, 2**32 - 1),
|
||||
("mask_expand_pixels", 0, 64),
|
||||
("mask_feather_pixels", 0, 64),
|
||||
):
|
||||
if type(p[key]) is not int or not low <= p[key] <= high:
|
||||
raise invalid()
|
||||
if (
|
||||
type(p["preserve_audio"]) is not bool
|
||||
or type(p["guidance_scale"]) not in {int, float}
|
||||
or not 1 <= p["guidance_scale"] <= 20
|
||||
):
|
||||
raise invalid()
|
||||
return p
|
||||
|
||||
|
||||
class SafeModel(BaseModel):
|
||||
model_config = ConfigDict(extra="ignore", strict=True, allow_inf_nan=False)
|
||||
|
||||
|
||||
class Video(SafeModel):
|
||||
width: int = Field(gt=0, le=16384)
|
||||
height: int = Field(gt=0, le=16384)
|
||||
fps: int = Field(ge=24, le=24)
|
||||
frames: int = Field(gt=0)
|
||||
duration_seconds: float = Field(gt=0)
|
||||
|
||||
|
||||
class Sample(SafeModel):
|
||||
frame: int = Field(ge=0)
|
||||
bbox: list[float] = Field(min_length=4, max_length=4)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def valid_box(self):
|
||||
x1, y1, x2, y2 = self.bbox
|
||||
if not 0 <= x1 < x2 <= 1 or not 0 <= y1 < y2 <= 1:
|
||||
raise ValueError("Invalid normalized bbox")
|
||||
return self
|
||||
|
||||
|
||||
class Person(SafeModel):
|
||||
id: str = Field(pattern=r"^person_[0-9]{4,}$", max_length=64)
|
||||
label: str = Field(min_length=1, max_length=128)
|
||||
thumbnail_output_index: int = Field(ge=0)
|
||||
first_frame: int = Field(ge=0)
|
||||
last_frame: int = Field(ge=0)
|
||||
confidence: float = Field(ge=0, le=1)
|
||||
samples: list[Sample] = Field(min_length=1, max_length=128)
|
||||
|
||||
|
||||
class Analysis(SafeModel):
|
||||
profile: str
|
||||
analysis_token: str = Field(min_length=1, max_length=512)
|
||||
source_sha256: str = Field(pattern=r"^[a-f0-9]{64}$")
|
||||
video: Video
|
||||
poster_output_index: int = Field(ge=0)
|
||||
people: list[Person] = Field(max_length=1000)
|
||||
warnings: list[str] = Field(max_length=128)
|
||||
|
||||
|
||||
def safe_analysis(value, settings, *, output_count=None):
|
||||
try:
|
||||
data = Analysis.model_validate(value)
|
||||
if (
|
||||
data.profile != getattr(settings, "video_edit_profile", PROFILE)
|
||||
or data.video.duration_seconds > getattr(settings, "video_edit_max_seconds", 120)
|
||||
or len(data.people) > getattr(settings, "video_edit_max_people", 12)
|
||||
):
|
||||
raise ValueError("Analysis exceeds profile limits")
|
||||
indexes = [data.poster_output_index] + [p.thumbnail_output_index for p in data.people]
|
||||
if len(set(indexes)) != len(indexes) or len({p.id for p in data.people}) != len(
|
||||
data.people
|
||||
):
|
||||
raise ValueError("Duplicate analysis index or person")
|
||||
if output_count is not None and any(i >= output_count for i in indexes):
|
||||
raise ValueError("Missing preview output")
|
||||
if abs(data.video.frames - round(data.video.duration_seconds * 24)) > 1:
|
||||
raise ValueError("Analysis timeline duration differs")
|
||||
for p in data.people:
|
||||
frames = {s.frame for s in p.samples}
|
||||
if not {p.first_frame, p.last_frame} <= frames or len(frames) < min(
|
||||
3, p.last_frame - p.first_frame + 1
|
||||
):
|
||||
raise ValueError("Analysis needs visible start/middle/end samples")
|
||||
if not p.first_frame <= p.last_frame < data.video.frames or any(
|
||||
not p.first_frame <= s.frame <= p.last_frame for s in p.samples
|
||||
):
|
||||
raise ValueError("Invalid person timing")
|
||||
return data.model_dump()
|
||||
except (ValidationError, ValueError, TypeError):
|
||||
raise MediaError("invalid_analysis", "人物分析结果无效或已过期。") from None
|
||||
@ -1,45 +0,0 @@
|
||||
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.owner_id == job.owner_id, Asset.library_scope == 'private', 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, "execution_mode": job.execution_mode, "desired_state": job.desired_state, "hold_reasons": job.hold_reasons or [], "run_id": job.run_id, "step_key": job.step_key, "batch_id": job.batch_id, "current_execution_id": job.current_execution_id, "explicit_attempt": job.explicit_attempt, "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)}
|
||||
@ -1,86 +0,0 @@
|
||||
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
|
||||
if token.startswith("Bearer "):
|
||||
from .v2_models import ApiToken
|
||||
async with db.session() as session:
|
||||
return (await session.scalar(select(ApiToken.id).join(User,User.id==ApiToken.owner_id).where(ApiToken.token_hash==token_hash(token[7:]),ApiToken.revoked_at.is_(None),User.disabled.is_(False), (ApiToken.expires_at.is_(None) | (ApiToken.expires_at>utcnow()))))) is not None
|
||||
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
|
||||
minimum = await session.scalar(select(func.min(Event.id)).where(Event.owner_id == owner_id)) or 0
|
||||
if after > maximum or (after > 0 and minimum > 0 and after < minimum - 1):
|
||||
yield f"id: {maximum}\nevent: reset\ndata: {{}}\n\n"
|
||||
after = maximum
|
||||
while not await request.is_disconnected():
|
||||
if getattr(request.app.state,"draining",False):return
|
||||
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.headers.get("Authorization") if actor.auth_kind=="bearer" else request.cookies.get(COOKIE), cursor),
|
||||
media_type="text/event-stream", headers={"Cache-Control": "no-cache, no-transform", "X-Accel-Buffering": "no"})
|
||||
|
||||
# Domain events share the existing owner stream and caller transaction.
|
||||
emit_event = emit_asset
|
||||
@ -1,103 +0,0 @@
|
||||
import secrets
|
||||
from sqlalchemy import select,func
|
||||
from .models import Job,utcnow
|
||||
from .v2_models import Execution
|
||||
|
||||
async def begin_execution(session,job_id,phase_key="execute",resource_pool="cpu_media"):
|
||||
job=await session.get(Job,job_id)
|
||||
if not job or job.deleted_at is not None:raise ValueError("Job is unavailable")
|
||||
ordinal=(await session.scalar(select(func.max(Execution.ordinal)).where(Execution.job_id==job_id)) or 0)+1
|
||||
row=Execution(job_id=job_id,ordinal=ordinal,phase_key=phase_key,resource_pool=resource_pool,fence_token=secrets.token_hex(24),state="running",started_at=utcnow())
|
||||
session.add(row);await session.flush();job.current_execution_id=row.id
|
||||
return row
|
||||
|
||||
async def accept_manifest(session,execution_id,fence_token,manifest):
|
||||
row=await session.get(Execution,execution_id)
|
||||
if not row or row.fence_token!=fence_token:return False
|
||||
job=await session.get(Job,row.job_id)
|
||||
if not job or job.deleted_at is not None or job.current_execution_id!=execution_id or job.cancel_requested:return False
|
||||
row.manifest_json=manifest;row.state="results_ready";row.finished_at=utcnow()
|
||||
return True
|
||||
|
||||
async def request_control(session,job_id,desired_state,expected_execution_id=None):
|
||||
job=await session.get(Job,job_id)
|
||||
if not job or job.deleted_at is not None or (expected_execution_id and job.current_execution_id!=expected_execution_id):return {"accepted":False}
|
||||
if job.state in {"succeeded","failed","cancelled","timed_out"}:return {"accepted":False,"state":job.state}
|
||||
if job.desired_state!="cancel":job.desired_state=desired_state
|
||||
if desired_state=="cancel":job.cancel_requested=True
|
||||
return {"accepted":True,"execution_id":job.current_execution_id,"desired_state":job.desired_state}
|
||||
|
||||
|
||||
async def observe_gpu_execution(session,job,remote):
|
||||
"""Observe real upstream attempts without fabricating missed/queued claims.
|
||||
|
||||
Return (accepted_snapshot, current_observed_execution). This runs inside the
|
||||
same transaction as the Job update/event, under the database unit lock.
|
||||
"""
|
||||
import hashlib,json
|
||||
if not job or job.deleted_at is not None:return False,None
|
||||
if remote.get("id") and remote["id"]!=job.upstream_id:return False,None
|
||||
attempt=int(remote.get("attempt_count",job.attempt_count))
|
||||
if attempt<0:raise ValueError("Invalid upstream attempt")
|
||||
rows=list((await session.scalars(select(Execution).where(Execution.job_id==job.id,Execution.phase_key.like("gpu:%")).order_by(Execution.ordinal))).all())
|
||||
highest=max([job.attempt_count]+[(row.manifest_json or {}).get("upstream_attempt",0) for row in rows])
|
||||
if attempt<highest:return False,None
|
||||
state=remote["state"]
|
||||
identity=f"{job.upstream_id}:{attempt}"
|
||||
if remote.get("execution_id") and remote["execution_id"]!=identity:raise ValueError("Upstream execution identity mismatch")
|
||||
execution=next((row for row in rows if (row.manifest_json or {}).get("upstream_execution_id")==identity),None)
|
||||
if execution and remote.get("fence_token") and (execution.manifest_json or {}).get("upstream_fence")!=remote["fence_token"]:return False,None
|
||||
if execution and execution.state in {"exited","results_ready"}:
|
||||
if execution.state=="exited" and state in {"running","succeeded"}:return False,None
|
||||
if execution.state=="results_ready" and state!="succeeded":return False,None
|
||||
unlaunched=remote.get("stage")=="launching" or ("runner_pid" in remote and remote["runner_pid"] is None and "started_at" in remote and remote["started_at"] is None)
|
||||
actual=attempt>0 and (state=="running" and not unlaunched or state in {"succeeded","failed","timed_out","cancelled"} and (not unlaunched or execution is not None))
|
||||
if execution is None and actual:
|
||||
previous=await session.get(Execution,job.current_execution_id) if job.current_execution_id else None
|
||||
if previous and previous.state=="running":
|
||||
previous.state="exited";previous.finished_at=utcnow()
|
||||
previous.manifest_json={**(previous.manifest_json or {}),"superseded_by":identity}
|
||||
execution=await begin_execution(session,job.id,f"gpu:{attempt}","new_gpu")
|
||||
execution.manifest_json={"schema":1,"kind":"upstream_gpu","upstream_id":job.upstream_id,"upstream_execution_id":identity,"upstream_attempt":attempt,"upstream_fence":remote.get("fence_token") or identity,"local_fence":execution.fence_token}
|
||||
if execution is None:
|
||||
no_runner=("runner_pid" in remote and remote["runner_pid"] is None) or remote.get("cleanup_ack") is True
|
||||
if no_runner and state in {"queued","paused","cancelled"} and job.current_execution_id:
|
||||
previous=await session.get(Execution,job.current_execution_id)
|
||||
if previous and previous.phase_key.startswith("gpu:") and previous.state=="running":
|
||||
previous.state="exited";previous.finished_at=utcnow()
|
||||
previous.manifest_json={**(previous.manifest_json or {}),"cleanup_ack":True,"ack_observed_attempt":attempt}
|
||||
return True,None
|
||||
manifest=dict(execution.manifest_json or {})
|
||||
manifest["observed_state"]=state
|
||||
if state=="succeeded":
|
||||
result=remote.get("result") or {}
|
||||
digest=hashlib.sha256(json.dumps(result,sort_keys=True,separators=(",",":"),allow_nan=False).encode()).hexdigest()
|
||||
if execution.state=="results_ready" and manifest.get("result_hash")!=digest:return False,None
|
||||
manifest["result_hash"]=digest
|
||||
execution.state="results_ready";execution.finished_at=utcnow()
|
||||
elif state in {"failed","cancelled","timed_out"}:
|
||||
execution.state="exited";execution.finished_at=utcnow()
|
||||
elif state in {"queued","paused"}:
|
||||
no_runner=("runner_pid" in remote and remote["runner_pid"] is None) or remote.get("cleanup_ack") is True
|
||||
if no_runner:
|
||||
execution.state="exited";execution.finished_at=utcnow();manifest["cleanup_ack"]=True
|
||||
execution.manifest_json=manifest
|
||||
return True,execution
|
||||
|
||||
|
||||
def gpu_result_fence(execution):
|
||||
manifest=execution.manifest_json or {}
|
||||
return {"execution_id":execution.id,"fence_token":execution.fence_token,"upstream_execution_id":manifest.get("upstream_execution_id"),"upstream_attempt":manifest.get("upstream_attempt"),"result_hash":manifest.get("result_hash")}
|
||||
|
||||
|
||||
async def gpu_publication_matches(session,job,fence):
|
||||
import hashlib,json
|
||||
if not job or job.deleted_at is not None:return False
|
||||
if not fence:return job.current_execution_id is None
|
||||
if job.current_execution_id!=fence.get("execution_id"):return False
|
||||
execution=await session.get(Execution,job.current_execution_id)
|
||||
if not execution or execution.job_id!=job.id or execution.state!="results_ready" or execution.fence_token!=fence.get("fence_token"):return False
|
||||
manifest=execution.manifest_json or {}
|
||||
result={key:value for key,value in (job.upstream_result or {}).items() if key!="_visual_execution"}
|
||||
digest=hashlib.sha256(json.dumps(result,sort_keys=True,separators=(",",":"),allow_nan=False).encode()).hexdigest()
|
||||
return manifest.get("upstream_execution_id")==fence.get("upstream_execution_id") and manifest.get("upstream_attempt")==job.attempt_count==fence.get("upstream_attempt") and manifest.get("result_hash")==digest==fence.get("result_hash")
|
||||
@ -1,68 +0,0 @@
|
||||
"""Public GPU summary. Never expose scheduler job IDs or host PID details."""
|
||||
import math
|
||||
from datetime import datetime, timezone
|
||||
|
||||
|
||||
def summarize(gpus, scheduler, now, generated):
|
||||
active, queued = [], None
|
||||
try:
|
||||
stamp = scheduler['updated_at']
|
||||
if type(stamp) not in (int, float) or not math.isfinite(stamp) or not now - 5 <= stamp <= now + 1:
|
||||
raise ValueError('Stale scheduler')
|
||||
if scheduler.get('schema_version') == 2:
|
||||
entries = scheduler.get('active_jobs', [])
|
||||
if not isinstance(entries, list) or len(entries) > len(gpus):
|
||||
raise ValueError('Invalid active list')
|
||||
indexes = set()
|
||||
for entry in entries:
|
||||
index = entry['gpu_index']
|
||||
if type(index) is not int or index in indexes or not any(
|
||||
row['index'] == index and row['_uuid'] == entry['gpu_uuid'] for row in gpus
|
||||
):
|
||||
raise ValueError('Invalid lease')
|
||||
indexes.add(index)
|
||||
count = scheduler.get('queued_count')
|
||||
if count is not None and (type(count) is not int or not 0 <= count <= 10000000):
|
||||
raise ValueError('Invalid queue count')
|
||||
active, queued = entries, count
|
||||
elif scheduler.get('state') == 'leased':
|
||||
lease = scheduler.get('lease') or {}
|
||||
active = [{'gpu_index': lease.get('index'), 'gpu_uuid': lease.get('uuid'), 'state': 'running'}]
|
||||
except (KeyError, TypeError, ValueError):
|
||||
scheduler, active, queued = None, [], None
|
||||
active_indexes = set()
|
||||
for entry in active:
|
||||
gpu = next((row for row in gpus if row['index'] == entry.get('gpu_index')
|
||||
and row['_uuid'] == entry.get('gpu_uuid')), None)
|
||||
if gpu is None:
|
||||
continue
|
||||
active_indexes.add(gpu['index'])
|
||||
state = entry.get('state')
|
||||
gpu.update(busy=True, eligible=False,
|
||||
state=state if state in {'preempting', 'blocked', 'launching'} else 'running',
|
||||
stage=entry.get('stage') if entry.get('stage') in
|
||||
{'launching', 'executing', 'cleanup', 'model', 'upscale', 'collecting'} else None)
|
||||
running = sum(row['index'] in active_indexes or row['_own'] for row in gpus)
|
||||
available = sum(row['eligible'] for row in gpus)
|
||||
state = 'running' if running else 'ready' if available else 'waiting'
|
||||
reason = (f'正在运行{running}个GPU任务,{available}张卡可接新任务。' if running
|
||||
else None if available else '等待可用GPU,外部任务优先。')
|
||||
dispatch_blocked = bool(scheduler and scheduler.get('state') == 'blocked')
|
||||
if dispatch_blocked:
|
||||
reason = '执行器需要管理员检查,新任务暂停派发。'
|
||||
if not running:
|
||||
state = 'blocked'
|
||||
available = 0
|
||||
for gpu in gpus:
|
||||
gpu['eligible'] = False
|
||||
if gpu['state'] == 'ready':
|
||||
gpu['state'] = 'waiting'
|
||||
elif scheduler and 'memory' in str(scheduler.get('reason', '')).lower():
|
||||
reason = '共享内存不足,任务按入队顺序等待资源。'
|
||||
for gpu in gpus:
|
||||
gpu.pop('_uuid')
|
||||
gpu.pop('_own')
|
||||
return {'available': True, 'state': state, 'reason': reason, 'gpus': gpus,
|
||||
'running_count': running, 'available_count': available, 'queued_count': queued,
|
||||
'dispatch_blocked': dispatch_blocked,
|
||||
'updated_at': datetime.fromtimestamp(generated, timezone.utc).isoformat()}
|
||||
@ -1,290 +0,0 @@
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
import json
|
||||
from fastapi import APIRouter, Depends, Header, Request
|
||||
from pydantic import BaseModel, Field, ConfigDict
|
||||
from typing import Literal
|
||||
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):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
execution_mode: Literal["interactive", "batch"] = "interactive"
|
||||
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,
|
||||
Job.deleted_at.is_(None)).with_for_update())
|
||||
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, *, frozen_workflow=False):
|
||||
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 not frozen_workflow:
|
||||
from .runtime_policy import read_runtime_policy
|
||||
policy=read_runtime_policy(settings)
|
||||
if policy.get('configuration_error'):fail(503,'runtime_policy_unavailable','运行配置无效,请联系管理员')
|
||||
if len(body.parameters.get('clips',[]))>policy['workflow_max_shots']:
|
||||
fail(422,'workflow_shot_limit',f"当前配置最多允许{policy['workflow_max_shots']}个视频片段")
|
||||
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, internal=False, *, frozen_workflow=False):
|
||||
if key is not None and not 1 <= len(key) <= 128:
|
||||
fail(422, "invalid_idempotency_key", "幂等键长度须为 1–128")
|
||||
payload = body.model_dump(mode="json")
|
||||
if body.execution_mode == "interactive":
|
||||
payload.pop("execution_mode", None)
|
||||
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", "此幂等键已用于不同的任务参数")
|
||||
if any(job.deleted_at is not None for job in existing):
|
||||
fail(410, "resource_purged", "此幂等键对应的任务已删除")
|
||||
from .submissions import accept_submission
|
||||
saved=await accept_submission(session,actor.id,"jobs.create",key,2,body.model_dump(mode="json"))
|
||||
saved.resource_json={"job_ids":[job.id for job in existing]}
|
||||
return existing
|
||||
from .submissions import accept_submission
|
||||
record = await accept_submission(session, actor.id, "jobs.create", key, 2, body.model_dump(mode="json")) if key else None
|
||||
from .quotas import reserve_budget
|
||||
await reserve_budget(session, actor.id, "workflow.child" if internal else "jobs.create", units=body.count, settings=settings)
|
||||
from .maintenance import require_writable
|
||||
require_writable(settings)
|
||||
if actor.auth_kind == "bearer" and body.execution_mode == "interactive" and "interactive:write" not in actor.scopes:
|
||||
fail(403,"scope_required","Machine tokens require interactive:write for interactive jobs")
|
||||
from .quotas import check_storage_budget
|
||||
await check_storage_budget(session,settings,actor.id,new_jobs=body.count)
|
||||
if settings.max_interactive_gpu_jobs>0 and body.execution_mode=="interactive" and body.task_type in GPU_TYPES:
|
||||
active=await session.scalar(select(func.count()).select_from(Job).where(Job.owner_id==actor.id,Job.execution_mode=="interactive",Job.task_type.in_(GPU_TYPES),Job.state.notin_(TERMINAL)))
|
||||
if active+body.count>settings.max_interactive_gpu_jobs:fail(429,"quota_exceeded","Interactive GPU queue limit reached")
|
||||
# Internal quota accounting also covers newly submitted batch members.
|
||||
# Only children of an already accepted, frozen workflow bypass a new cap.
|
||||
ids = await validate_submission(session, body, actor.id, settings, frozen_workflow=frozen_workflow)
|
||||
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",
|
||||
execution_mode=body.execution_mode, 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)
|
||||
if record is not None:
|
||||
record.resource_json = {"job_ids": [job.id for job in jobs]}
|
||||
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)):
|
||||
recovering=False
|
||||
if idempotency_key:
|
||||
async with request.app.state.db.session() as session:
|
||||
recovering=bool(await session.scalar(select(Job.id).where(Job.owner_id==actor.id,Job.request_key==idempotency_key).limit(1)))
|
||||
if body.execution_mode=="batch" and body.task_type in GPU_TYPES and not recovering:
|
||||
provider=request.app.state.provider
|
||||
capabilities=await provider.upstream_capabilities() if hasattr(provider,"upstream_capabilities") else {}
|
||||
if capabilities.get("protocol_version",0)<2 or not capabilities.get("admission_policy",False):
|
||||
fail(503,"upstream_protocol_incompatible","Batch requires scheduling protocol v2")
|
||||
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)
|
||||
await session.commit()
|
||||
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 = "", root_only: bool = False,
|
||||
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, Job.deleted_at.is_(None))
|
||||
if root_only:
|
||||
query = query.where(Job.run_id.is_(None))
|
||||
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.delete("/{job_id}")
|
||||
async def delete_job(job_id: str, request: Request, if_match: str | None = Header(default=None),
|
||||
actor: Actor = Depends(csrf_actor)):
|
||||
from .deletions import archive_records
|
||||
async with request.app.state.db.session() as session:
|
||||
result = await archive_records(session, Job, job_id, actor.id, if_match)
|
||||
await session.commit()
|
||||
return result
|
||||
|
||||
|
||||
@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, idempotency_key: str | None = Header(default=None), 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", "请先等待或取消当前任务")
|
||||
if old.run_id:
|
||||
fail(409, "workflow_child", "Use workflow step retry")
|
||||
if old.batch_id:
|
||||
fail(409,"parent_control_required","Batch members require parent control")
|
||||
from .submissions import accept_submission
|
||||
record = await accept_submission(session, actor.id, "jobs.retry", idempotency_key, 2, {"job_id":job_id}) if idempotency_key else None
|
||||
if record and record.resource_json.get("job_ids"):
|
||||
jobs = list((await session.scalars(select(Job).where(Job.owner_id == actor.id,
|
||||
Job.id.in_(record.resource_json["job_ids"]), Job.deleted_at.is_(None)))).all())
|
||||
if len(jobs) != len(record.resource_json["job_ids"]):
|
||||
fail(410, "resource_purged", "重试任务已删除")
|
||||
return {"jobs": [await job_dto(session, job) for job in jobs]}
|
||||
from .v2_models import Execution
|
||||
unsafe=await session.scalar(select(Execution.id).where(Execution.job_id==old.id,Execution.state.in_(["allocated","running","stopping","unknown"])).limit(1))
|
||||
if unsafe:fail(409,"cleanup_pending","Previous execution has not confirmed cleanup")
|
||||
body = Submit(task_type=old.task_type, input=old.input_json, parameters=old.parameters, execution_mode=old.execution_mode)
|
||||
jobs = await create_jobs(session, body, actor, request.app.state.settings)
|
||||
if record:
|
||||
record.resource_json = {"job_ids":[j.id for j in jobs]}
|
||||
await session.commit()
|
||||
result = {"jobs": [await job_dto(session, job) for job in jobs]}
|
||||
wake(request)
|
||||
return result
|
||||
@ -1,146 +1,6 @@
|
||||
from contextlib import asynccontextmanager
|
||||
import asyncio
|
||||
import logging
|
||||
import time
|
||||
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, submissions, tokens, workflows, batches, shared_assets
|
||||
from .config import Settings
|
||||
from .coordinator import Coordinator
|
||||
from .database import Database
|
||||
from .timeline import DEFAULT_SOURCE_FRAMES, MAX_SOURCE_FRAMES, DEFAULT_CLIP_FRAMES, MAX_CLIP_FRAMES
|
||||
|
||||
|
||||
def workflow_limits(policy):
|
||||
return {"max_shots":policy["workflow_max_shots"],"source_frames":DEFAULT_SOURCE_FRAMES,
|
||||
"default_source_frames":DEFAULT_SOURCE_FRAMES,"max_source_frames":MAX_SOURCE_FRAMES,
|
||||
"default_clip_frames":DEFAULT_CLIP_FRAMES,"max_clip_frames":MAX_CLIP_FRAMES,"fps":24}
|
||||
|
||||
|
||||
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
|
||||
app.state.draining = False
|
||||
async def after_tick():
|
||||
from .workflow_engine import advance_workflows
|
||||
await advance_workflows(db, configuration, live_provider)
|
||||
coordinator.after_tick = after_tick
|
||||
try:
|
||||
await db.initialize()
|
||||
await auth.bootstrap_admin(db, configuration)
|
||||
from .public_preflight import require_public_ready
|
||||
await require_public_ready(db, configuration)
|
||||
if configuration.run_coordinator:
|
||||
await coordinator.start()
|
||||
yield
|
||||
finally:
|
||||
app.state.draining = True
|
||||
await coordinator.close()
|
||||
await live_provider.aclose()
|
||||
await db.close()
|
||||
|
||||
app = FastAPI(title="CMVR Visual", lifespan=lifespan)
|
||||
from .upload_guard import UploadGuard
|
||||
app.add_middleware(UploadGuard)
|
||||
@app.middleware("http")
|
||||
async def maintenance_writes(request, call_next):
|
||||
from .maintenance import maintenance_active
|
||||
configuration = getattr(request.app.state, "settings", None)
|
||||
if (configuration and request.method in {"POST", "PUT", "PATCH", "DELETE"}
|
||||
and request.url.path.startswith("/api/")
|
||||
and request.url.path not in {"/api/auth/login", "/api/auth/logout"}
|
||||
and maintenance_active(configuration)):
|
||||
return JSONResponse(status_code=503, content={"detail":{
|
||||
"code":"maintenance", "message":"系统维护中,任务和草稿已保留,请稍后重试"}})
|
||||
return await call_next(request)
|
||||
@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, shared_assets.router, shared_assets.publish_router,
|
||||
jobs.router, events.router, submissions.router, tokens.router,
|
||||
workflows.router, workflows.runs_router, batches.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/live")
|
||||
async def live():
|
||||
return {"status": "ok"}
|
||||
|
||||
@app.get("/api/ready")
|
||||
async def ready():
|
||||
from .maintenance import maintenance_active
|
||||
checks = {"database": False, "coordinator": True, "upstream_protocol": False,
|
||||
"accepting": not app.state.draining and not maintenance_active(app.state.settings)}
|
||||
try:
|
||||
async with app.state.db.session() as session:
|
||||
await session.execute(text("SELECT 1"))
|
||||
checks["database"] = True # Schema was verified before coordinator startup.
|
||||
except SQLAlchemyError:
|
||||
pass
|
||||
coordinator = app.state.coordinator
|
||||
if app.state.settings.run_coordinator:
|
||||
heartbeat = getattr(coordinator, "last_tick_success", None)
|
||||
checks["coordinator"] = bool(coordinator._task and not coordinator._task.done()
|
||||
and heartbeat is not None and time.monotonic() - heartbeat < 90)
|
||||
try:
|
||||
caps = await asyncio.wait_for(app.state.provider.upstream_capabilities(), 3)
|
||||
checks["upstream_protocol"] = caps.get("protocol_version", 0) >= 2 and bool(caps.get("admission_policy"))
|
||||
except (Exception, asyncio.TimeoutError):
|
||||
pass
|
||||
healthy = all(checks.values())
|
||||
return JSONResponse(status_code=200 if healthy else 503,
|
||||
content={"status": "ready" if healthy else "not_ready", "checks": checks})
|
||||
|
||||
@app.get("/api/capabilities", dependencies=[Depends(auth.current_actor)])
|
||||
async def capabilities():
|
||||
from .providers import capabilities as provider_capabilities
|
||||
from .resource_policy import execution_policy
|
||||
from .runtime_policy import read_runtime_policy
|
||||
policy=read_runtime_policy(app.state.settings)
|
||||
return {"items": provider_capabilities(app.state.settings),
|
||||
"scheduler": await app.state.provider.scheduler_status(), "execution_policy": execution_policy(settings=app.state.settings),
|
||||
"workflow_limits":workflow_limits(policy)}
|
||||
|
||||
@app.get("/api/system/status", dependencies=[Depends(auth.current_actor)])
|
||||
async def status():
|
||||
from .providers import capabilities as provider_capabilities
|
||||
from .resource_policy import execution_policy
|
||||
from .runtime_policy import read_runtime_policy
|
||||
policy=read_runtime_policy(app.state.settings)
|
||||
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(),
|
||||
"execution_policy": execution_policy(settings=app.state.settings),
|
||||
"workflow_limits":workflow_limits(policy),
|
||||
"public_access": getattr(app.state.settings, "public_access", False)}
|
||||
|
||||
return app
|
||||
"""稳定的 ASGI 入口;Docker、本地启动和测试均从这里加载。"""
|
||||
|
||||
from app.bootstrap import create_app
|
||||
|
||||
app = create_app()
|
||||
__all__ = ["app", "create_app"]
|
||||
|
||||
@ -1,8 +0,0 @@
|
||||
"""Server-owned admission switch. Reads, synchronization and archival continue."""
|
||||
from pathlib import Path
|
||||
from .errors import fail
|
||||
|
||||
def maintenance_active(settings):return (Path(settings.state_root)/"maintenance").exists()
|
||||
|
||||
def require_writable(settings):
|
||||
if maintenance_active(settings):fail(503,"maintenance","Service is in maintenance mode")
|
||||
@ -1,310 +0,0 @@
|
||||
"""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)
|
||||
|
||||
async def inspect_video_track(path: Path, settings) -> dict:
|
||||
"""Count decoded video frames; container or audio duration cannot mask a short source."""
|
||||
from fractions import Fraction
|
||||
source=confined(path,settings)
|
||||
raw=await run_process([settings.ffprobe_bin,'-v','error',*input_options(),'-select_streams','v:0','-count_frames','-show_entries','stream=width,height,avg_frame_rate,nb_read_frames,duration,time_base:format=duration','-of','json',str(source)],timeout=120,max_output=256*1024)
|
||||
try:
|
||||
data=json.loads(raw);stream=data['streams'][0]
|
||||
frames=int(stream['nb_read_frames']);fps=Fraction(stream['avg_frame_rate'])
|
||||
width,height=int(stream['width']),int(stream['height'])
|
||||
if frames<=0 or fps<=0 or width<=0 or height<=0 or width*height>40000000:raise ValueError
|
||||
return {'frames':frames,'fps':float(fps),'width':width,'height':height,'duration':float(data['format']['duration']),'time_base':stream.get('time_base')}
|
||||
except (KeyError,IndexError,TypeError,ValueError,ZeroDivisionError):
|
||||
raise MediaError('invalid_media','Video frame decoding failed.') from None
|
||||
|
||||
|
||||
async def compose_workflow(plan,work_dir,control=None,*,settings,sources,audio=None):
|
||||
"""Render a frozen multi-shot timeline from internal resolved asset paths."""
|
||||
from .providers import CpuResult
|
||||
if len(sources)!=len(plan.spec['shots']):raise MediaError('invalid_timeline','Source videos differ from the frozen shot count.')
|
||||
shot_frames=plan.shot_frames or (plan.clip_frames,)*len(sources)
|
||||
duration=plan.frames/plan.fps
|
||||
duration_text=f'{duration:.9f}'.rstrip('0').rstrip('.')
|
||||
sources=[confined(p,settings) for p in sources]
|
||||
work=Path(work_dir).resolve()
|
||||
if not work.is_relative_to(Path(settings.workspace_root).resolve()):raise MediaError('invalid_asset','Invalid work directory.')
|
||||
width,height=plan.canvas
|
||||
expected=(plan.generation_parameters['upscale_width'],plan.generation_parameters['upscale_height'])
|
||||
for source,frames in zip(sources,shot_frames):
|
||||
info=await inspect_video_track(source,settings)
|
||||
if info['frames']<frames:raise MediaError('short_source',f'Each source needs at least {frames} decoded video frames for its selected duration.')
|
||||
if info['fps']!=24 or (info['width'],info['height'])!=expected:raise MediaError('invalid_video_profile','Source video differs from frozen enhanced profile.')
|
||||
audio_spec=plan.spec['render']['audio']
|
||||
if bool(audio_spec)!=bool(audio):raise MediaError('invalid_timeline','Audio source does not match timeline.')
|
||||
if audio:
|
||||
audio=confined(audio,settings);info=await inspect_media(audio,settings)
|
||||
if info['kind']!='audio' or audio_spec['source_end_ms']>round(info['duration_seconds']*1000):raise MediaError('invalid_timeline','Audio cut exceeds decoded source.')
|
||||
work.mkdir(parents=True,exist_ok=True)
|
||||
async def checkpoint():
|
||||
if control is not None:
|
||||
result=control() if callable(control) else control.checkpoint()
|
||||
if hasattr(result,'__await__'):await result
|
||||
parts=[]
|
||||
for index,(source,frames) in enumerate(zip(sources,shot_frames)):
|
||||
await checkpoint();target=work/f'shot-{index}.mp4'
|
||||
fit=plan.spec['render']['fit']
|
||||
canvas=f'scale={width}:{height}:force_original_aspect_ratio=' + ('decrease' if fit=='contain' else 'increase')
|
||||
canvas+=f',pad={width}:{height}:(ow-iw)/2:(oh-ih)/2' if fit=='contain' else f',crop={width}:{height}'
|
||||
vf=f'trim=start_frame=0:end_frame={frames},setpts=PTS-STARTPTS,'+canvas+',setsar=1'
|
||||
await run_process([settings.ffmpeg_bin,'-v','error','-nostdin',*input_options(),'-i',str(source),'-map','0:v:0','-an','-vf',vf,'-r','24','-frames:v',str(frames),'-c:v','libx264','-preset','veryfast','-crf','20','-pix_fmt','yuv420p','-threads','2','-fs',str(settings.max_output_bytes),str(target)],timeout=600)
|
||||
parts.append(target)
|
||||
if sum(p.stat().st_size for p in parts)>=settings.max_output_bytes:raise MediaError('output_too_large','Intermediate media exceeds size budget.')
|
||||
listing=work/'concat.txt';listing.write_text(''.join(f"file '{p.name}'\n" for p in parts),encoding='utf-8')
|
||||
target=work/'workflow.mp4'
|
||||
command=[settings.ffmpeg_bin,'-v','error','-nostdin','-f','concat','-safe','1','-i',listing.name]
|
||||
if audio:command += [*input_options(),'-i',str(audio)]
|
||||
else:command += ['-f','lavfi','-i','anullsrc=channel_layout=stereo:sample_rate=48000']
|
||||
filters=[]
|
||||
for index,cue in enumerate(plan.spec['render']['subtitles']):
|
||||
name=f'cue-{index:04d}.txt';(work/name).write_text(cue['text'],encoding='utf-8')
|
||||
filters.append(f"drawtext=font='Noto Sans CJK SC':textfile={name}:expansion=none:fontcolor=white:fontsize=48:borderw=3:x=(w-tw)/2:y=h-th-60:enable='gte(n,{cue['start_frame']})*lt(n,{cue['end_frame']})'")
|
||||
if audio:
|
||||
start,end=audio_spec['source_start_ms']/1000,audio_spec['source_end_ms']/1000
|
||||
delay=audio_spec['offset_frame']*1000/24
|
||||
af=f'atrim=start={start:.3f}:end={end:.3f},asetpts=PTS-STARTPTS,adelay={delay:.9f}:all=1,apad,atrim=duration={duration_text}'
|
||||
else:af=f'atrim=duration={duration_text}'
|
||||
command+=['-map','0:v:0','-map','1:a:0']
|
||||
if filters:command+=['-vf',','.join(filters)]
|
||||
command+=['-af',af,'-frames:v',str(plan.frames),'-r','24','-c:v','libx264','-preset','veryfast','-crf','20','-pix_fmt','yuv420p','-c:a','aac','-ar','48000','-ac','2','-threads','2','-movflags','+faststart','-fs',str(settings.max_output_bytes),str(target)]
|
||||
await checkpoint();await run_process(command,timeout=min(3600,max(600,duration*5)),cwd=work)
|
||||
info=await inspect_video_track(target,settings)
|
||||
if info['frames']!=plan.frames or info['fps']!=24 or (info['width'],info['height'])!=plan.canvas or abs(info['duration']-duration)>.10 or target.stat().st_size>=settings.max_output_bytes:
|
||||
raise MediaError('composition_incomplete','Final video differs from the frozen frame count, profile or duration.')
|
||||
result={'frames':plan.frames,'fps':24,'duration_seconds':duration,'width':width,'height':height,'clip_count':len(sources),'subtitle_count':len(filters)}
|
||||
return CpuResult([target],result,{'provider':'ffmpeg-cpu','profile':plan.spec['profile'],'template_version':'plain-v1'})
|
||||
38
backend/app/models/__init__.py
Normal file
38
backend/app/models/__init__.py
Normal file
@ -0,0 +1,38 @@
|
||||
# 统一注册18张业务表,迁移与运行时共享同一个 metadata。
|
||||
from .folders import Folder, AssetFolder
|
||||
from .base import Base, Timestamp, new_id, utcnow
|
||||
from .accounts import User, Session, ApiToken
|
||||
from .assets import Asset, AssetReference, AssetTag, SharedAsset
|
||||
from .jobs import Job, JobAsset, Event, Execution
|
||||
from .workflows import WorkflowDraft, WorkflowRun, WorkflowStep, Batch, BatchItem
|
||||
from .operations import Submission, QuotaReservation
|
||||
from .stories import ShotCandidate, ShotSelection
|
||||
|
||||
__all__ = [
|
||||
"Folder",
|
||||
"AssetFolder",
|
||||
"Base",
|
||||
"Timestamp",
|
||||
"new_id",
|
||||
"utcnow",
|
||||
"User",
|
||||
"Session",
|
||||
"ApiToken",
|
||||
"Asset",
|
||||
"AssetReference",
|
||||
"AssetTag",
|
||||
"SharedAsset",
|
||||
"Job",
|
||||
"JobAsset",
|
||||
"Event",
|
||||
"Execution",
|
||||
"WorkflowDraft",
|
||||
"WorkflowRun",
|
||||
"WorkflowStep",
|
||||
"Batch",
|
||||
"BatchItem",
|
||||
"Submission",
|
||||
"QuotaReservation",
|
||||
"ShotCandidate",
|
||||
"ShotSelection",
|
||||
]
|
||||
43
backend/app/models/accounts.py
Normal file
43
backend/app/models/accounts.py
Normal file
@ -0,0 +1,43 @@
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
from sqlalchemy import Boolean, ForeignKey, JSON, String, UniqueConstraint
|
||||
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
|
||||
from app.models.base import Base, Timestamp, new_id, utcnow
|
||||
|
||||
|
||||
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)
|
||||
must_change_password: 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 ApiToken(Base):
|
||||
__tablename__ = "visual_api_tokens"
|
||||
__table_args__ = (UniqueConstraint("token_hash"),)
|
||||
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
|
||||
owner_id: Mapped[str] = mapped_column(String(32), ForeignKey("visual_users.id"), index=True)
|
||||
name: Mapped[str] = mapped_column(String(128))
|
||||
token_hash: Mapped[str] = mapped_column(String(64))
|
||||
scopes: Mapped[list] = mapped_column(JSON, default=list)
|
||||
expires_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True)
|
||||
revoked_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow)
|
||||
91
backend/app/models/assets.py
Normal file
91
backend/app/models/assets.py
Normal file
@ -0,0 +1,91 @@
|
||||
from datetime import datetime
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from app.models.folders import AssetFolder
|
||||
|
||||
|
||||
from sqlalchemy import BigInteger, Boolean, ForeignKey, Integer, JSON, String, UniqueConstraint
|
||||
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
|
||||
from app.models.base import Base, Timestamp, new_id, utcnow
|
||||
|
||||
|
||||
class Asset(Base):
|
||||
__tablename__ = "visual_assets"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("source_job_id", "source_output_index"),
|
||||
UniqueConstraint("source_upstream_id", "source_output_index"),
|
||||
)
|
||||
folder_links: Mapped[list["AssetFolder"]] = relationship(
|
||||
"AssetFolder", lazy="selectin", cascade="all, delete-orphan", passive_deletes=True
|
||||
)
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
kwargs.setdefault("folder_links", [])
|
||||
super().__init__(**kwargs)
|
||||
|
||||
@property
|
||||
def folder_ids(self):
|
||||
return [link.folder_id for link in self.folder_links]
|
||||
|
||||
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")
|
||||
library_scope: Mapped[str] = mapped_column(
|
||||
String(16), default="private", server_default="private", index=True
|
||||
)
|
||||
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 AssetReference(Base):
|
||||
__tablename__ = "visual_asset_refs"
|
||||
__table_args__ = (UniqueConstraint("asset_id", "ref_kind", "ref_id"),)
|
||||
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
|
||||
owner_id: Mapped[str] = mapped_column(String(32), ForeignKey("visual_users.id"), index=True)
|
||||
asset_id: Mapped[str] = mapped_column(String(32))
|
||||
ref_kind: Mapped[str] = mapped_column(String(32))
|
||||
ref_id: Mapped[str] = mapped_column(String(32))
|
||||
|
||||
|
||||
class AssetTag(Base):
|
||||
__tablename__ = "visual_asset_tags"
|
||||
__table_args__ = (UniqueConstraint("asset_id", "tag"),)
|
||||
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
|
||||
owner_id: Mapped[str] = mapped_column(String(32), ForeignKey("visual_users.id"), index=True)
|
||||
asset_id: Mapped[str] = mapped_column(String(32))
|
||||
tag: Mapped[str] = mapped_column(String(128))
|
||||
|
||||
|
||||
class SharedAsset(Base):
|
||||
__tablename__ = "visual_shared_assets"
|
||||
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
|
||||
publisher_id: Mapped[str] = mapped_column(String(32), ForeignKey("visual_users.id"), index=True)
|
||||
asset_id: Mapped[str] = mapped_column(String(32), ForeignKey("visual_assets.id"), unique=True)
|
||||
source_asset_id: Mapped[str | None] = mapped_column(
|
||||
String(32), ForeignKey("visual_assets.id"), nullable=True, index=True
|
||||
)
|
||||
version: Mapped[int] = mapped_column(Integer, default=1, server_default="1")
|
||||
created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow, index=True)
|
||||
withdrawn_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True)
|
||||
25
backend/app/models/base.py
Normal file
25
backend/app/models/base.py
Normal file
@ -0,0 +1,25 @@
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import DateTime
|
||||
|
||||
from sqlalchemy.orm import DeclarativeBase
|
||||
|
||||
from sqlalchemy.dialects.mysql import DATETIME
|
||||
|
||||
|
||||
# MySQL 保留微秒,防止同秒创建的任务丢失 FIFO 顺序;不能退回普通 DATETIME。
|
||||
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
|
||||
31
backend/app/models/folders.py
Normal file
31
backend/app/models/folders.py
Normal file
@ -0,0 +1,31 @@
|
||||
from datetime import datetime
|
||||
from sqlalchemy import ForeignKey, String, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
from app.models.base import Base, Timestamp, new_id, utcnow
|
||||
|
||||
|
||||
class Folder(Base):
|
||||
__tablename__ = "visual_folders"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("owner_id", "parent_key", "name", name="uq_visual_folders_sibling"),
|
||||
)
|
||||
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))
|
||||
parent_id: Mapped[str | None] = mapped_column(
|
||||
ForeignKey("visual_folders.id", ondelete="CASCADE"), nullable=True, index=True
|
||||
)
|
||||
# 根目录使用空字符串,避免 MySQL 唯一键对 NULL 允许重复。
|
||||
parent_key: Mapped[str] = mapped_column(String(32), default="", server_default="")
|
||||
created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow)
|
||||
|
||||
|
||||
class AssetFolder(Base):
|
||||
__tablename__ = "visual_asset_folders"
|
||||
asset_id: Mapped[str] = mapped_column(
|
||||
ForeignKey("visual_assets.id", ondelete="CASCADE"), primary_key=True
|
||||
)
|
||||
folder_id: Mapped[str] = mapped_column(
|
||||
ForeignKey("visual_folders.id", ondelete="CASCADE"), primary_key=True, index=True
|
||||
)
|
||||
@ -1,80 +1,33 @@
|
||||
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")
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
def utcnow():
|
||||
return datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
from sqlalchemy import (
|
||||
BigInteger,
|
||||
Boolean,
|
||||
ForeignKey,
|
||||
Index,
|
||||
Integer,
|
||||
JSON,
|
||||
String,
|
||||
Text,
|
||||
UniqueConstraint,
|
||||
)
|
||||
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
|
||||
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)
|
||||
must_change_password: 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")
|
||||
library_scope: Mapped[str] = mapped_column(String(16), default="private", server_default="private", index=True)
|
||||
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)
|
||||
from app.models.base import Base, Timestamp, new_id, utcnow
|
||||
|
||||
|
||||
class Job(Base):
|
||||
__tablename__ = "visual_jobs"
|
||||
__table_args__ = (UniqueConstraint("owner_id", "request_key", "batch_index"),
|
||||
Index("visual_jobs_dispatch", "state", "next_action_at"))
|
||||
__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)
|
||||
folder_id: Mapped[str | None] = mapped_column(ForeignKey("visual_folders.id", ondelete="SET NULL"), nullable=True, index=True)
|
||||
output_folder_id: Mapped[str | None] = mapped_column(ForeignKey("visual_folders.id", ondelete="SET NULL"), nullable=True, index=True)
|
||||
owner_id: Mapped[str] = mapped_column(ForeignKey("visual_users.id"), index=True)
|
||||
task_type: Mapped[str] = mapped_column(String(48))
|
||||
execution_mode: Mapped[str] = mapped_column(String(16), default="interactive")
|
||||
@ -126,9 +79,27 @@ class JobAsset(Base):
|
||||
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)
|
||||
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)
|
||||
|
||||
|
||||
class Execution(Base):
|
||||
__tablename__ = "visual_job_executions"
|
||||
__table_args__ = (UniqueConstraint("job_id", "ordinal"),)
|
||||
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
|
||||
job_id: Mapped[str] = mapped_column(String(32))
|
||||
ordinal: Mapped[int] = mapped_column(Integer)
|
||||
phase_key: Mapped[str] = mapped_column(String(48))
|
||||
resource_pool: Mapped[str] = mapped_column(String(32))
|
||||
fence_token: Mapped[str] = mapped_column(String(64))
|
||||
state: Mapped[str] = mapped_column(String(32), default="allocated")
|
||||
manifest_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)
|
||||
started_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True)
|
||||
finished_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True)
|
||||
error_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)
|
||||
35
backend/app/models/operations.py
Normal file
35
backend/app/models/operations.py
Normal file
@ -0,0 +1,35 @@
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
from sqlalchemy import ForeignKey, Integer, JSON, String, UniqueConstraint
|
||||
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
|
||||
from app.models.base import Base, Timestamp, new_id, utcnow
|
||||
|
||||
|
||||
class Submission(Base):
|
||||
__tablename__ = "visual_submissions"
|
||||
__table_args__ = (UniqueConstraint("owner_id", "operation", "key"),)
|
||||
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
|
||||
owner_id: Mapped[str] = mapped_column(String(32), ForeignKey("visual_users.id"), index=True)
|
||||
operation: Mapped[str] = mapped_column(String(128))
|
||||
key: Mapped[str] = mapped_column(String(128))
|
||||
payload_schema: Mapped[int] = mapped_column(Integer, default=2)
|
||||
body_hash: Mapped[str] = mapped_column(String(64))
|
||||
request_json: Mapped[dict] = mapped_column(JSON, default=dict)
|
||||
resource_json: Mapped[dict] = mapped_column(JSON, default=dict)
|
||||
status: Mapped[str] = mapped_column(String(32), default="accepted")
|
||||
created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow)
|
||||
|
||||
|
||||
class QuotaReservation(Base):
|
||||
__tablename__ = "visual_quota_reservations"
|
||||
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
|
||||
owner_id: Mapped[str] = mapped_column(String(32), ForeignKey("visual_users.id"), index=True)
|
||||
operation: Mapped[str] = mapped_column(String(128))
|
||||
units: Mapped[int] = mapped_column(Integer, default=1)
|
||||
bytes_reserved: Mapped[int] = mapped_column(Integer, default=0)
|
||||
released_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow)
|
||||
45
backend/app/models/stories.py
Normal file
45
backend/app/models/stories.py
Normal file
@ -0,0 +1,45 @@
|
||||
"""候选保留冻结输入,选择追加记录;普通草稿 JSON 无法伪造批准。"""
|
||||
|
||||
from datetime import datetime
|
||||
from sqlalchemy import ForeignKey, Integer, JSON, String, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
from app.models.base import Base, Timestamp, new_id, utcnow
|
||||
|
||||
|
||||
class ShotCandidate(Base):
|
||||
__tablename__ = "visual_shot_candidates"
|
||||
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
|
||||
owner_id: Mapped[str] = mapped_column(String(32), ForeignKey("visual_users.id"), index=True)
|
||||
draft_id: Mapped[str] = mapped_column(String(32), ForeignKey("visual_drafts.id"), index=True)
|
||||
shot_id: Mapped[str] = mapped_column(String(32), index=True)
|
||||
kind: Mapped[str] = mapped_column(String(16))
|
||||
source_kind: Mapped[str] = mapped_column(String(16))
|
||||
job_id: Mapped[str | None] = mapped_column(String(32), nullable=True, index=True)
|
||||
asset_id: Mapped[str | None] = mapped_column(String(32), nullable=True)
|
||||
asset_sha256: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
context_hash: Mapped[str] = mapped_column(String(64))
|
||||
generation_hash: Mapped[str] = mapped_column(String(64))
|
||||
created_revision: Mapped[int] = mapped_column(Integer)
|
||||
version: Mapped[int] = mapped_column(Integer, default=1)
|
||||
state: Mapped[str] = mapped_column(String(32), default="queued")
|
||||
plan_json: Mapped[dict] = mapped_column(JSON, default=dict)
|
||||
error_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)
|
||||
batch_id: Mapped[str | None] = mapped_column(String(32), nullable=True, index=True)
|
||||
created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow)
|
||||
deleted_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True)
|
||||
|
||||
|
||||
class ShotSelection(Base):
|
||||
__tablename__ = "visual_shot_selections"
|
||||
__table_args__ = (UniqueConstraint("draft_id", "shot_id", "kind", "version"),)
|
||||
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
|
||||
owner_id: Mapped[str] = mapped_column(String(32), ForeignKey("visual_users.id"), index=True)
|
||||
draft_id: Mapped[str] = mapped_column(String(32), ForeignKey("visual_drafts.id"), index=True)
|
||||
shot_id: Mapped[str] = mapped_column(String(32), index=True)
|
||||
kind: Mapped[str] = mapped_column(String(16))
|
||||
candidate_id: Mapped[str | None] = mapped_column(String(32), nullable=True)
|
||||
asset_id: Mapped[str | None] = mapped_column(String(32), nullable=True)
|
||||
decision_json: Mapped[dict] = mapped_column(JSON, default=dict)
|
||||
context_hash: Mapped[str] = mapped_column(String(64))
|
||||
version: Mapped[int] = mapped_column(Integer, default=1)
|
||||
created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow)
|
||||
109
backend/app/models/workflows.py
Normal file
109
backend/app/models/workflows.py
Normal file
@ -0,0 +1,109 @@
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
from sqlalchemy import ForeignKey, Integer, JSON, String, UniqueConstraint
|
||||
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
|
||||
from app.models.base import Base, Timestamp, new_id, utcnow
|
||||
|
||||
|
||||
class WorkflowDraft(Base):
|
||||
__tablename__ = "visual_drafts"
|
||||
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
|
||||
folder_id: Mapped[str | None] = mapped_column(
|
||||
ForeignKey("visual_folders.id", ondelete="SET NULL"), nullable=True, index=True
|
||||
)
|
||||
owner_id: Mapped[str] = mapped_column(String(32), ForeignKey("visual_users.id"), index=True)
|
||||
name: Mapped[str] = mapped_column(String(255))
|
||||
kind: Mapped[str] = mapped_column(String(48), default="three_shot")
|
||||
spec: Mapped[dict] = mapped_column(JSON, default=dict)
|
||||
editor_manifest: Mapped[dict | None] = mapped_column(JSON, nullable=True)
|
||||
revision: Mapped[int] = mapped_column(Integer, default=1)
|
||||
version: Mapped[int] = mapped_column(Integer, default=1)
|
||||
current_run_id: Mapped[str | None] = mapped_column(String(32), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow)
|
||||
deleted_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True)
|
||||
|
||||
|
||||
class WorkflowRun(Base):
|
||||
__tablename__ = "visual_workflow_runs"
|
||||
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
|
||||
folder_id: Mapped[str | None] = mapped_column(
|
||||
ForeignKey("visual_folders.id", ondelete="SET NULL"), nullable=True, index=True
|
||||
)
|
||||
output_folder_id: Mapped[str | None] = mapped_column(
|
||||
ForeignKey("visual_folders.id", ondelete="SET NULL"), nullable=True, index=True
|
||||
)
|
||||
owner_id: Mapped[str] = mapped_column(String(32), ForeignKey("visual_users.id"), index=True)
|
||||
draft_id: Mapped[str] = mapped_column(String(32))
|
||||
draft_revision: Mapped[int] = mapped_column(Integer)
|
||||
spec_snapshot: Mapped[dict] = mapped_column(JSON, default=dict)
|
||||
spec_hash: Mapped[str] = mapped_column(String(64))
|
||||
run_kind: Mapped[str] = mapped_column(String(32), default="legacy", server_default="legacy")
|
||||
output_goal: Mapped[str] = mapped_column(String(16), default="film", server_default="film")
|
||||
base_run_id: Mapped[str | None] = mapped_column(String(32), nullable=True)
|
||||
source_draft_version: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
plan_snapshot: Mapped[dict | None] = mapped_column(JSON, nullable=True)
|
||||
result_manifest: Mapped[dict | None] = mapped_column(JSON, nullable=True)
|
||||
apply_state: Mapped[str | None] = mapped_column(String(16), nullable=True)
|
||||
execution_mode: Mapped[str] = mapped_column(String(16), default="interactive")
|
||||
state: Mapped[str] = mapped_column(String(32), default="queued")
|
||||
desired_state: Mapped[str] = mapped_column(String(16), default="run")
|
||||
hold_reasons: Mapped[list] = mapped_column(JSON, default=list)
|
||||
version: Mapped[int] = mapped_column(Integer, default=1)
|
||||
batch_id: Mapped[str | None] = mapped_column(String(32), nullable=True)
|
||||
batch_item_index: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
current_output_asset_id: Mapped[str | None] = mapped_column(String(32), nullable=True)
|
||||
error_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow)
|
||||
started_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True)
|
||||
finished_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True)
|
||||
deleted_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True)
|
||||
|
||||
|
||||
class WorkflowStep(Base):
|
||||
__tablename__ = "visual_workflow_steps"
|
||||
__table_args__ = (UniqueConstraint("run_id", "step_key"),)
|
||||
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
|
||||
run_id: Mapped[str] = mapped_column(String(32))
|
||||
step_key: Mapped[str] = mapped_column(String(32))
|
||||
kind: Mapped[str] = mapped_column(String(48))
|
||||
dependencies: Mapped[list] = mapped_column(JSON, default=list)
|
||||
semantic_input_hash: Mapped[str] = mapped_column(String(64))
|
||||
selected_job_id: Mapped[str | None] = mapped_column(String(32), nullable=True)
|
||||
state: Mapped[str] = mapped_column(String(32), default="waiting")
|
||||
recipe_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)
|
||||
resolved_input_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)
|
||||
result_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)
|
||||
explicit_attempt: Mapped[int] = mapped_column(Integer, default=0)
|
||||
version: Mapped[int] = mapped_column(Integer, default=1)
|
||||
|
||||
|
||||
class Batch(Base):
|
||||
__tablename__ = "visual_batches"
|
||||
hold_reasons: Mapped[list] = mapped_column(JSON, default=list)
|
||||
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
|
||||
owner_id: Mapped[str] = mapped_column(String(32), ForeignKey("visual_users.id"), index=True)
|
||||
name: Mapped[str] = mapped_column(String(255))
|
||||
spec_snapshot: Mapped[dict] = mapped_column(JSON, default=dict)
|
||||
state: Mapped[str] = mapped_column(String(32), default="queued")
|
||||
desired_state: Mapped[str] = mapped_column(String(16), default="run")
|
||||
version: Mapped[int] = mapped_column(Integer, default=1)
|
||||
created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow)
|
||||
finished_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True)
|
||||
deleted_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True)
|
||||
|
||||
|
||||
class BatchItem(Base):
|
||||
__tablename__ = "visual_batch_items"
|
||||
__table_args__ = (UniqueConstraint("batch_id", "item_index"),)
|
||||
id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id)
|
||||
batch_id: Mapped[str] = mapped_column(String(32))
|
||||
item_index: Mapped[int] = mapped_column(Integer)
|
||||
target_kind: Mapped[str] = mapped_column(String(16))
|
||||
target_id: Mapped[str] = mapped_column(String(32))
|
||||
spec_json: Mapped[dict] = mapped_column(JSON, default=dict)
|
||||
state: Mapped[str] = mapped_column(String(32), default="queued")
|
||||
@ -1,843 +0,0 @@
|
||||
"""Database-independent adapters for deployed GPU jobs, text/vision and CPU media."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from contextvars import ContextVar
|
||||
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
|
||||
|
||||
|
||||
current_phase_callback = ContextVar('current_phase_callback', default=None)
|
||||
|
||||
|
||||
async def enter_phase(phase_key, resource_pool):
|
||||
callback = current_phase_callback.get()
|
||||
if callback is not None:
|
||||
await callback(phase_key, resource_pool)
|
||||
|
||||
|
||||
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]:
|
||||
from .runtime_policy import read_runtime_policy
|
||||
compose_limit=read_runtime_policy(settings)['workflow_max_shots']
|
||||
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': 361, '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, '单镜头最多361帧、24fps,约15秒无声视频;默认约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': compose_limit},
|
||||
'source_duration_seconds': {'min': .05, 'max': 86400}},
|
||||
'按顺序裁剪拼接片段,支持上传音轨和人工字幕;无热度预测。'),
|
||||
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, 361)
|
||||
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':
|
||||
if 'workflow_spec' in p:
|
||||
from .timeline import WorkflowSpec
|
||||
_keys(inputs, {'asset_ids', 'audio_asset_id'})
|
||||
_keys(p, {'workflow_spec', 'clips'})
|
||||
try:
|
||||
spec = WorkflowSpec.model_validate(p['workflow_spec'])
|
||||
except ValueError:
|
||||
raise _invalid('Invalid frozen workflow timeline.') from None
|
||||
clips = p.get('clips')
|
||||
if not isinstance(clips, list) or len(clips) != len(spec.shots):
|
||||
raise _invalid('Workflow clips must match the frozen shot count.')
|
||||
for clip in clips:
|
||||
_keys(clip, {'asset_id'})
|
||||
_string(clip.get('asset_id'), 64)
|
||||
if inputs.get('asset_ids') != [c['asset_id'] for c in clips]:
|
||||
raise _invalid('Workflow clip order differs.')
|
||||
if inputs.get('audio_asset_id') != (spec.render.audio.asset_id if spec.render.audio else None):
|
||||
raise _invalid('Workflow audio differs.')
|
||||
return
|
||||
_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) <= 1000:
|
||||
raise _invalid('请选择1至1000个视频片段,并遵守当前配置的资源上限。')
|
||||
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, 86400)
|
||||
if clip.get('end_seconds') is not None and _float(clip['end_seconds'], 0, 86400) <= 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, 86400*1000), _float(cue.get('end'), 0, 86400*1000)
|
||||
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)
|
||||
eligible = not busy and free >= 76 and idle is not None and now - idle >= 15
|
||||
gpus.append({'index': index, 'name': f'GPU {index}', 'busy': busy,
|
||||
'eligible': eligible, 'free_gib': free, '_uuid': gpu['uuid'], '_own': bool(own),
|
||||
'state': 'external' if external else 'running' if own else 'ready' if eligible else 'waiting',
|
||||
'stage': None})
|
||||
scheduler = None
|
||||
try:
|
||||
scheduler_path = Path(self.settings.gpu_scheduler_path)
|
||||
if scheduler_path.stat().st_size <= 1024 * 1024:
|
||||
scheduler = json.loads(scheduler_path.read_bytes())
|
||||
except (OSError, ValueError, TypeError, AttributeError):
|
||||
pass
|
||||
from .gpu_summary import summarize
|
||||
return summarize(gpus, scheduler, now, generated)
|
||||
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':
|
||||
await enter_phase('extract_audio', 'cpu_media')
|
||||
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
|
||||
await enter_phase('transcribe', 'new_gpu')
|
||||
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, 361)
|
||||
if normalized['num_frames'] % 4 != 1 or type(normalized['fps']) is not int or normalized['fps'] != 24:
|
||||
raise _invalid('视频仅支持4n+1帧、最多361帧和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 upstream_capabilities(self):
|
||||
cached = getattr(self, '_capabilities_cache', None)
|
||||
if cached and time.monotonic() - cached[0] < 30:
|
||||
return json.loads(json.dumps(cached[1]))
|
||||
value = await self._json('GET', _url(self.settings.inference_base_url, '/capabilities'), headers=self._headers())
|
||||
features = value.get('features', {})
|
||||
value['admission_policy'] = bool(value.get('admission_policy') or (features.get('scheduling') and features.get('admission_pause')))
|
||||
self._capabilities_cache = (time.monotonic(), value)
|
||||
return json.loads(json.dumps(value))
|
||||
|
||||
async def control(self, upstream_id, desired_state, command_id, expected_version=None, expected_execution_id=None):
|
||||
if desired_state not in {'run', 'pause', 'cancel'}:
|
||||
raise _invalid('Invalid control intention.')
|
||||
_string(command_id, 128)
|
||||
payload = {'desired_state': desired_state, 'command_id': command_id}
|
||||
if expected_version is not None:
|
||||
payload['expected_version'] = _int(expected_version, 0, 2**63-1)
|
||||
if expected_execution_id is not None:
|
||||
payload['expected_execution_id'] = _string(expected_execution_id, 64)
|
||||
return self._sanitize_job(await self._json('PUT', _url(self.settings.inference_base_url,
|
||||
'/jobs/' + self._job_id(upstream_id) + '/control'), payload=payload, 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':
|
||||
await enter_phase('solve', 'qwen_http')
|
||||
_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':
|
||||
await enter_phase('compose', 'cpu_media')
|
||||
return await self._compose(inputs, parameters, assets, work)
|
||||
if task_type == 'audio.speech':
|
||||
await enter_phase('speech', 'cpu_media')
|
||||
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':
|
||||
await enter_phase('sample_frames', 'cpu_media')
|
||||
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 index, (timestamp, frame) in enumerate(samples):
|
||||
image_uri = await self._image_uri(frame)
|
||||
await enter_phase(f'describe_frame_{index}', 'qwen_http')
|
||||
text = await self._chat([{'role': 'user', 'content': [
|
||||
{'type': 'image_url', 'image_url': {'url': image_uri}},
|
||||
{'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):
|
||||
if 'workflow_spec' in p:
|
||||
from .timeline import compile_timeline
|
||||
from .media import compose_workflow
|
||||
validate_arguments('video.compose', inputs, p, self.settings)
|
||||
audio_id = inputs.get('audio_asset_id')
|
||||
audio = self._asset(audio_id, assets) if audio_id else None
|
||||
owned = {audio_id: await inspect_media(audio, self.settings)} if audio else {}
|
||||
try:
|
||||
plan = compile_timeline(p['workflow_spec'], owned)
|
||||
except ValueError:
|
||||
raise _invalid('Invalid workflow audio timeline.') from None
|
||||
return await compose_workflow(plan, work, settings=self.settings, sources=[self._asset(c['asset_id'], assets) for c in p['clips']], audio=audio)
|
||||
_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) <= 1000:
|
||||
raise _invalid('请选择1至1000个视频片段。')
|
||||
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, 86400)
|
||||
end = clip.get('end_seconds')
|
||||
if end is not None and _float(end, 0, 86400) <= 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, 86400*1000), _float(cue.get('end'), 0, 86400*1000)
|
||||
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
|
||||
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'})
|
||||
@ -1,72 +0,0 @@
|
||||
from sqlalchemy import select,func
|
||||
from .models import Job,User,Asset,utcnow
|
||||
from datetime import timedelta
|
||||
import shutil
|
||||
import asyncio
|
||||
from .v2_models import QuotaReservation
|
||||
from .errors import fail
|
||||
CREATION_OPERATIONS={"jobs.create","workflow.run","batch.create"}
|
||||
|
||||
async def reserve_budget(session,owner_id,operation,units=1,bytes_reserved=0,settings=None):
|
||||
owner=await session.scalar(select(User).where(User.id==owner_id).with_for_update())
|
||||
if owner is None or owner.disabled:fail(403,"owner_disabled","Owner is disabled")
|
||||
if operation in CREATION_OPERATIONS:
|
||||
recent=await session.scalar(select(func.count()).select_from(QuotaReservation).where(QuotaReservation.owner_id==owner_id,QuotaReservation.operation.in_(CREATION_OPERATIONS),QuotaReservation.created_at>utcnow()-timedelta(minutes=1)))
|
||||
if recent>=getattr(settings,"max_creation_commands_per_minute",6):fail(429,"quota_exceeded","Creation rate limit reached")
|
||||
active=Job.state.notin_(["succeeded","failed","cancelled","timed_out"])
|
||||
own=await session.scalar(select(func.count()).select_from(Job).where(Job.owner_id==owner_id,active))
|
||||
total=await session.scalar(select(func.count()).select_from(Job).where(active))
|
||||
if own+units>getattr(settings,"max_owner_jobs",500) or total+units>getattr(settings,"max_global_jobs",2000):
|
||||
fail(429,"quota_exceeded","Unfinished task quota exceeded")
|
||||
row=QuotaReservation(owner_id=owner_id,operation=operation,units=units,bytes_reserved=bytes_reserved)
|
||||
session.add(row)
|
||||
return row
|
||||
|
||||
async def check_parent_capacity(session,settings,owner_id,kind):
|
||||
from .v2_models import WorkflowRun,Batch
|
||||
model,terminal,owner_limit,global_limit=(WorkflowRun,{'succeeded','cancelled','failed'},settings.max_owner_runs,settings.max_global_runs) if kind=='run' else (Batch,{'succeeded','cancelled','completed_with_errors'},settings.max_owner_batches,settings.max_global_batches)
|
||||
active=model.state.notin_(terminal)
|
||||
own=await session.scalar(select(func.count()).select_from(model).where(model.owner_id==owner_id,active))
|
||||
total=await session.scalar(select(func.count()).select_from(model).where(active))
|
||||
if own>=owner_limit or total>=global_limit:
|
||||
fail(429,'quota_exceeded','Queued workflow or batch limit reached')
|
||||
|
||||
|
||||
async def check_storage_budget(session,settings,owner_id,incoming_bytes=0,new_jobs=0,global_incoming_bytes=None):
|
||||
size=await session.scalar(select(func.coalesce(func.sum(Asset.size_bytes),0)).where(
|
||||
Asset.owner_id==owner_id,Asset.ready.is_(True)|Asset.deleted_at.is_(None)))
|
||||
if size+incoming_bytes>getattr(settings,"max_owner_asset_bytes",100*1024**3):fail(429,"quota_exceeded","Owner asset quota exceeded")
|
||||
if settings.mode=="production":
|
||||
storage_incoming=incoming_bytes if global_incoming_bytes is None else global_incoming_bytes
|
||||
# Account only this application's mounted assets/work directories. The
|
||||
# independent model service owns its raw output retention policy.
|
||||
def occupied(root):
|
||||
total=0
|
||||
for path in root.rglob("*"):
|
||||
if path.is_file() and not path.is_symlink():
|
||||
total+=path.stat().st_size
|
||||
return total
|
||||
tmp=(settings.asset_root.parent/"tmp").resolve()
|
||||
if not tmp.is_relative_to(settings.workspace_root):raise ValueError("Temporary storage is outside workspace")
|
||||
roots={settings.asset_root.resolve(),settings.job_work_root.resolve(),tmp}
|
||||
# Avoid counting a nested custom mount twice.
|
||||
roots=[root for root in roots if not any(root!=other and root.is_relative_to(other) for other in roots)]
|
||||
actual=sum(await asyncio.gather(*(asyncio.to_thread(occupied,root) for root in roots)))
|
||||
active=await session.scalar(select(func.count()).select_from(Job).where(Job.state.notin_(["succeeded","failed","cancelled","timed_out"])))
|
||||
reserved=(active+new_jobs)*settings.max_output_bytes*2
|
||||
if actual+reserved+storage_incoming>getattr(settings,"max_data_bytes",2*1024**4):fail(503,"storage_insufficient","Application output and temporary storage budget exceeded")
|
||||
disk=shutil.disk_usage(settings.asset_root)
|
||||
minimum=max(getattr(settings,"min_free_bytes",50*1024**3),int(disk.total*.05))
|
||||
if disk.free-reserved-storage_incoming<minimum:fail(503,"storage_insufficient","Insufficient reserved storage")
|
||||
|
||||
|
||||
class AssetBudgetError(ValueError):
|
||||
code="quota_exceeded"
|
||||
message="Owner asset storage quota exceeded; output retained for reconciliation"
|
||||
retriable=False
|
||||
|
||||
async def enforce_owner_asset_budget(session,settings,owner_id,incoming_bytes):
|
||||
await session.scalar(select(User).where(User.id==owner_id).with_for_update())
|
||||
size=await session.scalar(select(func.coalesce(func.sum(Asset.size_bytes),0)).where(
|
||||
Asset.owner_id==owner_id,Asset.ready.is_(True)|Asset.deleted_at.is_(None)))
|
||||
if size+incoming_bytes>getattr(settings,"max_owner_asset_bytes",100*1024**3):raise AssetBudgetError()
|
||||
@ -1,34 +0,0 @@
|
||||
"""Admission is evaluated at phase boundaries. A closing window never cancels work."""
|
||||
from datetime import datetime,timezone,timedelta
|
||||
from .runtime_policy import read_runtime_policy
|
||||
# fixed UTC+8 has no DST; avoids depending on OS IANA data on Windows.
|
||||
SHANGHAI=timezone(timedelta(hours=8))
|
||||
|
||||
def execution_policy(now=None, *, settings=None):
|
||||
policy=read_runtime_policy(settings)
|
||||
now=now or datetime.now(timezone.utc)
|
||||
if now.tzinfo is None: now=now.replace(tzinfo=timezone.utc)
|
||||
local=now.astimezone(SHANGHAI)
|
||||
opened=local.hour>=21 or local.hour<8
|
||||
next_at=local.replace(hour=21,minute=0,second=0,microsecond=0)
|
||||
if local.hour>=21: next_at+=timedelta(days=1)
|
||||
enabled=policy["batch_window_enabled"]
|
||||
return {"timezone":"Asia/Shanghai","start":"21:00","end":"08:00",
|
||||
"batch_window_enabled":enabled,"configuration_error":policy["configuration_error"],
|
||||
"batch_open":not policy["configuration_error"] and (not enabled or opened),
|
||||
"next_batch_at":next_at.astimezone(timezone.utc).isoformat() if enabled and not policy["configuration_error"] else None,
|
||||
"close_behavior":"finish_current"}
|
||||
|
||||
def admits(job,now=None, *, settings=None):
|
||||
if job.cancel_requested or job.desired_state!="run": return False
|
||||
if set(job.hold_reasons or [])-{"window"}: return False
|
||||
if job.execution_mode!="batch":return True
|
||||
policy=read_runtime_policy(settings)
|
||||
if policy["configuration_error"]:return False
|
||||
return not policy["batch_window_enabled"] or execution_policy(now)["batch_open"]
|
||||
|
||||
def resource_plan(task_type,input_kind=None):
|
||||
if task_type=="audio.transcribe": return [("extract_audio","cpu_media"),("transcribe","new_gpu")] if input_kind=="video" else [("transcribe","new_gpu")]
|
||||
if task_type=="media.structure": return [("sample_frames","cpu_media"),("describe_frames","qwen_http")] if input_kind=="video" else [("describe_frames","qwen_http")]
|
||||
if task_type=="math.solve":return [("solve","qwen_http")]
|
||||
return [("execute","new_gpu" if task_type in {"image.generate","video.generate","defect.generate"} else "cpu_media")]
|
||||
@ -1,35 +0,0 @@
|
||||
"""Conservative first-release GC: inventory only, then explicit opt-in deletion.
|
||||
Unknown/untracked files are never deleted. Asset references protect live snapshots.
|
||||
"""
|
||||
from datetime import timedelta
|
||||
from sqlalchemy import select
|
||||
from .models import Asset,JobAsset,utcnow
|
||||
from .v2_models import AssetReference,SharedAsset
|
||||
from .assets import confined
|
||||
|
||||
async def collect_garbage(db,settings,dry_run=True,grace_days=14):
|
||||
report={"dry_run":dry_run,"candidates":[],"deleted":[],"protected":[]}
|
||||
# Hold the database unit lock across reference recheck and unlink to exclude
|
||||
# new snapshot references. This service is only called in maintenance.
|
||||
async with db.session() as session:
|
||||
rows=(await session.scalars(select(Asset).where(Asset.deleted_at<utcnow()-timedelta(days=grace_days)))).all()
|
||||
for asset in rows:
|
||||
referenced=await session.scalar(select(JobAsset.job_id).where(JobAsset.asset_id==asset.id).limit(1))
|
||||
snapshot=await session.scalar(select(AssetReference.id).where(AssetReference.asset_id==asset.id).limit(1))
|
||||
publication=await session.scalar(select(SharedAsset.id).where(SharedAsset.asset_id==asset.id,SharedAsset.withdrawn_at.is_(None)).limit(1))
|
||||
if referenced or snapshot or publication or not asset.ready:
|
||||
report["protected"].append(asset.id);continue
|
||||
report["candidates"].append(asset.id)
|
||||
# Physical deletion disabled unless maintenance is explicitly active.
|
||||
if not dry_run:
|
||||
from .maintenance import maintenance_active
|
||||
if not maintenance_active(settings):raise RuntimeError("Physical GC requires maintenance")
|
||||
for key in (asset.storage_key,asset.thumbnail_key):
|
||||
if key:
|
||||
path=confined(settings.asset_root,key)
|
||||
if path.is_file():path.unlink()
|
||||
asset.ready=False
|
||||
report["deleted"].append(asset.id)
|
||||
if not dry_run:
|
||||
await session.commit()
|
||||
return report
|
||||
@ -1,64 +0,0 @@
|
||||
from dataclasses import dataclass,field
|
||||
from sqlalchemy import inspect,text,Boolean,String,Text
|
||||
from sqlalchemy.dialects.mysql import TINYINT
|
||||
|
||||
@dataclass
|
||||
class SchemaDiff:
|
||||
differences:list[str]=field(default_factory=list)
|
||||
@property
|
||||
def matches(self):return not self.differences
|
||||
|
||||
def compatible_type(expected,observed,dialect):
|
||||
# Reflection includes inherited database collation; generic VARCHAR does not
|
||||
# assert one. Explicit model collation/charset still remains a hard contract.
|
||||
if isinstance(expected,Boolean) and dialect.name=="mysql":
|
||||
return isinstance(observed,Boolean) or isinstance(observed,TINYINT) and observed.display_width==1
|
||||
if isinstance(expected,String) and isinstance(observed,String):
|
||||
if isinstance(expected,Text)!=isinstance(observed,Text):return False
|
||||
if expected.length!=observed.length:return False
|
||||
for option in ("collation","charset"):
|
||||
desired=getattr(expected,option,None)
|
||||
if desired is not None and desired!=getattr(observed,option,None):return False
|
||||
return True
|
||||
return expected.compile(dialect=dialect).upper()==observed.compile(dialect=dialect).upper()
|
||||
|
||||
def schema_preflight(connection,metadata):
|
||||
inspector=inspect(connection);diff=SchemaDiff()
|
||||
tables=set(inspector.get_table_names())
|
||||
for table in metadata.sorted_tables:
|
||||
if table.name not in tables:diff.differences.append("Missing table: "+table.name);continue
|
||||
if connection.dialect.name=="mysql":
|
||||
options=inspector.get_table_options(table.name)
|
||||
charset=options.get("mysql_default charset") or options.get("mysql_default_charset") or options.get("mysql_charset")
|
||||
if charset and charset!="utf8mb4":diff.differences.append("Unexpected charset: "+table.name)
|
||||
actual={c["name"]:c for c in inspector.get_columns(table.name)}
|
||||
if set(actual)!=set(table.columns.keys()):diff.differences.append("Unexpected/missing columns: "+table.name)
|
||||
if tuple(inspector.get_pk_constraint(table.name)["constrained_columns"])!=tuple(c.name for c in table.primary_key.columns):diff.differences.append("Primary key: "+table.name)
|
||||
for col in table.columns:
|
||||
current=actual.get(col.name)
|
||||
if not current:diff.differences.append(f"Missing column: {table.name}.{col.name}");continue
|
||||
expected=col.type.compile(dialect=connection.dialect)
|
||||
observed=current["type"].compile(dialect=connection.dialect)
|
||||
if not compatible_type(col.type,current["type"],connection.dialect):diff.differences.append(f"Column type: {table.name}.{col.name}: {observed} != {expected}")
|
||||
if not col.primary_key and col.nullable!=current["nullable"]:diff.differences.append(f"Nullability: {table.name}.{col.name}")
|
||||
expected_fks={(tuple(fk.parent.name for fk in constraint.elements),constraint.elements[0].column.table.name,tuple(fk.column.name for fk in constraint.elements)) for constraint in table.foreign_key_constraints}
|
||||
actual_fks={(tuple(fk["constrained_columns"]),fk["referred_table"],tuple(fk["referred_columns"])) for fk in inspector.get_foreign_keys(table.name)}
|
||||
if not expected_fks<=actual_fks:diff.differences.append("Missing foreign key: "+table.name)
|
||||
expected_unique={tuple(c.name for c in constraint.columns) for constraint in table.constraints if constraint.__class__.__name__=="UniqueConstraint"}
|
||||
observed_unique={tuple(c["column_names"]) for c in inspector.get_unique_constraints(table.name)}
|
||||
observed_unique|={tuple(c["column_names"]) for c in inspector.get_indexes(table.name) if c.get("unique")}
|
||||
if not expected_unique<=observed_unique:diff.differences.append("Missing unique constraint: "+table.name)
|
||||
expected_indexes={tuple(c.name for c in index.columns) for index in table.indexes}
|
||||
observed_indexes={tuple(c["column_names"]) for c in inspector.get_indexes(table.name)}
|
||||
if not expected_indexes<=observed_indexes:diff.differences.append("Missing index: "+table.name)
|
||||
return diff
|
||||
|
||||
def check_schema_revision(connection,supported):
|
||||
inspector=inspect(connection)
|
||||
if "alembic_version" not in inspector.get_table_names():raise RuntimeError("Schema is unversioned; preflight and explicit migration required")
|
||||
revisions=set(connection.execute(text("SELECT version_num FROM alembic_version")).scalars())
|
||||
if len(revisions)!=1 or not revisions<=supported:raise RuntimeError("Unsupported schema revision")
|
||||
from .models import Base
|
||||
from . import v2_models
|
||||
diff=schema_preflight(connection,Base.metadata)
|
||||
if not diff.matches:raise RuntimeError("Schema drift: "+"; ".join(diff.differences))
|
||||
0
backend/app/schemas/__init__.py
Normal file
0
backend/app/schemas/__init__.py
Normal file
13
backend/app/schemas/assets.py
Normal file
13
backend/app/schemas/assets.py
Normal file
@ -0,0 +1,13 @@
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class SharedImport(BaseModel):
|
||||
model_config = {"extra": "forbid"}
|
||||
folder_id: str | None = None
|
||||
|
||||
|
||||
class AssetPatch(BaseModel):
|
||||
folder_ids: list[str] | None = Field(default=None, max_length=200)
|
||||
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
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user