cpuai commited on
Commit
94a0de3
·
verified ·
1 Parent(s): 3d75d0c

Deploy Blender Render Studio with Gradio API and MCP

Browse files
.gitattributes CHANGED
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ examples/demo.blend filter=lfs diff=lfs merge=lfs -text
37
+ test-artifacts/cpu-render-preview.png filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.py[cod]
3
+ .pytest_cache/
4
+ .venv/
5
+ venv/
6
+ .env
7
+ .env.*
8
+ runtime_data/
9
+ outputs/
10
+ .client-downloads/
11
+ render-job.json
12
+ *.log
13
+ *.blend1
14
+ *.blend2
15
+ .DS_Store
LICENSE ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Blender Render Studio contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
23
+ This license covers this application's original source code. Blender,
24
+ FFmpeg, PyTorch, Gradio, and other third-party software retain their own
25
+ licenses. Blender is downloaded from its official distribution at runtime;
26
+ the Blender executable is not included in this application's source package.
README.md CHANGED
@@ -1,13 +1,135 @@
1
  ---
2
  title: Blender Render Studio
3
- emoji: 😻
4
- colorFrom: indigo
5
- colorTo: indigo
6
  sdk: gradio
7
  sdk_version: 6.28.0
8
- python_version: '3.13'
9
  app_file: app.py
10
  pinned: false
 
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  title: Blender Render Studio
3
+ emoji: 🎬
4
+ colorFrom: green
5
+ colorTo: blue
6
  sdk: gradio
7
  sdk_version: 6.28.0
8
+ python_version: "3.12"
9
  app_file: app.py
10
  pinned: false
11
+ license: mit
12
  ---
13
 
14
+ # Blender Render Studio
15
+
16
+ 上传 `.blend`、纹理/缓存 ZIP 和 JSON 渲染配置,使用 Blender Cycles 生成图片、帧序列或 MP4 视频。提供中文 Gradio 界面、API、MCP,以及可连续提交批次、断点续渲、下载结果的 Python 客户端。
17
+
18
+ **ZeroGPU 渲染路径已实现,但 Blender 原生子进程与真实 ZeroGPU 的组合尚未在 Hugging Face 上验证。** 部署后必须先通过内置的真实 GPU 渲染自检。ZeroGPU 官方主要面向 PyTorch 工作负载,不能仅凭 `@spaces.GPU`、CUDA 可见或 PyTorch 自检成功就宣称 Blender 可用。本应用使用 Blender 自己渲染小场景来验证;GPU 失败会报错,不会悄悄转为 CPU。[官方兼容性说明](https://huggingface.co/docs/hub/en/spaces-zerogpu)
19
+
20
+ ## 能做什么
21
+
22
+ - 上传单个已打包资源的 `.blend`,或包含工程与外部资源的 ZIP。
23
+ - JSON 设置场景、相机、视图层、分辨率、采样、降噪、透明背景、帧区间和 GPU 时间预算。
24
+ - Cycles 的 AUTO / CUDA / OptiX 渲染;管理员可显式选择 CPU 测试模式。
25
+ - PNG 8/16 位、OpenEXR 16/32 位帧输出;PNG 序列合成 H.264 MP4。
26
+ - 按批申请 GPU,保存完成帧;取消、恢复、导出部分结果与日志。
27
+ - 使用同一套服务逻辑处理 UI、API 与 MCP 请求。
28
+
29
+ 这是渲染服务:它保留模型、材质、灯光、动画与受支持的已烘焙缓存,但不会替用户建立动画。自动脚本、OSL、合成器与视频序列编辑器被禁用,不安装用户插件。长动画需要多次租约,**不承诺免费、不承诺无限 GPU 时间,也不保证单帧超出平台时限的大场景能够完成**。
30
+
31
+ ## 部署到 Hugging Face
32
+
33
+ 1. 新建 **Gradio SDK、Python 3.12** 的 Space,推荐设置为私有。
34
+ 2. 把本项目根目录全部文件上传到 Space 根目录,保留此 README 的 YAML 配置。
35
+ 3. 在 Space Settings 选择 **ZeroGPU** 硬件;是否可选取决于账号与平台当前资格。设置变量 `RENDER_BACKEND=zerogpu`。
36
+ 4. 等待构建完成。`requirements.txt` 已包含 PyTorch;`packages.txt` 会安装 FFmpeg 与 Blender 的系统依赖。首次启动自动下载官方 Blender **5.2.2** 并校验 SHA-256。
37
+ 5. 打开「环境自检」页,先查看环境,再运行真实 GPU 渲染自检。只有返回 `ok=true` 且 `gpu_verified=true` 才开始正式 GPU 任务。
38
+
39
+ 若 ZeroGPU 自检失败,下载诊断日志;可以由你在 Space 设置中选择普通 NVIDIA GPU,并设置 `RENDER_BACKEND=gpu`。应用不会替你升级付费硬件。完整步骤、系统变量与问题排查见 [部署文档](docs/DEPLOY.zh-CN.md)。
40
+
41
+ ## 立即试一个图片任务
42
+
43
+ 在 Blender 中打开模型,先选择 `File → External Data → Pack Resources`,保存 `.blend`。不能内嵌的资源、外链 `.blend` 和已烘焙缓存放进工程目录,并执行 `Make Paths Relative`,将整个目录内容打包为 ZIP。
44
+
45
+ 源码包自带 [演示模型 demo.blend](examples/demo.blend),可以先上传它确认流程,再上传自己的工程。
46
+
47
+ 在界面上传工程,使用下面配置,然后依次点击「准备渲染任务」「检查场景与资源」「渲染下一批」「打包下载 / 合成视频」。动画可点击「连续渲染剩余帧」,应用会自动逐批执行,遇到错误或配额不足停止;随时可以点击「停止任务」并保留已完成帧。
48
+
49
+ ```json
50
+ {
51
+ "mode": "image",
52
+ "width": 640,
53
+ "height": 360,
54
+ "samples": 16,
55
+ "frame": 1,
56
+ "device": "AUTO",
57
+ "batch_size": 1,
58
+ "gpu_seconds": 120
59
+ }
60
+ ```
61
+
62
+ 上传 JSON 文件后,它优先于编辑器内容。调整编辑器前请清空 JSON 文件上传框。若 ZIP 中有多个 `.blend`,设置 `"blend_file": "project/scene.blend"`,路径以 ZIP 解压根目录为准,使用 `/`。
63
+
64
+ 项目提供 [图片配置](examples/image.json)、[5 秒视频配置](examples/video.json)、[EXR 帧序列配置](examples/frames-exr.json)。实际耗时由场景决定,示例的 GPU 秒数只是请求预算。
65
+
66
+ ## Agent 一条龙调用
67
+
68
+ 客户端可在 Windows、macOS 或 Linux 使用,服务部署目标为 Linux x64。客户端只需要安装 `gradio_client`:
69
+
70
+ ```bash
71
+ python -m pip install "gradio_client>=2.0,<3"
72
+ python examples/client_render.py --space YOUR_NAME/YOUR_SPACE --project scene.zip --config examples/video.json --output outputs --self-test
73
+ ```
74
+
75
+ 私有 Space 或需要账号配额时,通过环境变量 `HF_TOKEN` 提供有权访问该 Space 的令牌,不要写进配置或源码。脚本在 `outputs/render-job.json` 保存任务 ID,遇到服务端错误、配额问题或没有进展会停止,尽量下载已完成帧和日志。任务 ID 和下载链接都应保密。
76
+
77
+ ```bash
78
+ # 接着上一次任务继续,沿用服务端原配置和已经完成的帧。
79
+ python examples/client_render.py --space YOUR_NAME/YOUR_SPACE --resume-job --output outputs
80
+
81
+ # 指定已有任务 ID,也可换一台客户端电脑继续。
82
+ python examples/client_render.py --space YOUR_NAME/YOUR_SPACE --resume-job YOUR_JOB_ID --output restored
83
+ ```
84
+
85
+ Space 重启、睡眠后的磁盘更替或过期清理可能使任务失效;保存本机任务 ID 不等于已备份帧文件。更多 API、MCP 文件上传说明见 [API 文档](docs/API.zh-CN.md)。
86
+
87
+ ## MCP
88
+
89
+ 应用启动时启用 `mcp_server=True`,原生 Streamable HTTP 地址为:
90
+
91
+ ```text
92
+ https://YOUR-SPACE-DOMAIN.hf.space/gradio_api/mcp/
93
+ ```
94
+
95
+ 参考 [MCP 客户端配置](examples/mcp-client.json)。MCP 客户端的身份验证字段因产品而异;私有 Space 需要提供 HF 认证。Agent 本机的 `C:\project\scene.zip` 不会自动成为 Space 文件,先使用客户端上传或该 MCP 客户端支持的文件上传能力,再调用准备任务。上传本地大文件最直接的方式是使用上面的 Python 脚本。
96
+
97
+ ## 本机开发与验证
98
+
99
+ ```bash
100
+ python3.12 -m venv .venv
101
+ source .venv/bin/activate
102
+ python -m pip install -r requirements.txt
103
+ # Debian/Ubuntu 上先安装 packages.txt 中的系统包;已有 Blender 时可设 BLENDER_BIN。
104
+ export RENDER_BACKEND=cpu
105
+ python app.py
106
+ ```
107
+
108
+ 浏览器访问 `http://127.0.0.1:7860`。完整依赖包含较大的 PyTorch CUDA 包,便于原样部署 ZeroGPU;CPU 逻辑测试本身不需要 GPU。
109
+
110
+ ```bash
111
+ python -m pip install -r requirements-dev.txt
112
+ python -m pytest -q
113
+ # 真实启动 Gradio、上传工程与 JSON、用 CPU 渲染并验证下载:
114
+ python scripts/smoke_test.py
115
+ ```
116
+
117
+ 已完成 98 项 pytest 检查,以及 Blender 5.2.2 真实 CPU 的 PNG、EXR、3 帧视频、API 上传/下载和 MCP 10 个工具的发现/调用验证。详情见 [测试报告](docs/TEST_REPORT.zh-CN.md)。这些本地测试不能证明 HF ZeroGPU 已兼容 Blender,仍需部署后的真实 GPU 自检。详细规划、状态与限制见 [架构文档](docs/ARCHITECTURE.zh-CN.md)。
118
+
119
+ ## 项目结构
120
+
121
+ | 路径 | 用途 |
122
+ | --- | --- |
123
+ | `app.py` | Gradio 界面、API、MCP 注册 |
124
+ | `service.py` | 任务、批次、GPU 租约、取消与导出 |
125
+ | `render_config.py` | 严格 JSON 校验及 JSON Schema |
126
+ | `uploads.py` | 上传、ZIP 解压与路径校验 |
127
+ | `blender_runtime.py` | 官方 Blender 安装、子进程、超时与日志 |
128
+ | `render_worker.py` | Blender 内的场景检查、设备选择与逐帧渲染 |
129
+ | `examples/` | 配置、自动渲染客户端、MCP 配置 |
130
+ | `scripts/create_demo.py` | 在 Blender 中生成自包含演示场景 |
131
+ | `scripts/smoke_test.py` | 真实 Gradio API 上传、CPU 渲染与下载检查 |
132
+ | `tests/` | 配置、上传、任务流程等测试 |
133
+ | `docs/` | 规划、部署与 API 说明 |
134
+
135
+ 应用原创代码采用 MIT 许可;Blender、FFmpeg 等依赖保留各自许可。只上传你有权渲染的工程;推荐将本服务用于自己和受信任协作者的模型。
SHA256SUMS.txt ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 01ca9723815bf82ce4f5a5ea72b3ffca1e3f0861ca031f0611a9fbfb028352d8 .gitignore
2
+ 9859366fd6a1e412cde3018acec7a11746d71282e23a8e0b51f9ae83a153b02c LICENSE
3
+ fdd9c182d075133d5ecb63c78f66138fe285eb5e48e6078fff6422a9f59ad717 README.md
4
+ c9c3c0a625432125e2d67e4ec41cab2da24d4a2a82ea90bb4c2cb4b4f373a1ce app.py
5
+ ef5284556766604a33ca95d4006f1360c395475426a7a660069aaa810c9a337b blender_runtime.py
6
+ ed94fb81f67c9d88a3cc4f81cc0b41824bda38315b282ff0a0ac44cd75c76a74 docs/API.zh-CN.md
7
+ b0bbcff7f95847cd795389f006a59d57d356ea7f3366bc0ffea5fdf77ad4869e docs/ARCHITECTURE.zh-CN.md
8
+ dbc14cecfa03c85d526460de1cba82498356e3b42368806728f8c9a619d88dd6 docs/DEPLOY.zh-CN.md
9
+ aec2bf3529cf4e44a17e33e5620b6a121a0e87c36e7be1087d756c0fc4353c55 docs/TEST_REPORT.zh-CN.md
10
+ c43d9cd5812344d06e492deb695d8d56590a3ae49bad83d44f97cf0d3615e65f examples/client_render.py
11
+ 5526526b59e34340d00fd0f50c9eb154b6cbc2a20966e978676016c76246b299 examples/demo.blend
12
+ bf20fe326c04e0da1fb73ca274bdeb1aab3f376b6a58436fb61f36b8ef92b4d1 examples/frames-exr.json
13
+ adb035c8df07ca5ae548246ae06cf4e4d1d950e5979c654dd2a6d026bebb2bf6 examples/image.json
14
+ 9c31eed31fe6dbf766c61a8d2a496e10e7217dd6484ea8110664df9876285078 examples/mcp-client.json
15
+ 315f3e2a287d0432731ac338226adda7f2a0417f89d16def6f5a19b1814ea851 examples/video.json
16
+ e4559cf2075458310e2d45adfa6a194abe3c5f0c190281761d82baa0882a0920 packages.txt
17
+ eac6acad35c1807caefed69ff8a24241a5b282aa78d07eff2dc7466ef190aa6b render.schema.json
18
+ 9fddaee1f11cdea4e873da26372cf89660d2226b04c5c441c2d8f028872e005d render_config.py
19
+ 192dbfb9677d30f47de762c670ccaf4614fc9d3dbe60e5e4710155be79b8bb66 render_worker.py
20
+ 5e80794bcc6d2549958645e311fe2e150307ca42d1a05b154959c044697327ad requirements-dev.txt
21
+ 87a9e0631bcf876ec66709de42468e22aad8d55ec7eacfcecc6cb4042b0b9685 requirements.txt
22
+ 65e361844de06033efda047b4a4092f6d073f03e5bfef61af95cf0af66a1c9a0 scripts/create_demo.py
23
+ 0011be2a80cf0b9c33343060c9686673c49dbbb38959eeaedd981de4e1920771 scripts/smoke_test.py
24
+ f53672630ccacee5d9f0d6dd255f1e60e5d72b31111500e722b5479faf950703 service.py
25
+ 5b460e5eb194c451fe914693222c182a084f4e4d49029248c4f37de7e6ffb442 test-artifacts/api-smoke-report.json
26
+ 37c0bcbd782040c859387845cb02eefc787628b70da1c591fbcbf3866926d06f test-artifacts/cpu-animation-preview.mp4
27
+ 106a45a39d7d4bfc3c42b2366ccff21261afa6b4d62b4757396f6bf7b086dea6 test-artifacts/cpu-render-preview.png
28
+ c36a41702e9d6fa2c080926aaeb1a54028fe845fd987ceee01b15dec44c9c1e3 test-artifacts/exr-smoke-report.json
29
+ f780ddecea166cabf5b6ee4ce8abe1d94f9ff24abdf9c2c7b27d3b04722be6aa test-artifacts/video-smoke-report.json
30
+ 6ec47b34933b82755ad54217aa0fd2a9ac9d9636c2f1c87a42d3d735ea2d6cfa tests/test_config_uploads.py
31
+ c650d0b654da4e7bea54fa931b79c1fbe0f22044cc5a60e066944666c40ff3a2 tests/test_runtime.py
32
+ 711e0f562fc6d0bfdc9e4007475f99ceda6a343185d106c016546c5b6dbe3a27 tests/test_service.py
33
+ 4fb5d2d55725d9adb5f8c58be6192cde4d825f2f31c1b698458eb39f8add3a37 uploads.py
app.py ADDED
@@ -0,0 +1,469 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Blender Render Space 的 Gradio 界面、公开 API 和 MCP 入口。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ # ZeroGPU 要求 spaces 在可能加载 CUDA 的库之前导入。
6
+ import spaces # noqa: F401
7
+
8
+ import json
9
+ import logging
10
+ import os
11
+ from collections.abc import Iterator
12
+ from typing import Any, Callable, TypeVar
13
+
14
+ import gradio as gr
15
+
16
+ import service
17
+ from blender_runtime import ensure_blender
18
+ from render_config import RenderConfig
19
+
20
+
21
+ LOGGER = logging.getLogger(__name__)
22
+ T = TypeVar("T")
23
+
24
+ CSS = """
25
+ .gradio-container { max-width: 1480px !important; margin: 0 auto; }
26
+ #render-hero {
27
+ background: linear-gradient(125deg, #102331, #1b4148 62%, #2c6062);
28
+ border: 1px solid #31565b; border-radius: 20px;
29
+ padding: 30px 32px; margin: 8px 0 18px; color: #f3fbfc;
30
+ }
31
+ #render-hero .eyebrow { font-size: 12px; letter-spacing: .15em; color: #9be3d8; }
32
+ #render-hero h1 { color: #f3fbfc; font-size: clamp(27px, 4vw, 39px); margin: 7px 0 9px; }
33
+ #render-hero p { color: #c7dcdf; margin: 0; line-height: 1.75; }
34
+ #render-hero .pills { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 19px; }
35
+ #render-hero .pill {
36
+ font-size: 12px; background: #ffffff12; border: 1px solid #ffffff26;
37
+ border-radius: 30px; padding: 5px 12px; color: #e4f5f4;
38
+ }
39
+ .workflow-note { border-left: 3px solid #3d9e91; padding-left: 12px; }
40
+ .section-caption { margin-top: 8px; margin-bottom: 0; }
41
+ #job-actions { align-items: stretch; }
42
+ @media (max-width: 640px) {
43
+ #render-hero { padding: 24px 20px; border-radius: 14px; }
44
+ }
45
+ """
46
+
47
+ HERO = """
48
+ <section id="render-hero">
49
+ <div class="eyebrow">BLENDER RENDER SPACE</div>
50
+ <h1>把场景变成作品</h1>
51
+ <p>上传 Blender 工程与资源,用 JSON 驱动图片或动画渲染。<br>
52
+ 按批次保存帧,通过 API 与 MCP 接入你的创作 Agent。</p>
53
+ <div class="pills">
54
+ <span class="pill">Cycles 渲染</span>
55
+ <span class="pill">逐批续渲</span>
56
+ <span class="pill">图片 / 视频</span>
57
+ <span class="pill">API + MCP</span>
58
+ </div>
59
+ </section>
60
+ """
61
+
62
+
63
+ def _invoke(function: Callable[..., T], *args: Any) -> T:
64
+ """把服务异常转换成可读的 Gradio / API 错误,保留后台诊断日志。"""
65
+ try:
66
+ return function(*args)
67
+ except gr.Error:
68
+ raise
69
+ except Exception as exc:
70
+ LOGGER.exception("Render service request failed: %s", function.__name__)
71
+ raise gr.Error(str(exc) or "操作失败,请查看 Space 日志。") from exc
72
+
73
+
74
+ def _job_id(value: str) -> str:
75
+ """任务 ID 也是访问任务的凭据,禁止将空字符串传入服务。"""
76
+ value = (value or "").strip()
77
+ if not value:
78
+ raise gr.Error("请先准备任务,或填入之前保存的任务 ID。")
79
+ return value
80
+
81
+
82
+ def environment_info() -> dict[str, Any]:
83
+ """Inspect the runtime, Blender installation and selected rendering backend.
84
+
85
+ Returns:
86
+ Environment information without allocating a ZeroGPU lease.
87
+ """
88
+ return _invoke(service.environment_info)
89
+
90
+
91
+ def config_schema() -> dict[str, Any]:
92
+ """Get the JSON Schema for every supported render configuration option.
93
+
94
+ Returns:
95
+ The authoritative configuration schema, defaults and validation limits.
96
+ """
97
+ return _invoke(service.config_schema)
98
+
99
+
100
+ def prepare_job(
101
+ files: list[str], config_json: str, config_file: str | None = None
102
+ ) -> tuple[str, dict[str, Any]]:
103
+ """Upload and validate a Blender project and create a resumable render job.
104
+
105
+ Args:
106
+ files: Uploaded .blend files, resource ZIP archives and supporting assets.
107
+ config_json: Render configuration encoded as a JSON object.
108
+ config_file: Optional uploaded JSON configuration file.
109
+
110
+ Returns:
111
+ A private job ID and the initial job status. Keep the ID for later calls.
112
+ """
113
+ if not files:
114
+ raise gr.Error("请上传 .blend 工程,或包含工程及资源的 ZIP 文件。")
115
+ return _invoke(service.prepare_job, files, config_json or "{}", config_file)
116
+
117
+
118
+ def inspect_job(job_id: str) -> dict[str, Any]:
119
+ """Inspect a Blender scene, cameras and referenced assets before rendering.
120
+
121
+ Args:
122
+ job_id: The private job ID returned by prepare_job.
123
+
124
+ Returns:
125
+ Scene inspection results and the current job status.
126
+ """
127
+ return _invoke(service.inspect_job, _job_id(job_id))
128
+
129
+
130
+ def render_chunk(job_id: str) -> dict[str, Any]:
131
+ """Render the next bounded batch and retain completed frames for resuming.
132
+
133
+ Args:
134
+ job_id: The private job ID returned by prepare_job.
135
+
136
+ Returns:
137
+ Updated job status. Call again while pending frames remain, then finalize.
138
+ """
139
+ return _invoke(service.render_chunk, _job_id(job_id))
140
+
141
+
142
+ def _render_remaining(job_id: str) -> Iterator[dict[str, Any]]:
143
+ """界面专用连续模式:每批正常申请 GPU,错误或取消后立即结束。"""
144
+ job_id = _job_id(job_id)
145
+ current = _invoke(service.job_status, job_id)
146
+ yield current
147
+ halted = {"cancelled", "cancelling", "canceled", "failed", "error"}
148
+ if current.get("status") in {"cancelled", "cancelling", "canceled"}:
149
+ gr.Warning("任务已停止,请先点击「恢复任务」,再启动连续渲染。")
150
+ return
151
+ if current.get("error") or current.get("status") in halted:
152
+ gr.Warning("任务存在错误。请先检查日志并处理原因,再恢复任务;连续模式不会自动重试。")
153
+ return
154
+ if current.get("status") == "rendering":
155
+ gr.Warning("此任务正在渲染,请等待当前批次完成。")
156
+ return
157
+
158
+ while current.get("remaining_frames"):
159
+ # 每轮先检查取消标志;绝不自动清除标志或重试配额错误。
160
+ current = _invoke(service.job_status, job_id)
161
+ if current.get("error") or current.get("status") in halted:
162
+ yield current
163
+ return
164
+ remaining = current.get("remaining_frames", [])
165
+ if not remaining:
166
+ yield current
167
+ return
168
+ previous_count = len(remaining)
169
+ current = _invoke(service.render_chunk, job_id)
170
+ yield current
171
+ if current.get("error") or current.get("status") in halted:
172
+ return
173
+ pending = current.get("remaining_frames", [])
174
+ if pending and len(pending) >= previous_count:
175
+ # 避免异常状态无进展却反复租用 GPU。
176
+ gr.Warning("本批次未减少剩余帧,连续渲染已停止。请检查任务状态与日志。")
177
+ return
178
+
179
+
180
+ def job_status(job_id: str) -> dict[str, Any]:
181
+ """Read render progress without waiting for the Blender execution queue.
182
+
183
+ Args:
184
+ job_id: The private job ID returned by prepare_job.
185
+
186
+ Returns:
187
+ Current job state and completed-frame progress.
188
+ """
189
+ return _invoke(service.job_status, _job_id(job_id))
190
+
191
+
192
+ def cancel_job(job_id: str) -> dict[str, Any]:
193
+ """Request cancellation while preserving already completed render frames.
194
+
195
+ Args:
196
+ job_id: The private job ID returned by prepare_job.
197
+
198
+ Returns:
199
+ Cancellation status. Use job_status to observe the final state.
200
+ """
201
+ return _invoke(service.cancel_job, _job_id(job_id))
202
+
203
+
204
+ def resume_job(job_id: str) -> dict[str, Any]:
205
+ """Resume a stopped job while retaining successfully rendered frames.
206
+
207
+ Args:
208
+ job_id: The private job ID returned by prepare_job.
209
+
210
+ Returns:
211
+ Updated job state. Call render_chunk to render the next batch.
212
+ """
213
+ return _invoke(service.resume_job, _job_id(job_id))
214
+
215
+
216
+ def finalize_job(
217
+ job_id: str,
218
+ ) -> tuple[dict[str, Any], list[str], str | None, str | None]:
219
+ """Package rendered frames and encode a video when the job is complete.
220
+
221
+ Args:
222
+ job_id: The private job ID returned by prepare_job.
223
+
224
+ Returns:
225
+ A result summary, downloadable files, optional image and optional video.
226
+ """
227
+ return _invoke(service.finalize_job, _job_id(job_id))
228
+
229
+
230
+ def gpu_self_test() -> tuple[dict[str, Any], list[str], str | None]:
231
+ """Test actual Blender GPU rendering with a small built-in scene.
232
+
233
+ Returns:
234
+ Diagnostic results, downloadable logs and an optional test render.
235
+ A failed GPU test does not silently switch the render job to CPU.
236
+ """
237
+ return _invoke(service.gpu_self_test)
238
+
239
+
240
+ def _preset(mode: str) -> str:
241
+ """从同一配置模型生成示例,避免界面默认值与后端校验发生偏差。"""
242
+ data = RenderConfig().model_dump(mode="json")
243
+ data["mode"] = mode
244
+ return json.dumps(data, indent=2, ensure_ascii=False)
245
+
246
+
247
+ def build_app() -> gr.Blocks:
248
+ """构建界面;导入本模块不会下载 Blender,也不会申请 GPU。"""
249
+ with gr.Blocks(title="Blender Render Space", delete_cache=(3600, 86400)) as demo:
250
+ gr.HTML(HERO)
251
+ gr.Markdown(
252
+ "**ZeroGPU + Blender 为实验性组合。** 首次使用请运行「环境自检」:"
253
+ "必须确认 Blender 子进程能在当前 Space 的 GPU 租约内实际渲染。"
254
+ "GPU 失败会明确报错;不会静默转为 CPU。"
255
+ "长动画由多个有时限的批次完成,单帧仍需在单次租约内完成。",
256
+ elem_classes="workflow-note",
257
+ )
258
+
259
+ with gr.Tabs():
260
+ with gr.Tab("渲染工作台"):
261
+ with gr.Row():
262
+ with gr.Column(scale=5, min_width=320):
263
+ gr.Markdown("### 01 · 上传工程", elem_classes="section-caption")
264
+ upload = gr.File(
265
+ label="Blender 工程与资源",
266
+ file_count="multiple",
267
+ type="filepath",
268
+ height=190,
269
+ )
270
+ gr.Markdown(
271
+ "推荐上传**包含 .blend 与纹理目录的 ZIP**,保留相对路径;"
272
+ "也可以先在 Blender 中打包外部资源,再上传 .blend。"
273
+ "多个单独上传文件的目录结构不会自动保留。"
274
+ )
275
+ config_upload = gr.File(
276
+ label="渲染配置 JSON(可选)",
277
+ file_types=[".json"],
278
+ type="filepath",
279
+ )
280
+ gr.Markdown("### 02 · 设置渲染", elem_classes="section-caption")
281
+ with gr.Row():
282
+ image_preset = gr.Button("图片配置", size="sm")
283
+ video_preset = gr.Button("视频配置", size="sm")
284
+ config_editor = gr.Code(
285
+ value=_preset("image"),
286
+ language="json",
287
+ label="JSON 配置编辑器",
288
+ lines=19,
289
+ max_lines=32,
290
+ interactive=True,
291
+ )
292
+ gr.Markdown(
293
+ "上传 JSON 文件后,将使用文件中的配置。"
294
+ "使用编辑器时,请先清空上方 JSON 上传框。"
295
+ "`batch_size` 控制每次提交的帧数;建议先用低分辨率、"
296
+ "少量采样验证,再提高画质。"
297
+ )
298
+ prepare = gr.Button("准备渲染任务", variant="primary", size="lg")
299
+
300
+ with gr.Column(scale=6, min_width=320):
301
+ gr.Markdown("### 03 · 检查与渲染", elem_classes="section-caption")
302
+ job = gr.Textbox(
303
+ label="任务 ID",
304
+ placeholder="准备后自动填入,也可粘贴已有任务 ID",
305
+ interactive=True,
306
+ buttons=["copy"],
307
+ )
308
+ gr.Markdown(
309
+ "保存任务 ID,便于 API 调用和续渲。"
310
+ "任务 ID 可访问对应结果,请勿公开。Space 重启可能清除临时任务。"
311
+ )
312
+ with gr.Row(elem_id="job-actions"):
313
+ inspect = gr.Button("检查场景与资源")
314
+ render = gr.Button("渲染下一批", variant="primary")
315
+ render_remaining = gr.Button("连续渲染剩余帧", variant="primary")
316
+ with gr.Row():
317
+ refresh = gr.Button("刷新进度", size="sm")
318
+ cancel = gr.Button("停止任务", variant="stop", size="sm")
319
+ resume = gr.Button("恢复任务", size="sm")
320
+ status = gr.JSON(label="任务状态 / 场景检查", value={"status": "请先准备任务"})
321
+ gr.Markdown(
322
+ "每次点击「渲染下一批」处理一个批次;剩余帧可继续提交。"
323
+ "「连续渲染剩余帧」会逐批提交,遇到错误或配额不足立即结束,"
324
+ "不会自动重试。**连续模式可能耗尽 GPU 配额,可随时点击「停止任务」。**"
325
+ "API / Agent 也可按状态自动循环。"
326
+ "停止后保留已完成帧;点击「恢复任务」后再提交渲染。"
327
+ )
328
+ gr.Markdown("### 04 · 导出作品", elem_classes="section-caption")
329
+ finalize = gr.Button("整理结果 / 合成视频", variant="primary")
330
+ result = gr.JSON(label="导出结果")
331
+ downloads = gr.File(
332
+ label="下载结果与日志", file_count="multiple", interactive=False
333
+ )
334
+ with gr.Tabs():
335
+ with gr.Tab("图片预览"):
336
+ image = gr.Image(
337
+ label="渲染图片",
338
+ type="filepath",
339
+ interactive=False,
340
+ height=340,
341
+ buttons=["download", "fullscreen"],
342
+ )
343
+ with gr.Tab("视频预览"):
344
+ video = gr.Video(label="渲染视频", interactive=False, height=340)
345
+
346
+ with gr.Tab("环境自检"):
347
+ gr.Markdown(
348
+ "### 先验证运行环境\n\n"
349
+ "「读取环境」不会申请 GPU。"
350
+ "「运行 GPU 自检」会尝试实际渲染一个小场景,可能消耗 ZeroGPU 配额。"
351
+ "自检失败时,请下载日志检查原因,或选择常驻 GPU Space。\n\n"
352
+ "后端由 Space 环境变量 `RENDER_BACKEND` 选择:"
353
+ "`auto`、`zerogpu`、`gpu` 或 `cpu`。"
354
+ "CPU 模式用于功能验证;GPU 模式不进行静默 CPU 回退。"
355
+ )
356
+ with gr.Row():
357
+ env_button = gr.Button("读取环境")
358
+ probe_button = gr.Button("运行 GPU 自检", variant="primary")
359
+ env_output = gr.JSON(label="环境信息")
360
+ with gr.Row():
361
+ with gr.Column():
362
+ probe_output = gr.JSON(label="自检报告")
363
+ probe_files = gr.File(
364
+ label="下载自检日志", file_count="multiple", interactive=False
365
+ )
366
+ probe_image = gr.Image(
367
+ label="自检渲染图", type="filepath", interactive=False, height=300
368
+ )
369
+
370
+ with gr.Tab("Agent / API"):
371
+ gr.Markdown(
372
+ "### 可直接调用的渲染工具\n\n"
373
+ "API 名称与下表一致。点击页面底部 **Use via API** 查看当前 Space "
374
+ "地址、参数格式与代码示例。所有接口也作为 MCP 工具提供。\n\n"
375
+ "| API | 用途 |\n| --- | --- |\n"
376
+ "| `environment_info` | 检查后端与安装信息 |\n"
377
+ "| `config_schema` | 获取完整 JSON Schema |\n"
378
+ "| `gpu_self_test` | 验证 Blender 实际 GPU 渲染 |\n"
379
+ "| `prepare_job` | 上传工程和配置,创建任务 |\n"
380
+ "| `inspect_job` | 检查场景、相机与资源 |\n"
381
+ "| `render_chunk` | 渲染下一批,保存已完成帧 |\n"
382
+ "| `job_status` | 不等待渲染队列,读取进度 |\n"
383
+ "| `cancel_job` | 请求停止,保留已完成帧 |\n"
384
+ "| `resume_job` | 将停止的任务恢复为可继续状态 |\n"
385
+ "| `finalize_job` | 导出结果、日志并合成视频 |\n\n"
386
+ "**建议调用顺序:** 获取配置 Schema → 准备任务 → 检查场景 → "
387
+ "循环调用 `render_chunk` → 确认完成 → 调用 `finalize_job`。"
388
+ "遇到错误先读取状态与日志;不要无条件重复申请 GPU。\n\n"
389
+ "### MCP 连接\n\n"
390
+ "Streamable HTTP:`https://<你的-Space-域名>.hf.space/gradio_api/mcp/`\n\n"
391
+ "兼容 SSE:`https://<你的-Space-域名>.hf.space/gradio_api/mcp/sse`\n\n"
392
+ "MCP 工具使用上传后的文件引用;Agent 本机路径不会自动出现在 Space 中。"
393
+ "上传本地大文件优先使用 `gradio_client.handle_file`,"
394
+ "后续操作只需传任务 ID。私有 Space 的客户端还需要 Hugging Face 令牌。"
395
+ )
396
+ schema_button = gr.Button("读取配置 JSON Schema")
397
+ schema_output = gr.JSON(label="配置 Schema")
398
+
399
+ # Blender 操作共用一个执行队列,防止多个进程争用同一个 GPU 或输出目录。
400
+ blender_queue = {"concurrency_id": "blender", "concurrency_limit": 1}
401
+ prepare.click(
402
+ prepare_job,
403
+ inputs=[upload, config_editor, config_upload],
404
+ outputs=[job, status],
405
+ api_name="prepare_job",
406
+ **blender_queue,
407
+ )
408
+ inspect.click(inspect_job, job, status, api_name="inspect_job", **blender_queue)
409
+ render.click(render_chunk, job, status, api_name="render_chunk", **blender_queue)
410
+ render_remaining.click(
411
+ _render_remaining,
412
+ job,
413
+ status,
414
+ api_visibility="private",
415
+ **blender_queue,
416
+ )
417
+ # 进度与停止请求不进入渲染队列,否则长渲染会阻塞取消操作。
418
+ refresh.click(job_status, job, status, api_name="job_status", queue=False)
419
+ cancel.click(cancel_job, job, status, api_name="cancel_job", queue=False)
420
+ resume.click(resume_job, job, status, api_name="resume_job", queue=False)
421
+ finalize.click(
422
+ finalize_job,
423
+ job,
424
+ [result, downloads, image, video],
425
+ api_name="finalize_job",
426
+ **blender_queue,
427
+ )
428
+ env_button.click(environment_info, None, env_output, api_name="environment_info", queue=False)
429
+ schema_button.click(config_schema, None, schema_output, api_name="config_schema", queue=False)
430
+ probe_button.click(
431
+ gpu_self_test,
432
+ None,
433
+ [probe_output, probe_files, probe_image],
434
+ api_name="gpu_self_test",
435
+ **blender_queue,
436
+ )
437
+ # 纯界面快捷操作不作为 Agent 工具暴露。
438
+ image_preset.click(
439
+ lambda: _preset("image"), None, config_editor, queue=False, api_visibility="private"
440
+ )
441
+ video_preset.click(
442
+ lambda: _preset("video"), None, config_editor, queue=False, api_visibility="private"
443
+ )
444
+
445
+ return demo.queue(default_concurrency_limit=1, max_size=32)
446
+
447
+
448
+ demo = build_app()
449
+
450
+
451
+ if __name__ == "__main__":
452
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
453
+ # 安装与解压在申请 GPU 之前完成,避免把下载时间算进 ZeroGPU 租约。
454
+ LOGGER.info("正在准备 Blender 运行时(首次运行需要下载并校验安装包)")
455
+ binary = ensure_blender()
456
+ LOGGER.info("Blender 运行时已就绪:%s", binary)
457
+ service.PUBLIC_ROOT.mkdir(parents=True, exist_ok=True)
458
+ demo.launch(
459
+ server_name=os.environ.get("GRADIO_SERVER_NAME", "0.0.0.0"),
460
+ server_port=int(os.environ.get("PORT", os.environ.get("GRADIO_SERVER_PORT", "7860"))),
461
+ mcp_server=True,
462
+ max_file_size="1gb",
463
+ theme=gr.themes.Soft(primary_hue="teal", neutral_hue="slate"),
464
+ css=CSS,
465
+ # 仅发布服务显式导出的文件;不允许浏览整个任务目录或上传源文件。
466
+ allowed_paths=[str(service.PUBLIC_ROOT.resolve())],
467
+ footer_links=["api"],
468
+ show_error=False,
469
+ )
blender_runtime.py ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """安装可信 Blender 运行时,并在可取消的隔离子进程中执行固定渲染脚本。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import hashlib
7
+ import json
8
+ import os
9
+ import posixpath
10
+ import re
11
+ import shutil
12
+ import signal
13
+ import subprocess
14
+ import tarfile
15
+ import tempfile
16
+ import threading
17
+ import time
18
+ import urllib.error
19
+ import urllib.request
20
+ from pathlib import Path
21
+ from typing import Any, Iterator
22
+
23
+
24
+ _INSTALL_LOCK = threading.Lock()
25
+ _VERSION_RE = re.compile(r"^[0-9]+\.[0-9]+\.[0-9]+$")
26
+ _WORKER = Path(__file__).resolve().with_name("render_worker.py")
27
+ _MAX_ARCHIVE_BYTES = 4 * 1024**3
28
+ _MAX_EXTRACTED_BYTES = 12 * 1024**3
29
+
30
+
31
+ def _valid_executable(path: Path) -> bool:
32
+ return path.is_file() and os.access(path, os.X_OK)
33
+
34
+
35
+ @contextlib.contextmanager
36
+ def _installation_file_lock(path: Path) -> Iterator[None]:
37
+ """Linux 进程间锁;与线程锁一起避免重复下载和并发解压。"""
38
+ if os.name != "posix":
39
+ raise RuntimeError("自动安装 Blender 目前只支持 Linux;请设置 BLENDER_BIN。")
40
+ import fcntl
41
+
42
+ with path.open("a+b") as lock_file:
43
+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
44
+ try:
45
+ yield
46
+ finally:
47
+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
48
+
49
+
50
+ def _download(url: str, destination: Path, maximum: int) -> None:
51
+ """HTTPS 流式下载;首次失败后最多重试两次,每次重写临时文件。"""
52
+ last_error: Exception | None = None
53
+ for attempt in range(3):
54
+ try:
55
+ request = urllib.request.Request(
56
+ url, headers={"User-Agent": "Blender-Render-Space/1.0"}
57
+ )
58
+ started = time.monotonic()
59
+ with urllib.request.urlopen(request, timeout=60) as response:
60
+ if not response.geturl().startswith("https://"):
61
+ raise RuntimeError("下载发生了非 HTTPS 重定向,已拒绝。")
62
+ content_length = response.headers.get("Content-Length")
63
+ if content_length and int(content_length) > maximum:
64
+ raise RuntimeError("下载内容超过允许大小。")
65
+ total = 0
66
+ with destination.open("wb") as output:
67
+ while block := response.read(1024 * 1024):
68
+ total += len(block)
69
+ if total > maximum:
70
+ raise RuntimeError("下载内容超过允许大小。")
71
+ if time.monotonic() - started > 1800:
72
+ raise TimeoutError("单次下载超过 30 分钟。")
73
+ output.write(block)
74
+ return
75
+ except (OSError, urllib.error.URLError, ValueError, RuntimeError) as error:
76
+ last_error = error
77
+ destination.unlink(missing_ok=True)
78
+ if attempt < 2:
79
+ time.sleep(attempt + 1)
80
+ raise RuntimeError(f"无法下载 Blender 官方文件:{url};原因:{last_error}") from last_error
81
+
82
+
83
+ def _expected_digest(checksums: Path, filename: str) -> str:
84
+ matches: set[str] = set()
85
+ for line in checksums.read_text(encoding="utf-8").splitlines():
86
+ match = re.fullmatch(r"([a-fA-F0-9]{64})\s+\*?(.+?)\s*", line)
87
+ if match and match.group(2) == filename:
88
+ matches.add(match.group(1).lower())
89
+ if len(matches) != 1:
90
+ raise RuntimeError(f"官方 SHA-256 清单中没有唯一匹配的 {filename},安装已停止。")
91
+ return matches.pop()
92
+
93
+
94
+ def _safe_extract(archive: Path, destination: Path, archive_root: str) -> Path:
95
+ """只接受官方根目录中的普通文件、目录和不越界的内部链接。"""
96
+ with tarfile.open(archive, "r:xz") as bundle:
97
+ members = bundle.getmembers()
98
+ if len(members) > 200_000:
99
+ raise RuntimeError("Blender 压缩包文件数量异常。")
100
+ expanded_size = 0
101
+ seen: set[str] = set()
102
+ for member in members:
103
+ name = member.name.rstrip("/")
104
+ parts = name.split("/")
105
+ if (
106
+ not name
107
+ or "\\" in name
108
+ or name.startswith("/")
109
+ or any(part in {"", ".", ".."} for part in parts)
110
+ or parts[0] != archive_root
111
+ ):
112
+ raise RuntimeError(f"Blender 压缩包含有不安全路径:{member.name}")
113
+ if name in seen:
114
+ raise RuntimeError(f"Blender 压缩包含有重复路径:{member.name}")
115
+ seen.add(name)
116
+ if member.isfile():
117
+ expanded_size += member.size
118
+ if expanded_size > _MAX_EXTRACTED_BYTES:
119
+ raise RuntimeError("Blender 压缩包解压大小超过限制。")
120
+ elif member.issym() or member.islnk():
121
+ target = member.linkname
122
+ if not target or target.startswith("/") or "\\" in target:
123
+ raise RuntimeError(f"Blender 压缩包含有不安全链接:{name}")
124
+ # 符号链接相对于所在目录,tar 硬链接相对于压缩包根目录。
125
+ resolved = posixpath.normpath(
126
+ posixpath.join(posixpath.dirname(name), target)
127
+ if member.issym()
128
+ else target
129
+ )
130
+ if not (resolved == archive_root or resolved.startswith(archive_root + "/")):
131
+ raise RuntimeError(f"Blender 压缩包链接指向安装目录之外:{name}")
132
+ elif not member.isdir():
133
+ raise RuntimeError(f"Blender 压缩包包含不允许的特殊文件:{name}")
134
+ # Python 3.12 的 data filter 还会检查已解压链接链,拒绝实际越界。
135
+ bundle.extractall(destination, members=members, filter="data")
136
+ return destination / archive_root
137
+
138
+
139
+ def ensure_blender() -> Path:
140
+ """优先使用 BLENDER_BIN、系统 Blender,否则校验后安装官方 Linux x64 版本。"""
141
+ configured = os.environ.get("BLENDER_BIN", "").strip()
142
+ if configured:
143
+ binary = Path(configured).expanduser().resolve()
144
+ if not _valid_executable(binary):
145
+ raise RuntimeError(f"BLENDER_BIN 不存在或不可执行:{binary}")
146
+ return binary
147
+ installed = shutil.which("blender")
148
+ if installed:
149
+ return Path(installed).resolve()
150
+
151
+ import platform
152
+
153
+ if platform.system() != "Linux" or platform.machine().lower() not in {"x86_64", "amd64"}:
154
+ raise RuntimeError("自动下载只支持 Linux x64;请安装 Blender 并设置 BLENDER_BIN。")
155
+ version = os.environ.get("BLENDER_VERSION", "5.2.2").strip()
156
+ if not _VERSION_RE.fullmatch(version):
157
+ raise RuntimeError("BLENDER_VERSION 必须是类似 5.2.2 的三段数字版本号。")
158
+ cache = Path(
159
+ os.environ.get("BLENDER_CACHE", str(Path.home() / ".cache" / "blender-render-space"))
160
+ ).expanduser().resolve()
161
+ installation = cache / f"blender-{version}"
162
+ binary = installation / "blender"
163
+ if _valid_executable(binary):
164
+ return binary
165
+
166
+ with _INSTALL_LOCK:
167
+ cache.mkdir(parents=True, exist_ok=True)
168
+ with _installation_file_lock(cache / f".install-{version}.lock"):
169
+ if _valid_executable(binary):
170
+ return binary
171
+ release = ".".join(version.split(".")[:2])
172
+ base_url = f"https://download.blender.org/release/Blender{release}/"
173
+ archive_root = f"blender-{version}-linux-x64"
174
+ archive_name = archive_root + ".tar.xz"
175
+ try:
176
+ with tempfile.TemporaryDirectory(prefix=".install-", dir=cache) as temporary:
177
+ staging = Path(temporary)
178
+ checksum_file = staging / "checksums.sha256"
179
+ archive = staging / archive_name
180
+ _download(base_url + f"blender-{version}.sha256", checksum_file, 1024**2)
181
+ expected = _expected_digest(checksum_file, archive_name)
182
+ _download(base_url + archive_name, archive, _MAX_ARCHIVE_BYTES)
183
+ with archive.open("rb") as source:
184
+ actual = hashlib.file_digest(source, "sha256").hexdigest()
185
+ if actual != expected:
186
+ raise RuntimeError("Blender 安装包 SHA-256 校验失败,已停止安装。")
187
+ extracted = _safe_extract(archive, staging, archive_root)
188
+ if not _valid_executable(extracted / "blender"):
189
+ raise RuntimeError("官方安装包中未找到可执行的 Blender。")
190
+ # 与最终目录位于同一文件系统,rename 只会暴露完整安装。
191
+ previous = staging / "previous-installation"
192
+ if installation.exists() or installation.is_symlink():
193
+ installation.rename(previous)
194
+ try:
195
+ os.replace(extracted, installation)
196
+ except OSError:
197
+ if previous.exists() or previous.is_symlink():
198
+ previous.rename(installation)
199
+ raise
200
+ except (OSError, tarfile.TarError, ValueError) as error:
201
+ raise RuntimeError(f"Blender 自动安装失败:{error}。可设置 BLENDER_BIN 使用已有安装。") from error
202
+ return binary
203
+
204
+
205
+ def _worker_environment() -> dict[str, str]:
206
+ """移除应用服务凭据,保留 CUDA、NVIDIA 和动态库搜索路径。"""
207
+ forbidden_prefixes = (
208
+ "HF_", "HUGGINGFACE_", "HUGGING_FACE_", "AWS_", "AZURE_", "GOOGLE_",
209
+ "GCP_", "OPENAI_", "ANTHROPIC_", "SPACES_", "GRADIO_AUTH",
210
+ )
211
+ sensitive = re.compile(r"TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL|API_KEY|ACCESS_KEY|PRIVATE_KEY|AUTHORIZATION")
212
+ environment = {
213
+ name: value
214
+ for name, value in os.environ.items()
215
+ if not name.upper().startswith(forbidden_prefixes) and not sensitive.search(name.upper())
216
+ }
217
+ # 部分 OpenMP / TBB 库���认按宿主逻辑核心数开线程,需限制过度并行。
218
+ threads = _thread_count()
219
+ environment["OMP_NUM_THREADS"] = str(threads)
220
+ environment["OPENBLAS_NUM_THREADS"] = str(threads)
221
+ environment["MKL_NUM_THREADS"] = str(threads)
222
+ environment["PYTHONNOUSERSITE"] = "1"
223
+ return environment
224
+
225
+
226
+ def _thread_count() -> int:
227
+ try:
228
+ threads = int(os.environ.get("BLENDER_THREADS", "4"))
229
+ except ValueError as error:
230
+ raise RuntimeError("BLENDER_THREADS 必须为 1 至 256 之间的整数。") from error
231
+ if not 1 <= threads <= 256:
232
+ raise RuntimeError("BLENDER_THREADS 必须为 1 至 256 之间的整数。")
233
+ return threads
234
+
235
+
236
+ def _stop_process_group(process: subprocess.Popen[Any]) -> None:
237
+ """先请求终止,再结束整个进程组,包括仍在运行的后代进程。"""
238
+ if os.name == "posix":
239
+ try:
240
+ os.killpg(process.pid, signal.SIGTERM)
241
+ except ProcessLookupError:
242
+ pass
243
+ try:
244
+ process.wait(timeout=3)
245
+ except subprocess.TimeoutExpired:
246
+ pass
247
+ try:
248
+ os.killpg(process.pid, signal.SIGKILL)
249
+ except ProcessLookupError:
250
+ pass
251
+ else:
252
+ # 本地 Windows 指定 BLENDER_BIN 时,同样终止进程树。
253
+ subprocess.run(
254
+ ["taskkill", "/PID", str(process.pid), "/T", "/F"],
255
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False, timeout=10,
256
+ )
257
+ try:
258
+ process.wait(timeout=5)
259
+ except subprocess.TimeoutExpired:
260
+ process.kill()
261
+ process.wait(timeout=5)
262
+
263
+
264
+ def _log_tail(path: Path) -> str:
265
+ try:
266
+ with path.open("rb") as source:
267
+ source.seek(0, os.SEEK_END)
268
+ source.seek(max(0, source.tell() - 12_000))
269
+ return source.read().decode("utf-8", errors="replace").strip()
270
+ except OSError:
271
+ return "日志不可读取。"
272
+
273
+
274
+ def run_task(
275
+ task: dict,
276
+ timeout: int,
277
+ log_path: Path,
278
+ cancel_path: Path | None = None,
279
+ ) -> dict:
280
+ """以可信 worker 执行任务;成功时读取 result_path,失败保留完整日志。"""
281
+ if not isinstance(task, dict) or not task.get("result_path"):
282
+ raise ValueError("渲染任务必须包含 result_path。")
283
+ if not isinstance(timeout, (int, float)) or isinstance(timeout, bool) or timeout <= 0:
284
+ raise ValueError("渲染超时必须是正数秒数。")
285
+ if not _WORKER.is_file():
286
+ raise RuntimeError(f"缺少可信 Blender 工作脚本:{_WORKER.name}")
287
+ binary = ensure_blender()
288
+ log_path = Path(log_path).resolve()
289
+ log_path.parent.mkdir(parents=True, exist_ok=True)
290
+ result_path = Path(task["result_path"]).resolve()
291
+ result_path.parent.mkdir(parents=True, exist_ok=True)
292
+ cancel_path = Path(cancel_path) if cancel_path is not None else None
293
+ if cancel_path is not None and cancel_path.exists():
294
+ raise RuntimeError("渲染任务已取消。")
295
+ result_path.unlink(missing_ok=True)
296
+ task_copy = {**task, "result_path": str(result_path)}
297
+ descriptor, task_filename = tempfile.mkstemp(prefix=".render-task-", suffix=".json", dir=log_path.parent)
298
+ process: subprocess.Popen[Any] | None = None
299
+ try:
300
+ with os.fdopen(descriptor, "w", encoding="utf-8") as output:
301
+ json.dump(task_copy, output, ensure_ascii=False, allow_nan=False)
302
+ command = [
303
+ str(binary), "--background", "--factory-startup", "--disable-autoexec",
304
+ "--threads", str(_thread_count()), "--python-exit-code", "1",
305
+ "--python", str(_WORKER), "--", task_filename,
306
+ ]
307
+ with log_path.open("wb") as log:
308
+ process = subprocess.Popen(
309
+ command,
310
+ stdin=subprocess.DEVNULL,
311
+ stdout=log,
312
+ stderr=subprocess.STDOUT,
313
+ cwd=log_path.parent,
314
+ env=_worker_environment(),
315
+ start_new_session=os.name == "posix",
316
+ creationflags=subprocess.CREATE_NEW_PROCESS_GROUP if os.name == "nt" else 0,
317
+ )
318
+ started = time.monotonic()
319
+ while process.poll() is None:
320
+ if cancel_path is not None and cancel_path.exists():
321
+ _stop_process_group(process)
322
+ raise RuntimeError("渲染任务已取消;已完成的帧保留,可继续渲染。")
323
+ if time.monotonic() - started >= timeout:
324
+ _stop_process_group(process)
325
+ raise TimeoutError(f"渲染任务超过 {timeout} 秒,进程组已终止;已完成的帧保留。")
326
+ time.sleep(0.15)
327
+ if process.returncode != 0:
328
+ _stop_process_group(process)
329
+ raise RuntimeError(f"Blender 执行失败(退出码 {process.returncode}):\n{_log_tail(log_path)}")
330
+ if not result_path.is_file() or result_path.stat().st_size > 16 * 1024**2:
331
+ raise RuntimeError(f"Blender 未生成有效结果文件:\n{_log_tail(log_path)}")
332
+ try:
333
+ result = json.loads(result_path.read_text(encoding="utf-8"))
334
+ except (OSError, ValueError) as error:
335
+ raise RuntimeError(f"Blender 返回的结果 JSON 无效:{error}") from error
336
+ if not isinstance(result, dict):
337
+ raise RuntimeError("Blender 结果必须是 JSON 对象。")
338
+ return result
339
+ finally:
340
+ if process is not None and process.poll() is None:
341
+ _stop_process_group(process)
342
+ Path(task_filename).unlink(missing_ok=True)
docs/API.zh-CN.md ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # API、MCP 与 Agent 调用
2
+
3
+ API 与 UI 共用同一任务实现,不能通过 API 绕开配置、上传、资源或 GPU 时限。启动后点击 Gradio 底部「Use via API」查看当前服务器生成的权威接口说明。任务 ID 是访问凭据,返回的文件 URL 也不应公开。
4
+
5
+ ## 端点约定
6
+
7
+ 使用 `gradio_client.Client.predict(..., api_name="/端点名")` 调用。服务端函数返回 JSON 并不代表业务成功,必须同时检查 `status`、`error`、`remaining_frames`;导出还应检查 `export_complete` / `export_error`。
8
+
9
+ | API 名称 | 输入顺序 | 返回 |
10
+ | --- | --- | --- |
11
+ | `/environment_info` | 无 | 环境版本、ZeroGPU 标志、FFmpeg 可用性;不申请 GPU |
12
+ | `/config_schema` | 无 | 允许字段、默认值与校验限制的 JSON Schema |
13
+ | `/gpu_self_test` | 无 | `(report, files, image)`;真实小场景渲染,GPU 模式必须检查 `gpu_verified` |
14
+ | `/prepare_job` | `files`, `config_json`, `config_file` | `(job_id, status)`;`config_file` 可为 null,非空时优先 |
15
+ | `/inspect_job` | `job_id` | 状态与 `inspection`,包括场景/相机/`missing_assets` |
16
+ | `/render_chunk` | `job_id` | 新状态;最多处理配置中的 `batch_size` 帧 |
17
+ | `/job_status` | `job_id` | 当前状态与完成帧列表;不等待 Blender 队列 |
18
+ | `/cancel_job` | `job_id` | 请求停止并保留完成帧;不等待 Blender 队列 |
19
+ | `/resume_job` | `job_id` | 清除取消标记、验证已完成帧;不会启动渲染 |
20
+ | `/finalize_job` | `job_id` | `(summary, files, image, video)`;部分结果也可导出,视频需完整帧 |
21
+
22
+ `render_chunk` 使用队列并等待当前批次结束;客户端不应把多个批次并行提交。`job_status` 适合进度查看,轮询本身不会推进渲染。`prepare_job` 冻结配置,恢复沿用原配置;需要修改时创建新任务。
23
+
24
+ ## 完整命令行客户端
25
+
26
+ ```bash
27
+ python -m pip install "gradio_client>=2.0,<3"
28
+ python examples/client_render.py --space YOUR_NAME/YOUR_SPACE --project project.zip --config examples/video.json --output outputs --self-test
29
+ ```
30
+
31
+ 脚本会上传本地文件、保存 ID、检查资源、串行渲染、检查每批 `error`,再调用导出并把文件复制到 `outputs`。所有进度为 JSON 行,便于 agent 解析。新建任务若发现已有任务文件会停止,避免不小心重复上传渲染。
32
+
33
+ | 参数 | 含义 |
34
+ | --- | --- |
35
+ | `--space` | 必需;`用户名/Space名` 或 Gradio 根 URL |
36
+ | `--project` | 新任务必需;一个 ZIP 或多个本机文件路径 |
37
+ | `--config` | 新任务必需;本机 JSON 配置路径 |
38
+ | `--output` | 下载目录,默认 `outputs` |
39
+ | `--job-file` | 任务凭据保存位置,默认 `OUTPUT/render-job.json` |
40
+ | `--resume-job [ID]` | 有 ID 时恢复它;省略 ID 时从任务文件恢复 |
41
+ | `--inspect` / `--inspect-only` | 上传/恢复后只检查,不开始渲染 |
42
+ | `--max-batches N` | 本次最多处理 N 批并导出;0 为直到完成 |
43
+ | `--self-test` | 先运行真实小场景自检 |
44
+
45
+ ```bash
46
+ # 只检查,保留 ID;确认相机/资源后再续渲。
47
+ python examples/client_render.py --space YOUR_NAME/YOUR_SPACE --project project.zip --config examples/image.json --output image-result --inspect
48
+
49
+ # 每次处理最多 5 批,下载阶段性结果。
50
+ python examples/client_render.py --space YOUR_NAME/YOUR_SPACE --resume-job --output image-result --max-batches 5
51
+
52
+ # 多个上传文件:复杂目录结构请优先使用 ZIP。
53
+ python examples/client_render.py --space YOUR_NAME/YOUR_SPACE --project scene.blend texture.png --config examples/image.json --output another-result
54
+ ```
55
+
56
+ 脚本默认把缺失/被阻止的资源视为错误;若 JSON 明确设置 `strict_assets=false`,会输出警告信息并继续,渲染效果可能因此变化。退出码:0 为完成或主动达到批数上限/仅检查;1 为错误;130 为键盘中断。遇到配额和超时不会循环重试。
57
+
58
+ ## 身份验证
59
+
60
+ 私有 Space 以及需要账号身份的调用,先在运行客户端的环境设置 `HF_TOKEN`。令牌须有访问该 Space 的权限。不要将令牌写到场景、JSON、MCP 示例文件或 git 仓库里。脚本从环境读取令牌并兼容新版 `token=` 与旧版 `hf_token=` 构造参数,不打印令牌。
61
+
62
+ 本机 PowerShell 可交互读取并设置令牌:
63
+
64
+ ```powershell
65
+ $env:HF_TOKEN = Read-Host "HF Token" -MaskInput
66
+ python examples/client_render.py --space YOUR_NAME/YOUR_SPACE --project project.zip --config examples/video.json --output outputs
67
+ ```
68
+
69
+ `-MaskInput` 需要 PowerShell 7;其他环境可使用系统环境变量/密码管理器。平台的账号配额、访问和计费规则仍适用。
70
+
71
+ ## Python 最小闭环
72
+
73
+ 以下代码可直接保存执行;将 Space ID 与本机路径改为实际值。部署目录自带客户端提供更完整的恢复、下载与错误处理。
74
+
75
+ ```python
76
+ import inspect
77
+ import json
78
+ import os
79
+ from pathlib import Path
80
+
81
+ from gradio_client import Client, handle_file
82
+
83
+ space = "YOUR_NAME/YOUR_SPACE"
84
+ output = Path("outputs").resolve()
85
+ output.mkdir(parents=True, exist_ok=True)
86
+ auth_name = "token" if "token" in inspect.signature(Client).parameters else "hf_token"
87
+ client = Client(space, download_files=str(output), **{auth_name: os.getenv("HF_TOKEN")})
88
+
89
+ config = Path("examples/image.json").read_text(encoding="utf-8-sig")
90
+ job_id, status = client.predict(
91
+ [handle_file("project.zip")], config, None, api_name="/prepare_job"
92
+ )
93
+ # ID 要立即保存;不要因网络中断直接重复 prepare_job。
94
+ (output / "job-id.txt").write_text(job_id, encoding="utf-8")
95
+
96
+ status = client.predict(job_id, api_name="/inspect_job")
97
+ if status.get("error"):
98
+ raise RuntimeError(status["error"])
99
+ missing = (status.get("inspection") or {}).get("missing_assets") or []
100
+ if missing and status.get("config", {}).get("strict_assets", True):
101
+ raise RuntimeError(json.dumps(missing, ensure_ascii=False))
102
+
103
+ while status.get("remaining_frames"):
104
+ before = status["completed_count"]
105
+ status = client.predict(job_id, api_name="/render_chunk")
106
+ print(status["completed_count"], "/", status["total_frames"])
107
+ if status.get("error"):
108
+ # 先导出完成帧与日志,再终止;不要在配额不足时无限重试。
109
+ client.predict(job_id, api_name="/finalize_job")
110
+ raise RuntimeError(status["error"])
111
+ if status["completed_count"] <= before:
112
+ raise RuntimeError("没有完成新帧,停止自动重试。")
113
+
114
+ summary, files, image, video = client.predict(job_id, api_name="/finalize_job")
115
+ if not summary.get("export_complete"):
116
+ raise RuntimeError(summary.get("export_error") or "输出未完整生成")
117
+ print(json.dumps({"job_id": job_id, "files": files}, ensure_ascii=False))
118
+ ```
119
+
120
+ 客户端使用 `handle_file` 自动上传;不能直接把本机路径文本当作远端服务器文件。若想上传独立 JSON 文件:
121
+
122
+ ```python
123
+ job_id, status = client.predict(
124
+ [handle_file("project.zip")],
125
+ "{}",
126
+ handle_file("examples/video.json"),
127
+ api_name="/prepare_job",
128
+ )
129
+ ```
130
+
131
+ ## 常用 JSON 配置字段
132
+
133
+ 以下是本应用字段,与任意 Blender Python 属性不是一一透传关系。未列出的完整字段请查询 `/config_schema`。
134
+
135
+ | 字段 | 示例 / 范围 | 说明 |
136
+ | --- | --- | --- |
137
+ | `schema_version` | `1` | 配置协议版本 |
138
+ | `blend_file` | `project/scene.blend` 或 null | 主工程的解压根目录相对路径 |
139
+ | `mode` | `image` / `frames` / `video` | 单图、帧序列或视频 |
140
+ | `scene` / `camera` / `view_layer` | 名称或 null | 指定 Blender 数据块;默认沿用场景设置 |
141
+ | `width` / `height` | 16–8192 | 基础分辨率,受像素总量上限限制 |
142
+ | `resolution_percentage` | 1–100 | 实际输出缩放比例 |
143
+ | `samples` | 1–4096 | Cycles 最大采样数 |
144
+ | `denoise` | true / false | 降噪 |
145
+ | `adaptive_threshold` | 0.0–1.0 | 自适应采样阈值 |
146
+ | `frame` | 正整数 | 单图帧号 |
147
+ | `frame_start` / `frame_end` / `frame_step` | 正整数 | 动画帧范围与步长 |
148
+ | `fps` | 1–120 | 时间基准;跳帧输出的播放帧率为 `fps/frame_step` |
149
+ | `format` | `PNG` / `OPEN_EXR` | 视频模式只接受 PNG |
150
+ | `color_depth` | 8 / 16 / 32 | PNG:8/16;EXR:16/32 |
151
+ | `transparent` | true / false | 透明背景;MP4 不支持 |
152
+ | `device` | `AUTO` / `CUDA` / `OPTIX` / `CPU` | CPU 必须同时由管理员启用 CPU 后端 |
153
+ | `batch_size` | 1–64 | 每次请求最多渲染帧数 |
154
+ | `gpu_seconds` | 10–600 | ZeroGPU 请求预算;平台可能另有限制,不是时长保证 |
155
+ | `cpu_timeout` | 10–7200 | 普通 GPU/CPU 子进程与编码超时 |
156
+ | `strict_assets` | true / false | 默认缺失资源拒绝渲染 |
157
+ | `video_crf` | 0–40 | 视频质量;通常 18,越小输出越大 |
158
+ | `video_preset` | medium / fast / slow | FFmpeg 编码速度/压缩取舍 |
159
+
160
+ `gpu_seconds` 是当前批次的预算,不是整个动画的预算。应用给子进程预留收尾时间,因此可用于 Blender 的时间略短。普通 GPU/CPU 模式使用 `cpu_timeout`,名称保留用于同一配置协议。
161
+
162
+ ## MCP 接入
163
+
164
+ 本项目通过 `demo.launch(mcp_server=True)` 暴露工具,要求已安装 `gradio[mcp]`。使用 Streamable HTTP:
165
+
166
+ ```json
167
+ {
168
+ "mcpServers": {
169
+ "blender-render": {
170
+ "type": "http",
171
+ "url": "https://YOUR-SPACE-DOMAIN.hf.space/gradio_api/mcp/"
172
+ }
173
+ }
174
+ }
175
+ ```
176
+
177
+ 不同 MCP 客户端可能使用 `servers` 代替 `mcpServers`,或自行管理 `Authorization` 头/OAuth;请在客户端的安全凭据设置中添加认证。示例文件不硬编码令牌。工具名以 `tools/list` 实际发现结果为准;某些客户端会自动添加服务名前缀。
178
+
179
+ MCP 的 JSON 参数不能携带本机文件系统权限。可采用以下方式:
180
+
181
+ 1. Agent 先用 `gradio_client` 或完整示例脚本上传本地文件并执行 `/prepare_job`,取得 job ID;后续全部使用 MCP 的检查、渲染、查询与导出工具。
182
+ 2. MCP 客户端支持 Gradio 文件上传时,使用其上传功能得到有效文件引用。不能虚构服务器路径或简单传入本机绝对路径。
183
+ 3. 有可访问的托管文件时,遵循服务器生成的 MCP 文件 schema 和客户端支持的 URL 上传流程。服务器必须可访问该 URL;本应用不提供任意 URL 代理或自定义下载器,也不会替 URL 补上私有存储的认证。
184
+
185
+ 大文件和私有本机文件推荐第一种方式。返回的结果由 Gradio 表达为文件引用/下载地址,MCP 客户端能否自动下载取决于其文件支持能力;Python 客户端已处理鉴权下载。
186
+
187
+ HF 也提供 Hub MCP 集成;是否能直接添加某个私有 Space、如何传递用户身份,以其客户端及 Hub 当前能力为准。[HF 的 MCP 官方文档](https://huggingface.co/docs/hub/en/spaces-mcp-servers)、[Gradio MCP 指南](https://www.gradio.app/guides/building-mcp-server-with-gradio)
188
+
189
+ ## 推荐 Agent 策略
190
+
191
+ 先读取 `environment_info` 与 `config_schema`;首次部署调用 `gpu_self_test`。准备后立刻保存 ID,检查场景相机和缺失资产,再串行调用 `render_chunk`,每次都判断错误和完成帧增量。全部完成后 `finalize_job` 并核验输出。出现配额、超时或兼容性失败时停止自动重试、取回部分输出和日志,明确报告原因;修复后用相同 ID 恢复,若修改工程或配置则新建任务。
docs/ARCHITECTURE.zh-CN.md ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 架构与实施规划
2
+
3
+ 版本:1.0.0。目标是用相同的工程文件与 JSON 参数,把 Blender 渲染任务交给 HF Space,允许人操作界面,也允许 agent 全程使用 API/MCP。交付为可部署代码,不包含已经创建的 Space,也不包含 HF 上真实 ZeroGPU 渲染成功的声明。
4
+
5
+ ## 可行性结论与技术选择
6
+
7
+ ZeroGPU 通过 `spaces.GPU` 为函数申请有时间限制的 GPU;官方重点支持 Gradio/PyTorch。Blender Cycles 是外部原生程序,因此平台兼容性是必须实测的前提,而不是装饰器能自动保证的事情。当前采取「租约内启动 Blender 子进程 → 检测 Cycles 设备 → 实际渲染 → 读取报告」路径。平台如果禁止或不支持这条路径,就明确失败并保留日志。普通 NVIDIA GPU Space 作为显式备选,CPU 作为显式开发测试模式。[ZeroGPU 文档](https://huggingface.co/docs/hub/en/spaces-zerogpu)
8
+
9
+ 采用官方 Blender Linux x64 分发包而不是在 Python 中嵌入 `bpy`:保持 Blender 自己的 Python、Cycles 与打包库版本一致,同时便于超时后结束进程树。服务端 Python 3.12、Gradio 6.28.0、spaces 0.51.3;PyTorch 固定为官方支持的 2.8.0,用于 ZeroGPU 平台运行时,真正的图像生成仍由 Blender 完成。[spaces 发布记录](https://pypi.org/project/spaces/0.51.3/)、[Gradio 发布记录](https://pypi.org/project/gradio/6.28.0/)
10
+
11
+ 默认 Blender 为 5.2.2;管理员可设置 `BLENDER_BIN` 指向已有安装,或设置 `BLENDER_VERSION`。不同 Blender 版本对工程、节点、色彩与缓存的兼容性可能不同,首帧确认后再批量渲染。
12
+
13
+ ## 分阶段实施与验收
14
+
15
+ | 阶段 | 实施内容 | 验收条件 |
16
+ | --- | --- | --- |
17
+ | 1. 配置协议 | 严格 JSON Schema;图片/视频/序列参数与服务端资源上限 | 错误类型、未知字段、越界值、重复键和无效格式被拒绝 |
18
+ | 2. 工程暂存 | 多文件、ZIP、相对路径、大小限制、主工程选择 | 资源结构保留;路径穿越、链接和冲突不被接受 |
19
+ | 3. Blender 执行 | 自动安装校验、禁自动脚本、场景检查、真实设备选择 | 有小场景输出;失败时有明确报告和日志 |
20
+ | 4. 任务与续渲 | 原子保存帧、批次、取消、恢复、状态查询 | 中断后保留完成帧;再次提交不重复已验证帧 |
21
+ | 5. 导出 | PNG/EXR ZIP、manifest、日志、FFmpeg MP4 | 视频只在所有帧完成后生成;部分结果始终可导出 |
22
+ | 6. UI/API/MCP | 同一服务函数、Schema 发现、上传与 agent 客户端 | 客户端能准备、检查、逐批、恢复、下载 |
23
+ | 7. 平台验收 | 上传到真实 ZeroGPU Space,运行自检和少量真实帧 | `gpu_verified=true`,检查输出后再扩大任务 |
24
+
25
+ 第 7 阶段需要用户的真实 HF Space 和平台 GPU;交付代码中已提供验收入口,未在本地测试中替代或伪造此项结果。
26
+
27
+ ## 数据流
28
+
29
+ ```mermaid
30
+ flowchart TD
31
+ A["UI / API / MCP"] --> B["配置校验与工程暂存"]
32
+ B --> C["场景、相机与资源检查"]
33
+ C --> D{"执行后端"}
34
+ D --> E["ZeroGPU 租约"]
35
+ D --> F["普通 GPU / 显式 CPU"]
36
+ E --> G["Blender 渲染当前批次"]
37
+ F --> G
38
+ G --> H["原子保存完成帧"]
39
+ H --> I{"还有待渲染帧?"}
40
+ I -->|是,调用下一批| D
41
+ I -->|否| J["CPU 打包 / FFmpeg 编码"]
42
+ J --> K["下载结果与日志"]
43
+ ```
44
+
45
+ 上传、解压、Blender 下载、场景检查、ZIP 打包和视频编码放在 GPU 租约之外。每次 GPU 租约只执行一个有界 Blender 渲染批次。初次场景加载、BVH 建立和内核初始化仍发生在租约内,因此重复租约存在启动开销。
46
+
47
+ ## 任务状态
48
+
49
+ | 状态 | 含义 | 下一步 |
50
+ | --- | --- | --- |
51
+ | `prepared` | 工程已暂存,配置已冻结 | `inspect_job` |
52
+ | `ready` | 已成功运行场景检查;仍需查看 `missing_assets` | `render_chunk` |
53
+ | `rendering` | 当前有 Blender 批次执行 | 查询或取消 |
54
+ | `cancelling` | 已设置取消标记,等待进程退出 | 查询状态 |
55
+ | `partial` | 有部分帧,或恢复后仍有待渲染帧 | 无 `error` 可继续;有错误先排查 |
56
+ | `complete` | 预期帧均已完成 | `finalize_job` |
57
+ | `failed` | 检查或渲染失败且尚无可保留完成帧 | 查看 `error` 与日志,修复后恢复/新建 |
58
+ | `cancelled` | 已停止,成功帧仍在 | `resume_job` 后提交下一批 |
59
+
60
+ HTTP 请求成功不代表渲染成功,所有调用者都必须检查 `error`。批次中前几帧完成、后一帧超时时,状态可能是 `partial` 且 `error` 非空。`resume_job` 清除暂停标记、校验已有帧并清除旧错误;不会自行启动渲染,也不能改变任务配置。需要修改分辨率、采样、主工程或预算时新建任务。
61
+
62
+ ## 配置协议与输出
63
+
64
+ 配置只接受 UTF-8 JSON 对象,最大 64 KiB。不执行表达式,不接受 Python、shell 命令或自定义 Blender 脚本。`config_file` 优先于 `config_json`。使用 `/config_schema` 获取全部参数和当前上限。
65
+
66
+ 图片模式只渲染 `frame`;序列/视频模式渲染 `frame_start..frame_end` 间隔 `frame_step` 的帧。视频编码播放帧率为 `fps/frame_step`,保持跳帧预览的时间尺度。例如 1 至 120 帧、24 fps、step=2,将得到 60 帧、12 fps 的 5 秒视频。
67
+
68
+ 渲染先写临时文件,成功后原子重命名为 `frame_000001.png` 或 `.exr`。恢复时会校验 PNG 的尺寸和文件完整性;EXR 使用成功落盘的最终文件及大小判断,没有做与 PNG 相同级别的像素解码校验。输出 ZIP 包括帧、manifest 和日志;视频使用 CPU FFmpeg/libx264,输出无音轨 H.264 MP4。视频要求 PNG 中间帧、非透明背景和最终宽高为偶数。
69
+
70
+ ## 资源与并发
71
+
72
+ Gradio 中 Blender 操作使用同一队列,默认并发 1;每任务还有线程锁和文件锁,避免相同任务的并发写入。状态读取、取消请求不排在长渲染之后。取消与超时由父进程监控,结束 Blender 进程组;已经成功写出的帧保留。
73
+
74
+ 单次上传、解压总量、文件数、像素数、帧数、任务数和磁盘最低余量均有限制。默认任务过期时间 24 小时,在创建新任务时清理过期且未被执行锁占用的任务。此设计适合单 Space、低并发、受信任工程;不是跨机器渲染农场,也没有分布式调度、对象存储帧备份或账号隔离数据库。
75
+
76
+ ## 模型与安全边界
77
+
78
+ 推荐私有 Space,只接收自己或受信任协作者的工程。上传的 `.blend` 是复杂原生二进制输入;禁脚本与路径检查能降低风险,**不能把 Blender 变成完整的恶意文件沙箱**。应用未提供按用户账号隔离的任务授权,随机任务 ID 是访问凭据。公共部署前需要额外鉴权、隔离容器、配额与滥用治理。
79
+
80
+ 已做的控制包括:ZIP 路径与文件大小校验、拒绝越界路径和链接、禁用自动 Python/OSL、阻止不允许的外部资源访问、删除外部导入/脚本节点、关闭合成器/VSE、限制线程与执行时长、仅导出明确的结果文件。渲染 worker 不需要 HF 令牌;客户端令牌只用于访问 Space。
81
+
82
+ 这些控制会改变某些工程的结果:插件、复杂 Python 驱动器、自定义 OSL、合成节点、VSE 编辑、外部文件动态导入不会原样运行。物理、流体、布料、粒子和几何节点模拟应提前烘焙并上传所需缓存;不要依赖每个独立 Blender 批次中的未烘焙模拟状态。
83
+
84
+ ## 性能与计费边界
85
+
86
+ 先用 640×360、16 samples、单帧建立实际测量,再提高画质。`batch_size=1` 是可靠的初始值;确认单帧总耗时后,可增加同一批中的帧数以分摊场景加载成本。批次预算须包含加载、内核初始化、渲染和落盘。单帧无法在租约中完成时,拆分更多批次没有作用,应降低画质/复杂度或手动选择普通 GPU。
87
+
88
+ GPU 配额由 HF 账号、排队和平台规则决定;应用不绕过配额,不自动购买配额,不自动升级硬件。但用户账号若启用了平台额外付费使用,调用仍遵循其计费设置。长视频需要的总 GPU 时间约为所有帧渲染时间加重复加载开销,不能只按视频播放时长估算。[当前 ZeroGPU 规则](https://huggingface.co/docs/hub/en/spaces-zerogpu)
89
+
90
+ ## 验证边界
91
+
92
+ 自动化可检查 JSON/ZIP 拒绝路径、任务状态、断点、API 参数、CPU 小场景和 FFmpeg 输出。实际 HF ZeroGPU 的租约、GPU 子进程可见性、驱动/OptiX 兼容性、账号配额、真实场景显存、长时间稳定性必须在目标 Space 验证。自检通过只证明该次小场景成功;不能推出所有工程和无限长度视频都能成功。
93
+
94
+ 建议部署验收顺序:真实自检 → 低分辨率单帧 → 3 帧连续动画 → 一次中断/恢复 → 下载并核对结果 → 正式任务。只做针对剩余风险的验证,不以重复 CPU 测试代替 GPU 实测。
docs/DEPLOY.zh-CN.md ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 部署与运行
2
+
3
+ 本项目的服务端部署目标是 **Linux x64 + Python 3.12**,默认下载 Blender 5.2.2。客户端可以在 Windows 使用;不要求你的 Windows 电脑安装渲染服务依赖。源代码包不包含 Blender 二进制和 Python 依赖,需要部署环境联网下载。
4
+
5
+ ## Hugging Face ZeroGPU Space
6
+
7
+ 1. 登录 Hugging Face,新建 Space,SDK 选择 **Gradio**,建议可见性为 Private。
8
+ 2. 上传解压后项目目录中的文件到 Space 根目录。根目录必须直接包含 `app.py`、`README.md`、`requirements.txt`、`packages.txt`,不要再套一层项目文件夹。
9
+ 3. 保留 README frontmatter:`sdk: gradio`、`sdk_version: 6.28.0`、`python_version: "3.12"`、`app_file: app.py`。
10
+ 4. 在 Settings 的硬件选项选择 **ZeroGPU**。此项目不使用 Docker Space,因为 ZeroGPU 由 Gradio SDK 提供。若账号没有该硬件选项,请查看当前 HF 资格要求;项目不会通过设置变量绕过硬件分配。
11
+ 5. 在 Settings → Variables 设置 `RENDER_BACKEND=zerogpu`。不要手工设置或伪造 HF 的内部 ZeroGPU 环境变量。
12
+ 6. 等待构建。PyTorch CUDA 依赖和 Blender 都较大,第一次构建和启动需要下载。启动日志应显示 Blender 安装完成,然后 Gradio 开始监听。
13
+ 7. 打开「环境自检」,读取环境确认后端;点击真实渲染自检,等待报告和测试图。必须同时满足 `ok=true`、`gpu_verified=true`。
14
+ 8. 使用 640×360、16 samples、1 帧配置检查自己的工程。低成本验证通过后再提交完整视频。
15
+
16
+ 当前硬件资格、GPU 类型、时限和配额以 [Hugging Face ZeroGPU 官方文档](https://huggingface.co/docs/hub/en/spaces-zerogpu) 为准。账号拥有 ZeroGPU 访问权不等于 Blender 子进程必然兼容;本项目的真实自检就是这一部署前提的验证入口。
17
+
18
+ ## 自检失败时
19
+
20
+ 下载 `probe.log` 与 JSON 报告,区分以下情况:
21
+
22
+ | 现象 | 检查内容 | 处理方向 |
23
+ | --- | --- | --- |
24
+ | 非 ZeroGPU 环境 | Space 硬件、`RENDER_BACKEND`、重启后的环境 | 正确选择硬件并重启 |
25
+ | Blender 自动安装失败 | 官方下载网络、磁盘空间、校验结果 | 重试构建,或设置可信的已有 `BLENDER_BIN` |
26
+ | 缺少共享库 | 构建是否安装 `packages.txt` | 保留系统依赖列表,重新构建 |
27
+ | Cycles 找不到 GPU | Blender 子进程设备报告、平台可见设备 | 收集日志;必要时改用普通 GPU Space |
28
+ | CUDA / OptiX 初始化失败 | 驱动、当前 Blender 版本与设备 | 尝试工程配置 `device=CUDA`;若仍失败使用兼容的普通 GPU |
29
+ | 超时 | 场景加载与首帧总耗时 | 降低采样/分辨率;单帧不能完成时使用普通 GPU |
30
+ | 配额用尽或排队拒绝 | HF 调用账号当前配额 | 等待配额恢复;不要无休止自动重试 |
31
+
32
+ 普通 GPU 备选需要你手动选择硬件,并将 `RENDER_BACKEND=gpu`。这可能产生费用;代码不会操作 HF 硬件设置。`gpu_self_test` 在显式 CPU 模式下会测试 CPU 渲染,但返回 `gpu_verified=false`,不能当作 GPU 成功证据。
33
+
34
+ ## 工程准备
35
+
36
+ ### 推荐:自包含 `.blend`
37
+
38
+ 在 Blender 中执行 `File → External Data → Pack Resources`,保存文件,再上传。资源能否内嵌取决于其类型;外链工程、模拟缓存或其他大文件可能仍需单独携带。
39
+
40
+ ### 推荐:完整工程 ZIP
41
+
42
+ 把主 `.blend`、纹理、HDRI、链接库和已烘焙缓存放在同一工程目录内;使用相对路径,在压缩前自行打开项目检查纹理和缓存是否可读。[Blender 文件打包说明](https://docs.blender.org/manual/en/latest/files/blend/packed_data.html)
43
+
44
+ ZIP 可包含如下路径:
45
+
46
+ | ZIP 条目 | 用途 |
47
+ | --- | --- |
48
+ | `project/scene.blend` | 主工程 |
49
+ | `project/textures/wood.png` | 纹理 |
50
+ | `project/world/studio.exr` | HDRI |
51
+ | `project/libraries/furniture.blend` | 链接库 |
52
+ | `project/cache/...` | 已烘焙模拟缓存 |
53
+
54
+ 这时设置 `"blend_file": "project/scene.blend"`。若只有一个 `.blend` 可省略该字段;存在多个 `.blend` 必须指明主工程。ZIP 内相对路径是可靠来源;多个单独上传文件会失去本机目录层级,适合已打包工程或少量同目录资源。
55
+
56
+ 不要上传 Blender 可执行文件、第三方 Python 插件或渲染脚本。本应用不执行这些文件;JSON 仅控制已支持的渲染参数。场景需要有相机;可在 `inspect_job` 的报告中查询相机名称,并通过 `camera` 精确指定。
57
+
58
+ ## 服务端环境变量
59
+
60
+ 这些是 Space 管理员配置,不是用户渲染 JSON 的字段。可调整上限时应同时检查磁盘、内存与预算。
61
+
62
+ | 变量 | 默认值 | 作用 |
63
+ | --- | --- | --- |
64
+ | `RENDER_BACKEND` | `auto` | `auto` 检测 ZeroGPU,否则普通 GPU;可显式 `zerogpu` / `gpu` / `cpu` |
65
+ | `BLENDER_VERSION` | `5.2.2` | 自动下载的官方 Blender 三段版本号 |
66
+ | `BLENDER_BIN` | 未设置 | 已安装 Blender 可执行文件绝对路径;优先于自动下载 |
67
+ | `BLENDER_CACHE` | 用户缓存目录内的 `blender-render-space` | Blender 下载和安装缓存 |
68
+ | `RENDER_DATA_DIR` | 项目下的 `runtime_data` | 任务、完成帧、日志和导出文件 |
69
+ | `BLENDER_THREADS` | `4` | Blender CPU 线程数,范围 1–256 |
70
+ | `FFMPEG_THREADS` | `4` | FFmpeg 编码线程数 |
71
+ | `MAX_UPLOAD_MB` | `1024` | 每任务上传总量上限,MiB |
72
+ | `MAX_EXTRACT_MB` | `4096` | 工程解压/暂存上限,MiB |
73
+ | `MAX_ARCHIVE_FILES` | `5000` | 工程文件与 ZIP 条目上限 |
74
+ | `MAX_PIXELS` | `16777216` | 最终输出单帧像素总数上限 |
75
+ | `MAX_FRAMES` | `2000` | 单任务最大预期帧数 |
76
+ | `MAX_JOBS` | `32` | 同时保留的任务数量上限 |
77
+ | `MIN_FREE_MB` | `512` | 新建任务前最低空闲空间,MiB |
78
+ | `JOB_TTL_HOURS` | `24` | 空闲过期任务的保留时间;新建任务时触发清理 |
79
+ | `GRADIO_SERVER_NAME` | `0.0.0.0` | 本机服务监听地址 |
80
+ | `PORT` / `GRADIO_SERVER_PORT` | `7860` | 服务端口,优先读取 `PORT` |
81
+
82
+ Gradio 入口还限制单个上传文件最多 `1gb`;仅调大 `MAX_UPLOAD_MB` 不会改变这个入口限制。`MIN_FREE_MB` 是新任务开始前的检查,并非整个渲染过程中保留空间的硬配额;高清长序列仍可能耗尽磁盘。合理限制帧数并及时下载结果。
83
+
84
+ ## 本机 CPU 验证
85
+
86
+ 在 Debian/Ubuntu Linux 上:
87
+
88
+ ```bash
89
+ sudo apt-get update
90
+ sudo xargs -a packages.txt apt-get install -y
91
+ python3.12 -m venv .venv
92
+ source .venv/bin/activate
93
+ python -m pip install --upgrade pip
94
+ python -m pip install -r requirements.txt
95
+ export RENDER_BACKEND=cpu
96
+ python app.py
97
+ ```
98
+
99
+ 已有 Blender 时先设置其路径:
100
+
101
+ ```bash
102
+ export BLENDER_BIN=/opt/blender/blender
103
+ export RENDER_BACKEND=cpu
104
+ python app.py
105
+ ```
106
+
107
+ `requirements.txt` 包含面向 ZeroGPU 的 PyTorch CUDA 包,下载量大。应用在普通 CPU/GPU 环境下不会构造 ZeroGPU 装饰器;如仅做开发逻辑测试,可以单独安装 Gradio/Spaces/Pydantic/Pillow 和 pytest。但上传到 HF 时仍应保留完整 `requirements.txt`,不要遗漏 ZeroGPU 所需 PyTorch。固定 2.8.0 是已公布支持范围内的兼容基线,不代表它是最新 PyTorch。[官方 PyTorch 版本安装表](https://pytorch.org/get-started/previous-versions/)
108
+
109
+ ## 数据保存、恢复与模型信任
110
+
111
+ 默认使用 Space 当前磁盘。HF Space 的存储持久性取决于实际配置;睡眠重建、重启、部署更新和过期清理可能丢失任务。只有服务器帧目录仍存在时,相同 job ID 才能续渲。请及时使用「打包下载」或客户端 `--max-batches` 分段取回结果。程序没有自动把帧上传到 HF Dataset、Bucket 或其他对象存储。
112
+
113
+ 若你已配置持久化挂载,可将 `RENDER_DATA_DIR` 指向该挂载的可写目录;本应用不会自动购买或创建持久存储。持久化数据还应自行备份。[HF 存储文档](https://huggingface.co/docs/hub/en/spaces-storage)
114
+
115
+ 推荐私有 Space、受信任工程、不存放与渲染无关的敏感凭据。随机 job ID 是任务访问凭据,获得 ID 的调用者可以访问任务状态和输出。现有路径控制和禁脚本不是强隔离沙箱,复杂恶意 `.blend` 仍可能触发 Blender 原生漏洞。
docs/TEST_REPORT.zh-CN.md ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 验证报告
2
+
3
+ 验证日期:2026-09-22;版本:1.0.0。
4
+
5
+ ## 验证结论
6
+
7
+ 应用代码、CPU 渲染链路、Gradio 文件 API 和 MCP 已在本地实测。**没有创建 Hugging Face Space,没有访问真实 ZeroGPU 或 NVIDIA GPU,因此未验证该平台上的 Blender GPU 兼容性、速度与可用配额。** ZeroGPU 支持为实验性;部署后先运行真实渲染自检。
8
+
9
+ | 验证项目 | 实测结果 |
10
+ | --- | --- |
11
+ | 自动化测试 | `python -m pytest -q`:98 passed |
12
+ | 配置与上传 | 69 项;未知字段、错误类型、重复 JSON 键、非有限数、非法帧/尺寸、ZIP 路径穿越、符号链接、特殊文件、压缩比、文件数、重名冲突与原子暂存 |
13
+ | 任务服务 | 22 项;进度、分批、续渲、失败保留、取消、并发锁、凭据/路径隔离、损坏 PNG 处理、过期清理、公开 JSON 路径修复,以及实际 FFmpeg 编码 |
14
+ | 安装与进程管理 | 7 项;校验和、恶意 tar/链接拒绝、并发安装、凭据过滤、CUDA 环境保留、实际子进程超时与取消;这些进程测试使用测试执行器,不冒充 Blender GPU |
15
+ | Blender 版本 | 官方 Linux x64 Blender 5.2.2 LTS,build hash `d13f752e3b9c` |
16
+ | CPU 自检 | Cycles 实际渲染 32×32、1 sample,`ok=true`、`gpu_verified=false` |
17
+ | HTTP API 图片全流程 | Gradio Client 上传含子目录的项目 ZIP 和独立 JSON;检查资源、渲染 640×360 PNG、下载预览与 ZIP,校验 PNG 和 ZIP 内容成功 |
18
+ | CPU 视频全流程 | 示例 `.blend`,320×180、4 samples,渲染源帧 1/3/5;分两批完成;FFprobe 确认 H.264、3 帧、12 fps(配置 fps=24、step=2) |
19
+ | OpenEXR | CPU 实际渲染 64×64、16 位 EXR;输出非空且标准 EXR 文件头正确 |
20
+ | GPU 缺失行为 | 当前无 NVIDIA GPU;AUTO 尝试 OPTIX/CUDA 后明确失败,没有切换 CPU |
21
+ | 资源缺失行为 | 缺图被正确识别;strict_assets=true 拒绝渲染,false 时 CPU 渲染成功并保留缺图报告 |
22
+ | API/MCP | 本地 HTTP 页面与 API schema 正常;MCP initialize、tools/list、tools/call 成功;公开工具数量 10 |
23
+ | 连续渲染 UI | 控制流程验证:完成、初始取消、配额错误、无进展均按设计停止;没有真实 GPU 连续租约测试 |
24
+
25
+ `test-artifacts/` 包含实际渲染的图片、短视频与机器可读报告。短视频只用于验证帧序列合成,不代表长动画性能。
26
+
27
+ ## 已发现并修复的问题
28
+
29
+ 1. Blender 的通用 RNA 遍历会将 UI 工作区路径误判为缺失资源,部分数据访问还会崩溃。改为检查明确的渲染资源、节点和缓存。
30
+ 2. 严格整数 JSON 的色深字段需要转换成 Blender 的字符串枚举。
31
+ 3. 续渲状态会将损坏 PNG 计为完成;现在校验并移除无效最终帧,后续重渲。
32
+ 4. Gradio Client 会将 JSON 内含 `path` 的帧记录当成下载对象,导致私有路径下载 403;公开报告现只返回 `filename`,可下载文件经专用输出组件导出。
33
+ 5. 改进任务锁异常释放、取消状态、导出统计一致性和自检导出过期清理。
34
+
35
+ ## 复现方式
36
+
37
+ ```bash
38
+ python -m pip install -r requirements-dev.txt
39
+ python -m pytest -q
40
+ ```
41
+
42
+ 已有 Blender 时,运行真实 CPU API 烟测:
43
+
44
+ ```bash
45
+ BLENDER_BIN=/path/to/blender python scripts/smoke_test.py
46
+ ```
47
+
48
+ 该脚本在 localhost 启动临时 Gradio 服务,并通过真实文件 API 上传、渲染、下载,结束后关闭服务。会将最新测试图片和报告写入 `test-artifacts/`,不申请 GPU。
49
+
50
+ ## 仍需目标环境验收
51
+
52
+ - Hugging Face ZeroGPU 对 Blender 子进程的实际设备访问能力。
53
+ - 目标 GPU 驱动与 CUDA/OptiX 内核兼容性、GPU 渲染速度与显存容量。
54
+ - 真实账号的 GPU 排队、配额、时限和长任务稳定性。
55
+ - 目标 Space 首次访问 Blender 官方下载服务器并校验安装包的过程。本地使用已提供的官方 Blender 压缩包;下载/校验分支通过模拟网络测试,没有假称已在 HF 构建成功。
56
+ - 私有 Space 的实际账号认证。MCP 协议和文件 API 已在本机验证,未声称已验证用户账号的远程权限。
57
+
58
+ 源代码中包含与正式渲染相同执行链路的自检,部署后以 `ok=true`、`gpu_verified=true` 及可见输出图片为 GPU 可用依据。小场景成功仍不等于所有复杂工程都可完成。
examples/client_render.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """上传工程、检查资源、逐批渲染并下载结果;仅依赖 gradio_client。
3
+
4
+ 新任务:python examples/client_render.py --space USER/SPACE --project scene.zip --config examples/video.json
5
+ 续渲:python examples/client_render.py --space USER/SPACE --resume-job --output outputs
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import inspect
12
+ import json
13
+ import os
14
+ from pathlib import Path
15
+ import shutil
16
+ import sys
17
+ import time
18
+ from typing import Any
19
+
20
+ from gradio_client import Client, handle_file
21
+
22
+
23
+ def emit(event: str, **values: Any) -> None:
24
+ """使用 JSON 行输出,方便 agent 读取进度和最终结果。"""
25
+ print(json.dumps({"event": event, **values}, ensure_ascii=False), flush=True)
26
+
27
+
28
+ def save_json(path: Path, value: dict[str, Any]) -> None:
29
+ """原子保存任务 ID,避免进程被中断后重新创建重复任务。"""
30
+ path.parent.mkdir(parents=True, exist_ok=True)
31
+ temporary = path.with_name(path.name + ".tmp")
32
+ temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
33
+ try:
34
+ temporary.chmod(0o600)
35
+ except OSError:
36
+ pass
37
+ temporary.replace(path)
38
+
39
+
40
+ def make_client(space: str, cache: Path) -> Client:
41
+ # Gradio Client 新版参数为 token;兼容使用 hf_token 的旧版本。
42
+ token = os.environ.get("HF_TOKEN") or None
43
+ parameters = inspect.signature(Client).parameters
44
+ kwargs: dict[str, Any] = {"verbose": False, "download_files": str(cache)}
45
+ kwargs["token" if "token" in parameters else "hf_token"] = token
46
+ return Client(space, **kwargs)
47
+
48
+
49
+ def local_file(value: Any) -> Path:
50
+ """Client 已负责鉴权下载;只复制本机文件,不向任意 URL 转发令牌。"""
51
+ if isinstance(value, str):
52
+ path = Path(value)
53
+ elif isinstance(value, dict) and value.get("path"):
54
+ path = Path(value["path"])
55
+ else:
56
+ raise RuntimeError("API 返回了无法识别的文件结构,请更新 gradio_client。")
57
+ if not path.is_file():
58
+ raise RuntimeError(f"Client 未能下载输出文件:{path.name}")
59
+ return path
60
+
61
+
62
+ def export_results(client: Client, job_id: str, output: Path) -> dict[str, Any]:
63
+ summary, files, _image, _video = client.predict(job_id, api_name="/finalize_job")
64
+ downloaded: list[str] = []
65
+ for value in files or []:
66
+ source = local_file(value)
67
+ destination = output / source.name
68
+ if source.resolve() != destination.resolve():
69
+ shutil.copy2(source, destination)
70
+ downloaded.append(str(destination.resolve()))
71
+ save_json(output / "client-summary.json", summary)
72
+ emit("export", job_id=job_id, export_complete=summary.get("export_complete", False),
73
+ files=downloaded, error=summary.get("export_error"))
74
+ return summary
75
+
76
+
77
+ def ensure_healthy(status: dict[str, Any]) -> None:
78
+ # 部分帧成功后出错时 status 仍可能是 partial,必须同时检查 error。
79
+ if status.get("error"):
80
+ raise RuntimeError(str(status["error"]))
81
+ if status.get("status") in {"failed", "cancelled", "cancelling"}:
82
+ raise RuntimeError(f"任务已停止:{status.get('status')}。确认原因后使用 --resume-job。")
83
+
84
+
85
+ def parser() -> argparse.ArgumentParser:
86
+ result = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
87
+ result.add_argument("--space", required=True, help="HF Space ID(USER/SPACE),或 Gradio 根 URL")
88
+ result.add_argument("--project", nargs="+", type=Path, help="一个项目 ZIP,或 .blend 与资源文件")
89
+ result.add_argument("--config", type=Path, help="UTF-8 JSON 渲染配置;新任务必需")
90
+ result.add_argument("--output", type=Path, default=Path("outputs"), help="下载目录,默认 outputs")
91
+ result.add_argument("--job-file", type=Path, help="任务凭据文件,默认 OUTPUT/render-job.json")
92
+ result.add_argument("--resume-job", nargs="?", const="@job-file", metavar="JOB_ID",
93
+ help="恢复指定任务;不传 ID 时从 --job-file 读取")
94
+ result.add_argument("--inspect", "--inspect-only", dest="inspect_only", action="store_true",
95
+ help="准备并检查任务后退出,不渲染;正常渲染也会先检查")
96
+ result.add_argument("--max-batches", type=int, default=0, help="本次最多渲染几批;0 表示直到完成")
97
+ result.add_argument("--self-test", action="store_true", help="渲染前运行真实 GPU 小场景自检")
98
+ return result
99
+
100
+
101
+ def run(args: argparse.Namespace) -> int:
102
+ if args.max_batches < 0:
103
+ raise ValueError("--max-batches 不能小于零。")
104
+ args.output = args.output.expanduser().resolve()
105
+ args.output.mkdir(parents=True, exist_ok=True)
106
+ job_file = (args.job_file or args.output / "render-job.json").expanduser().resolve()
107
+ if args.resume_job is None and job_file.exists():
108
+ raise ValueError(f"任务文件已存在:{job_file}。请使用 --resume-job 续渲,或改用新的 --output。")
109
+ if args.resume_job is not None and (args.project or args.config):
110
+ raise ValueError("续渲沿用服务端原配置;请勿同时传入 --project 或 --config。")
111
+ if args.resume_job is None:
112
+ if not args.project or args.config is None:
113
+ raise ValueError("新任务必须提供 --project 和 --config。")
114
+ for path in [*args.project, args.config]:
115
+ if not path.is_file():
116
+ raise ValueError(f"找不到文件:{path}")
117
+ config_text = args.config.read_text(encoding="utf-8-sig")
118
+ if not isinstance(json.loads(config_text), dict):
119
+ raise ValueError("配置根节点必须是 JSON 对象。")
120
+ else:
121
+ config_text = "{}"
122
+
123
+ client = make_client(args.space, args.output / ".client-downloads")
124
+ job_id: str | None = None
125
+
126
+ def remember(status: dict[str, Any]) -> None:
127
+ save_json(job_file, {"space": args.space, "job_id": job_id, "updated_at": time.time(),
128
+ "status": status.get("status"), "completed_count": status.get("completed_count"),
129
+ "total_frames": status.get("total_frames")})
130
+
131
+ try:
132
+ environment = client.predict(api_name="/environment_info")
133
+ emit("environment", info=environment)
134
+ if args.self_test:
135
+ probe, _files, _image = client.predict(api_name="/gpu_self_test")
136
+ emit("self_test", report=probe)
137
+ if not probe.get("ok"):
138
+ raise RuntimeError("真实渲染自检失败,请先查看 Space 的自检日志。")
139
+ if probe.get("deployment_backend") != "cpu" and not probe.get("gpu_verified"):
140
+ raise RuntimeError("自检未确认 Blender GPU 渲染成功。")
141
+
142
+ if args.resume_job:
143
+ if args.resume_job == "@job-file":
144
+ saved = json.loads(job_file.read_text(encoding="utf-8"))
145
+ if saved.get("space") != args.space:
146
+ raise ValueError("任务文件中的 Space 与 --space 不一致;请使用原 Space 标识。")
147
+ job_id = str(saved["job_id"])
148
+ else:
149
+ job_id = args.resume_job
150
+ status = client.predict(job_id, api_name="/resume_job")
151
+ else:
152
+ uploads = [handle_file(str(path.resolve())) for path in args.project]
153
+ job_id, status = client.predict(uploads, config_text, None, api_name="/prepare_job")
154
+ remember(status)
155
+ emit("job", job_id=job_id, job_file=str(job_file), status=status.get("status"))
156
+
157
+ # 在申请 GPU 之前检查相机、场景和资源,避免浪费租约。
158
+ status = client.predict(job_id, api_name="/inspect_job")
159
+ remember(status)
160
+ save_json(args.output / "inspection.json", status)
161
+ ensure_healthy(status)
162
+ inspection = status.get("inspection") or {}
163
+ missing = inspection.get("missing_assets") or []
164
+ emit("inspection", missing_assets=missing, warnings=inspection.get("warnings", []))
165
+ if missing and status.get("config", {}).get("strict_assets", True):
166
+ raise RuntimeError("工程存在缺失或被阻止的外部资源;检查 inspection.json 并修复后创建新任务。")
167
+ if args.inspect_only:
168
+ emit("inspection_complete", job_id=job_id, next_action="使用 --resume-job 开始渲染")
169
+ return 0
170
+
171
+ batches = 0
172
+ while status.get("remaining_frames"):
173
+ before = status.get("completed_count", 0)
174
+ status = client.predict(job_id, api_name="/render_chunk")
175
+ batches += 1
176
+ remember(status)
177
+ emit("progress", job_id=job_id, status=status.get("status"),
178
+ completed=status.get("completed_count"), total=status.get("total_frames"),
179
+ error=status.get("error"))
180
+ ensure_healthy(status)
181
+ if status.get("completed_count", 0) <= before:
182
+ raise RuntimeError("本批没有完成新帧,停止重试;请检查日志和 GPU 时限。")
183
+ if args.max_batches and batches >= args.max_batches and status.get("remaining_frames"):
184
+ export_results(client, job_id, args.output)
185
+ emit("paused", job_id=job_id, message="已达到本次批数上限,可使用 --resume-job 继续。")
186
+ return 0
187
+
188
+ summary = export_results(client, job_id, args.output)
189
+ if not summary.get("export_complete"):
190
+ raise RuntimeError(summary.get("export_error") or "输出尚未完整生成。")
191
+ emit("complete", job_id=job_id, output=str(args.output))
192
+ return 0
193
+ except KeyboardInterrupt:
194
+ if job_id:
195
+ try:
196
+ remember(client.predict(job_id, api_name="/cancel_job"))
197
+ except Exception:
198
+ pass
199
+ emit("interrupted", job_id=job_id, message="已请求停止;保留任务文件后可续渲。")
200
+ return 130
201
+ except Exception:
202
+ if job_id:
203
+ # 即使某一帧失败,也尽量取回已完成帧和诊断日志。
204
+ try:
205
+ export_results(client, job_id, args.output)
206
+ except Exception:
207
+ pass
208
+ emit("resume_available", job_id=job_id, job_file=str(job_file))
209
+ raise
210
+
211
+
212
+ def main() -> int:
213
+ try:
214
+ return run(parser().parse_args())
215
+ except Exception as exc:
216
+ message = str(exc)
217
+ token = os.environ.get("HF_TOKEN")
218
+ if token:
219
+ message = message.replace(token, "[REDACTED]")
220
+ print(f"错误:{message}", file=sys.stderr)
221
+ return 1
222
+
223
+
224
+ if __name__ == "__main__":
225
+ raise SystemExit(main())
examples/demo.blend ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5526526b59e34340d00fd0f50c9eb154b6cbc2a20966e978676016c76246b299
3
+ size 284950
examples/frames-exr.json ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": 1,
3
+ "mode": "frames",
4
+ "width": 1920,
5
+ "height": 1080,
6
+ "frame_start": 1,
7
+ "frame_end": 12,
8
+ "frame_step": 1,
9
+ "fps": 24,
10
+ "samples": 64,
11
+ "denoise": true,
12
+ "format": "OPEN_EXR",
13
+ "color_depth": 16,
14
+ "transparent": true,
15
+ "device": "AUTO",
16
+ "strict_assets": true,
17
+ "batch_size": 1,
18
+ "gpu_seconds": 120,
19
+ "cpu_timeout": 600,
20
+ "seed": 0
21
+ }
examples/image.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": 1,
3
+ "mode": "image",
4
+ "width": 1280,
5
+ "height": 720,
6
+ "resolution_percentage": 100,
7
+ "frame": 1,
8
+ "samples": 64,
9
+ "denoise": true,
10
+ "adaptive_threshold": 0.02,
11
+ "format": "PNG",
12
+ "color_depth": 8,
13
+ "transparent": false,
14
+ "device": "AUTO",
15
+ "strict_assets": true,
16
+ "batch_size": 1,
17
+ "gpu_seconds": 120,
18
+ "cpu_timeout": 600,
19
+ "seed": 0
20
+ }
examples/mcp-client.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "mcpServers": {
3
+ "blender-render": {
4
+ "type": "http",
5
+ "url": "https://YOUR-SPACE-DOMAIN.hf.space/gradio_api/mcp/"
6
+ }
7
+ }
8
+ }
examples/video.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": 1,
3
+ "mode": "video",
4
+ "width": 1280,
5
+ "height": 720,
6
+ "resolution_percentage": 100,
7
+ "frame_start": 1,
8
+ "frame_end": 120,
9
+ "frame_step": 1,
10
+ "fps": 24,
11
+ "samples": 32,
12
+ "denoise": true,
13
+ "adaptive_threshold": 0.03,
14
+ "motion_blur": false,
15
+ "format": "PNG",
16
+ "color_depth": 8,
17
+ "transparent": false,
18
+ "device": "AUTO",
19
+ "strict_assets": true,
20
+ "batch_size": 1,
21
+ "gpu_seconds": 120,
22
+ "cpu_timeout": 600,
23
+ "video_crf": 18,
24
+ "video_preset": "medium",
25
+ "seed": 0
26
+ }
packages.txt ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ffmpeg
2
+ libx11-6
3
+ libxi6
4
+ libxrender1
5
+ libxfixes3
6
+ libxkbcommon0
7
+ libsm6
8
+ libgl1
9
+ libegl1
10
+ libgomp1
11
+ libdbus-1-3
12
+ libxxf86vm1
13
+ libxrandr2
14
+ libxcursor1
15
+ libwayland-client0
render.schema.json ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additionalProperties": false,
3
+ "description": "可直接传递给渲染任务的、版本化的严格配置。",
4
+ "properties": {
5
+ "schema_version": {
6
+ "const": 1,
7
+ "default": 1,
8
+ "title": "Schema Version",
9
+ "type": "integer"
10
+ },
11
+ "blend_file": {
12
+ "anyOf": [
13
+ {
14
+ "type": "string"
15
+ },
16
+ {
17
+ "type": "null"
18
+ }
19
+ ],
20
+ "default": null,
21
+ "title": "Blend File"
22
+ },
23
+ "mode": {
24
+ "default": "image",
25
+ "enum": [
26
+ "image",
27
+ "frames",
28
+ "video"
29
+ ],
30
+ "title": "Mode",
31
+ "type": "string"
32
+ },
33
+ "scene": {
34
+ "anyOf": [
35
+ {
36
+ "type": "string"
37
+ },
38
+ {
39
+ "type": "null"
40
+ }
41
+ ],
42
+ "default": null,
43
+ "title": "Scene"
44
+ },
45
+ "camera": {
46
+ "anyOf": [
47
+ {
48
+ "type": "string"
49
+ },
50
+ {
51
+ "type": "null"
52
+ }
53
+ ],
54
+ "default": null,
55
+ "title": "Camera"
56
+ },
57
+ "view_layer": {
58
+ "anyOf": [
59
+ {
60
+ "type": "string"
61
+ },
62
+ {
63
+ "type": "null"
64
+ }
65
+ ],
66
+ "default": null,
67
+ "title": "View Layer"
68
+ },
69
+ "width": {
70
+ "default": 1280,
71
+ "maximum": 8192,
72
+ "minimum": 16,
73
+ "title": "Width",
74
+ "type": "integer"
75
+ },
76
+ "height": {
77
+ "default": 720,
78
+ "maximum": 8192,
79
+ "minimum": 16,
80
+ "title": "Height",
81
+ "type": "integer"
82
+ },
83
+ "resolution_percentage": {
84
+ "default": 100,
85
+ "maximum": 100,
86
+ "minimum": 1,
87
+ "title": "Resolution Percentage",
88
+ "type": "integer"
89
+ },
90
+ "samples": {
91
+ "default": 64,
92
+ "maximum": 4096,
93
+ "minimum": 1,
94
+ "title": "Samples",
95
+ "type": "integer"
96
+ },
97
+ "denoise": {
98
+ "default": true,
99
+ "title": "Denoise",
100
+ "type": "boolean"
101
+ },
102
+ "adaptive_threshold": {
103
+ "default": 0.02,
104
+ "maximum": 1,
105
+ "minimum": 0,
106
+ "title": "Adaptive Threshold",
107
+ "type": "number"
108
+ },
109
+ "transparent": {
110
+ "default": false,
111
+ "title": "Transparent",
112
+ "type": "boolean"
113
+ },
114
+ "frame": {
115
+ "default": 1,
116
+ "maximum": 1000000,
117
+ "minimum": 1,
118
+ "title": "Frame",
119
+ "type": "integer"
120
+ },
121
+ "frame_start": {
122
+ "default": 1,
123
+ "maximum": 1000000,
124
+ "minimum": 1,
125
+ "title": "Frame Start",
126
+ "type": "integer"
127
+ },
128
+ "frame_end": {
129
+ "default": 120,
130
+ "maximum": 1000000,
131
+ "minimum": 1,
132
+ "title": "Frame End",
133
+ "type": "integer"
134
+ },
135
+ "frame_step": {
136
+ "default": 1,
137
+ "maximum": 1000000,
138
+ "minimum": 1,
139
+ "title": "Frame Step",
140
+ "type": "integer"
141
+ },
142
+ "fps": {
143
+ "default": 24,
144
+ "maximum": 120,
145
+ "minimum": 1,
146
+ "title": "Fps",
147
+ "type": "integer"
148
+ },
149
+ "format": {
150
+ "default": "PNG",
151
+ "enum": [
152
+ "PNG",
153
+ "OPEN_EXR"
154
+ ],
155
+ "title": "Format",
156
+ "type": "string"
157
+ },
158
+ "color_depth": {
159
+ "default": 8,
160
+ "enum": [
161
+ 8,
162
+ 16,
163
+ 32
164
+ ],
165
+ "title": "Color Depth",
166
+ "type": "integer"
167
+ },
168
+ "device": {
169
+ "default": "AUTO",
170
+ "enum": [
171
+ "AUTO",
172
+ "CUDA",
173
+ "OPTIX",
174
+ "CPU"
175
+ ],
176
+ "title": "Device",
177
+ "type": "string"
178
+ },
179
+ "seed": {
180
+ "default": 0,
181
+ "maximum": 2147483647,
182
+ "minimum": 0,
183
+ "title": "Seed",
184
+ "type": "integer"
185
+ },
186
+ "motion_blur": {
187
+ "default": false,
188
+ "title": "Motion Blur",
189
+ "type": "boolean"
190
+ },
191
+ "strict_assets": {
192
+ "default": true,
193
+ "title": "Strict Assets",
194
+ "type": "boolean"
195
+ },
196
+ "batch_size": {
197
+ "default": 1,
198
+ "maximum": 64,
199
+ "minimum": 1,
200
+ "title": "Batch Size",
201
+ "type": "integer"
202
+ },
203
+ "gpu_seconds": {
204
+ "default": 120,
205
+ "maximum": 600,
206
+ "minimum": 10,
207
+ "title": "Gpu Seconds",
208
+ "type": "integer"
209
+ },
210
+ "cpu_timeout": {
211
+ "default": 600,
212
+ "maximum": 7200,
213
+ "minimum": 10,
214
+ "title": "Cpu Timeout",
215
+ "type": "integer"
216
+ },
217
+ "video_crf": {
218
+ "default": 18,
219
+ "maximum": 40,
220
+ "minimum": 0,
221
+ "title": "Video Crf",
222
+ "type": "integer"
223
+ },
224
+ "video_preset": {
225
+ "default": "medium",
226
+ "enum": [
227
+ "medium",
228
+ "fast",
229
+ "slow"
230
+ ],
231
+ "title": "Video Preset",
232
+ "type": "string"
233
+ }
234
+ },
235
+ "title": "RenderConfig",
236
+ "type": "object"
237
+ }
render_config.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """渲染配置:严格校验所有来自 UI、API 和 MCP 的 JSON 参数。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import re
8
+ from typing import Annotated, Literal
9
+
10
+ from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
11
+
12
+
13
+ MAX_CONFIG_BYTES = 64 * 1024
14
+ _DRIVE = re.compile(r"^[A-Za-z]:")
15
+
16
+
17
+ def positive_env_int(name: str, default: int) -> int:
18
+ """读取服务端资源上限;错误配置直接报错,避免意外取消限制。"""
19
+ value = os.environ.get(name, str(default))
20
+ try:
21
+ parsed = int(value)
22
+ except (ValueError, TypeError) as exc:
23
+ raise ValueError(f"环境变量 {name} 必须为正整数。") from exc
24
+ if parsed <= 0:
25
+ raise ValueError(f"环境变量 {name} 必须为正整数。")
26
+ return parsed
27
+
28
+
29
+ def safe_relative_path(value: str) -> str:
30
+ """保留路径原样;禁止跨平台歧义、越界路径和 Windows ADS。"""
31
+ if not isinstance(value, str) or not value:
32
+ raise ValueError("文件路径必须是非空相对路径。")
33
+ if value.startswith("/") or _DRIVE.match(value) or "\\" in value:
34
+ raise ValueError("文件路径必须使用相对路径和 / 分隔符。")
35
+ if any(ord(char) < 32 or ord(char) == 127 for char in value):
36
+ raise ValueError("文件路径不能包含 NUL 或控制字符。")
37
+ parts = value.split("/")
38
+ if any(part in {"", ".", ".."} for part in parts):
39
+ raise ValueError("文件路径不能包含空层级、. 或 ..。")
40
+ if any(":" in part or part.endswith((".", " ")) for part in parts):
41
+ raise ValueError("文件路径包含不安全的跨平台文件名。")
42
+ return value
43
+
44
+
45
+ class RenderConfig(BaseModel):
46
+ """可直接传递给渲染任务的、版本化的严格配置。"""
47
+
48
+ model_config = ConfigDict(extra="forbid", strict=True, allow_inf_nan=False)
49
+
50
+ schema_version: Literal[1] = 1
51
+ blend_file: str | None = None
52
+ mode: Literal["image", "frames", "video"] = "image"
53
+ scene: str | None = None
54
+ camera: str | None = None
55
+ view_layer: str | None = None
56
+ width: Annotated[int, Field(ge=16, le=8192)] = 1280
57
+ height: Annotated[int, Field(ge=16, le=8192)] = 720
58
+ resolution_percentage: Annotated[int, Field(ge=1, le=100)] = 100
59
+ samples: Annotated[int, Field(ge=1, le=4096)] = 64
60
+ denoise: bool = True
61
+ adaptive_threshold: Annotated[float, Field(ge=0, le=1)] = 0.02
62
+ transparent: bool = False
63
+ frame: Annotated[int, Field(ge=1, le=1_000_000)] = 1
64
+ frame_start: Annotated[int, Field(ge=1, le=1_000_000)] = 1
65
+ frame_end: Annotated[int, Field(ge=1, le=1_000_000)] = 120
66
+ frame_step: Annotated[int, Field(ge=1, le=1_000_000)] = 1
67
+ fps: Annotated[int, Field(ge=1, le=120)] = 24
68
+ format: Literal["PNG", "OPEN_EXR"] = "PNG"
69
+ color_depth: Literal[8, 16, 32] = 8
70
+ device: Literal["AUTO", "CUDA", "OPTIX", "CPU"] = "AUTO"
71
+ seed: Annotated[int, Field(ge=0, le=2_147_483_647)] = 0
72
+ motion_blur: bool = False
73
+ strict_assets: bool = True
74
+ batch_size: Annotated[int, Field(ge=1, le=64)] = 1
75
+ gpu_seconds: Annotated[int, Field(ge=10, le=600)] = 120
76
+ cpu_timeout: Annotated[int, Field(ge=10, le=7200)] = 600
77
+ video_crf: Annotated[int, Field(ge=0, le=40)] = 18
78
+ video_preset: Literal["medium", "fast", "slow"] = "medium"
79
+
80
+ @field_validator("schema_version", "color_depth", mode="before")
81
+ @classmethod
82
+ def require_integer_literal(cls, value: object) -> object:
83
+ # Python 的 True == 1;Literal 仍需显式防止 bool/float 伪装成整数。
84
+ if type(value) is not int:
85
+ raise ValueError("此字段必须使用 JSON 整数。")
86
+ return value
87
+
88
+ @field_validator("blend_file")
89
+ @classmethod
90
+ def validate_blend_file(cls, value: str | None) -> str | None:
91
+ if value is not None:
92
+ safe_relative_path(value)
93
+ if not value.casefold().endswith(".blend"):
94
+ raise ValueError("blend_file 必须指定 .blend 文件。")
95
+ return value
96
+
97
+ @field_validator("scene", "camera", "view_layer")
98
+ @classmethod
99
+ def validate_datablock_name(cls, value: str | None) -> str | None:
100
+ if value is not None and (
101
+ not value.strip() or len(value) > 1024 or "\x00" in value
102
+ ):
103
+ raise ValueError("场景、相机和视图层名称必须为有效的非空名称。")
104
+ return value
105
+
106
+ @model_validator(mode="after")
107
+ def validate_render_constraints(self) -> "RenderConfig":
108
+ if self.frame_end < self.frame_start:
109
+ raise ValueError("frame_end 不能小于 frame_start。")
110
+ if self.format == "PNG" and self.color_depth not in (8, 16):
111
+ raise ValueError("PNG 的 color_depth 只能为 8 或 16。")
112
+ if self.format == "OPEN_EXR" and self.color_depth not in (16, 32):
113
+ raise ValueError("OPEN_EXR 的 color_depth 只能为 16 或 32。")
114
+ if self.output_width < 1 or self.output_height < 1:
115
+ raise ValueError("缩放后的输出尺寸必须至少为 1 × 1。")
116
+ if self.output_width * self.output_height > positive_env_int(
117
+ "MAX_PIXELS", 16_777_216
118
+ ):
119
+ raise ValueError("输出像素总数超过服务端 MAX_PIXELS 限制。")
120
+ frame_count = 1 if self.mode == "image" else (
121
+ (self.frame_end - self.frame_start) // self.frame_step + 1
122
+ )
123
+ if frame_count > positive_env_int("MAX_FRAMES", 2000):
124
+ raise ValueError("帧数超过服务端 MAX_FRAMES 限制。")
125
+ if self.mode == "video":
126
+ if self.format != "PNG":
127
+ raise ValueError("video 模式只支持 PNG 中间帧。")
128
+ if self.transparent:
129
+ raise ValueError("MP4 视频不支持透明背景,请设置 transparent=false。")
130
+ if self.output_width % 2 or self.output_height % 2:
131
+ raise ValueError("video 模式的最终宽、高必须均为偶数。")
132
+ return self
133
+
134
+ @property
135
+ def output_width(self) -> int:
136
+ return max(1, self.width * self.resolution_percentage // 100)
137
+
138
+ @property
139
+ def output_height(self) -> int:
140
+ return max(1, self.height * self.resolution_percentage // 100)
141
+
142
+ def frame_numbers(self) -> list[int]:
143
+ """逐帧任务使用此列表;隔帧采样由编码端同步调整播放帧率以保持时间尺度。"""
144
+ if self.mode == "image":
145
+ return [self.frame]
146
+ return list(range(self.frame_start, self.frame_end + 1, self.frame_step))
147
+
148
+
149
+ def _reject_duplicate_keys(pairs: list[tuple[str, object]]) -> dict[str, object]:
150
+ result: dict[str, object] = {}
151
+ for key, value in pairs:
152
+ if key in result:
153
+ raise ValueError(f"JSON 包含重复字段:{key}")
154
+ result[key] = value
155
+ return result
156
+
157
+
158
+ def _reject_nonfinite(value: str) -> None:
159
+ raise ValueError(f"JSON 不允许非有限数值:{value}")
160
+
161
+
162
+ def parse_config(text: str) -> RenderConfig:
163
+ """解析 JSON;限制输入大小并拒绝重复字段、NaN 和隐式类型转换。"""
164
+ if not isinstance(text, str):
165
+ raise ValueError("配置必须是 JSON 文本。")
166
+ try:
167
+ byte_count = len(text.encode("utf-8"))
168
+ except UnicodeEncodeError as exc:
169
+ raise ValueError("配置文本包含无效 Unicode 字符。") from exc
170
+ if byte_count > MAX_CONFIG_BYTES:
171
+ raise ValueError("配置文件不能超过 64 KiB。")
172
+ try:
173
+ raw = json.loads(
174
+ text, object_pairs_hook=_reject_duplicate_keys, parse_constant=_reject_nonfinite
175
+ )
176
+ except (json.JSONDecodeError, RecursionError) as exc:
177
+ raise ValueError(f"无效的 JSON 配置:{exc}") from exc
178
+ if not isinstance(raw, dict):
179
+ raise ValueError("配置根节点必须是 JSON 对象。")
180
+ return RenderConfig.model_validate(raw)
181
+
182
+
183
+ def json_schema() -> dict:
184
+ """返回标准 JSON Schema,方便 agent 发现可用参数。"""
185
+ return RenderConfig.model_json_schema()
render_worker.py ADDED
@@ -0,0 +1,521 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Blender 内执行的渲染工作进程;请通过 Blender --python 调用。
2
+
3
+ 输入只接受服务端创建的 task.json,不执行用户提供的 Python。
4
+ 文件路径限制属于纵深防御,不替代操作系统对原生 .blend 解析器的隔离。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import os
11
+ import re
12
+ import sys
13
+ import time
14
+ import traceback
15
+ from pathlib import Path
16
+
17
+ import bpy
18
+
19
+
20
+ def atomic_json(path: Path, value: dict) -> None:
21
+ path.parent.mkdir(parents=True, exist_ok=True)
22
+ temp = path.with_name(path.name + ".tmp")
23
+ temp.write_text(json.dumps(value, ensure_ascii=False, indent=2), encoding="utf-8")
24
+ os.replace(temp, path)
25
+
26
+
27
+ def inside(path: Path, root: Path) -> bool:
28
+ try:
29
+ path.resolve().relative_to(root.resolve())
30
+ return True
31
+ except (OSError, ValueError):
32
+ return False
33
+
34
+
35
+ def all_ids():
36
+ """遍历 Blender 的顶层数据块,不遍历文本内容,也不执行驱动器。"""
37
+ seen = set()
38
+ for prop in bpy.data.bl_rna.properties:
39
+ if prop.type != "COLLECTION":
40
+ continue
41
+ for value in getattr(bpy.data, prop.identifier, ()):
42
+ if isinstance(value, bpy.types.ID) and value.as_pointer() not in seen:
43
+ seen.add(value.as_pointer())
44
+ yield value
45
+
46
+
47
+ class AssetGuard:
48
+ def __init__(self, root: Path, blend_path: Path, warnings: list):
49
+ self.root = root.resolve()
50
+ self.blend_path = blend_path.resolve()
51
+ self.warnings = warnings
52
+ self.assets = []
53
+ self._seen = set()
54
+ self.files = {}
55
+ self.directories = {}
56
+ # 只重定位到真正上传的文件;拒绝指向目录外的符号链接。
57
+ for path in self.root.rglob("*"):
58
+ if not inside(path, self.root):
59
+ continue
60
+ mapping = self.directories if path.is_dir() else self.files
61
+ mapping.setdefault(path.name.casefold(), []).append(path.resolve())
62
+
63
+ def resolve(self, original: str, owner=None, is_dir=False):
64
+ normalized = original.replace("\\", "/")
65
+ base = self.blend_path.parent
66
+ library = getattr(owner, "library", None)
67
+ if library:
68
+ try:
69
+ libpath = Path(bpy.path.abspath(library.filepath)).resolve()
70
+ if inside(libpath, self.root):
71
+ base = libpath.parent
72
+ except Exception:
73
+ pass
74
+ if normalized.startswith("//"):
75
+ target = base / normalized[2:]
76
+ elif re.match(r"^[A-Za-z]:/", normalized):
77
+ target = Path("/__unavailable_windows_drive__/") / normalized[3:]
78
+ else:
79
+ target = Path(normalized)
80
+ if not target.is_absolute():
81
+ target = base / target
82
+ target = target.resolve()
83
+ if inside(target, self.root) and (target.is_dir() if is_dir else target.is_file()):
84
+ return target, "ok"
85
+ # UDIM 路径中的 token 不是实际文件,但每张 tile 都必须在上传目录。
86
+ if "<UDIM>" in normalized and inside(target.parent, self.root):
87
+ tiles = list(target.parent.glob(target.name.replace("<UDIM>", "[0-9][0-9][0-9][0-9]")))
88
+ if tiles and all(inside(p, self.root) and p.is_file() for p in tiles):
89
+ return target, "ok"
90
+ # 相对路径被保留时优先匹配尾部路径,适应 Windows 上传至 Linux。
91
+ parts = [p for p in normalized.split("/") if p and p not in (".", "..") and not p.endswith(":")]
92
+ for count in range(min(len(parts), 8), 0, -1):
93
+ candidate = (self.root.joinpath(*parts[-count:])).resolve()
94
+ if inside(candidate, self.root) and (candidate.is_dir() if is_dir else candidate.is_file()):
95
+ return candidate, "remapped"
96
+ mapping = self.directories if is_dir else self.files
97
+ matches = mapping.get(Path(normalized).name.casefold(), [])
98
+ if len(matches) == 1:
99
+ return matches[0], "remapped"
100
+ return None, "missing" if inside(target, self.root) else "blocked"
101
+
102
+ def record(self, kind, name, original, resolved, status):
103
+ key = (kind, name, original)
104
+ if key not in self._seen:
105
+ self._seen.add(key)
106
+ self.assets.append({"kind": kind, "name": name, "original": original,
107
+ "resolved": str(resolved) if resolved else None, "status": status})
108
+
109
+ def clean_libraries(self):
110
+ bad_libraries = set()
111
+ for library in list(bpy.data.libraries):
112
+ original = library.filepath
113
+ # 链接库已在 open_mainfile 内加载:不能将越界库的已加载数据保留下来。
114
+ # 不对已加载的库做 basename 重定位,以免把来源判断误认为已重载成功。
115
+ raw = Path(bpy.path.abspath(original)).resolve()
116
+ allowed = inside(raw, self.root) and raw.is_file()
117
+ self.record("library", library.name, original, raw if allowed else None,
118
+ "ok" if allowed else "blocked")
119
+ if allowed:
120
+ library.filepath = str(raw)
121
+ else:
122
+ bad_libraries.add(library)
123
+ changed = True
124
+ while changed:
125
+ changed = False
126
+ for library in bpy.data.libraries:
127
+ if getattr(library, "parent", None) in bad_libraries and library not in bad_libraries:
128
+ bad_libraries.add(library)
129
+ changed = True
130
+ if bad_libraries:
131
+ unsafe = [item for item in all_ids() if getattr(item, "library", None) in bad_libraries]
132
+ bpy.data.batch_remove(ids=unsafe + list(bad_libraries))
133
+ self.warnings.append("已删除上传目录外链接库及其数据块;请将库文件随项目一起上传。")
134
+
135
+ def clean_datablock_files(self):
136
+ # 未上传数据块直接删除,避免已经缓存于内存的外部像素或字体进入渲染。
137
+ collections = ("images", "fonts", "sounds", "movieclips", "volumes", "cache_files")
138
+ remove = []
139
+ for kind in collections:
140
+ for item in list(getattr(bpy.data, kind, ())):
141
+ original = getattr(item, "filepath", "")
142
+ if not original or (kind == "fonts" and original == "<builtin>"):
143
+ continue
144
+ packed = bool(getattr(item, "packed_file", None)) or bool(getattr(item, "packed_files", []))
145
+ if packed:
146
+ self.record(kind, item.name, original, None, "packed")
147
+ continue
148
+ # 程序化图像和内部渲染结果不依赖磁盘。
149
+ if kind == "images" and getattr(item, "source", "") in ("GENERATED", "VIEWER"):
150
+ continue
151
+ path, status = self.resolve(original, item)
152
+ self.record(kind, item.name, original, path, status)
153
+ if path:
154
+ try:
155
+ item.filepath = str(path)
156
+ if kind == "images" and status == "remapped":
157
+ item.reload()
158
+ except (AttributeError, RuntimeError) as exc:
159
+ raise RuntimeError(f"无法安全重定位资源 {item.name}: {exc}") from exc
160
+ else:
161
+ remove.append(item)
162
+ if remove:
163
+ bpy.data.batch_remove(ids=remove)
164
+
165
+ def clean_rna_paths(self):
166
+ # 仅检查明确参与渲染的属性;遍历整个 RNA 会进入 UI 工作区或巨大网格,
167
+ # 还可能访问 Blender 中尚未初始化的指针,因此不能用通用递归扫描。
168
+ visited = set()
169
+
170
+ def scan(value, owner):
171
+ if value is None or not hasattr(value, "bl_rna"):
172
+ return
173
+ pointer = value.as_pointer()
174
+ if pointer in visited:
175
+ return
176
+ visited.add(pointer)
177
+ for prop in value.bl_rna.properties:
178
+ if prop.type != "STRING" or prop.subtype not in {"FILE_PATH", "DIR_PATH"} or prop.is_readonly:
179
+ continue
180
+ original = getattr(value, prop.identifier)
181
+ if not original or original == "<builtin>":
182
+ continue
183
+ path, status = self.resolve(original, owner, prop.subtype == "DIR_PATH")
184
+ self.record(f"{value.bl_rna.identifier}.{prop.identifier}", owner.name, original, path, status)
185
+ try:
186
+ setattr(value, prop.identifier, str(path) if path else "")
187
+ except Exception as exc:
188
+ raise RuntimeError(f"无法清除外部文件路径 {owner.name}/{prop.identifier}") from exc
189
+
190
+ for scene in bpy.data.scenes:
191
+ # 输出和烘焙路径不属于输入资产,由可信渲染流程另行指定。
192
+ scene.render.filepath = ""
193
+ if hasattr(scene.render, "bake"):
194
+ scene.render.bake.filepath = ""
195
+ rigid = scene.rigidbody_world
196
+ if rigid:
197
+ scan(rigid.point_cache, scene)
198
+
199
+ for obj in bpy.data.objects:
200
+ for modifier in obj.modifiers:
201
+ scan(modifier, obj)
202
+ for field in ("domain_settings", "flow_settings", "effector_settings", "point_cache"):
203
+ scan(getattr(modifier, field, None), obj)
204
+ for bake in getattr(modifier, "bakes", ()):
205
+ scan(bake, obj)
206
+ canvas = getattr(modifier, "canvas_settings", None)
207
+ if canvas:
208
+ for surface in canvas.canvas_surfaces:
209
+ scan(surface, obj)
210
+ scan(surface.point_cache, obj)
211
+ for system in obj.particle_systems:
212
+ scan(system.point_cache, obj)
213
+ scan(system.settings, obj)
214
+
215
+ for texture in bpy.data.textures:
216
+ scan(texture, texture)
217
+ for field in ("voxel_data", "point_density"):
218
+ scan(getattr(texture, field, None), texture)
219
+
220
+ for cache_file in bpy.data.cache_files:
221
+ # Alembic 缓存除了主文件,也可能叠加多份外部 layer 文件。
222
+ for layer in getattr(cache_file, "layers", ()):
223
+ scan(layer, cache_file)
224
+
225
+ trees = list(bpy.data.node_groups)
226
+ for collection in (bpy.data.materials, bpy.data.worlds, bpy.data.lights):
227
+ for owner in collection:
228
+ tree = getattr(owner, "node_tree", None)
229
+ if tree:
230
+ trees.append(tree)
231
+ for tree in trees:
232
+ # 合成器和视频序列已经关闭,文件输出节点永远不能参与执行。
233
+ if tree.bl_idname == "CompositorNodeTree":
234
+ continue
235
+ scan(tree, tree)
236
+ for node in tree.nodes:
237
+ scan(node, tree)
238
+
239
+ def clean_nodes(self):
240
+ trees = list(bpy.data.node_groups)
241
+ for item in all_ids():
242
+ tree = getattr(item, "node_tree", None)
243
+ if tree:
244
+ trees.append(tree)
245
+ for tree in trees:
246
+ for node in list(tree.nodes):
247
+ kind = node.bl_idname
248
+ # 几何节点的导入路径可能由动态字符串计算而来,不能靠静态路径检查保证安全。
249
+ if kind == "ShaderNodeScript" or (kind.startswith("GeometryNode") and ("Import" in kind or "File" in kind)):
250
+ self.warnings.append(f"已禁用外部文件/脚本节点:{tree.name}/{node.name} ({kind})。")
251
+ tree.nodes.remove(node)
252
+
253
+ def run(self):
254
+ self.clean_libraries()
255
+ self.clean_datablock_files()
256
+ self.clean_nodes()
257
+ self.clean_rna_paths()
258
+ return self.assets
259
+
260
+
261
+ def harden_scenes(warnings):
262
+ bpy.context.preferences.filepaths.use_scripts_auto_execute = False
263
+ warnings.append("自动 Python 脚本、脚本节点和 OSL 已禁用;依赖 Python 表达式的驱动器或插件不会按原项目执行。")
264
+ for scene in bpy.data.scenes:
265
+ if scene.render.use_compositing:
266
+ warnings.append(f"场景 {scene.name} 的合成器已禁用;输出为相机直接渲染结果。")
267
+ if scene.render.use_sequencer and scene.sequence_editor:
268
+ warnings.append(f"场景 {scene.name} 的视频序列编辑器已禁用。")
269
+ scene.render.use_compositing = False
270
+ scene.render.use_sequencer = False
271
+ scene.render.use_stamp = False
272
+ if hasattr(scene.render, "use_persistent_data"):
273
+ scene.render.use_persistent_data = False
274
+ if hasattr(scene, "cycles"):
275
+ scene.cycles.shading_system = False
276
+ # 禁止模拟缓存自动写入来源路径;模拟应事先烘焙并上传缓存。
277
+ for obj in scene.objects:
278
+ for modifier in obj.modifiers:
279
+ if modifier.type == "FLUID" and modifier.fluid_type == "DOMAIN":
280
+ settings = modifier.domain_settings
281
+ if settings and hasattr(settings, "cache_type"):
282
+ settings.cache_type = "MODULAR"
283
+
284
+
285
+ def select_scene(config):
286
+ name = config.get("scene")
287
+ scene = bpy.data.scenes.get(name) if name else bpy.context.scene
288
+ if scene is None:
289
+ raise ValueError(f"找不到场景:{name}")
290
+ if bpy.context.window:
291
+ bpy.context.window.scene = scene
292
+ camera_name = config.get("camera")
293
+ if camera_name:
294
+ camera = scene.objects.get(camera_name)
295
+ if camera is None or camera.type != "CAMERA":
296
+ raise ValueError(f"场景 {scene.name} 中没有相机:{camera_name}")
297
+ scene.camera = camera
298
+ return scene
299
+
300
+
301
+ def inspect_scene(assets):
302
+ scenes = []
303
+ for scene in bpy.data.scenes:
304
+ scenes.append({"name": scene.name, "camera": scene.camera.name if scene.camera else None,
305
+ "cameras": [obj.name for obj in scene.objects if obj.type == "CAMERA"],
306
+ "frame_start": scene.frame_start, "frame_end": scene.frame_end,
307
+ "frame_step": scene.frame_step, "fps": scene.render.fps,
308
+ "fps_base": scene.render.fps_base,
309
+ "width": scene.render.resolution_x, "height": scene.render.resolution_y,
310
+ "resolution_percentage": scene.render.resolution_percentage,
311
+ "engine": scene.render.engine,
312
+ "view_layers": [layer.name for layer in scene.view_layers]})
313
+ return {"scenes": scenes, "cameras": [obj.name for obj in bpy.data.objects if obj.type == "CAMERA"],
314
+ "assets": assets,
315
+ "missing_assets": [a for a in assets if a["status"] in {"missing", "blocked"}]}
316
+
317
+
318
+ def configure_cycles(scene, config):
319
+ scene.render.engine = "CYCLES"
320
+ for key, default in (("resolution_x", 960), ("resolution_y", 540)):
321
+ source = "width" if key == "resolution_x" else "height"
322
+ setattr(scene.render, key, int(config.get(source, default)))
323
+ scene.render.resolution_percentage = int(config.get("resolution_percentage", 100))
324
+ scene.render.film_transparent = bool(config.get("transparent", False))
325
+ scene.render.fps = int(config.get("fps", 24))
326
+ scene.render.fps_base = 1.0
327
+ scene.render.use_file_extension = True
328
+ scene.render.use_overwrite = True
329
+ scene.render.use_placeholder = False
330
+ scene.render.image_settings.file_format = config.get("format", "PNG")
331
+ scene.render.image_settings.color_mode = "RGBA"
332
+ scene.render.image_settings.color_depth = str(config.get("color_depth", 8))
333
+ scene.cycles.samples = int(config.get("samples", 64))
334
+ scene.cycles.use_denoising = bool(config.get("denoise", True))
335
+ scene.cycles.use_adaptive_sampling = True
336
+ scene.cycles.adaptive_threshold = float(config.get("adaptive_threshold", 0.01))
337
+ scene.cycles.seed = int(config.get("seed", 0))
338
+ scene.cycles.shading_system = False
339
+ if hasattr(scene.render, "use_motion_blur"):
340
+ scene.render.use_motion_blur = bool(config.get("motion_blur", False))
341
+ elif hasattr(scene.cycles, "use_motion_blur"):
342
+ scene.cycles.use_motion_blur = bool(config.get("motion_blur", False))
343
+ layer_name = config.get("view_layer")
344
+ if layer_name:
345
+ if scene.view_layers.get(layer_name) is None:
346
+ raise ValueError(f"找不到视图层:{layer_name}")
347
+ for layer in scene.view_layers:
348
+ layer.use = layer.name == layer_name
349
+ if not scene.camera:
350
+ raise ValueError("场景没有活动相机,请在 JSON 中指定 camera 或先在 Blender 中添加相机。")
351
+
352
+
353
+ def device_candidates(requested):
354
+ if requested == "AUTO":
355
+ return ("OPTIX", "CUDA")
356
+ if requested not in {"OPTIX", "CUDA", "CPU"}:
357
+ raise ValueError(f"不支持的设备类型:{requested}")
358
+ return (requested,)
359
+
360
+
361
+ def use_device(scene, backend):
362
+ addon = bpy.context.preferences.addons.get("cycles")
363
+ if addon is None:
364
+ raise RuntimeError("此 Blender 安装不包含 Cycles。")
365
+ prefs = addon.preferences
366
+ if backend == "CPU":
367
+ scene.cycles.device = "CPU"
368
+ return [{"name": "CPU", "type": "CPU", "use": True}]
369
+ prefs.compute_device_type = backend
370
+ if hasattr(prefs, "refresh_devices"):
371
+ prefs.refresh_devices()
372
+ else:
373
+ prefs.get_devices()
374
+ devices = []
375
+ for device in prefs.devices:
376
+ # 绝不启用混合 CPU 渲染;ZeroGPU 验证失败时必须明确报错。
377
+ device.use = device.type == backend
378
+ if device.use:
379
+ devices.append({"name": device.name, "type": device.type, "id": device.id, "use": True})
380
+ if not devices:
381
+ raise RuntimeError(f"Cycles 未找到可用的 {backend} GPU;拒绝静默回退至 CPU。")
382
+ scene.cycles.device = "GPU"
383
+ return devices
384
+
385
+
386
+ def choose_device(scene, requested):
387
+ failures = []
388
+ for backend in device_candidates(requested):
389
+ try:
390
+ return backend, use_device(scene, backend)
391
+ except Exception as exc:
392
+ failures.append(f"{backend}: {exc}")
393
+ raise RuntimeError("GPU 设备初始化失败。" + " | ".join(failures))
394
+
395
+
396
+ def make_probe_scene():
397
+ bpy.ops.wm.read_factory_settings(use_empty=True)
398
+ scene = bpy.context.scene
399
+ bpy.ops.mesh.primitive_cube_add()
400
+ obj = bpy.context.object
401
+ obj.rotation_euler = (0.2, 0.3, 0.0)
402
+ bpy.ops.object.camera_add(location=(3, -4, 3))
403
+ camera = bpy.context.object
404
+ camera.rotation_euler = (-camera.location).to_track_quat("-Z", "Y").to_euler()
405
+ scene.camera = camera
406
+ bpy.ops.object.light_add(type="AREA", location=(2, -2, 4))
407
+ bpy.context.object.data.energy = 500
408
+ bpy.context.object.data.size = 3
409
+ return scene
410
+
411
+
412
+ def render_one(scene, output_dir, frame, config):
413
+ extension = ".exr" if config.get("format", "PNG") == "OPEN_EXR" else ".png"
414
+ final = output_dir / f"frame_{frame:06d}{extension}"
415
+ temporary = output_dir / f".frame_{frame:06d}.partial{extension}"
416
+ scene.frame_set(frame)
417
+ scene.render.filepath = str(temporary)
418
+ started = time.monotonic()
419
+ bpy.ops.render.render(write_still=True, scene=scene.name)
420
+ if not temporary.is_file() or temporary.stat().st_size == 0:
421
+ raise RuntimeError(f"Blender 没有生成第 {frame} 帧输出。")
422
+ os.replace(temporary, final)
423
+ record = {"frame": frame, "path": str(final), "seconds": round(time.monotonic() - started, 3),
424
+ "bytes": final.stat().st_size}
425
+ # 每帧刷盘:GPU 租约中途结束时,父进程仍能恢复已经完成的帧。
426
+ with (output_dir / "completed.jsonl").open("a", encoding="utf-8") as handle:
427
+ handle.write(json.dumps(record, ensure_ascii=False) + "\n")
428
+ handle.flush()
429
+ os.fsync(handle.fileno())
430
+ print("RENDER_FRAME_COMPLETED " + json.dumps(record), flush=True)
431
+ return record
432
+
433
+
434
+ def main():
435
+ if "--" not in sys.argv or len(sys.argv[sys.argv.index("--") + 1:]) != 1:
436
+ raise ValueError("用法:blender --background --factory-startup --disable-autoexec --python render_worker.py -- task.json")
437
+ task_path = Path(sys.argv[sys.argv.index("--") + 1]).resolve(strict=True)
438
+ task = json.loads(task_path.read_text(encoding="utf-8"))
439
+ result_path = Path(task["result_path"]).resolve()
440
+ output_dir = Path(task["output_dir"]).resolve()
441
+ output_dir.mkdir(parents=True, exist_ok=True)
442
+ config = task.get("config", {})
443
+ result = {"ok": False, "action": task["action"], "blender_version": bpy.app.version_string,
444
+ "warnings": [], "devices": [], "backend": None, "frames": [], "timings": {}}
445
+ start = time.monotonic()
446
+ try:
447
+ action = task["action"]
448
+ if action == "probe":
449
+ scene = make_probe_scene()
450
+ probe_config = {**config, "width": 32, "height": 32, "resolution_percentage": 100,
451
+ "samples": 1, "denoise": False, "format": "PNG", "color_depth": "8"}
452
+ harden_scenes(result["warnings"])
453
+ configure_cycles(scene, probe_config)
454
+ failures = []
455
+ for backend in device_candidates(config.get("device", "AUTO")):
456
+ try:
457
+ result["devices"] = use_device(scene, backend)
458
+ result["backend"] = backend
459
+ result["frames"] = [render_one(scene, output_dir, 1, probe_config)]
460
+ result["probe_render_succeeded"] = True
461
+ break
462
+ except Exception as exc:
463
+ failures.append(f"{backend}: {exc}")
464
+ else:
465
+ raise RuntimeError("实际 Cycles 探针渲染失败;检测到 CUDA 不代表 ZeroGPU 可以运行 Blender。" + " | ".join(failures))
466
+ result["warnings"].extend(failures)
467
+ elif action in {"inspect", "render"}:
468
+ root = Path(task["project_root"]).resolve(strict=True)
469
+ blend_path = Path(task["blend_path"]).resolve(strict=True)
470
+ if not inside(blend_path, root) or blend_path.suffix.lower() != ".blend":
471
+ raise ValueError(".blend 文件必须位于上传项目目录内。")
472
+ bpy.context.preferences.filepaths.use_scripts_auto_execute = False
473
+ bpy.ops.wm.open_mainfile(filepath=str(blend_path), load_ui=False, use_scripts=False)
474
+ harden_scenes(result["warnings"])
475
+ assets = AssetGuard(root, blend_path, result["warnings"]).run()
476
+ result.update(inspect_scene(assets))
477
+ result["timings"]["load_and_inspect_seconds"] = round(time.monotonic() - start, 3)
478
+ if action == "render":
479
+ if config.get("strict_assets", True) and result["missing_assets"]:
480
+ missing = ", ".join(a["name"] for a in result["missing_assets"][:8])
481
+ raise ValueError(f"存在缺失或越界资源:{missing}。请上传完整资源,或将 strict_assets 设为 false 后接受缺失效果。")
482
+ scene = select_scene(config)
483
+ configure_cycles(scene, config)
484
+ frames = task.get("frames") or [int(config.get("frame", config.get("frame_start", scene.frame_current)))]
485
+ for frame in frames:
486
+ if not isinstance(frame, int) or isinstance(frame, bool) or abs(frame) > 1_048_574:
487
+ raise ValueError("帧编号必须是 Blender 支持范围内的整数。")
488
+ # AUTO 必须通过实际首帧验证;OPTIX 初始化成功也可能在加载内核时失败。
489
+ failures = []
490
+ for backend in device_candidates(config.get("device", "AUTO")):
491
+ try:
492
+ result["devices"] = use_device(scene, backend)
493
+ result["backend"] = backend
494
+ result["frames"].append(render_one(scene, output_dir, frames[0], config))
495
+ break
496
+ except Exception as exc:
497
+ failures.append(f"{backend}: {exc}")
498
+ else:
499
+ raise RuntimeError("所有指定后端的首帧实际渲染均失败;没有回退至 CPU。" + " | ".join(failures))
500
+ result["warnings"].extend(failures)
501
+ atomic_json(result_path, result)
502
+ for frame in frames[1:]:
503
+ result["frames"].append(render_one(scene, output_dir, frame, config))
504
+ result["timings"]["elapsed_seconds"] = round(time.monotonic() - start, 3)
505
+ atomic_json(result_path, result)
506
+ else:
507
+ raise ValueError(f"未知任务:{action}")
508
+ result["ok"] = True
509
+ except Exception as exc:
510
+ result["error"] = str(exc)
511
+ result["error_type"] = type(exc).__name__
512
+ traceback.print_exc()
513
+ finally:
514
+ result["timings"]["elapsed_seconds"] = round(time.monotonic() - start, 3)
515
+ atomic_json(result_path, result)
516
+ if not result["ok"]:
517
+ raise RuntimeError(result.get("error", "渲染失败"))
518
+
519
+
520
+ if __name__ == "__main__":
521
+ main()
requirements-dev.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ -r requirements.txt
2
+ pytest>=8.3,<10
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # ZeroGPU 部署完整依赖。PyTorch 是 spaces 的 ZeroGPU 运行时依赖,不能省略。
2
+ gradio[mcp]==6.28.0
3
+ spaces==0.51.3
4
+ torch==2.8.0
5
+ pydantic>=2.11,<3
6
+ Pillow>=11,<13
scripts/create_demo.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """生成无需外部贴图的演示场景。
2
+
3
+ blender --background --factory-startup --python scripts/create_demo.py -- --output demo.blend
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import argparse
8
+ import math
9
+ import sys
10
+ from pathlib import Path
11
+
12
+ import bpy
13
+ from mathutils import Vector
14
+
15
+
16
+ def material(name, color, metallic=0.0, roughness=0.4):
17
+ value = bpy.data.materials.new(name)
18
+ value.diffuse_color = (*color, 1)
19
+ value.use_nodes = True
20
+ shader = value.node_tree.nodes.get("Principled BSDF")
21
+ shader.inputs["Base Color"].default_value = (*color, 1)
22
+ shader.inputs["Metallic"].default_value = metallic
23
+ shader.inputs["Roughness"].default_value = roughness
24
+ return value
25
+
26
+
27
+ def smooth(obj):
28
+ for polygon in obj.data.polygons:
29
+ polygon.use_smooth = True
30
+
31
+
32
+ def aim(obj, target):
33
+ obj.rotation_euler = (Vector(target) - obj.location).to_track_quat("-Z", "Y").to_euler()
34
+
35
+
36
+ def area(name, location, energy, color, size, target=(0, 0, 1)):
37
+ bpy.ops.object.light_add(type="AREA", location=location)
38
+ obj = bpy.context.object
39
+ obj.name = name
40
+ obj.data.energy = energy
41
+ obj.data.color = color
42
+ obj.data.shape = "DISK"
43
+ obj.data.size = size
44
+ aim(obj, target)
45
+ return obj
46
+
47
+
48
+ def build(output: Path):
49
+ bpy.ops.wm.read_factory_settings(use_empty=True)
50
+ scene = bpy.context.scene
51
+ scene.name = "Studio"
52
+ scene.render.engine = "CYCLES"
53
+ scene.cycles.samples = 64
54
+ scene.cycles.use_denoising = True
55
+ scene.render.resolution_x = 960
56
+ scene.render.resolution_y = 540
57
+ scene.render.resolution_percentage = 100
58
+ scene.render.fps = 24
59
+ scene.frame_start = 1
60
+ scene.frame_end = 120
61
+ scene.render.image_settings.file_format = "PNG"
62
+ scene.world = bpy.data.worlds.new("Studio World")
63
+ scene.world.use_nodes = True
64
+ scene.world.node_tree.nodes["Background"].inputs["Color"].default_value = (0.055, 0.085, 0.13, 1)
65
+ scene.world.node_tree.nodes["Background"].inputs["Strength"].default_value = 0.3
66
+ try:
67
+ scene.view_settings.view_transform = "AgX"
68
+ except TypeError:
69
+ pass
70
+
71
+ jade = material("Jade ceramic", (0.05, 0.42, 0.32), metallic=0.24, roughness=0.2)
72
+ gold = material("Champagne metal", (0.8, 0.55, 0.2), metallic=0.88, roughness=0.24)
73
+ cream = material("Warm porcelain", (0.76, 0.68, 0.55), roughness=0.28)
74
+ navy = material("Midnight plinth", (0.023, 0.054, 0.085), metallic=0.2, roughness=0.35)
75
+ floor = material("Studio floor", (0.055, 0.085, 0.11), roughness=0.45)
76
+
77
+ bpy.ops.mesh.primitive_plane_add(size=200)
78
+ bpy.context.object.name = "Floor"
79
+ bpy.context.object.data.materials.append(floor)
80
+
81
+ bpy.ops.mesh.primitive_cylinder_add(vertices=96, radius=1.85, depth=0.32, location=(0, 0, 0.16))
82
+ plinth = bpy.context.object
83
+ plinth.name = "Display plinth"
84
+ plinth.data.materials.append(navy)
85
+ bevel = plinth.modifiers.new("Soft edges", "BEVEL")
86
+ bevel.width = 0.08
87
+ bevel.segments = 4
88
+ smooth(plinth)
89
+
90
+ bpy.ops.mesh.primitive_monkey_add(location=(0.0, 0, 1.45))
91
+ hero = bpy.context.object
92
+ hero.name = "Jade Suzanne"
93
+ hero.rotation_euler.z = math.radians(-12)
94
+ hero.data.materials.append(jade)
95
+ subdivision = hero.modifiers.new("Sculpted surface", "SUBSURF")
96
+ subdivision.levels = 2
97
+ subdivision.render_levels = 2
98
+ smooth(hero)
99
+
100
+ bpy.ops.mesh.primitive_torus_add(major_segments=96, minor_segments=24,
101
+ location=(0, 0.25, 1.6), rotation=(math.radians(76), 0.2, 0),
102
+ major_radius=1.52, minor_radius=0.052)
103
+ ring = bpy.context.object
104
+ ring.name = "Golden orbit"
105
+ ring.data.materials.append(gold)
106
+ smooth(ring)
107
+
108
+ for name, loc, radius, mat in [
109
+ ("Porcelain sphere", (1.23, -0.63, 0.63), 0.31, cream),
110
+ ("Golden sphere", (-1.16, -0.67, 0.59), 0.27, gold),
111
+ ("Small jade sphere", (0.7, 0.9, 0.5), 0.18, jade),
112
+ ]:
113
+ bpy.ops.mesh.primitive_uv_sphere_add(segments=48, ring_count=24, radius=radius, location=loc)
114
+ obj = bpy.context.object
115
+ obj.name = name
116
+ obj.data.materials.append(mat)
117
+ smooth(obj)
118
+
119
+ area("Large warm key", (3, -4, 6), 1100, (1.0, 0.84, 0.67), 4)
120
+ area("Soft cool fill", (-4, -1, 3), 800, (0.50, 0.76, 1.0), 3)
121
+ area("Golden rim", (1, 4, 5), 1500, (1.0, 0.65, 0.28), 2.5)
122
+
123
+ bpy.ops.object.empty_add(type="PLAIN_AXES", location=(0, 0, 1.12))
124
+ target = bpy.context.object
125
+ target.name = "Camera target"
126
+ bpy.ops.object.camera_add(location=(5.4, -7.5, 4.2))
127
+ camera = bpy.context.object
128
+ camera.name = "OrbitCamera"
129
+ camera.data.lens = 52
130
+ camera.data.dof.use_dof = True
131
+ camera.data.dof.focus_object = target
132
+ camera.data.dof.aperture_fstop = 6.3
133
+ aim(camera, target.location)
134
+ track = camera.constraints.new("TRACK_TO")
135
+ track.target = target
136
+ track.track_axis = "TRACK_NEGATIVE_Z"
137
+ track.up_axis = "UP_Y"
138
+ scene.camera = camera
139
+ # 逐帧记录相机位��,不使用驱动器或自动脚本。
140
+ for frame in range(1, 121):
141
+ angle = math.radians(-68 + (frame - 1) * 70 / 119)
142
+ camera.location = (8.9 * math.cos(angle), 8.9 * math.sin(angle), 4.0)
143
+ camera.keyframe_insert(data_path="location", frame=frame)
144
+ scene.frame_set(1)
145
+ output.parent.mkdir(parents=True, exist_ok=True)
146
+ bpy.ops.wm.save_as_mainfile(filepath=str(output.resolve()), check_existing=False)
147
+ print(f"已创建演示场景:{output.resolve()}")
148
+
149
+
150
+ if __name__ == "__main__":
151
+ parser = argparse.ArgumentParser()
152
+ parser.add_argument("--output", default="demo.blend")
153
+ args = parser.parse_args(sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else [])
154
+ build(Path(args.output))
scripts/smoke_test.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """真实集成烟测:本机启动 Gradio,上传工程/JSON,渲染PNG并验证下载。
3
+
4
+ 运行:BLENDER_BIN=/path/to/blender python scripts/smoke_test.py
5
+ 默认明确使用 CPU;不声称测试了 ZeroGPU。需要先安装 requirements。
6
+ """
7
+ from __future__ import annotations
8
+ import json
9
+ import os
10
+ from pathlib import Path
11
+ import sys
12
+ import tempfile
13
+ import zipfile
14
+
15
+ ROOT = Path(__file__).resolve().parents[1]
16
+ sys.path.insert(0, str(ROOT))
17
+ os.environ['RENDER_BACKEND'] = 'cpu'
18
+ os.environ.setdefault('GRADIO_ANALYTICS_ENABLED', 'False')
19
+ os.environ['NO_PROXY'] = ','.join(filter(None, [os.environ.get('NO_PROXY', ''), '127.0.0.1', 'localhost']))
20
+
21
+
22
+ def main():
23
+ from gradio_client import Client, handle_file
24
+ from PIL import Image
25
+ with tempfile.TemporaryDirectory(prefix='blender-space-smoke-') as tmp:
26
+ temp = Path(tmp)
27
+ os.environ['RENDER_DATA_DIR'] = str(temp / 'jobs-data')
28
+ import app
29
+ import service
30
+ from blender_runtime import ensure_blender
31
+ binary = ensure_blender()
32
+ demo_file = ROOT / 'examples/demo.blend'
33
+ if not demo_file.is_file():
34
+ raise RuntimeError('缺少 examples/demo.blend,请先运行 scripts/create_demo.py。')
35
+ project = temp / 'project.zip'
36
+ with zipfile.ZipFile(project, 'w') as archive:
37
+ archive.write(demo_file, 'scene/demo.blend')
38
+ config = temp / 'render.json'
39
+ config.write_text(json.dumps({'blend_file':'scene/demo.blend','mode':'image',
40
+ 'width':640,'height':360,'samples':16,'batch_size':1}), encoding='utf-8')
41
+ demo = app.build_app().queue()
42
+ _, url, _ = demo.launch(server_name='127.0.0.1', server_port=7867,
43
+ prevent_thread_lock=True, quiet=True, mcp_server=True,
44
+ allowed_paths=[str(service.PUBLIC_ROOT)],
45
+ theme=app.gr.themes.Soft(), css=app.CSS)
46
+ try:
47
+ client = Client(url, verbose=False, download_files=str(temp / 'downloads'),
48
+ httpx_kwargs={'trust_env':False})
49
+ environment = client.predict(api_name='/environment_info')
50
+ probe, _, _ = client.predict(api_name='/gpu_self_test')
51
+ assert probe['ok'] and probe['backend'] == 'CPU' and not probe['gpu_verified']
52
+ job_id, prepared = client.predict([handle_file(str(project))], '{}', handle_file(str(config)),
53
+ api_name='/prepare_job')
54
+ checked = client.predict(job_id, api_name='/inspect_job')
55
+ assert checked['status'] == 'ready', checked
56
+ status = client.predict(job_id, api_name='/render_chunk')
57
+ assert status['status'] == 'complete' and not status['error'], status
58
+ summary, files, image, video = client.predict(job_id, api_name='/finalize_job')
59
+ assert summary['export_complete'] and image and not video, summary
60
+ with Image.open(image) as rendered:
61
+ assert rendered.size == (640,360)
62
+ rendered.verify()
63
+ archive_file = next(Path(f) for f in files if str(f).endswith('.zip'))
64
+ with zipfile.ZipFile(archive_file) as result_zip:
65
+ assert 'frames/frame_000001.png' in result_zip.namelist()
66
+ assert result_zip.testzip() is None
67
+ artifacts = ROOT / 'test-artifacts'
68
+ artifacts.mkdir(exist_ok=True)
69
+ import shutil
70
+ shutil.copy2(image, artifacts / 'cpu-render-preview.png')
71
+ report = {'ok':True,'backend':'CPU','blender':probe['blender_version'],
72
+ 'api_upload_zip':True,'api_upload_config':True,'api_render_png':True,
73
+ 'image_dimensions':[640,360],'api_download_zip_verified':True,
74
+ 'zero_gpu_tested':False,'environment':environment}
75
+ (artifacts / 'api-smoke-report.json').write_text(json.dumps(report,ensure_ascii=False,indent=2),encoding='utf-8')
76
+ print(json.dumps(report,ensure_ascii=False,indent=2))
77
+ finally:
78
+ demo.close()
79
+
80
+
81
+ if __name__ == '__main__':
82
+ main()
service.py ADDED
@@ -0,0 +1,484 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """任务服务:CPU 负责文件,GPU 租约仅覆盖真实 Blender 渲染。"""
2
+ from __future__ import annotations
3
+
4
+ import spaces # 必须先于可能加载 CUDA 的库导入。
5
+ import contextlib
6
+ import importlib.metadata
7
+ import json
8
+ import os
9
+ from pathlib import Path
10
+ import re
11
+ import secrets
12
+ import shutil
13
+ import subprocess
14
+ import threading
15
+ import time
16
+ import zipfile
17
+
18
+ from blender_runtime import ensure_blender, run_task
19
+ from render_config import RenderConfig, parse_config, json_schema
20
+ from uploads import stage_uploads
21
+
22
+ BASE = Path(__file__).resolve().parent
23
+ DATA_ROOT = Path(os.environ.get('RENDER_DATA_DIR', BASE / 'runtime_data')).resolve()
24
+ JOB_ROOT = DATA_ROOT / 'jobs'
25
+ PUBLIC_ROOT = DATA_ROOT / 'public'
26
+ for folder in (JOB_ROOT, PUBLIC_ROOT):
27
+ folder.mkdir(parents=True, exist_ok=True)
28
+ _LOCKS: dict[str, threading.Lock] = {}
29
+ _LOCKS_GUARD = threading.Lock()
30
+
31
+
32
+ def _atomic_json(path: Path, data: dict) -> None:
33
+ tmp = path.with_suffix('.tmp-' + secrets.token_hex(4))
34
+ tmp.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding='utf-8')
35
+ os.replace(tmp, path)
36
+
37
+
38
+ def _job(job_id: str) -> Path:
39
+ # ID 同时是访问凭证,不允许任意路径访问。
40
+ if not re.fullmatch(r'[0-9a-f]{48}', job_id or ''):
41
+ raise ValueError('任务 ID 无效。请先准备任务。')
42
+ path = JOB_ROOT / job_id
43
+ if not (path / 'job.json').is_file():
44
+ raise ValueError('任务不存在或已过期;Space 临时磁盘重置后请重新上传。')
45
+ return path
46
+
47
+
48
+ def _load(path: Path) -> dict:
49
+ return json.loads((path / 'job.json').read_text(encoding='utf-8'))
50
+
51
+
52
+ def _save(path: Path, meta: dict) -> None:
53
+ meta['updated_at'] = time.time()
54
+ _atomic_json(path / 'job.json', meta)
55
+
56
+
57
+ @contextlib.contextmanager
58
+ def _lock(path: Path):
59
+ with _LOCKS_GUARD:
60
+ lock = _LOCKS.setdefault(path.name, threading.Lock())
61
+ if not lock.acquire(blocking=False):
62
+ raise ValueError('该任务正在执行,请等待或取消当前批次。')
63
+ handle = None
64
+ try:
65
+ handle = (path / '.lock').open('a+')
66
+ # Linux 文件锁使重入和多进程请求也不能同时更改同一任务。
67
+ import fcntl
68
+ try:
69
+ fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
70
+ except BlockingIOError:
71
+ raise ValueError('该任务正在另一个进程执行。') from None
72
+ yield
73
+ finally:
74
+ if handle is not None:
75
+ handle.close()
76
+ lock.release()
77
+
78
+
79
+ def _backend() -> str:
80
+ choice = os.environ.get('RENDER_BACKEND', 'auto').lower()
81
+ if choice not in {'auto', 'zerogpu', 'gpu', 'cpu'}:
82
+ raise ValueError('RENDER_BACKEND 必须为 auto / zerogpu / gpu / cpu。')
83
+ from spaces.config import Config
84
+ zero = bool(Config.zero_gpu)
85
+ if choice == 'auto':
86
+ return 'zerogpu' if zero else 'gpu'
87
+ if choice == 'zerogpu' and not zero:
88
+ raise ValueError('当前不是 ZeroGPU 运行环境。请在 Space 设置选择 ZeroGPU;本地测试请设置 RENDER_BACKEND=cpu 或 gpu。')
89
+ return choice
90
+
91
+
92
+ def _config(meta: dict) -> RenderConfig:
93
+ return parse_config(json.dumps(meta['config']))
94
+
95
+
96
+ def _frame_path(path: Path, frame: int, config: RenderConfig) -> Path:
97
+ return path / 'frames' / f"frame_{frame:06d}.{'png' if config.format == 'PNG' else 'exr'}"
98
+
99
+
100
+ def _completed(path: Path, config: RenderConfig, verify: bool = False) -> list[int]:
101
+ result = []
102
+ # 只信任 worker 原子改名完成的最终文件,不接纳 .part 或用户上传文件。
103
+ for frame in config.frame_numbers():
104
+ p = _frame_path(path, frame, config)
105
+ if not p.is_file() or p.stat().st_size < 32:
106
+ continue
107
+ if verify and config.format == 'PNG':
108
+ try:
109
+ from PIL import Image
110
+ with Image.open(p) as img:
111
+ if img.size != (config.output_width, config.output_height):
112
+ continue
113
+ img.verify()
114
+ except Exception:
115
+ continue
116
+ result.append(frame)
117
+ return result
118
+
119
+
120
+ def _public_report(value):
121
+ """JSON 中的 path 会被 Gradio Client 当作可下载文件;内部路径只输出文件名。"""
122
+ if isinstance(value, dict):
123
+ return {('filename' if key == 'path' else key):
124
+ (Path(item).name if key == 'path' and isinstance(item, str) else _public_report(item))
125
+ for key, item in value.items()}
126
+ if isinstance(value, list):
127
+ return [_public_report(item) for item in value]
128
+ return value
129
+
130
+
131
+ def _status(path: Path, verified_done: list[int] | None = None) -> dict:
132
+ meta = _load(path)
133
+ cfg = _config(meta)
134
+ done = _completed(path, cfg) if verified_done is None else verified_done
135
+ expected = cfg.frame_numbers()
136
+ status = meta['status']
137
+ if (path / 'cancel.flag').exists():
138
+ status = 'cancelling' if status == 'rendering' else 'cancelled'
139
+ return {
140
+ 'job_id': path.name, 'status': status, 'mode': cfg.mode,
141
+ 'backend': meta.get('backend'), 'completed_count': len(done),
142
+ 'total_frames': len(expected), 'completed_frames': done,
143
+ 'remaining_frames': [f for f in expected if f not in set(done)],
144
+ 'progress': round(len(done) / len(expected), 4),
145
+ 'config': meta['config'], 'inspection': _public_report(meta.get('inspection')),
146
+ 'last_render': _public_report(meta.get('last_render')), 'error': meta.get('error'),
147
+ 'created_at': meta['created_at'], 'updated_at': meta['updated_at'],
148
+ 'note': '任务 ID 是访问凭证,请勿公开;断点依赖当前 Space 磁盘。',
149
+ }
150
+
151
+
152
+ def _cleanup() -> None:
153
+ """准备新任务时清理过期的空闲任务,不删除仍持有执行锁的任务。"""
154
+ ttl = int(os.environ.get('JOB_TTL_HOURS', '24')) * 3600
155
+ now = time.time()
156
+ for public in PUBLIC_ROOT.glob('probe-*'):
157
+ if public.is_dir() and now - public.stat().st_mtime > ttl:
158
+ shutil.rmtree(public, ignore_errors=True)
159
+ for path in JOB_ROOT.iterdir():
160
+ if not path.is_dir() or not (path / 'job.json').is_file():
161
+ continue
162
+ try:
163
+ if now - _load(path)['updated_at'] > ttl:
164
+ with _lock(path):
165
+ shutil.rmtree(PUBLIC_ROOT / path.name, ignore_errors=True)
166
+ shutil.rmtree(path)
167
+ with _LOCKS_GUARD:
168
+ _LOCKS.pop(path.name, None)
169
+ except (ValueError, OSError, KeyError, json.JSONDecodeError):
170
+ continue
171
+
172
+
173
+ def environment_info() -> dict:
174
+ """Describe deployment capabilities without allocating a GPU."""
175
+ from spaces.config import Config
176
+ versions = {}
177
+ for name in ('gradio', 'spaces', 'torch'):
178
+ try:
179
+ versions[name] = importlib.metadata.version(name)
180
+ except importlib.metadata.PackageNotFoundError:
181
+ versions[name] = None
182
+ return {
183
+ 'app_version': '1.0.0', 'versions': versions,
184
+ 'zerogpu_environment': bool(Config.zero_gpu),
185
+ 'configured_backend': os.environ.get('RENDER_BACKEND', 'auto'),
186
+ 'ffmpeg_available': bool(shutil.which('ffmpeg')),
187
+ 'gpu_verified': False,
188
+ 'message': '本接口不分配 GPU。请运行真实渲染自检;ZeroGPU 对 Blender 的兼容性尚需部署验证。',
189
+ 'mcp_path': '/gradio_api/mcp/',
190
+ 'job_ttl_hours': int(os.environ.get('JOB_TTL_HOURS', '24')),
191
+ }
192
+
193
+
194
+ def config_schema() -> dict:
195
+ """Return the JSON Schema for supported render settings."""
196
+ return json_schema()
197
+
198
+
199
+ def prepare_job(files: list[str], config_json: str, config_file: str | None = None) -> tuple[str, dict]:
200
+ """Stage Blender files and validate configuration without a GPU allocation.
201
+
202
+ Args:
203
+ files: Uploaded .blend, resource ZIPs, textures and cache files.
204
+ config_json: Render configuration as a JSON string.
205
+ config_file: Optional uploaded JSON file; takes precedence over config_json.
206
+ """
207
+ if config_file:
208
+ p = Path(config_file)
209
+ if p.stat().st_size > 65536:
210
+ raise ValueError('配置文件不得超过 64 KiB。')
211
+ config_json = p.read_text(encoding='utf-8-sig')
212
+ cfg = parse_config(config_json)
213
+ backend = _backend()
214
+ if backend != 'cpu' and cfg.device == 'CPU':
215
+ raise ValueError('CPU 渲染必须由管理员设置 RENDER_BACKEND=cpu,GPU 模式不允许静默回退。')
216
+ if backend == 'cpu':
217
+ cfg = cfg.model_copy(update={'device': 'CPU'})
218
+ _cleanup()
219
+ # 预留任务目录与数量检查是一个原子步骤,避免并行 API 越过任务上限。
220
+ import fcntl
221
+ with (DATA_ROOT / 'prepare.lock').open('a+') as reservation:
222
+ fcntl.flock(reservation, fcntl.LOCK_EX)
223
+ maximum = int(os.environ.get('MAX_JOBS', '32'))
224
+ if sum(p.is_dir() for p in JOB_ROOT.iterdir()) >= maximum:
225
+ raise ValueError(f'任务数量已到上限 {maximum},请等待过期清理或由管理员清理空闲任务。')
226
+ free = shutil.disk_usage(DATA_ROOT).free
227
+ if free < int(os.environ.get('MIN_FREE_MB', '512')) * 1024**2:
228
+ raise ValueError('磁盘剩余空间不足,请先清理任务。')
229
+ job_id = secrets.token_hex(24)
230
+ path = JOB_ROOT / job_id
231
+ path.mkdir(mode=0o700)
232
+ try:
233
+ blend = stage_uploads(files, path / 'project', cfg.blend_file)
234
+ (path / 'frames').mkdir()
235
+ meta = {'job_id': job_id, 'status': 'prepared', 'config': cfg.model_dump(),
236
+ 'blend_relative': blend.relative_to(path / 'project').as_posix(),
237
+ 'created_at': time.time(), 'backend': backend, 'error': None}
238
+ _save(path, meta)
239
+ return job_id, _status(path)
240
+ except Exception:
241
+ shutil.rmtree(path, ignore_errors=True)
242
+ raise
243
+
244
+
245
+ def _task(path: Path, meta: dict, action: str, frames: list[int] | None = None) -> dict:
246
+ return {'action': action, 'project_root': str(path / 'project'),
247
+ 'blend_path': str(path / 'project' / meta['blend_relative']),
248
+ 'output_dir': str(path / 'frames'), 'result_path': str(path / f'{action}-result.json'),
249
+ 'frames': frames or [], 'config': meta['config']}
250
+
251
+
252
+ def inspect_job(job_id: str) -> dict:
253
+ """Inspect scene, cameras and resources before rendering.
254
+
255
+ Args:
256
+ job_id: Private job identifier returned by prepare_job.
257
+ """
258
+ path = _job(job_id)
259
+ ensure_blender()
260
+ with _lock(path):
261
+ meta = _load(path)
262
+ try:
263
+ result = run_task(_task(path, meta, 'inspect'), 120, path / 'inspect.log')
264
+ if not result.get('ok', False):
265
+ raise RuntimeError(result.get('error', '场景检查失败。'))
266
+ meta.update(inspection=result, status='ready', error=None)
267
+ _save(path, meta)
268
+ except Exception as exc:
269
+ meta.update(status='failed', error=str(exc)); _save(path, meta)
270
+ return _status(path)
271
+
272
+
273
+ def _duration(task: dict, log_path: str, cancel_path: str, seconds: int) -> int:
274
+ return seconds
275
+
276
+
277
+ def _allocated_render(task: dict, log_path: str, cancel_path: str, seconds: int) -> dict:
278
+ # 租约内启动外部 Blender,保留平台给出的 CUDA_VISIBLE_DEVICES。
279
+ # 给平台超时预留收尾时间;子进程 timeout 会终止整个进程组。
280
+ return run_task(task, max(5, seconds - 8), Path(log_path), Path(cancel_path) if cancel_path else None)
281
+
282
+
283
+ # 只有 ZeroGPU 环境才构造装饰器,本地 CPU/GPU 无需安装 PyTorch。
284
+ from spaces.config import Config as _SpacesConfig
285
+ _zero_render = spaces.GPU(duration=_duration)(_allocated_render) if _SpacesConfig.zero_gpu else None
286
+
287
+
288
+ def _execute(task: dict, path: Path, backend: str, cfg: RenderConfig, log: Path) -> dict:
289
+ if backend == 'zerogpu':
290
+ if _zero_render is None:
291
+ raise ValueError('ZeroGPU 装饰器未激活;请检查 Space 硬件配置并重启。')
292
+ return _zero_render(task, str(log), str(path / 'cancel.flag'), cfg.gpu_seconds)
293
+ return run_task(task, cfg.cpu_timeout, log, path / 'cancel.flag')
294
+
295
+
296
+ def render_chunk(job_id: str) -> dict:
297
+ """Render one bounded batch, preserving completed frames on failure.
298
+
299
+ Args:
300
+ job_id: Private job identifier returned by prepare_job.
301
+ """
302
+ path = _job(job_id)
303
+ ensure_blender() # 下载/安装绝不占用 GPU 租约。
304
+ with _lock(path):
305
+ meta = _load(path); cfg = _config(meta)
306
+ if (path / 'cancel.flag').exists():
307
+ raise ValueError('任务已暂停;先调用 resume_job 清除取消标记。')
308
+ done = set(_completed(path, cfg, verify=True))
309
+ for frame in cfg.frame_numbers():
310
+ if frame not in done:
311
+ _frame_path(path, frame, cfg).unlink(missing_ok=True)
312
+ pending = [f for f in cfg.frame_numbers() if f not in done]
313
+ if not pending:
314
+ meta.update(status='complete', error=None); _save(path, meta)
315
+ return _status(path)
316
+ batch = pending[:cfg.batch_size]
317
+ meta.update(status='rendering', error=None); _save(path, meta)
318
+ try:
319
+ result = _execute(_task(path, meta, 'render', batch), path, meta['backend'], cfg,
320
+ path / f'render-{batch[0]:06d}-{int(time.time())}.log')
321
+ meta['last_render'] = result
322
+ if not result.get('ok', False):
323
+ raise RuntimeError(result.get('error', 'Blender 渲染失败。'))
324
+ meta['status'] = 'complete' if len(_completed(path, cfg, verify=True)) == len(cfg.frame_numbers()) else 'partial'
325
+ except Exception as exc:
326
+ meta['status'] = 'cancelled' if (path / 'cancel.flag').exists() else 'partial' if _completed(path, cfg) else 'failed'
327
+ meta['error'] = str(exc)
328
+ _save(path, meta)
329
+ return _status(path)
330
+
331
+
332
+ def job_status(job_id: str) -> dict:
333
+ """Read progress without allocating a GPU.
334
+
335
+ Args:
336
+ job_id: Private job identifier returned by prepare_job.
337
+ """
338
+ return _status(_job(job_id))
339
+
340
+
341
+ def cancel_job(job_id: str) -> dict:
342
+ """Request cancellation of the active Blender process, retaining finished frames.
343
+
344
+ Args:
345
+ job_id: Private job identifier returned by prepare_job.
346
+ """
347
+ path = _job(job_id)
348
+ (path / 'cancel.flag').touch()
349
+ return {**_status(path), 'message': '已请求暂停;正在执行的 Blender 会在进程监控轮询时结束。'}
350
+
351
+
352
+ def resume_job(job_id: str) -> dict:
353
+ """Clear cancellation and validate saved frames; call render_chunk to continue.
354
+
355
+ Args:
356
+ job_id: Private job identifier returned by prepare_job.
357
+ """
358
+ path = _job(job_id)
359
+ with _lock(path):
360
+ (path / 'cancel.flag').unlink(missing_ok=True)
361
+ meta = _load(path); cfg = _config(meta)
362
+ done = _completed(path, cfg, verify=True)
363
+ for frame in cfg.frame_numbers():
364
+ if frame not in done:
365
+ _frame_path(path, frame, cfg).unlink(missing_ok=True)
366
+ meta.update(status='complete' if len(done) == len(cfg.frame_numbers()) else 'partial', error=None)
367
+ _save(path, meta)
368
+ return _status(path, verified_done=done)
369
+
370
+
371
+ def _export(path: Path, source: Path) -> str:
372
+ target = PUBLIC_ROOT / path.name
373
+ target.mkdir(parents=True, exist_ok=True)
374
+ dest = target / source.name
375
+ shutil.copy2(source, dest)
376
+ return str(dest)
377
+
378
+
379
+ def _encode_video(path: Path, cfg: RenderConfig) -> Path:
380
+ ffmpeg = shutil.which('ffmpeg')
381
+ if not ffmpeg:
382
+ raise RuntimeError('找不到 FFmpeg;请在 Space 的 packages.txt 安装 ffmpeg。')
383
+ # 使用顺序硬链接避免 frame_step > 1 时 ffmpeg 将间隔误认为缺帧。
384
+ sequence = path / 'video-sequence'
385
+ sequence.mkdir(exist_ok=True)
386
+ for index, frame in enumerate(cfg.frame_numbers()):
387
+ dst = sequence / f'{index:06d}.png'
388
+ if not dst.exists():
389
+ try:
390
+ os.link(_frame_path(path, frame, cfg), dst)
391
+ except OSError:
392
+ shutil.copy2(_frame_path(path, frame, cfg), dst)
393
+ output = path / 'animation.mp4'
394
+ temporary = path / 'animation.part.mp4'
395
+ # step=2 表示隔帧采样,播放帧率同步除2以维持时间尺度。
396
+ fps = f'{cfg.fps}/{cfg.frame_step}'
397
+ command = [ffmpeg, '-hide_banner', '-nostdin', '-y', '-framerate', fps,
398
+ '-i', str(sequence / '%06d.png'), '-c:v', 'libx264', '-preset', cfg.video_preset,
399
+ '-crf', str(cfg.video_crf), '-pix_fmt', 'yuv420p', '-movflags', '+faststart',
400
+ '-threads', os.environ.get('FFMPEG_THREADS', '4'), '-an', str(temporary)]
401
+ with (path / 'ffmpeg.log').open('w') as log:
402
+ try:
403
+ subprocess.run(command, stdout=log, stderr=subprocess.STDOUT, check=True, timeout=cfg.cpu_timeout)
404
+ os.replace(temporary, output)
405
+ except Exception as exc:
406
+ temporary.unlink(missing_ok=True)
407
+ raise RuntimeError('视频合成失败;帧图片仍保留,详情见 ffmpeg.log。') from exc
408
+ finally:
409
+ shutil.rmtree(sequence, ignore_errors=True)
410
+ return output
411
+
412
+
413
+ def finalize_job(job_id: str) -> tuple[dict, list[str], str | None, str | None]:
414
+ """Export completed frames, manifest and logs; encode MP4 when every video frame exists.
415
+
416
+ Args:
417
+ job_id: Private job identifier returned by prepare_job.
418
+ """
419
+ path = _job(job_id)
420
+ with _lock(path):
421
+ meta = _load(path); cfg = _config(meta)
422
+ done = _completed(path, cfg, verify=True)
423
+ summary = _status(path)
424
+ summary.update(completed_frames=done, completed_count=len(done),
425
+ remaining_frames=[f for f in cfg.frame_numbers() if f not in set(done)],
426
+ progress=round(len(done) / len(cfg.frame_numbers()), 4))
427
+ if len(done) < len(cfg.frame_numbers()) and summary['status'] == 'complete':
428
+ summary['status'] = 'partial'
429
+ files = []; image = video = None
430
+ if done and cfg.format == 'PNG':
431
+ image = _export(path, _frame_path(path, done[0], cfg))
432
+ files.append(image)
433
+ if cfg.mode == 'video' and len(done) == len(cfg.frame_numbers()):
434
+ try:
435
+ video = _export(path, _encode_video(path, cfg))
436
+ files.append(video)
437
+ except Exception as exc:
438
+ summary['export_error'] = str(exc)
439
+ summary['export_complete'] = len(done) == len(cfg.frame_numbers()) and not summary.get('export_error')
440
+ summary['video_playback_fps'] = cfg.fps / cfg.frame_step if cfg.mode == 'video' else None
441
+ _atomic_json(path / 'manifest.json', summary)
442
+ archive = path / 'render-output.zip'
443
+ temporary = path / 'render-output.part.zip'
444
+ with zipfile.ZipFile(temporary, 'w', compression=zipfile.ZIP_STORED) as z:
445
+ z.write(path / 'manifest.json', 'manifest.json')
446
+ for frame in done:
447
+ p = _frame_path(path, frame, cfg); z.write(p, f'frames/{p.name}')
448
+ for log in sorted(path.glob('*.log')):
449
+ z.write(log, 'logs/' + log.name)
450
+ for result in sorted(path.glob('*-result.json')):
451
+ z.write(result, 'reports/' + result.name)
452
+ if video:
453
+ z.write(path / 'animation.mp4', 'animation.mp4')
454
+ os.replace(temporary, archive)
455
+ files += [_export(path, archive), _export(path, path / 'manifest.json')]
456
+ return summary, files, image, video
457
+
458
+
459
+ def gpu_self_test() -> tuple[dict, list[str], str | None]:
460
+ """Run a real tiny Cycles render on the selected backend and return diagnostics."""
461
+ backend = _backend()
462
+ ensure_blender()
463
+ token = secrets.token_hex(24)
464
+ path = JOB_ROOT / ('probe-' + token)
465
+ path.mkdir()
466
+ cfg = RenderConfig(device='CPU' if backend == 'cpu' else 'AUTO')
467
+ task = {'action': 'probe', 'project_root': str(path), 'output_dir': str(path / 'frames'),
468
+ 'result_path': str(path / 'probe-result.json'), 'config': cfg.model_dump(), 'frames': [1]}
469
+ try:
470
+ result = _execute(task, path, backend, cfg, path / 'probe.log')
471
+ result['deployment_backend'] = backend
472
+ result['gpu_verified'] = bool(result.get('ok')) and backend != 'cpu'
473
+ except Exception as exc:
474
+ result = {'ok': False, 'gpu_verified': False, 'deployment_backend': backend,
475
+ 'error': str(exc), 'message': '该环境尚未通过 Blender GPU 渲染验证;请查看日志或改用普通 GPU Space。'}
476
+ result = _public_report(result)
477
+ _atomic_json(path / 'probe-result.json', result)
478
+ files = [_export(path, path / 'probe-result.json')]
479
+ if (path / 'probe.log').exists():
480
+ files.append(_export(path, path / 'probe.log'))
481
+ images = list((path / 'frames').glob('*.png'))
482
+ preview = _export(path, images[0]) if images else None
483
+ shutil.rmtree(path, ignore_errors=True)
484
+ return result, files, preview
test-artifacts/api-smoke-report.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "ok": true,
3
+ "backend": "CPU",
4
+ "blender": "5.2.2 LTS",
5
+ "api_upload_zip": true,
6
+ "api_upload_config": true,
7
+ "api_render_png": true,
8
+ "image_dimensions": [
9
+ 640,
10
+ 360
11
+ ],
12
+ "api_download_zip_verified": true,
13
+ "zero_gpu_tested": false,
14
+ "environment": {
15
+ "app_version": "1.0.0",
16
+ "versions": {
17
+ "gradio": "6.28.0",
18
+ "spaces": "0.51.3",
19
+ "torch": null
20
+ },
21
+ "zerogpu_environment": false,
22
+ "configured_backend": "cpu",
23
+ "ffmpeg_available": true,
24
+ "gpu_verified": false,
25
+ "message": "本接口不分配 GPU。请运行真实渲染自检;ZeroGPU 对 Blender 的兼容性尚需部署验证。",
26
+ "mcp_path": "/gradio_api/mcp/",
27
+ "job_ttl_hours": 24
28
+ }
29
+ }
test-artifacts/cpu-animation-preview.mp4 ADDED
Binary file (9.72 kB). View file
 
test-artifacts/cpu-render-preview.png ADDED

Git LFS Details

  • SHA256: 106a45a39d7d4bfc3c42b2366ccff21261afa6b4d62b4757396f6bf7b086dea6
  • Pointer size: 131 Bytes
  • Size of remote file: 311 kB
test-artifacts/exr-smoke-report.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "ok": true,
3
+ "backend": "CPU",
4
+ "format": "OPEN_EXR",
5
+ "depth": 16,
6
+ "size": 22396,
7
+ "magic_verified": true
8
+ }
test-artifacts/video-smoke-report.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "ok": true,
3
+ "backend": "CPU",
4
+ "frames": [
5
+ 1,
6
+ 3,
7
+ 5
8
+ ],
9
+ "batch_size": 2,
10
+ "complete_batches": 2,
11
+ "ffprobe": {
12
+ "programs": [],
13
+ "streams": [
14
+ {
15
+ "codec_name": "h264",
16
+ "width": 320,
17
+ "height": 180,
18
+ "r_frame_rate": "12/1",
19
+ "duration": "0.250000",
20
+ "nb_frames": "3"
21
+ }
22
+ ]
23
+ },
24
+ "zero_gpu_tested": false
25
+ }
tests/test_config_uploads.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """配置和资源导入安全边界;不需要 Blender 或 GPU。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import stat
8
+ import sys
9
+ import zipfile
10
+ from contextlib import nullcontext
11
+ from pathlib import Path
12
+
13
+ import pytest
14
+
15
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
16
+
17
+ from render_config import RenderConfig, json_schema, parse_config
18
+ from uploads import UploadError, stage_uploads
19
+
20
+
21
+ def make_zip(path: Path, entries: list[tuple[str | zipfile.ZipInfo, bytes]], compression=zipfile.ZIP_STORED) -> Path:
22
+ with zipfile.ZipFile(path, "w", compression=compression) as archive:
23
+ for name, contents in entries:
24
+ archive.writestr(name, contents)
25
+ return path
26
+
27
+
28
+ @pytest.mark.parametrize(
29
+ "payload",
30
+ [
31
+ {"width": "1920"}, {"width": True}, {"denoise": 1},
32
+ {"schema_version": True}, {"schema_version": 1.0}, {"schema_version": 2},
33
+ {"color_depth": "8"}, {"color_depth": 8.0},
34
+ {"width": 0}, {"height": 8193}, {"samples": 4097},
35
+ {"gpu_seconds": 601}, {"cpu_timeout": 9}, {"fps": 0},
36
+ {"unexpected": "do not silently ignore"},
37
+ {"scene": ""}, {"camera": "Camera\x00script"},
38
+ ],
39
+ )
40
+ def test_rejects_wrong_types_and_unknown_keys(payload):
41
+ with pytest.raises(ValueError):
42
+ parse_config(json.dumps(payload))
43
+
44
+
45
+ @pytest.mark.parametrize("path", ["../escape.blend", "/tmp/model.blend", "C:/model.blend", "a\\b.blend", "a/../b.blend", "a//b.blend", "a\x00.blend", "a:stream.blend"])
46
+ def test_config_rejects_unsafe_blend_path(path):
47
+ with pytest.raises(ValueError):
48
+ parse_config(json.dumps({"blend_file": path}))
49
+
50
+
51
+ @pytest.mark.parametrize("text", ['{"width": 1280,"width":1920}', '{"adaptive_threshold":NaN}', '{"adaptive_threshold":Infinity}', '[]', 'null', '{"width":', '{"scene":"' + "x" * 65536 + '"}'])
52
+ def test_json_syntax_and_size(text):
53
+ with pytest.raises(ValueError):
54
+ parse_config(text)
55
+
56
+
57
+ def test_defaults_schema_and_frame_sequence():
58
+ default = parse_config("{}")
59
+ assert default.frame_numbers() == [1]
60
+ assert (default.output_width, default.output_height) == (1280, 720)
61
+ config = parse_config('{"mode":"frames","frame_start":3,"frame_end":10,"frame_step":3}')
62
+ assert config.frame_numbers() == [3, 6, 9]
63
+ assert json_schema()["additionalProperties"] is False
64
+ assert json_schema()["properties"]["device"]["enum"] == ["AUTO", "CUDA", "OPTIX", "CPU"]
65
+
66
+
67
+ @pytest.mark.parametrize("payload", [
68
+ {"mode": "video", "transparent": True},
69
+ {"mode": "video", "width": 1279},
70
+ {"mode": "video", "width": 1282, "resolution_percentage": 50},
71
+ {"mode": "video", "format": "OPEN_EXR", "color_depth": 16},
72
+ {"format": "PNG", "color_depth": 32},
73
+ {"format": "OPEN_EXR", "color_depth": 8},
74
+ {"frame_start": 10, "frame_end": 9},
75
+ ])
76
+ def test_format_and_video_constraints(payload):
77
+ with pytest.raises(ValueError):
78
+ parse_config(json.dumps(payload))
79
+
80
+
81
+ def test_server_limits_count_rendered_frames_and_effective_pixels(monkeypatch):
82
+ monkeypatch.setenv("MAX_FRAMES", "3")
83
+ monkeypatch.setenv("MAX_PIXELS", "1000000")
84
+ assert len(RenderConfig(mode="frames", frame_start=1, frame_end=5, frame_step=2).frame_numbers()) == 3
85
+ assert RenderConfig(width=1920, height=1080, resolution_percentage=50).output_width == 960
86
+ with pytest.raises(ValueError, match="MAX_FRAMES"):
87
+ RenderConfig(mode="frames", frame_end=4)
88
+ with pytest.raises(ValueError, match="MAX_PIXELS"):
89
+ RenderConfig(width=1920, height=1080)
90
+
91
+
92
+ def test_blend_with_resource_zip_and_nested_zip(tmp_path):
93
+ blend = tmp_path / "scene.blend"
94
+ # 不限制 .blend 头:兼容 Blender 自身的压缩格式。
95
+ blend.write_bytes(b"compressed-placeholder")
96
+ resources = make_zip(tmp_path / "resources.zip", [
97
+ ("textures/albedo.png", b"png"), ("textures/", b""),
98
+ ("cache/nested.zip", b"not recursively expanded"),
99
+ ])
100
+ destination = tmp_path / "project"
101
+ selected = stage_uploads([str(blend), str(resources)], destination, None)
102
+ assert selected == destination / "scene.blend"
103
+ assert selected.is_absolute()
104
+ assert (destination / "textures/albedo.png").read_bytes() == b"png"
105
+ assert (destination / "cache/nested.zip").read_bytes() == b"not recursively expanded"
106
+
107
+
108
+ def test_multiple_blends_require_explicit_selection_and_preserve_paths(tmp_path):
109
+ archive = make_zip(tmp_path / "project.zip", [("scenes/a.blend", b"a"), ("scenes/b.blend", b"b")])
110
+ with pytest.raises(UploadError, match="多个"):
111
+ stage_uploads([str(archive)], tmp_path / "failed", None)
112
+ assert not (tmp_path / "failed").exists()
113
+ selected = stage_uploads([str(archive)], tmp_path / "valid", "scenes/b.blend")
114
+ assert selected.read_bytes() == b"b"
115
+
116
+
117
+ @pytest.mark.parametrize("malicious_name", [
118
+ "../escape", "/absolute", "C:/drive", "..\\escape", "folder/../../escape", "folder//escape",
119
+ "folder/file:stream", "folder/evil.py", "EVIL.PY", "folder/file.pyc", "folder/archive.tar.gz",
120
+ ])
121
+ def test_zip_rejects_unsafe_entries_without_partial_output(tmp_path, malicious_name):
122
+ archive = make_zip(tmp_path / "attack.zip", [("good.blend", b"blend"), (malicious_name, b"bad")])
123
+ destination = tmp_path / "project"
124
+ destination.mkdir()
125
+ with pytest.raises(UploadError):
126
+ stage_uploads([str(archive)], destination, None)
127
+ assert list(destination.iterdir()) == []
128
+ assert not list(tmp_path.glob(".project.upload-*"))
129
+ assert not (tmp_path / "escape").exists()
130
+
131
+
132
+ @pytest.mark.parametrize("names", [
133
+ ["scene.blend", "SCENE.blend"],
134
+ ["scene.blend", "scene.blend"],
135
+ ["scene.blend", "assets/x.png", "Assets/y.png"],
136
+ ["scene.blend", "assets", "assets/x.png"],
137
+ ])
138
+ def test_zip_rejects_collisions(tmp_path, names):
139
+ with pytest.warns(UserWarning) if names[0] == names[1] else nullcontext():
140
+ archive = make_zip(tmp_path / "conflict.zip", [(name, b"x") for name in names])
141
+ with pytest.raises(UploadError, match="冲突|重复"):
142
+ stage_uploads([str(archive)], tmp_path / "project", None)
143
+
144
+
145
+ def test_nul_zip_filename_is_not_silently_truncated(tmp_path):
146
+ archive = make_zip(tmp_path / "nul.zip", [("scene.blend", b"blend"), ("evilQname", b"bad")])
147
+ # zipfile.writestr 自身会截断 NUL,因此修改 local header 和 central directory。
148
+ archive.write_bytes(archive.read_bytes().replace(b"evilQname", b"evil\x00name"))
149
+ with pytest.raises(UploadError, match="NUL"):
150
+ stage_uploads([str(archive)], tmp_path / "project", None)
151
+
152
+
153
+ @pytest.mark.parametrize("kind", [stat.S_IFLNK, stat.S_IFIFO, stat.S_IFCHR, stat.S_IFSOCK])
154
+ def test_zip_special_files_are_rejected(tmp_path, kind):
155
+ entry = zipfile.ZipInfo("malicious")
156
+ entry.create_system = 3
157
+ entry.external_attr = (kind | 0o777) << 16
158
+ archive = make_zip(tmp_path / "special.zip", [("scene.blend", b"blend"), (entry, b"../outside")])
159
+ with pytest.raises(UploadError, match="符号链接|特殊"):
160
+ stage_uploads([str(archive)], tmp_path / "project", None)
161
+
162
+
163
+ def test_source_symlink_and_fifo_rejected(tmp_path):
164
+ source = tmp_path / "actual.blend"
165
+ source.write_bytes(b"blend")
166
+ link = tmp_path / "link.blend"
167
+ link.symlink_to(source)
168
+ with pytest.raises(UploadError, match="符号链接"):
169
+ stage_uploads([str(link)], tmp_path / "project", None)
170
+ if hasattr(os, "mkfifo"):
171
+ pipe = tmp_path / "pipe.blend"
172
+ os.mkfifo(pipe)
173
+ with pytest.raises(UploadError, match="普通文件"):
174
+ stage_uploads([str(pipe)], tmp_path / "project", None)
175
+
176
+
177
+ def test_zip_bomb_rejected_before_writing(tmp_path):
178
+ archive = make_zip(tmp_path / "bomb.zip", [("scene.blend", b"0" * 2_000_000)], compression=zipfile.ZIP_DEFLATED)
179
+ with pytest.raises(UploadError, match="压缩比"):
180
+ stage_uploads([str(archive)], tmp_path / "project", None)
181
+ assert not (tmp_path / "project").exists()
182
+
183
+
184
+ def test_extraction_size_and_entry_limits(tmp_path, monkeypatch):
185
+ archive = make_zip(tmp_path / "large.zip", [("scene.blend", b"s"), ("large.bin", b"x" * 1_048_576)])
186
+ monkeypatch.setenv("MAX_EXTRACT_MB", "1")
187
+ with pytest.raises(UploadError, match="MAX_EXTRACT_MB"):
188
+ stage_uploads([str(archive)], tmp_path / "project", None)
189
+ assert not (tmp_path / "project").exists()
190
+ monkeypatch.setenv("MAX_ARCHIVE_FILES", "1")
191
+ with pytest.raises(UploadError, match="MAX_ARCHIVE_FILES"):
192
+ stage_uploads([str(archive)], tmp_path / "project", None)
193
+
194
+
195
+ def test_upload_size_limit_and_script_rejection(tmp_path, monkeypatch):
196
+ source = tmp_path / "scene.blend"
197
+ source.write_bytes(b"x" * 1_048_577)
198
+ monkeypatch.setenv("MAX_UPLOAD_MB", "1")
199
+ with pytest.raises(UploadError, match="MAX_UPLOAD_MB"):
200
+ stage_uploads([str(source)], tmp_path / "project", None)
201
+ script = tmp_path / "helper.py"
202
+ script.write_text("raise RuntimeError('must never execute')")
203
+ with pytest.raises(UploadError, match="Python"):
204
+ stage_uploads([str(script)], tmp_path / "project", None)
205
+
206
+
207
+ def test_preexisting_data_is_never_removed_on_failure(tmp_path):
208
+ destination = tmp_path / "project"
209
+ destination.mkdir()
210
+ keep = destination / "keep.txt"
211
+ keep.write_text("important")
212
+ source = tmp_path / "scene.blend"
213
+ source.write_bytes(b"blend")
214
+ with pytest.raises(UploadError, match="覆盖"):
215
+ stage_uploads([str(source)], destination, None)
216
+ assert keep.read_text() == "important"
217
+
218
+
219
+ def test_separate_zip_and_file_cannot_overwrite_each_other(tmp_path):
220
+ source = tmp_path / "scene.blend"
221
+ source.write_bytes(b"original")
222
+ archive = make_zip(tmp_path / "resources.zip", [("scene.blend", b"replace")])
223
+ with pytest.raises(UploadError, match="冲突|重复"):
224
+ stage_uploads([str(source), str(archive)], tmp_path / "project", None)
225
+ assert source.read_bytes() == b"original"
tests/test_runtime.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """可复现的运行时边界测试,不联网,不需要 Blender 或 GPU。
2
+
3
+ 安装测试用本地压缩包替代下载;子进程测试真实启动临时 Python 可执行
4
+ 程序验证环境和进程树管理,不代表真实 Cycles / ZeroGPU 已通过测试。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import io
11
+ import json
12
+ import os
13
+ import sys
14
+ import tarfile
15
+ import threading
16
+ import time
17
+ from concurrent.futures import ThreadPoolExecutor
18
+ from pathlib import Path
19
+
20
+ import pytest
21
+
22
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
23
+ import blender_runtime as runtime
24
+
25
+
26
+ pytestmark = pytest.mark.skipif(sys.platform != "linux", reason="目标运行时是 Hugging Face Linux Space")
27
+ ARCHIVE_ROOT = "blender-5.2.2-linux-x64"
28
+ ARCHIVE_NAME = ARCHIVE_ROOT + ".tar.xz"
29
+
30
+
31
+ def make_archive(path: Path, entries: list[tuple[str, bytes | None, str | None]]) -> Path:
32
+ """None 内容表示目录;第三列非空表示符号链接。"""
33
+ with tarfile.open(path, "w:xz") as archive:
34
+ for name, data, link in entries:
35
+ member = tarfile.TarInfo(name)
36
+ if link is not None:
37
+ member.type = tarfile.SYMTYPE
38
+ member.linkname = link
39
+ archive.addfile(member)
40
+ elif data is None:
41
+ member.type = tarfile.DIRTYPE
42
+ member.mode = 0o755
43
+ archive.addfile(member)
44
+ else:
45
+ member.mode = 0o755
46
+ member.size = len(data)
47
+ archive.addfile(member, io.BytesIO(data))
48
+ return path
49
+
50
+
51
+ @pytest.fixture
52
+ def installation(monkeypatch, tmp_path):
53
+ archive = make_archive(tmp_path / ARCHIVE_NAME, [
54
+ (ARCHIVE_ROOT, None, None),
55
+ (ARCHIVE_ROOT + "/blender", b"#!/bin/sh\nexit 0\n", None),
56
+ ])
57
+ checksum = tmp_path / "checksums.sha256"
58
+ digest = hashlib.sha256(archive.read_bytes()).hexdigest()
59
+ checksum.write_text(f"{digest} {ARCHIVE_NAME}\n", encoding="utf-8")
60
+ cache = tmp_path / "cache"
61
+ monkeypatch.delenv("BLENDER_BIN", raising=False)
62
+ monkeypatch.setenv("BLENDER_VERSION", "5.2.2")
63
+ monkeypatch.setenv("BLENDER_CACHE", str(cache))
64
+ monkeypatch.setattr(runtime.shutil, "which", lambda _: None)
65
+ calls: list[str] = []
66
+
67
+ def local_download(url: str, destination: Path, maximum: int) -> None:
68
+ calls.append(url)
69
+ content = checksum.read_bytes() if url.endswith(".sha256") else archive.read_bytes()
70
+ assert len(content) < maximum
71
+ destination.write_bytes(content)
72
+
73
+ monkeypatch.setattr(runtime, "_download", local_download)
74
+ return archive, checksum, cache, calls, digest
75
+
76
+
77
+ def test_download_checksum_is_exact_and_mismatch_stops_installation(installation):
78
+ archive, checksum, cache, calls, digest = installation
79
+ assert runtime._expected_digest(checksum, ARCHIVE_NAME) == digest
80
+ with pytest.raises(RuntimeError, match="唯一匹配"):
81
+ runtime._expected_digest(checksum, "wrong-name.tar.xz")
82
+ # 模拟下载包损坏:官方清单保持不变,下载内容被更改。
83
+ archive.write_bytes(archive.read_bytes() + b"corrupted-download")
84
+ with pytest.raises(RuntimeError, match="SHA-256 校验失败"):
85
+ runtime.ensure_blender()
86
+ assert len(calls) == 2
87
+ assert not (cache / "blender-5.2.2" / "blender").exists()
88
+
89
+
90
+ def test_tar_rejects_traversal_and_absolute_paths(tmp_path):
91
+ for index, name in enumerate([
92
+ ARCHIVE_ROOT + "/../../outside", "/tmp/outside", ARCHIVE_ROOT + "/../outside",
93
+ ]):
94
+ archive = make_archive(tmp_path / f"bad-{index}.tar.xz", [(name, b"unsafe", None)])
95
+ with pytest.raises(RuntimeError, match="不安全路径"):
96
+ runtime._safe_extract(archive, tmp_path / "output", ARCHIVE_ROOT)
97
+ assert not (tmp_path / "outside").exists()
98
+
99
+
100
+ def test_tar_accepts_internal_symlinks_and_rejects_escaping_links(tmp_path):
101
+ archive = make_archive(tmp_path / "good.tar.xz", [
102
+ (ARCHIVE_ROOT, None, None),
103
+ (ARCHIVE_ROOT + "/blender", b"executable", None),
104
+ (ARCHIVE_ROOT + "/linked", None, "blender"),
105
+ ])
106
+ extracted = runtime._safe_extract(archive, tmp_path / "good", ARCHIVE_ROOT)
107
+ assert (extracted / "linked").is_symlink()
108
+ assert (extracted / "linked").read_bytes() == b"executable"
109
+ bad = make_archive(tmp_path / "escape.tar.xz", [
110
+ (ARCHIVE_ROOT + "/linked", None, "../../outside"),
111
+ ])
112
+ with pytest.raises(RuntimeError, match="目录之外"):
113
+ runtime._safe_extract(bad, tmp_path / "bad", ARCHIVE_ROOT)
114
+
115
+
116
+ def test_concurrent_installation_downloads_each_file_once(installation):
117
+ _, _, cache, calls, _ = installation
118
+ # Future.result() 会把线程中的异常带回测试主线程,避免漏报。
119
+ with ThreadPoolExecutor(max_workers=5) as executor:
120
+ futures = [executor.submit(runtime.ensure_blender) for _ in range(5)]
121
+ binaries = [future.result(timeout=10) for future in futures]
122
+ assert len(set(binaries)) == 1
123
+ assert binaries[0] == cache / "blender-5.2.2" / "blender"
124
+ assert os.access(binaries[0], os.X_OK)
125
+ assert len(calls) == 2
126
+ assert sum(url.endswith(".sha256") for url in calls) == 1
127
+ assert sum(url.endswith(".tar.xz") for url in calls) == 1
128
+ assert runtime.ensure_blender() == binaries[0]
129
+ assert len(calls) == 2
130
+
131
+
132
+ @pytest.fixture
133
+ def subprocess_runtime(monkeypatch, tmp_path):
134
+ fake = tmp_path / "fake-blender"
135
+ fake.write_text("#!" + sys.executable + "\n" + r'''
136
+ import json, os, subprocess, sys, time
137
+ from pathlib import Path
138
+ task = json.loads(Path(sys.argv[-1]).read_text(encoding="utf-8"))
139
+ if task.get("delay"):
140
+ child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])
141
+ Path(task["child_pid"]).write_text(str(child.pid), encoding="utf-8")
142
+ time.sleep(60)
143
+ else:
144
+ Path(task["result_path"]).write_text(json.dumps({
145
+ "ok": True,
146
+ "secret_present": "HF_TOKEN" in os.environ or "AWS_SECRET_ACCESS_KEY" in os.environ,
147
+ "cuda": os.environ.get("CUDA_VISIBLE_DEVICES"),
148
+ "threads": os.environ.get("OMP_NUM_THREADS"),
149
+ "autoexec_disabled": "--disable-autoexec" in sys.argv,
150
+ }), encoding="utf-8")
151
+ ''', encoding="utf-8")
152
+ fake.chmod(0o755)
153
+ monkeypatch.setattr(runtime, "_WORKER", fake)
154
+ monkeypatch.setattr(runtime, "ensure_blender", lambda: fake)
155
+ monkeypatch.setenv("BLENDER_THREADS", "4")
156
+ return tmp_path
157
+
158
+
159
+ def test_real_subprocess_scrubs_secrets_and_preserves_cuda(subprocess_runtime, monkeypatch):
160
+ root = subprocess_runtime
161
+ monkeypatch.setenv("HF_TOKEN", "test-only-never-log")
162
+ monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "test-only-never-log")
163
+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "test-gpu-uuid")
164
+ result = runtime.run_task({"result_path": str(root / "result.json")}, 5, root / "render.log")
165
+ assert result == {
166
+ "ok": True, "secret_present": False, "cuda": "test-gpu-uuid",
167
+ "threads": "4", "autoexec_disabled": True,
168
+ }
169
+ assert not list(root.glob(".render-task-*.json"))
170
+
171
+
172
+ def assert_descendant_stopped(pid_file: Path) -> None:
173
+ assert pid_file.exists(), "测试替身未成功创建子进程,无法验证进程树终止。"
174
+ pid = int(pid_file.read_text(encoding="utf-8"))
175
+ stat = Path(f"/proc/{pid}/stat")
176
+ # 被结束的孤儿子进程可能暂时等待容器 init 回收;Z 状态已不再执行。
177
+ deadline = time.monotonic() + 2
178
+ while stat.exists() and time.monotonic() < deadline:
179
+ try:
180
+ if stat.read_text().rsplit(")", 1)[1].split()[0] == "Z":
181
+ return
182
+ except FileNotFoundError:
183
+ return
184
+ time.sleep(0.02)
185
+ assert not stat.exists(), f"后代进程 {pid} 仍在运行。"
186
+
187
+
188
+ def test_timeout_terminates_real_descendant_process(subprocess_runtime):
189
+ root = subprocess_runtime
190
+ pid_file = root / "timeout-child.pid"
191
+ task = {"result_path": str(root / "timeout.json"), "delay": True, "child_pid": str(pid_file)}
192
+ with pytest.raises(TimeoutError, match="超过"):
193
+ runtime.run_task(task, 1, root / "timeout.log")
194
+ assert_descendant_stopped(pid_file)
195
+ assert not list(root.glob(".render-task-*.json"))
196
+
197
+
198
+ def test_cancellation_terminates_real_descendant_process(subprocess_runtime):
199
+ root = subprocess_runtime
200
+ pid_file = root / "cancel-child.pid"
201
+ cancel = root / "cancel.flag"
202
+ task = {"result_path": str(root / "cancel.json"), "delay": True, "child_pid": str(pid_file)}
203
+
204
+ def cancel_when_child_started():
205
+ deadline = time.monotonic() + 5
206
+ while not pid_file.exists() and time.monotonic() < deadline:
207
+ time.sleep(0.02)
208
+ cancel.touch()
209
+
210
+ thread = threading.Thread(target=cancel_when_child_started, daemon=True)
211
+ thread.start()
212
+ try:
213
+ with pytest.raises(RuntimeError, match="取消"):
214
+ runtime.run_task(task, 8, root / "cancel.log", cancel)
215
+ finally:
216
+ thread.join(timeout=6)
217
+ assert_descendant_stopped(pid_file)
218
+ assert not list(root.glob(".render-task-*.json"))
tests/test_service.py ADDED
@@ -0,0 +1,377 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """任务状态/隔离回归测试,以及真实 FFmpeg 合成测试。
2
+
3
+ Blender 调用在这里由测试替身替代;这些测试不表示 Blender 或 ZeroGPU
4
+ 已通过实测。最后的视频测试实际运行 FFmpeg/FFprobe 并读取生成的 MP4。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import importlib
10
+ import json
11
+ import shutil
12
+ import subprocess
13
+ import sys
14
+ import threading
15
+ import time
16
+ import zipfile
17
+ from pathlib import Path
18
+
19
+ import pytest
20
+ from PIL import Image
21
+
22
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
23
+
24
+
25
+ @pytest.fixture
26
+ def service(monkeypatch, tmp_path):
27
+ monkeypatch.setenv("RENDER_DATA_DIR", str(tmp_path / "runtime"))
28
+ monkeypatch.setenv("RENDER_BACKEND", "cpu")
29
+ monkeypatch.setenv("MIN_FREE_MB", "1")
30
+ module = importlib.import_module("service")
31
+ data = tmp_path / "runtime"
32
+ for attribute, value in (("DATA_ROOT", data), ("JOB_ROOT", data / "jobs"), ("PUBLIC_ROOT", data / "public")):
33
+ value.mkdir(parents=True, exist_ok=True)
34
+ monkeypatch.setattr(module, attribute, value)
35
+ monkeypatch.setattr(module, "_LOCKS", {})
36
+ monkeypatch.setattr(module, "ensure_blender", lambda: Path("/test/fake-blender"))
37
+ monkeypatch.setattr(module, "_backend", lambda: "cpu")
38
+ return module
39
+
40
+
41
+ @pytest.fixture
42
+ def make_job(service, tmp_path):
43
+ def create(**config):
44
+ source = tmp_path / "scene.blend"
45
+ source.write_bytes(b"TEST ONLY: Blender is not invoked by these unit tests")
46
+ settings = {"mode": "frames", "width": 32, "height": 24,
47
+ "samples": 1, "frame_start": 1, "frame_end": 5, "batch_size": 2}
48
+ settings.update(config)
49
+ return service.prepare_job([str(source)], json.dumps(settings))
50
+ return create
51
+
52
+
53
+ def write_frames(task: dict, frames: list[int] | None = None) -> None:
54
+ """使用真实 PNG 文件模拟 Blender 已原子提交的帧输出。"""
55
+ from render_config import RenderConfig
56
+ config = RenderConfig.model_validate(task["config"])
57
+ output = Path(task["output_dir"])
58
+ output.mkdir(parents=True, exist_ok=True)
59
+ for frame in frames if frames is not None else task["frames"]:
60
+ file = output / f"frame_{frame:06d}.png"
61
+ Image.new("RGB", (config.output_width, config.output_height),
62
+ (frame * 17 % 256, frame * 31 % 256, frame * 47 % 256)).save(file)
63
+
64
+
65
+ @pytest.fixture
66
+ def successful_worker(service, monkeypatch):
67
+ calls = []
68
+
69
+ def run(task, timeout, log_path, cancel_path=None):
70
+ calls.append(task)
71
+ Path(log_path).write_text("Unit-test worker; no GPU or Blender execution.\n")
72
+ if task["action"] == "inspect":
73
+ return {"ok": True, "scenes": ["Scene"], "cameras": ["Camera"]}
74
+ write_frames(task)
75
+ return {"ok": True, "backend": "CPU", "frames": task["frames"]}
76
+
77
+ monkeypatch.setattr(service, "run_task", run)
78
+ return calls
79
+
80
+
81
+ def test_prepare_inspect_render_in_batches_and_idempotent_complete(service, make_job, successful_worker):
82
+ job, status = make_job()
83
+ assert len(job) == 48 and status["status"] == "prepared"
84
+ assert status["completed_count"] == 0 and status["total_frames"] == 5
85
+ assert status["config"]["device"] == "CPU"
86
+ assert service.inspect_job(job)["status"] == "ready"
87
+ first = service.render_chunk(job)
88
+ assert first["status"] == "partial"
89
+ assert first["completed_frames"] == [1, 2]
90
+ assert first["remaining_frames"] == [3, 4, 5]
91
+ assert first["progress"] == 0.4
92
+ service.render_chunk(job)
93
+ final = service.render_chunk(job)
94
+ assert final["status"] == "complete" and final["progress"] == 1
95
+ assert [call["frames"] for call in successful_worker if call["action"] == "render"] == [[1, 2], [3, 4], [5]]
96
+ count = len(successful_worker)
97
+ assert service.render_chunk(job)["status"] == "complete"
98
+ assert len(successful_worker) == count
99
+
100
+
101
+ def test_prepare_config_file_takes_precedence_and_accepts_bom(service, tmp_path):
102
+ blend = tmp_path / "scene.blend"
103
+ blend.write_bytes(b"test")
104
+ config_file = tmp_path / "render.json"
105
+ config_file.write_text('{"width":64,"height":32}', encoding="utf-8-sig")
106
+ _, status = service.prepare_job([str(blend)], "invalid unused text", str(config_file))
107
+ assert status["config"]["width"] == 64
108
+ config_file.write_text("x" * 65537)
109
+ before = set(service.JOB_ROOT.iterdir())
110
+ with pytest.raises(ValueError, match="64"):
111
+ service.prepare_job([str(blend)], "{}", str(config_file))
112
+ assert set(service.JOB_ROOT.iterdir()) == before
113
+
114
+
115
+ def test_prepare_failure_leaves_no_job_and_rejects_capacity(service, tmp_path, make_job, monkeypatch):
116
+ script = tmp_path / "bad.py"
117
+ script.write_text("raise RuntimeError('never execute')")
118
+ with pytest.raises(ValueError):
119
+ service.prepare_job([str(script)], "{}")
120
+ assert list(service.JOB_ROOT.iterdir()) == []
121
+ monkeypatch.setenv("MAX_JOBS", "1")
122
+ make_job()
123
+ with pytest.raises(ValueError, match="上限"):
124
+ make_job()
125
+ assert len(list(service.JOB_ROOT.iterdir())) == 1
126
+
127
+
128
+ @pytest.mark.parametrize("job_id", ["../secret", "/tmp/file", "", "x" * 48, "0" * 48])
129
+ def test_private_job_ids_cannot_be_paths_or_unknown_jobs(service, job_id):
130
+ with pytest.raises(ValueError):
131
+ service.job_status(job_id)
132
+
133
+
134
+ def test_job_files_and_cancellation_are_isolated(service, make_job, successful_worker):
135
+ first, _ = make_job()
136
+ second, _ = make_job()
137
+ assert first != second
138
+ service.render_chunk(first)
139
+ assert service.job_status(second)["completed_frames"] == []
140
+ service.cancel_job(first)
141
+ service.render_chunk(second)
142
+ assert not (service.JOB_ROOT / second / "cancel.flag").exists()
143
+ summary, files, image, video = service.finalize_job(second)
144
+ assert image and not video
145
+ assert all(Path(file).parent == service.PUBLIC_ROOT / second for file in files)
146
+ assert summary["job_id"] == second
147
+ archive = next(Path(file) for file in files if file.endswith(".zip"))
148
+ with zipfile.ZipFile(archive) as data:
149
+ names = data.namelist()
150
+ assert "manifest.json" in names and "frames/frame_000001.png" in names
151
+ assert not any(name.endswith(".blend") or name.startswith("project/") for name in names)
152
+ assert json.loads(data.read("manifest.json"))["job_id"] == second
153
+
154
+
155
+ def test_partial_failure_retains_committed_frame_and_retries_only_missing(service, make_job, monkeypatch):
156
+ job, _ = make_job(batch_size=3)
157
+ seen = []
158
+
159
+ def failing_once(task, timeout, log_path, cancel_path=None):
160
+ seen.append(task["frames"])
161
+ if len(seen) == 1:
162
+ write_frames(task, task["frames"][:1])
163
+ raise TimeoutError("Synthetic worker timeout after one committed frame")
164
+ write_frames(task)
165
+ return {"ok": True}
166
+
167
+ monkeypatch.setattr(service, "run_task", failing_once)
168
+ partial = service.render_chunk(job)
169
+ assert partial["status"] == "partial" and partial["completed_frames"] == [1]
170
+ assert "Synthetic worker timeout" in partial["error"]
171
+ next_status = service.render_chunk(job)
172
+ assert seen == [[1, 2, 3], [2, 3, 4]]
173
+ assert next_status["error"] is None
174
+ assert service.render_chunk(job)["status"] == "complete"
175
+
176
+
177
+ def test_worker_error_result_is_failed_and_not_success(service, make_job, monkeypatch):
178
+ job, _ = make_job()
179
+ monkeypatch.setattr(service, "run_task", lambda *a, **k: {"ok": False, "error": "Synthetic render failure"})
180
+ status = service.render_chunk(job)
181
+ assert status["status"] == "failed"
182
+ assert status["completed_frames"] == [] and "Synthetic render failure" in status["error"]
183
+
184
+
185
+ def test_inspection_error_result_does_not_mark_scene_ready(service, make_job, monkeypatch):
186
+ job, _ = make_job()
187
+ monkeypatch.setattr(service, "run_task", lambda *a, **k: {"ok": False, "error": "Synthetic missing scene"})
188
+ status = service.inspect_job(job)
189
+ assert status["status"] == "failed"
190
+ assert "Synthetic missing scene" in status["error"]
191
+
192
+
193
+ def test_idle_cancel_is_visible_and_resume_retains_frames(service, make_job, successful_worker):
194
+ job, _ = make_job()
195
+ service.render_chunk(job)
196
+ paused = service.cancel_job(job)
197
+ assert paused["status"] == "cancelled"
198
+ with pytest.raises(ValueError, match="暂停|取消"):
199
+ service.render_chunk(job)
200
+ resumed = service.resume_job(job)
201
+ assert resumed["completed_frames"] == [1, 2]
202
+ assert not (service.JOB_ROOT / job / "cancel.flag").exists()
203
+ service.render_chunk(job)
204
+ assert [call["frames"] for call in successful_worker] == [[1, 2], [3, 4]]
205
+
206
+
207
+ def test_active_cancel_and_lock_protect_running_batch(service, make_job, monkeypatch):
208
+ job, _ = make_job()
209
+ started, release = threading.Event(), threading.Event()
210
+ response = {}
211
+
212
+ def waiting_worker(task, timeout, log_path, cancel_path=None):
213
+ write_frames(task, task["frames"][:1])
214
+ started.set()
215
+ if not release.wait(5):
216
+ raise TimeoutError("Test synchronization timed out")
217
+ assert Path(cancel_path).exists()
218
+ raise RuntimeError("Synthetic cancellation observed")
219
+
220
+ monkeypatch.setattr(service, "run_task", waiting_worker)
221
+
222
+ def render():
223
+ try:
224
+ response["status"] = service.render_chunk(job)
225
+ except BaseException as exc:
226
+ response["exception"] = exc
227
+
228
+ thread = threading.Thread(target=render, daemon=True)
229
+ thread.start()
230
+ try:
231
+ assert started.wait(5)
232
+ assert service.job_status(job)["status"] == "rendering"
233
+ with pytest.raises(ValueError, match="执行"):
234
+ service.render_chunk(job)
235
+ with pytest.raises(ValueError, match="执行"):
236
+ service.resume_job(job)
237
+ assert service.cancel_job(job)["status"] == "cancelling"
238
+ finally:
239
+ release.set()
240
+ thread.join(timeout=5)
241
+ assert not thread.is_alive()
242
+ assert "exception" not in response
243
+ assert response["status"]["status"] == "cancelled"
244
+ assert response["status"]["completed_frames"] == [1]
245
+
246
+
247
+ def test_corrupt_and_wrong_size_frames_are_rerendered(service, make_job, successful_worker):
248
+ job, _ = make_job(batch_size=5)
249
+ frames = service.JOB_ROOT / job / "frames"
250
+ (frames / "frame_000001.png").write_bytes(b"corrupt PNG" * 30)
251
+ Image.new("RGB", (16, 16)).save(frames / "frame_000002.png")
252
+ (frames / "frame_000003.part.png").write_bytes(b"unfinished" * 30)
253
+ status = service.render_chunk(job)
254
+ assert status["status"] == "complete"
255
+ assert successful_worker[0]["frames"] == [1, 2, 3, 4, 5]
256
+
257
+
258
+ def test_final_manifest_uses_verified_progress_consistently(service, make_job):
259
+ job, _ = make_job()
260
+ path = service.JOB_ROOT / job
261
+ config = service._load(path)
262
+ write_frames(service._task(path, config, "render", [1]))
263
+ (path / "frames/frame_000002.png").write_bytes(b"corrupt PNG" * 30)
264
+ summary, files, _, _ = service.finalize_job(job)
265
+ assert summary["completed_frames"] == [1]
266
+ assert summary["completed_count"] == 1
267
+ assert summary["remaining_frames"] == [2, 3, 4, 5]
268
+ assert summary["progress"] == 0.2
269
+ assert summary["export_complete"] is False
270
+
271
+
272
+ def test_resume_reports_corrupt_frames_as_pending(service, make_job):
273
+ job, _ = make_job()
274
+ path = service.JOB_ROOT / job
275
+ meta = service._load(path)
276
+ write_frames(service._task(path, meta, "render", [1]))
277
+ (path / "frames/frame_000002.png").write_bytes(b"corrupt PNG" * 30)
278
+ service.cancel_job(job)
279
+ summary = service.resume_job(job)
280
+ assert summary["completed_frames"] == [1]
281
+ assert summary["completed_count"] == 1
282
+ assert summary["remaining_frames"] == [2, 3, 4, 5]
283
+ assert summary["progress"] == 0.2
284
+
285
+
286
+ def test_file_lock_open_failure_does_not_permanently_lock_job(service, make_job, monkeypatch):
287
+ job, _ = make_job()
288
+ path = service.JOB_ROOT / job
289
+ original_open = Path.open
290
+ state = {"fail": True}
291
+
292
+ def fail_lock_once(self, *args, **kwargs):
293
+ if self.name == ".lock" and state["fail"]:
294
+ state["fail"] = False
295
+ raise OSError("Synthetic filesystem failure")
296
+ return original_open(self, *args, **kwargs)
297
+
298
+ monkeypatch.setattr(Path, "open", fail_lock_once)
299
+ with pytest.raises(OSError, match="Synthetic"):
300
+ with service._lock(path):
301
+ pass
302
+ with service._lock(path):
303
+ pass
304
+
305
+
306
+ def test_expiration_does_not_delete_active_locked_job(service, make_job, monkeypatch):
307
+ monkeypatch.setenv("JOB_TTL_HOURS", "1")
308
+ old_job, _ = make_job()
309
+ active_job, _ = make_job()
310
+ for job in (old_job, active_job):
311
+ path = service.JOB_ROOT / job
312
+ meta = service._load(path)
313
+ meta["updated_at"] = time.time() - 7200
314
+ service._atomic_json(path / "job.json", meta)
315
+ (service.PUBLIC_ROOT / job).mkdir()
316
+ with service._lock(service.JOB_ROOT / active_job):
317
+ service._cleanup()
318
+ assert (service.JOB_ROOT / active_job).exists()
319
+ assert (service.PUBLIC_ROOT / active_job).exists()
320
+ assert not (service.JOB_ROOT / old_job).exists()
321
+ assert not (service.PUBLIC_ROOT / old_job).exists()
322
+
323
+
324
+ @pytest.mark.skipif(not shutil.which("ffmpeg") or not shutil.which("ffprobe"), reason="真实视频验证需要 FFmpeg 和 FFprobe")
325
+ def test_real_ffmpeg_video_preserves_frame_step_timing_and_scaled_dimensions(service, make_job, successful_worker):
326
+ job, _ = make_job(mode="video", width=64, height=48, resolution_percentage=50,
327
+ frame_start=1, frame_end=9, frame_step=2, fps=24, batch_size=5)
328
+ before, _, _, video = service.finalize_job(job)
329
+ assert video is None and before["export_complete"] is False
330
+ assert service.render_chunk(job)["status"] == "complete"
331
+ summary, files, image, video = service.finalize_job(job)
332
+ assert summary["export_complete"] is True and image and video
333
+ assert summary["video_playback_fps"] == 12
334
+ result = subprocess.run(
335
+ [shutil.which("ffprobe"), "-v", "error", "-select_streams", "v:0", "-show_entries",
336
+ "stream=codec_name,width,height,nb_frames,avg_frame_rate,duration", "-of", "json", video],
337
+ check=True, capture_output=True, text=True, timeout=30,
338
+ )
339
+ stream = json.loads(result.stdout)["streams"][0]
340
+ assert stream["codec_name"] == "h264"
341
+ assert (stream["width"], stream["height"]) == (32, 24)
342
+ assert int(stream["nb_frames"]) == 5
343
+ numerator, denominator = map(int, stream["avg_frame_rate"].split("/"))
344
+ assert numerator / denominator == pytest.approx(12)
345
+ assert float(stream["duration"]) == pytest.approx(5 / 12, abs=0.02)
346
+ assert not (service.JOB_ROOT / job / "video-sequence").exists()
347
+ archive = next(file for file in files if file.endswith(".zip"))
348
+ with zipfile.ZipFile(archive) as exported:
349
+ assert "animation.mp4" in exported.namelist()
350
+ assert len([name for name in exported.namelist() if name.startswith("frames/")]) == 5
351
+
352
+
353
+ def test_video_encoder_failure_keeps_frame_export(service, make_job, successful_worker, monkeypatch):
354
+ job, _ = make_job(mode="video", frame_end=1)
355
+ service.render_chunk(job)
356
+
357
+ def unavailable(path, cfg):
358
+ raise RuntimeError("Synthetic FFmpeg failure")
359
+
360
+ monkeypatch.setattr(service, "_encode_video", unavailable)
361
+ summary, files, image, video = service.finalize_job(job)
362
+ assert "Synthetic FFmpeg failure" in summary["export_error"]
363
+ assert summary["export_complete"] is False and image and video is None
364
+ assert any(file.endswith(".zip") for file in files)
365
+
366
+
367
+ def test_private_frame_paths_do_not_become_gradio_downloads(service):
368
+ """真实回归:Client 会自动下载 JSON 内的 path,导致私有帧路径 403。"""
369
+ from gradio_client import utils
370
+ report = service._public_report({
371
+ 'frames': [{'frame': 1, 'path': '/private/job/frames/frame_000001.png'}],
372
+ 'ok': True,
373
+ })
374
+ found = []
375
+ utils.traverse(report, lambda obj: found.append(obj) or obj, utils.is_file_obj)
376
+ assert not found
377
+ assert report['frames'][0]['filename'] == 'frame_000001.png'
uploads.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """安全复制 Blender 项目及资源 ZIP;任何上传内容都不会被执行。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import shutil
7
+ import stat
8
+ import tempfile
9
+ import zipfile
10
+ from pathlib import Path
11
+ from typing import BinaryIO
12
+
13
+ from render_config import positive_env_int, safe_relative_path
14
+
15
+
16
+ _CHUNK_SIZE = 1024 * 1024
17
+ _SCRIPT_SUFFIXES = {".py", ".pyc", ".pyo", ".pyw"}
18
+ _TAR_SUFFIXES = (".tar", ".tar.gz", ".tar.bz2", ".tar.xz", ".tgz", ".tbz", ".tbz2", ".txz")
19
+
20
+
21
+ class UploadError(ValueError):
22
+ """可直接向调用者展示的上传错误。"""
23
+
24
+
25
+ class _Staging:
26
+ def __init__(self, root: Path, byte_limit: int, file_limit: int):
27
+ self.root = root
28
+ self.byte_limit = byte_limit
29
+ self.file_limit = file_limit
30
+ self.bytes_written = 0
31
+ self.entry_count = 0
32
+ # 文件和文件夹共用名称空间,大小写不同也视为冲突。
33
+ self.entries: dict[str, tuple[str, bool, bool]] = {}
34
+ self.blends: list[str] = []
35
+
36
+ def register(self, name: str, directory: bool = False) -> Path:
37
+ self.entry_count += 1
38
+ if self.entry_count > self.file_limit:
39
+ raise UploadError("上传条目数超过服务端 MAX_ARCHIVE_FILES 限制。")
40
+ try:
41
+ safe_relative_path(name)
42
+ except ValueError as exc:
43
+ raise UploadError(f"不安全的资源路径 {name!r}:{exc}") from exc
44
+ if not directory and Path(name).suffix.casefold() in _SCRIPT_SUFFIXES:
45
+ raise UploadError("不允许上传或解压 Python 脚本文件。")
46
+ if not directory and name.casefold().endswith(_TAR_SUFFIXES):
47
+ raise UploadError("不支持 TAR 压缩包,请使用 ZIP。")
48
+ components = name.split("/")
49
+ for index in range(1, len(components)):
50
+ parent = "/".join(components[:index])
51
+ folded = parent.casefold()
52
+ existing = self.entries.get(folded)
53
+ if existing and (existing[0] != parent or not existing[1]):
54
+ raise UploadError(f"路径存在大小写或文件/文件夹冲突:{parent}")
55
+ if not existing:
56
+ self.entries[folded] = (parent, True, False)
57
+ folded = name.casefold()
58
+ existing = self.entries.get(folded)
59
+ # 已创建的隐式父文件夹允许一次显式 ZIP 目录条目。
60
+ if existing and not (
61
+ directory and existing == (name, True, False)
62
+ ):
63
+ raise UploadError(f"上传包含重复或冲突路径:{name}")
64
+ self.entries[folded] = (name, directory, True)
65
+ target = self.root.joinpath(*components)
66
+ if directory:
67
+ target.mkdir(parents=True, exist_ok=True)
68
+ else:
69
+ target.parent.mkdir(parents=True, exist_ok=True)
70
+ if name.casefold().endswith(".blend"):
71
+ self.blends.append(name)
72
+ return target
73
+
74
+ def copy_stream(self, source: BinaryIO, target: Path, declared_size: int) -> None:
75
+ if declared_size < 0 or self.bytes_written + declared_size > self.byte_limit:
76
+ raise UploadError("解压/暂存总大小超过服务端 MAX_EXTRACT_MB 限制。")
77
+ actual = 0
78
+ with target.open("xb") as output:
79
+ while chunk := source.read(_CHUNK_SIZE):
80
+ actual += len(chunk)
81
+ self.bytes_written += len(chunk)
82
+ if self.bytes_written > self.byte_limit or actual > declared_size:
83
+ raise UploadError("文件实际大小超过声明值或服务端大小限制。")
84
+ output.write(chunk)
85
+ if actual != declared_size:
86
+ raise UploadError("上传文件不完整,实际大小与声明值不一致。")
87
+
88
+ def unpack(self, source: BinaryIO) -> None:
89
+ with zipfile.ZipFile(source) as archive:
90
+ infos = archive.infolist()
91
+ if len(infos) + self.entry_count > self.file_limit:
92
+ raise UploadError("压缩包条目数超过服务端 MAX_ARCHIVE_FILES 限制。")
93
+ for info in infos:
94
+ # ZipInfo.filename 会截断 NUL,必须检查保存的原始名称。
95
+ original = getattr(info, "orig_filename", info.filename)
96
+ if original != info.filename or "\x00" in original:
97
+ raise UploadError("ZIP 文件名包含 NUL 字符。")
98
+ mode = (info.external_attr >> 16) & 0xFFFF
99
+ kind = stat.S_IFMT(mode)
100
+ if kind not in (0, stat.S_IFREG, stat.S_IFDIR):
101
+ raise UploadError("ZIP 中不允许符号链接或特殊文件。")
102
+ directory = info.is_dir()
103
+ if kind == stat.S_IFDIR and not directory:
104
+ raise UploadError("ZIP 文件夹属性与路径不一致。")
105
+ if info.flag_bits & 1:
106
+ raise UploadError("不支持加密 ZIP。")
107
+ if info.file_size / max(info.compress_size, 1) > 500:
108
+ raise UploadError("ZIP 压缩比超过 500,拒绝潜在压缩炸弹。")
109
+ name = original[:-1] if directory else original
110
+ target = self.register(name, directory)
111
+ if directory:
112
+ if info.file_size:
113
+ raise UploadError("ZIP 文件夹条目不能包含文件数据。")
114
+ continue
115
+ # 内嵌 ZIP 作为普通资源复制,不递归解压。
116
+ with archive.open(info, "r") as member:
117
+ self.copy_stream(member, target, info.file_size)
118
+
119
+
120
+ def _open_regular_file(source: Path) -> BinaryIO:
121
+ source_mode = source.lstat().st_mode
122
+ if stat.S_ISLNK(source_mode):
123
+ raise UploadError("不允许上传符号链接。")
124
+ if not stat.S_ISREG(source_mode):
125
+ raise UploadError("上传对象必须是现有普通文件。")
126
+ # NONBLOCK 避免检查后被替换为 FIFO 的路径阻塞任务。
127
+ flags = (os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)
128
+ | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0))
129
+ descriptor = os.open(source, flags)
130
+ try:
131
+ if not stat.S_ISREG(os.fstat(descriptor).st_mode):
132
+ raise UploadError("上传对象必须是现有普通文件。")
133
+ return os.fdopen(descriptor, "rb")
134
+ except BaseException:
135
+ os.close(descriptor)
136
+ raise
137
+
138
+
139
+ def stage_uploads(files: list[str], project_dir: Path, blend_file: str | None) -> Path:
140
+ """原子暂存项目,成功返回所选 .blend 的绝对路径。
141
+
142
+ project_dir 必须不存在或为空。失败仅清理本次创建的临时目录,
143
+ 不会删除调用者已有文件;项目目录不会出现部分解压结果。
144
+ """
145
+ project_dir = Path(project_dir).absolute()
146
+ temporary: Path | None = None
147
+ try:
148
+ file_limit = positive_env_int("MAX_ARCHIVE_FILES", 5000)
149
+ upload_limit = positive_env_int("MAX_UPLOAD_MB", 1024) * 1024 * 1024
150
+ extract_limit = positive_env_int("MAX_EXTRACT_MB", 4096) * 1024 * 1024
151
+ if not files:
152
+ raise UploadError("请上传 .blend 文件及所需资源,或包含项目的 ZIP。")
153
+ if len(files) > file_limit:
154
+ raise UploadError("上传文件数量超过服务端 MAX_ARCHIVE_FILES 限制。")
155
+ if blend_file is not None:
156
+ safe_relative_path(blend_file)
157
+ if not blend_file.casefold().endswith(".blend"):
158
+ raise UploadError("blend_file 必须指定 .blend 文件。")
159
+ if project_dir.is_symlink():
160
+ raise UploadError("项目目录不能是符号链接。")
161
+ if project_dir.exists() and (
162
+ not project_dir.is_dir() or any(project_dir.iterdir())
163
+ ):
164
+ raise UploadError("项目目录必须为空,不能覆盖已有文件。")
165
+ project_dir.parent.mkdir(parents=True, exist_ok=True)
166
+ temporary = Path(tempfile.mkdtemp(prefix=f".{project_dir.name}.upload-", dir=project_dir.parent))
167
+ staging = _Staging(temporary, extract_limit, file_limit)
168
+ uploaded_bytes = 0
169
+ upload_names: set[str] = set()
170
+ for file_path in files:
171
+ source = Path(file_path)
172
+ name = source.name
173
+ safe_relative_path(name)
174
+ if name.casefold() in upload_names:
175
+ raise UploadError(f"上传文件名称重复:{name}")
176
+ upload_names.add(name.casefold())
177
+ if source.suffix.casefold() in _SCRIPT_SUFFIXES:
178
+ raise UploadError("不允许上传 Python 脚本文件。")
179
+ if name.casefold().endswith(_TAR_SUFFIXES):
180
+ raise UploadError("不支持 TAR 压缩包,请使用 ZIP。")
181
+ with _open_regular_file(source) as handle:
182
+ size = os.fstat(handle.fileno()).st_size
183
+ uploaded_bytes += size
184
+ if uploaded_bytes > upload_limit:
185
+ raise UploadError("上传总大小超过服务端 MAX_UPLOAD_MB 限制。")
186
+ if source.suffix.casefold() == ".zip":
187
+ staging.unpack(handle)
188
+ else:
189
+ staging.copy_stream(handle, staging.register(name), size)
190
+ if not staging.blends:
191
+ raise UploadError("上传内容中找不到 .blend 文件。")
192
+ if blend_file is None:
193
+ if len(staging.blends) != 1:
194
+ raise UploadError("存在多个 .blend 文件,请通过 blend_file 指定相对路径。")
195
+ selected = staging.blends[0]
196
+ else:
197
+ if blend_file not in staging.blends:
198
+ raise UploadError(f"找不到 blend_file 指定的文件:{blend_file}")
199
+ selected = blend_file
200
+ if project_dir.exists():
201
+ project_dir.rmdir() # 只移除空目录;发生竞争写入时安全失败。
202
+ os.replace(temporary, project_dir)
203
+ temporary = None
204
+ return project_dir.joinpath(*selected.split("/"))
205
+ except UploadError:
206
+ raise
207
+ except (OSError, ValueError, RuntimeError, zipfile.BadZipFile, NotImplementedError) as exc:
208
+ raise UploadError(f"无法暂存上传项目:{exc}") from exc
209
+ finally:
210
+ if temporary is not None:
211
+ shutil.rmtree(temporary, ignore_errors=True)