Upload folder using huggingface_hub (part 2)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- bw_0007/environment/LICENSEAdded+21
- bw_0007/environment/blender_startup.pyAdded+21
- bw_0007/environment/inputs/input.jsonAdded+9
- bw_0007/environment/inputs/instruction.htmlAdded
- bw_0007/environment/inputs/query.txtAdded+1
- bw_0007/environment/inputs/reference_images.base64.jsonAdded
- bw_0007/environment/inputs/references/image_01.jpgAdded
- bw_0007/environment/install_blender.shAdded+16
- bw_0007/environment/mcp_bridge.pyAdded+80
- bw_0007/environment/requirements-tools.txtAdded+6
- bw_0007/instruction.mdAdded+25
- bw_0007/task.tomlAdded+63
- bw_0007/tests/DockerfileAdded+31
- bw_0007/tests/LICENSEAdded+21
- bw_0007/tests/blenderworld/__init__.pyAdded+2
- bw_0007/tests/blenderworld/__main__.pyAdded+3
- bw_0007/tests/blenderworld/blender_runtime.pyAdded+65
- bw_0007/tests/blenderworld/cli.pyAdded+82
- bw_0007/tests/blenderworld/data.pyAdded+127
- bw_0007/tests/blenderworld/evaluation.pyAdded+270
- bw_0007/tests/blenderworld/evaluators/__init__.pyAdded+1
- bw_0007/tests/blenderworld/evaluators/asset_paths.pyAdded+163
- bw_0007/tests/blenderworld/evaluators/evidence_checks.pyAdded+250
- bw_0007/tests/blenderworld/evaluators/judge_blender_agent.pyAdded+878
- bw_0007/tests/blenderworld/evaluators/judge_blender_binary_rubrics.pyAdded
- bw_0007/tests/blenderworld/harbor_export.pyAdded+205
- bw_0007/tests/blenderworld/harbor_verify.pyAdded+80
- bw_0007/tests/blenderworld/render_agent.pyAdded+130
- bw_0007/tests/blenderworld/runtime.pyAdded+102
- bw_0007/tests/blenderworld/submissions.pyAdded+211
- bw_0007/tests/dataset/dataset.jsonlAdded+1
- bw_0007/tests/dataset/rubrics.jsonAdded+141
- bw_0007/tests/dataset/tasks/bw_0007/query.txtAdded+1
- bw_0007/tests/dataset/tasks/bw_0007/references/image_01.jpgAdded
- bw_0007/tests/dataset/tasks/bw_0007/rubric.jsonAdded+137
- bw_0007/tests/dataset/tasks/bw_0007/task.jsonAdded+42
- bw_0007/tests/install_blender.shAdded+16
- bw_0007/tests/requirements-verifier.txtAdded+4
- bw_0007/tests/test.shAdded+6
- bw_0008/environment/DockerfileAdded+37
- bw_0008/environment/LICENSEAdded+21
- bw_0008/environment/blender_startup.pyAdded+21
- bw_0008/environment/inputs/input.jsonAdded+9
- bw_0008/environment/inputs/instruction.htmlAdded
- bw_0008/environment/inputs/query.txtAdded+1
- bw_0008/environment/inputs/reference_images.base64.jsonAdded
- bw_0008/environment/inputs/references/image_01.jpgAdded
- bw_0008/environment/install_blender.shAdded+16
- bw_0008/environment/mcp_bridge.pyAdded+80
- bw_0008/environment/requirements-tools.txtAdded+6
123456789101112131415161718192021MIT License
Copyright (c) 2026 BlenderWorld contributors
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123456789101112131415161718192021"""Start the bundled, versioned MCP addon in an interactive Blender session."""import importlib.utilimport osimport sys
import bpy
if bpy.app.version != (4, 2, 10): raise RuntimeError("BlenderWorld requires Blender 4.2.10")
os.environ["BLENDERMCP_NO_UPDATE_CHECK"] = "1"path = os.environ.get("BLENDER_MCP_ADDON_PATH", "/opt/bw-mcp/addon.py")spec = importlib.util.spec_from_file_location("blendermcp", path)addon = importlib.util.module_from_spec(spec)sys.modules[spec.name] = addonspec.loader.exec_module(addon)addon.register()bpy.context.scene.blendermcp_port = int(os.environ["BLENDER_PORT"])bpy.context.scene.blendermcp_auto_start_server = Truebpy.context.scene.blendermcp_use_polyhaven = Trueprint("BlenderWorld MCP addon registered", flush=True)123456789{ "task_id": "bw_0007", "query_file": "query.txt", "files": [ "references/image_01.jpg", "instruction.html", "reference_images.base64.json" ]}1Promo shot for a tree-care company: an arborist high in a tall pine with pruned branch stubs. The climber wears a red helmet, dark top, red-and-black protective trousers, rigged with harness and climbing ropes, chainsaw on his belt; dense forest, blue sky above, proportions estimated. Key point—worker and safety gear read clearly, not buried in foliage, woodland realistic but not stealing focus. Give bark, fabric and metal materials, daylight, camera and render; send a render and keep the .blend.12345678910111213141516#!/bin/bashset -euo pipefailversion=4.2.10filename="blender-${version}-linux-x64.tar.xz"base_url="https://download.blender.org/release/Blender4.2"checksum=7b888b36cf5bd7e35d495eb9717f7a9b645ea5f2fb4fe9850991800b8f08d531curl --fail --location --retry 3 "${base_url}/${filename}" -o "/tmp/${filename}" || \ curl --fail --location --retry 3 "https://mirrors.ocf.berkeley.edu/blender/release/Blender4.2/${filename}" -o "/tmp/${filename}"cd /tmpprintf '%s %s\n' "$checksum" "$filename" | sha256sum --check -mkdir -p /opt/blendertar -xJf "$filename" --strip-components=1 -C /opt/blender/opt/blender/4.2/python/bin/python3.11 -m ensurepip/opt/blender/4.2/python/bin/python3.11 -m pip install --no-cache-dir requests==2.32.5rm "/tmp/${filename}"/opt/blender/blender --background --factory-startup --python-exit-code 2 --python-expr 'import bpy, requests; assert bpy.app.version == (4, 2, 10), bpy.app.version_string; print(bpy.app.version_string)'1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980#!/usr/local/bin/python"""Own a Blender session and expose its MCP server over clean stdio."""import osfrom pathlib import Pathimport signalimport socketimport subprocessimport sysimport time
def main(): env = os.environ.copy() env.setdefault("PATH", "/opt/blender:/usr/local/bin:/usr/bin:/bin") env["BLENDERMCP_NO_UPDATE_CHECK"] = "1" env["BLENDER_MCP_DISABLE_TELEMETRY"] = "1" env.setdefault("BLENDER_MCP_ADDON_PATH", "/opt/bw-mcp/addon.py") # Separate ports allow multiple MCP clients without borrowing another client's scene. with socket.socket() as reservation: reservation.bind(("127.0.0.1", 0)) port = reservation.getsockname()[1] env.update(BLENDER_HOST="127.0.0.1", BLENDER_PORT=str(port)) log = Path(env.get("BW_BLENDER_LOG", "/logs/artifacts/blender-mcp.log")) log.parent.mkdir(parents=True, exist_ok=True) blender = None server = None
def interrupted(signum, _frame): raise SystemExit(128 + signum)
for sig in (signal.SIGINT, signal.SIGTERM): signal.signal(sig, interrupted) try: with log.open("a") as stream: blender = subprocess.Popen( ["xvfb-run", "-a", env.get("BLENDER_BIN", "/opt/blender/blender"), "--factory-startup", "--python-exit-code", "1", "--python", str(Path(__file__).resolve().with_name("blender_startup.py"))], env=env, stdout=stream, stderr=subprocess.STDOUT, start_new_session=True) deadline = time.monotonic() + float(env.get("BW_MCP_STARTUP_TIMEOUT", "120")) while True: if blender.poll() is not None: raise RuntimeError(f"Blender exited during startup; see {log}") try: with socket.create_connection(("127.0.0.1", port), timeout=0.25): break except OSError: if time.monotonic() >= deadline: raise RuntimeError(f"Blender MCP startup timed out; see {log}") time.sleep(0.2) # stdin stays connected to the MCP client. Only this process writes to stdout. server = subprocess.Popen([env.get("BW_MCP_COMMAND", "/opt/bw-mcp/bin/mcp-for-blender")], env=env, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr, start_new_session=True) return server.wait() finally: for process in (server, blender): if process is None: continue # xvfb-run may exit before its descendants; terminate the owned process group. try: os.killpg(process.pid, signal.SIGTERM) except ProcessLookupError: pass try: process.wait(timeout=5) except subprocess.TimeoutExpired: try: os.killpg(process.pid, signal.SIGKILL) except ProcessLookupError: pass process.wait()
if __name__ == "__main__": try: raise SystemExit(main()) except (OSError, RuntimeError) as error: print(f"BlenderWorld MCP: {error}", file=sys.stderr) raise SystemExit(1)123456# Supporting tools from Appendix D.2. These package versions are release pins;# the paper specifies the tools but does not prescribe these package versions.numpy==2.2.6Pillow==11.3.0scipy==1.15.3imageio==2.37.012345678910111213141516171819202122232425# BlenderWorld bw_0007
## Task
Promo shot for a tree-care company: an arborist high in a tall pine with pruned branch stubs. The climber wears a red helmet, dark top, red-and-black protective trousers, rigged with harness and climbing ropes, chainsaw on his belt; dense forest, blue sky above, proportions estimated. Key point—worker and safety gear read clearly, not buried in foliage, woodland realistic but not stealing focus. Give bark, fabric and metal materials, daylight, camera and render; send a render and keep the .blend.
## Inputs
The original request is also in `/workspace/inputs/query.txt`.
- `reference_images`: `/workspace/inputs/references/image_01.jpg`
Read the supplied specifications and inspect the reference media before modeling. Relative filenames in the request refer to the files listed above.
## Deliverables
Save the editable project as `/workspace/exports/final.blend`. Put all requested images, videos, model exports, and texture dependencies under `/workspace/exports/`. Pack textures into the project or keep relative paths inside this directory so the project can be opened in a fresh environment.
## Tools
Blender is installed as `blender`. A Blender MCP server is configured for agents that support task MCP servers; use its advertised tools to inspect the scene, execute Blender Python, and capture viewport images. The Blender Python CLI is also available. Use Blender 4.2.10, Node.js 22.17.0, Codex CLI 0.147.0 or Claude Code 2.1.220; do not upgrade these tools. Inspect your result and save your work before finishing.
## Offline task preview
An HTML view of the task with embedded reference images is available at `/workspace/inputs/instruction.html`. Inspect the original reference image files listed under Inputs when modeling.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263schema_version = "1.3"artifacts = ["/workspace/exports"]
[task]name = "Qwen/BlenderWorld-bw_0007"description = "BlenderWorld bw_0007 (image)"keywords = ["blender", "3d", "image"]
[metadata]category = "Nature & Landscapes"subcategory = "Landscapes & Natural Environments"category_short = "Nature"subcategory_short = "Natural scenes"taxonomy_version = "taxonomy_223"task_id = "bw_0007"modality = "image"rubric_count = 7protocol_version = 1code_version = "0.3.0"blender_version = "4.2.10"node_version = "22.17.0"codex_version = "0.147.0"claude_code_version = "2.1.220"submission_format = "blenderworld-submission-v1"submission_project = "final.blend"
[agent]timeout_sec = 28800
[environment]build_timeout_sec = 3600cpus = 8memory_mb = 16384storage_mb = 102400gpus = 1workdir = "/workspace"
[[environment.mcp_servers]]name = "blender"transport = "stdio"command = "/usr/local/bin/bw-blender-mcp"args = []
[verifier]timeout_sec = 28800environment_mode = "separate"
[verifier.environment]build_timeout_sec = 3600cpus = 8memory_mb = 16384storage_mb = 102400gpus = 1workdir = "/workspace"
[verifier.env]ANTHROPIC_BASE_URL = "${BW_AGENT_JUDGE_ENDPOINT}"ANTHROPIC_API_KEY = "${BW_AGENT_JUDGE_API_KEY}"JUDGE_API_ENDPOINT = "${BW_VISION_JUDGE_ENDPOINT}"JUDGE_API_KEY = "${BW_VISION_JUDGE_API_KEY}"RENDER_AGENT_MODEL = "${BW_RENDER_MODEL:-gpt-5.6-terra}"AGENT_JUDGE_MODEL = "${BW_AGENT_JUDGE_MODEL:-gpt-5.6-terra}"JUDGE_MODEL = "${BW_VISION_JUDGE_MODEL:-gpt-5.6-terra}"12345678910111213141516171819202122232425262728293031FROM node:22.17.0-bookworm-slim AS nodeFROM python:3.12-slim-bookworm
ENV DEBIAN_FRONTEND=noninteractive \ BLENDER_BIN=/opt/blender/blender \ PYTHONPATH=/opt/blenderworld \ PATH=/opt/blender:/usr/local/bin:/usr/bin:/bin \ DISABLE_AUTOUPDATER=1RUN apt-get update && apt-get install -y --no-install-recommends \ bash ca-certificates curl xz-utils ffmpeg xvfb xauth procps \ libx11-6 libxi6 libxfixes3 libxrender1 libxxf86vm1 libxkbcommon0 \ libgl1 libegl1 libsm6 libice6 libdbus-1-3 libgomp1 libfontconfig1 \ fonts-dejavu-core && rm -rf /var/lib/apt/lists/*COPY install_blender.sh /opt/install_blender.shRUN bash /opt/install_blender.shCOPY --from=node /usr/local/bin/node /usr/local/bin/nodeCOPY --from=node /usr/local/lib/node_modules /usr/local/lib/node_modulesRUN ln -s /usr/local/lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm \ && ln -s /usr/local/lib/node_modules/npm/bin/npx-cli.js /usr/local/bin/npx \ && npm install --global @anthropic-ai/claude-code@2.1.220 \ && test "$(node --version)" = "v22.17.0" \ && test "$(claude --version)" = "2.1.220 (Claude Code)"COPY requirements-verifier.txt /opt/requirements-verifier.txtRUN python -m pip install --no-cache-dir -r /opt/requirements-verifier.txtCOPY blenderworld/ /opt/blenderworld/blenderworld/COPY test.sh /tests/test.shCOPY LICENSE /usr/local/share/licenses/BlenderWorld/LICENSERUN chmod 755 /tests/test.sh && mkdir -p /workspace /logs/verifierCOPY dataset/ /tests/dataset/WORKDIR /workspaceCMD ["sleep", "infinity"]123456789101112131415161718192021MIT License
Copyright (c) 2026 BlenderWorld contributors
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.12"""BlenderWorld task preparation and evaluation."""__version__ = "0.3.0"123from .cli import main
raise SystemExit(main())1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465"""Loaded by Blender before the render agent's script; records real render attempts."""import fcntlimport jsonimport osimport sysfrom pathlib import Path
import bpyfrom bpy.app.handlers import persistent
sys.path.insert(0, str(Path(__file__).resolve().parent / "evaluators"))import asset_paths
if bpy.app.version != (4, 2, 10): raise RuntimeError("BlenderWorld evaluation requires Blender 4.2.10")
asset_paths.register()
def update_attempt(scene, completed=False): folder = Path(os.environ["BLENDER_EVAL_VIEW_ROOT"]).resolve() target = Path(bpy.path.abspath(scene.render.filepath)).resolve() if not target.suffix and scene.render.use_file_extension: target = target.with_suffix(".png") if not target.is_relative_to(folder) or target.suffix.lower() != ".png": raise RuntimeError("Evaluator renders must be PNGs inside evaluation/multiview") state_path = folder / "render_attempts.json" with (folder / ".render.lock").open("a") as lock: fcntl.flock(lock, fcntl.LOCK_EX) state = json.loads(state_path.read_text()) if state_path.exists() else {} history = state.setdefault(str(target), []) if completed: if history: history[-1]["completed"] = True else: if len(history) >= 3: raise RuntimeError("Two corrective re-renders per view exhausted") if (scene.render.engine != "CYCLES" or scene.cycles.samples != 64 or scene.render.resolution_x != 1024 or scene.render.resolution_y != 1024 or scene.render.resolution_percentage != 100): raise RuntimeError("Required: Cycles, 64 samples, 1024x1024 at 100%") history.append({"engine": scene.render.engine, "samples": scene.cycles.samples, "device": scene.cycles.device, "completed": False}) temp = state_path.with_suffix(".tmp") temp.write_text(json.dumps(state, indent=2)) temp.replace(state_path)
@persistentdef before(scene, *_): try: update_attempt(scene) except Exception as error: # Blender ignores ordinary handler exceptions; abort this render subprocess. print("BLENDERWORLD_RENDER_REJECTED", str(error), flush=True) os._exit(2)
@persistentdef after(scene, *_): update_attempt(scene, completed=True)
bpy.app.handlers.render_pre.append(before)bpy.app.handlers.render_write.append(after)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182"""Command line interface for local task preparation and evaluation."""import argparseimport jsonimport osfrom pathlib import Path
from .data import load_tasks, prepare, verify
def main(): parser = argparse.ArgumentParser(prog="bw", description="BlenderWorld benchmark tools") commands = parser.add_subparsers(dest="command", required=True) download = commands.add_parser("download", help="Download the frozen dataset from Hugging Face") download.add_argument("--repo-id", default="Qwen/BlenderWorld") download.add_argument("--revision", default="main") download.add_argument("--output", default="data/BlenderWorld") check = commands.add_parser("verify", help="Verify task content, paths and checksums") check.add_argument("dataset") listing = commands.add_parser("list", help="List tasks") listing.add_argument("dataset") listing.add_argument("--modality", choices=["text", "image", "video"]) staging = commands.add_parser("prepare", help="Stage a task's generator-visible inputs") staging.add_argument("--dataset", required=True) staging.add_argument("--task-id", required=True) staging.add_argument("--output", required=True) packing = commands.add_parser("pack-submission", help="Package model outputs as one submission ZIP") packing.add_argument("--source", required=True, help="Output directory or ZIP with final.blend at its root") packing.add_argument("--task-id", required=True) packing.add_argument("--output", required=True, help="New submissions/bw_XXXX.zip") harbor = commands.add_parser("export-harbor", help="Export self-contained Harbor tasks (Python 3.12+)") harbor.add_argument("--dataset", required=True) harbor.add_argument("--output", required=True) harbor.add_argument("--namespace", default="Qwen") harbor.add_argument("--task-id", action="append") harbor.add_argument("--cpus", type=int, default=8) harbor.add_argument("--memory-mb", type=int, default=16384) harbor.add_argument("--gpus", type=int, default=0) harbor.add_argument("--agent-timeout", type=int, default=14400) harbor.add_argument("--verifier-timeout", type=int, default=28800) scoring = commands.add_parser("evaluate", help="Render and judge per-task BlenderWorld submission ZIPs") scoring.add_argument("--dataset", required=True) scoring.add_argument("--submissions", "--submission", dest="submissions", required=True, help="Directory of bw_XXXX.zip files, or a single task ZIP") scoring.add_argument("--output", required=True) scoring.add_argument("--task-id", action="append") scoring.add_argument("--dry-run", action="store_true") scoring.add_argument("--resume", action="store_true") scoring.add_argument("--blender-bin", default=os.environ.get("BLENDER_BIN", "blender")) scoring.add_argument("--render-agent-model", default=os.environ.get("RENDER_AGENT_MODEL", "gpt-5.6-terra")) scoring.add_argument("--agent-judge-model", default=os.environ.get("AGENT_JUDGE_MODEL", "gpt-5.6-terra")) scoring.add_argument("--judge-model", default=os.environ.get("JUDGE_MODEL", "gpt-5.6-terra")) scoring.add_argument("--judge-api-endpoint", default=os.environ.get("JUDGE_API_ENDPOINT", "https://api.openai.com/v1/chat/completions")) args = parser.parse_args() try: if args.command == "download": from huggingface_hub import snapshot_download snapshot_download(args.repo_id, repo_type="dataset", revision=args.revision, local_dir=args.output) result = verify(args.output) elif args.command == "verify": result = verify(args.dataset) elif args.command == "prepare": result = prepare(args.dataset, args.task_id, args.output) elif args.command == "pack-submission": from .submissions import pack_submission result = pack_submission(args.source, args.task_id, args.output) elif args.command == "list": result = [{"task_id": r["task_id"], "modality": r["modality"], "rubric_count": r["rubric_count"]} for r in load_tasks(args.dataset) if not args.modality or r["modality"] == args.modality] elif args.command == "export-harbor": from .harbor_export import export_harbor result = export_harbor(args.dataset, args.output, args.namespace, args.task_id, args.cpus, args.memory_mb, args.gpus, args.agent_timeout, args.verifier_timeout) else: from .evaluation import evaluate result = evaluate(args) print(json.dumps(result, ensure_ascii=False, indent=2)) if args.command == "evaluate" and not args.dry_run and result["overall"]["succeeded"] != result["overall"]["task_count"]: return 2 return 0 except (OSError, ValueError, RuntimeError) as error: parser.exit(2, f"bw: {error}\n")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127"""Load and verify the portable dataset without a model service."""from __future__ import annotations
import hashlibimport jsonimport reimport shutilfrom collections import Counterfrom pathlib import Path
RESOURCE_FIELDS = ("attachments", "supplemental_attachments", "reference_images", "reference_videos", "rubric_reference_images")
def sha256(path): h = hashlib.sha256() with Path(path).open("rb") as stream: for chunk in iter(lambda: stream.read(1024 * 1024), b""): h.update(chunk) return h.hexdigest()
def write_json(path, obj): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_suffix(path.suffix + ".tmp") temporary.write_text(json.dumps(obj, ensure_ascii=False, indent=2) + "\n") temporary.replace(path)
def resolve(root, relative): root = Path(root).resolve() path = root / relative if Path(relative).is_absolute() or not path.resolve().is_relative_to(root): raise ValueError(f"Path escapes dataset: {relative}") return path
def load_tasks(root): rows = [json.loads(s) for s in (Path(root) / "dataset.jsonl").read_text().splitlines() if s.strip()] ids = [r["task_id"] for r in rows] if len(set(ids)) != len(ids) or not all(re.fullmatch(r"bw_\d{4}", s) for s in ids): raise ValueError("Task IDs must be unique neutral identifiers") return rows
def verify(root): root = Path(root) rows = load_tasks(root) modalities = Counter(r["modality"] for r in rows) if modalities != {"text": 78, "image": 130, "video": 15}: raise ValueError(f"Unexpected benchmark task counts: {modalities}") bundled = json.loads((root / "rubrics.json").read_text())["results"] combined = {r["task_id"]: r for r in bundled} if len(combined) != 223 or len(bundled) != 223: raise ValueError("Combined rubric index must have 223 unique tasks") criteria, resources = 0, 0 for row in rows: task_root = root / "tasks" / row["task_id"] if json.loads((task_root / "task.json").read_text()) != row: raise ValueError(f"Task/index mismatch: {row['task_id']}") if resolve(root, row["query_file"]).read_text() != row["query"]: raise ValueError(f"Query mismatch: {row['task_id']}") rubric = json.loads(resolve(root, row["rubric_file"]).read_text()) if rubric != combined[row["task_id"]] or rubric["prompt"] != row["query"]: raise ValueError(f"Rubric/query/index mismatch: {row['task_id']}") ids = [r["id"] for r in rubric["rubrics"]] if len(set(ids)) != len(ids) or len(ids) != row["rubric_count"]: raise ValueError(f"Invalid criterion IDs: {row['task_id']}") for criterion in rubric["rubrics"]: if criterion["score_values"] != [0, 1] or criterion["importance_weight"] not in (1, 2, 3): raise ValueError("Invalid binary criterion/importance weight") if criterion["evidence_type"] not in {"scene_summary", "render", "either"}: raise ValueError("Unknown evidence route") for attachment in rubric["attachments"]: if not resolve(task_root, attachment["file"]).is_file(): raise ValueError(f"Missing rubric attachment: {attachment['file']}") if rubric.get("image_file") and not resolve(task_root, rubric["image_file"]).is_file(): raise ValueError(f"Missing rubric image: {rubric['image_file']}") for field in RESOURCE_FIELDS: for entry in row[field]: path = resolve(root, entry["path"]) if path != resolve(task_root, entry["task_relative_path"]): raise ValueError("Resource path aliases disagree") if path.stat().st_size != entry["bytes"] or sha256(path) != entry["sha256"]: raise ValueError(f"Resource checksum mismatch: {entry['path']}") resources += 1 criteria += len(ids) if criteria != 2651: raise ValueError(f"Expected 2651 criteria, got {criteria}") checksums = root / "SHA256SUMS" if not checksums.is_file(): raise ValueError("Missing release SHA256SUMS") checksum_paths = set() for line in checksums.read_text().splitlines(): checksum, relative = line.split(" ", 1) if relative in checksum_paths or sha256(resolve(root, relative)) != checksum: raise ValueError(f"Duplicate or incorrect checksum: {relative}") checksum_paths.add(relative) actual_paths = {p.relative_to(root).as_posix() for p in root.rglob("*") if p.is_file() and not any(part in {".git", ".cache"} for part in p.relative_to(root).parts)} if actual_paths != checksum_paths | {"SHA256SUMS"}: raise ValueError("Release checksum inventory does not cover the complete file tree") manifest = json.loads((root / "manifest.json").read_text()) if {r["path"] for r in manifest["files"]} != actual_paths - {"manifest.json", "SHA256SUMS"}: raise ValueError("Manifest does not cover the complete release payload") return {"tasks": len(rows), "modalities": dict(modalities), "criteria": criteria, "resources": resources, "checksums_verified": checksums.exists()}
def prepare(root, task_id, output): """Stage only generator-visible inputs; evaluation rubrics remain in the dataset.""" root, output = Path(root), Path(output) row = next((r for r in load_tasks(root) if r["task_id"] == task_id), None) if row is None: raise ValueError(f"Unknown task: {task_id}") output.mkdir(parents=True, exist_ok=False) (output / "query.txt").write_text(row["query"]) inputs = [] for field in ("attachments", "reference_images", "reference_videos"): for entry in row[field]: target = resolve(output, entry["task_relative_path"]) target.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(resolve(root, entry["path"]), target) inputs.append(entry["task_relative_path"]) write_json(output / "input.json", {"task_id": task_id, "query_file": "query.txt", "files": inputs}) return {"task_id": task_id, "output": str(output), "input_files": len(inputs)}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270"""Local evidence preparation, rendering, judging, and benchmark aggregation."""from __future__ import annotations
import csvimport fcntlimport jsonimport osimport shutilimport subprocessimport sysfrom pathlib import Path
from . import render_agentfrom .data import RESOURCE_FIELDS, load_tasks, resolve, sha256, write_jsonfrom .evaluators import judge_blender_binary_rubrics as visionfrom .evaluators.evidence_checks import cli_log_statusfrom .runtime import RuntimeValidationError, inspect_runtime, record_runtime, requirementsfrom .submissions import FORMAT, inspect_submission, unpack_submission
PROTOCOL = {"version": 1, "views": 8, "resolution": 1024, "samples": 64, "engine": "CYCLES", "max_corrective_rerenders": 2, "dimension_weight": 0.5, "score_cap": None, "structural_evidence": ["scene_summary"], "visual_evidence": ["render", "either"]}
def tree_hashes(root): root = Path(root) return {p.relative_to(root).as_posix(): sha256(p) for p in sorted(root.rglob("*")) if p.is_file()}
def sample_video(source, destination, count): destination.mkdir(parents=True, exist_ok=True) probe = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "json", str(source)], check=True, capture_output=True, text=True, timeout=60) duration = float(json.loads(probe.stdout)["format"]["duration"]) if duration <= 0: raise ValueError(f"Video has no positive duration: {source.name}") # Sample across the whole clip, including both ends without seeking past its last frame. for i in range(count): timestamp = max(0, duration - min(0.1, duration / count)) * i / max(1, count - 1) subprocess.run(["ffmpeg", "-v", "error", "-y", "-ss", str(timestamp), "-i", str(source), "-frames:v", "1", str(destination / f"frame_{i:03d}.png")], check=True, capture_output=True, timeout=120) if len(list(destination.glob("*.png"))) != count: raise ValueError(f"Incomplete video sampling: {source.name}")
def prepare_evaluation(dataset, row, submission, task_dir): task_dir.mkdir(parents=True, exist_ok=False) snapshot = task_dir / ".eval_workspace" # The public ZIP contract is independent of the model's generation harness. manifest = unpack_submission(submission, row["task_id"], snapshot) write_json(task_dir / "submission_archive.json", manifest) (task_dir / "query.txt").write_text(row["query"]) rubric = json.loads(resolve(dataset, row["rubric_file"]).read_text()) write_json(task_dir / "rubric.json", rubric) input_hashes = {entry["sha256"] for field in RESOURCE_FIELDS for entry in row[field]} write_json(task_dir / "input_media_sha256.json", sorted(input_hashes)) for field in RESOURCE_FIELDS: for entry in row[field]: path = resolve(task_dir, entry["task_relative_path"]) path.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(resolve(dataset, entry["path"]), path) judge_refs = task_dir / "image_assets" judge_refs.mkdir() image_entries = row["rubric_reference_images"] or row["reference_images"] for entry in image_entries: shutil.copyfile(resolve(dataset, entry["path"]), judge_refs / Path(entry["path"]).name) for i, entry in enumerate(row["reference_videos"]): sample_video(resolve(dataset, entry["path"]), judge_refs / f"video_{i:02d}", 4) for i, video in enumerate(sorted(snapshot.rglob("*"))): if (video.is_file() and video.suffix.lower() in {".mp4", ".mov", ".mkv", ".webm"} and sha256(video) not in input_hashes): sample_video(video, task_dir / "animation_frames" / f"clip_{i:03d}", 16) write_json(task_dir / "submission_sha256.json", tree_hashes(snapshot)) write_json(task_dir / "rubrics_batch.json", {"results": [{**rubric, "task_dir": str(task_dir.resolve())}]})
def run_module(module, args, log): with log.open("w") as stream: completed = subprocess.run([sys.executable, "-m", "blenderworld.evaluators." + module, *args], env={**os.environ, "DISABLE_AUTOUPDATER": "1"}, stdout=stream, stderr=subprocess.STDOUT, check=False) if completed.returncode: raise RuntimeError(f"{module} failed ({completed.returncode}); see {log.name}")
def validate_score(row, rubric, result): if result.get("ok") is not True or result.get("dry_run"): raise ValueError("Judge did not produce a successful scored result") if result.get("cap_applied") or not result.get("rendered_image_files"): raise ValueError("Result does not follow the public scoring protocol") scores = result.get("rubric_scores", []) expected = {r["id"] for r in rubric["rubrics"]} if {r["id"] for r in scores} != expected or len(scores) != len(expected): raise ValueError("Incomplete or duplicate rubric scores") if any(type(r.get("score")) is not int or r["score"] not in (0, 1) for r in scores): raise ValueError("Rubric scores must be binary integers") dimensions = result.get("dimension_scores", []) expected_dims = {r["id"] for r in vision.DIMENSIONS} if {r["id"] for r in dimensions} != expected_dims or len(dimensions) != len(expected_dims): raise ValueError("Incomplete or duplicate dimension scores") if any(type(r.get("score")) is not int or not 1 <= r["score"] <= 10 for r in dimensions): raise ValueError("Dimension scores must be integers from 1 to 10") rubric_score = vision.build_score_summary(rubric["rubrics"], scores)["weighted_score_0_100"] dimension_score = 10 * sum(d["score"] for d in dimensions) / len(dimensions) fused = 0.5 * (rubric_score + dimension_score) if abs(fused - result["fused_score_0_100"]) > 1e-6: raise ValueError("Fused score differs from the paper's uncapped 1:1 formula") return {"task_id": row["task_id"], "modality": row["modality"], "ok": True, "score": fused, "rubric_score": rubric_score, "dimension_score": dimension_score, "error": ""}
def score_task(row, task_dir, options): common = ["--rubrics-batch", str(task_dir / "rubrics_batch.json"), "--image-glob", "evaluation/multiview/*.png", "--max-images", "8", "--reference-image-glob", "image_assets/**/*", "--max-reference-images", "4", "--extra-image-glob", ".eval_workspace/**/*.png,.eval_workspace/**/*.jpg,.eval_workspace/**/*.jpeg,.eval_workspace/**/*.webp"] rubric = json.loads((task_dir / "rubric.json").read_text()) if any(r["evidence_type"] == "scene_summary" for r in rubric["rubrics"]): run_module("judge_blender_agent", common + ["--agent-evidence-types", "scene_summary", "--no-dimension-pass", "--blender-bin", options.blender_bin, "--model", options.agent_judge_model, "--task-concurrency", "1", "--batch-output", str(task_dir / "agent_batch.json")], task_dir / "agent_judge.log") folder = task_dir / "evaluation/agent_judge_multiview_eval" agent_result = json.loads((folder / "judgement.json").read_text()) if agent_result.get("agent_returncode") != 0: raise ValueError("Structural judge did not exit successfully") expected_logs = [folder / "agent_judge_stdout.jsonl"] + [ folder / f"agent_judge_stdout.attempt{i}.jsonl" for i in range(2, agent_result.get("agent_attempts", 1) + 1)] if any(not p.is_file() for p in expected_logs): raise ValueError("Structural judge attempt logs are incomplete") for log in folder.glob("agent_judge_stdout*.jsonl"): terminal, refused = cli_log_status(log) if refused: raise ValueError("Structural judge encountered an upstream content refusal") terminal, refused = cli_log_status(resolve(task_dir, agent_result["agent_stdout_path"])) if not terminal or terminal.get("is_error"): raise ValueError("Structural judge did not terminate successfully") for key in ("agent_raw_path", "bpy_dump_path"): if not json.loads(resolve(task_dir, agent_result[key]).read_text()): raise ValueError("Structural judge has no inspectable raw evidence") run_module("judge_blender_binary_rubrics", common + ["--evidence-routing", "--model", options.judge_model, "--api-endpoint", options.judge_api_endpoint, "--anim-frame-glob", "animation_frames/**/*.png", "--max-anim-frames", "16", "--task-concurrency", "1", "--batch-output", str(task_dir / "vision_batch.json")], task_dir / "vision_judge.log") result = json.loads((task_dir / "evaluation/judge_vlm/judgement.json").read_text()) if tree_hashes(task_dir / ".eval_workspace") != json.loads((task_dir / "submission_sha256.json").read_text()): raise ValueError("Evaluator modified the submitted workspace") return validate_score(row, rubric, result)
def summarize(rows, records): def aggregate(selected): count = len(selected) known = [records[r["task_id"]] for r in selected if r["task_id"] in records] return {"task_count": count, "completed": len(known), "succeeded": sum(r["ok"] for r in known), "mean_score": sum(r["score"] for r in known) / count if count else None} return {"complete": len(records) == len(rows), "overall": aggregate(rows), "text": aggregate([r for r in rows if r["modality"] == "text"]), "multimodal": aggregate([r for r in rows if r["modality"] != "text"]), "results": [records[r["task_id"]] for r in rows if r["task_id"] in records]}
def evaluate(options): dataset, submissions, output = map(lambda p: Path(p).resolve(), (options.dataset, options.submissions, options.output)) options.blender_bin = render_agent.normalize_blender_path(getattr(options, "blender_bin", "blender")) rows = load_tasks(dataset) single_zip = submissions.suffix.lower() == ".zip" and not submissions.is_dir() if single_zip and not options.task_id: options.task_id = [submissions.stem] if options.task_id: requested = set(options.task_id) rows = [r for r in rows if r["task_id"] in requested] if {r["task_id"] for r in rows} != requested: raise ValueError("Unknown task ID in selection") if single_zip and len(rows) != 1: raise ValueError("A single submission ZIP must select exactly one task") if output == submissions or (submissions.is_dir() and output.is_relative_to(submissions)): raise ValueError("Evaluation output must be outside the submissions directory") archives = {r["task_id"]: submissions if single_zip else submissions / (r["task_id"] + ".zip") for r in rows} output.mkdir(parents=True, exist_ok=True) # A run has one owner. A live owner must never be mistaken for a stopped run. with (output / ".run.lock").open("a") as lock: try: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError as error: raise RuntimeError("This run is already active") from error plan = {"dataset_sha256": sha256(dataset / "dataset.jsonl"), "rubrics_sha256": sha256(dataset / "rubrics.json"), "code_sha256": {str(p.relative_to(Path(__file__).parent)): sha256(p) for p in sorted(Path(__file__).parent.rglob("*.py"))}, "task_ids": [r["task_id"] for r in rows], "protocol": PROTOCOL, "models": {"render": options.render_agent_model, "agent": options.agent_judge_model, "vision": options.judge_model}, "submissions": str(submissions), "endpoints": {"vision": getattr(options, "judge_api_endpoint", ""), "agent": os.environ.get("ANTHROPIC_BASE_URL", "https://api.anthropic.com")}, "blender_bin": getattr(options, "blender_bin", "blender"), "submission_format": FORMAT, "runtime_requirements": requirements(), "submission_hashes": {tid: sha256(path) if path.is_file() and not path.is_symlink() else None for tid, path in archives.items()}} plan_file = output / "plan.json" if plan_file.exists(): if not options.resume: raise ValueError("Run exists; use --resume or choose a new output directory") if json.loads(plan_file.read_text()) != plan: raise ValueError("Inputs, models, code, or protocol changed; start a new run") else: write_json(plan_file, plan) if options.dry_run: inventory, errors = {}, {} for task_id, path in archives.items(): try: inventory[task_id] = inspect_submission(path, task_id) except (OSError, ValueError) as error: errors[task_id] = str(error) return {"dry_run": True, "tasks": len(rows), "plan": str(plan_file), "missing_submissions": [tid for tid, path in archives.items() if not path.is_file()], "submission_inventory": inventory, "submission_errors": errors} runtime_checked = False records = {} for row in rows: task_id = row["task_id"] task_dir = output / "tasks" / task_id outcome = task_dir / "result.json" if outcome.exists(): records[task_id] = json.loads(outcome.read_text()) continue if task_dir.exists(): # Preserve incomplete evidence; resume in a new attempt directory. n = 1 while (output / "incomplete" / f"{task_id}.{n}").exists(): n += 1 saved = output / "incomplete" / f"{task_id}.{n}" saved.parent.mkdir(parents=True, exist_ok=True) task_dir.rename(saved) print(f"Evaluating {task_id}", flush=True) try: submission = archives[task_id] if not submission.is_file(): raise ValueError("Missing submission ZIP: " + task_id + ".zip") if sha256(submission) != plan["submission_hashes"][task_id]: raise ValueError("Submission ZIP changed after planning") prepare_evaluation(dataset, row, submission, task_dir) if not runtime_checked: record_runtime(output, inspect_runtime(options.blender_bin)) runtime_checked = True render_agent.run(row, task_dir, options.blender_bin, options.render_agent_model) result = score_task(row, task_dir, options) if sha256(submission) != plan["submission_hashes"][task_id]: raise ValueError("Original submission ZIP changed during evaluation") except RuntimeValidationError: # A wrong evaluator runtime must not become 223 failed agent scores. raise except (OSError, ValueError, RuntimeError, subprocess.SubprocessError) as error: result = {"task_id": task_id, "modality": row["modality"], "ok": False, "score": 0.0, "rubric_score": None, "dimension_score": None, "error": str(error)} write_json(outcome, result) records[task_id] = result write_json(output / "summary.json", summarize(rows, records)) summary = summarize(rows, records) write_json(output / "summary.json", summary) with (output / "results.csv").open("w", newline="") as stream: writer = csv.DictWriter(stream, fieldnames=["task_id", "modality", "ok", "score", "rubric_score", "dimension_score", "error"]) writer.writeheader() writer.writerows(summary["results"]) return {k: v for k, v in summary.items() if k != "results"}1"""Evidence-routed BlenderWorld judges."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163"""Restore bundled image paths in memory when Blender opens an archived project.
The saved project is never rewritten. Ambiguous filenames remain unresolved;an evaluator must not silently substitute another task's texture."""
from __future__ import annotations
import jsonimport osfrom pathlib import Path, PurePosixPath
_handler = None
def workspace_for(blend_path, root): root = Path(root).resolve() blend = Path(blend_path).resolve() if not blend.is_relative_to(root): return None for parent in blend.parents: if not parent.is_relative_to(root): break if parent.name == ".eval_workspace": return parent candidate = parent / ".eval_workspace" if candidate.is_dir(): return candidate return None
def find_asset(saved_path, workspace): """Prefer the longest matching archived suffix; never pick an ambiguous name.""" workspace = Path(workspace).resolve() parts = PurePosixPath(str(saved_path).replace("\\", "/")).parts if not parts or ".." in parts: return None files = [ p for p in workspace.rglob(parts[-1]) if p.is_file() and p.resolve().is_relative_to(workspace) ] # Glob metacharacters in a legitimate filename must not select another file. files = [p for p in files if p.name == parts[-1]] for count in range(len(parts), 0, -1): suffix = parts[-count:] matches = [p for p in files if p.relative_to(workspace).parts[-count:] == suffix] if len(matches) == 1: return matches[0] if matches: return None return None
def restore_images(bpy, root): if not bpy.data.filepath: return [] workspace = workspace_for(bpy.data.filepath, root) if workspace is None: return [] changes = [] for image in bpy.data.images: if image.source != "FILE" or image.packed_file or not image.filepath: continue old = image.filepath if Path(bpy.path.abspath(old, library=image.library)).is_file(): continue replacement = find_asset(old, workspace) if replacement is None: changes.append({"action": "unresolved_image", "image": image.name, "path": old}) continue image.filepath = str(replacement) try: image.reload() if not all(image.size): raise RuntimeError("image has no readable pixels") except (RuntimeError, OSError, ValueError) as exc: image.filepath = old changes.append( { "action": "image_reload_failed", "image": image.name, "path": old, "error": str(exc), } ) else: changes.append( { "action": "restored_image", "image": image.name, "from": old, "to": str(replacement), } ) return changes
def compatible_denoising(scenes): changes = [] for scene in scenes: cycles = scene.cycles if cycles.use_denoising and cycles.denoiser == "OPTIX": # OptiX rendering can work even when its denoiser cannot initialize. # OIDN on CPU preserves denoising without changing render samples. cycles.denoiser = "OPENIMAGEDENOISE" if hasattr(cycles, "denoising_use_gpu"): cycles.denoising_use_gpu = False changes.append( { "action": "denoiser_compatibility", "scene": scene.name, "from": "OPTIX", "to": "OPENIMAGEDENOISE", } ) return changes
def apply_runtime(bpy): root = os.environ.get("BLENDER_EVAL_ASSET_ROOT") if not root or not getattr(bpy.data, "filepath", ""): return if workspace_for(bpy.data.filepath, root) is None: return changes = restore_images(bpy, root) + compatible_denoising(bpy.data.scenes) if not changes: return event = {"blend": bpy.data.filepath, "changes": changes} line = json.dumps(event, ensure_ascii=False) print("BLENDER_EVAL_RUNTIME " + line, flush=True) audit = os.environ.get("BLENDER_EVAL_RUNTIME_AUDIT") if audit: with Path(audit).open("a", encoding="utf-8") as stream: stream.write(line + "\n")
def register(): import bpy from bpy.app.handlers import persistent
global _handler if _handler is not None: return
@persistent def on_load_or_render(*_args): apply_runtime(bpy)
# Both hooks are needed: scripts may select another image or scene after load. bpy.app.handlers.load_post.append(on_load_or_render) bpy.app.handlers.render_pre.append(on_load_or_render) _handler = on_load_or_render
def unregister(): import bpy
global _handler for handlers in (bpy.app.handlers.load_post, bpy.app.handlers.render_pre): if _handler in handlers: handlers.remove(_handler) _handler = None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250#!/usr/bin/env python3"""Read-only evidence helpers; no task IDs or verdict overrides.
Normal Python: --inventory-root <materialized submission> --output <json>Blender: open the original with --disable-autoexec, then --python this_file -- --output <json> [--uv-layer <name>]. No scene is saved or rendered."""from __future__ import annotationsimport argparseimport hashlibimport jsonimport mathimport reimport structimport sysfrom pathlib import Path
def cli_event_content_refusal(event): """Recognize provider errors, never a prompt merely mentioning filtering.""" if not isinstance(event, dict): return False kind = event.get('type') status = event.get('api_error_status') if kind == 'result' and event.get('is_error') is True: text = str(event.get('result', '')) elif kind == 'assistant' and event.get('error'): message = event.get('message', {}) content = message.get('content', []) if isinstance(message, dict) else [] text = '\n'.join(str(block.get('text', '')) for block in content if isinstance(block, dict) and block.get('type') == 'text') elif kind == 'system' and event.get('subtype') == 'api_error': error = event.get('error', {}) if not isinstance(error, dict): return False status = error.get('status', error.get('status_code', status)) text = str(error.get('message', '')) elif kind == 'system' and event.get('subtype') in {'task_updated', 'task_notification'}: details = event.get('patch', {}) if event['subtype'] == 'task_updated' else event if not isinstance(details, dict) or details.get('status') != 'failed': return False text = str(details.get('error', details.get('summary', ''))) prefix = 'Agent terminated early due to an API error: ' if not text.startswith(prefix): return False text = text[len(prefix):] elif kind == 'user' and isinstance(event.get('tool_use_result'), str): # Claude Code emits this metadata for failed child tasks, alongside # system task notifications. Ordinary user messages have no such field. prefix = 'Error: Agent terminated early due to an API error: ' if not event['tool_use_result'].startswith(prefix): return False content = event.get('message', {}).get('content', []) if not isinstance(content, list) or not any( isinstance(block, dict) and block.get('type') == 'tool_result' and block.get('is_error') is True for block in content ): return False text = event['tool_use_result'][len(prefix):] else: return False return bool( (status == 400 or re.match(r'\s*API Error:\s*400\b', text)) and re.search(r'\b(?:content_policy_violation|content_filter)\b', text) )
def cli_log_status(path): """Inspect every CLI event, including child errors before parent success.""" terminal, refused = None, False for line in Path(path).read_text(encoding='utf-8', errors='replace').splitlines(): try: event = json.loads(line) except ValueError: continue refused = refused or cli_event_content_refusal(event) if isinstance(event, dict) and event.get('type') == 'result': terminal = event return terminal, refused
def png_metadata(path): with Path(path).open('rb') as f: header = f.read(33) if len(header) != 33 or header[:8] != b'\x89PNG\r\n\x1a\n' or header[12:16] != b'IHDR': raise ValueError('Invalid PNG IHDR') width, height, bits, color = struct.unpack('>IIBB', header[16:26]) result = {'format': 'PNG', 'width': width, 'height': height, 'bits_per_channel': bits, 'png_color_type': color, 'has_alpha_channel': color in (4, 6)} if color in (4, 6): try: from PIL import Image with Image.open(path) as image: # Pillow downconverts RGB(A)16 for display; alpha extrema here are # display-scale values, NOT a claim about native file bit depth. alpha = image.convert('RGBA').getchannel('A') lo, hi = alpha.getextrema() result['alpha_display_range_0_255'] = [lo, hi] result['has_visible_transparency'] = lo < 255 except (ImportError, OSError, ValueError) as exc: result['alpha_probe_error'] = type(exc).__name__ return result
def file_inventory(root): root = Path(root).resolve() rows = [] for folder in ('exports', 'output'): base = root / folder if not base.is_dir(): continue for path in sorted(base.rglob('*')): if not path.is_file() or not path.resolve().is_relative_to(root): continue row = {'path': str(path.relative_to(root)), 'bytes': path.stat().st_size, 'provenance': 'author_submission', 'suffix': path.suffix.lower()} try: if path.suffix.lower() == '.png': row.update(png_metadata(path)) elif path.suffix.lower() in ('.jpg', '.jpeg', '.webp'): from PIL import Image with Image.open(path) as im: row.update(format=im.format, width=im.width, height=im.height) except (ImportError, OSError, ValueError) as exc: row['metadata_error'] = type(exc).__name__ rows.append(row) return {'root': str(root), 'provenance': 'original files materialized from workspace_snapshot', 'file_count': len(rows), 'files': rows, 'note': 'Includes auxiliary textures and previews. Presence alone does not identify the final deliverable.'}
def polygon_area(points): if len(points) < 3: return 0.0 return abs(sum(a[0]*b[1]-b[0]*a[1] for a,b in zip(points, points[1:]+points[:1]))) * .5
def triangle_intersection_area(subject, triangle): def cross(a,b,c): return (b[0]-a[0])*(c[1]-a[1])-(b[1]-a[1])*(c[0]-a[0]) if cross(*triangle) < 0: triangle = triangle[::-1] output = list(subject) for a,b in zip(triangle, triangle[1:]+triangle[:1]): source, output = output, [] if not source: break prev = source[-1]; dp = cross(a,b,prev) for cur in source: dc = cross(a,b,cur) if (dp >= 0) != (dc >= 0): t = dp/(dp-dc) output.append((prev[0]+t*(cur[0]-prev[0]), prev[1]+t*(cur[1]-prev[1]))) if dc >= 0: output.append(cur) prev, dp = cur, dc return polygon_area(output)
def find_uv_overlap(triangles, max_pairs=2_000_000): """Positive-area overlap within one mesh; shared edges do not count.
A bounded sweep returns incomplete/unknown when its budget is exhausted; an incomplete scan must never be used to assert no overlap. """ boxes = [] degenerate = 0 for i,t in enumerate(triangles): if polygon_area(t) <= 1e-12: degenerate += 1 continue boxes.append((min(p[0] for p in t), max(p[0] for p in t), min(p[1] for p in t), max(p[1] for p in t), i)) boxes.sort() active = []; checked = 0 for box in boxes: xmin,xmax,ymin,ymax,i = box active = [b for b in active if b[1] > xmin] for b in active: checked += 1 if checked > max_pairs: return {'complete': False, 'overlap': None, 'pairs_checked': checked-1, 'reason': 'candidate pair budget exceeded', 'degenerate_triangles': degenerate} if b[3] <= ymin or ymax <= b[2]: continue area = triangle_intersection_area(triangles[b[4]], triangles[i]) if area > 1e-10: return {'complete': True, 'overlap': True, 'triangle_indices': [b[4],i], 'intersection_area': area, 'pairs_checked': checked, 'degenerate_triangles': degenerate} active.append(box) return {'complete': True, 'overlap': False, 'pairs_checked': checked, 'degenerate_triangles': degenerate}
def scene_facts(uv_layer=None): import bpy from mathutils import Vector scene = bpy.context.scene fps = scene.render.fps / scene.render.fps_base result = {'blender_version': bpy.app.version_string, 'blend_file': bpy.data.filepath, 'engine': scene.render.engine, 'effective_fps': fps, 'cameras': []} world = scene.rigidbody_world if world: result['rigid_body_world'] = { 'substeps_per_frame': world.substeps_per_frame, 'steps_per_second_at_scene_fps': world.substeps_per_frame * fps, 'solver_iterations': world.solver_iterations, 'time_scale': world.time_scale} for camera in (o for o in scene.objects if o.type == 'CAMERA'): direction = camera.matrix_world.to_quaternion() @ Vector((0,0,-1)) result['cameras'].append({'name': camera.name, 'active': camera == scene.camera, 'world_z': camera.matrix_world.translation.z, 'look_direction_world': list(direction), 'down_pitch_from_horizontal_degrees': math.degrees(math.atan2(-direction.z, math.hypot(direction.x,direction.y))), 'lens_mm': camera.data.lens, 'dof_enabled': camera.data.dof.use_dof, 'fstop': camera.data.dof.aperture_fstop}) if uv_layer: result['uv_checks'] = [] for obj in scene.objects: if obj.type != 'MESH': continue mesh = obj.data row = {'object': obj.name, 'collections': [c.name for c in obj.users_collection], 'hide_render': obj.hide_render, 'layer': uv_layer} uv = mesh.uv_layers.get(uv_layer) if uv is None: row.update(layer_present=False) else: mesh.calc_loop_triangles() triangles = [[tuple(uv.data[i].uv) for i in t.loops] for t in mesh.loop_triangles] row.update(layer_present=True, triangle_count=len(triangles), **find_uv_overlap(triangles)) result['uv_checks'].append(row) return result
def main(): parser = argparse.ArgumentParser() parser.add_argument('--inventory-root') parser.add_argument('--output', required=True) parser.add_argument('--uv-layer') argv = sys.argv[sys.argv.index('--')+1:] if '--' in sys.argv else sys.argv[1:] args = parser.parse_args(argv) data = file_inventory(args.inventory_root) if args.inventory_root else scene_facts(args.uv_layer) dest = Path(args.output); dest.parent.mkdir(parents=True, exist_ok=True) dest.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding='utf-8')
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878#!/usr/bin/env python3# -*- coding: utf-8 -*-"""Agent-as-Judge for Blender trajectory eval (runs in parallel with the GPT-5.6-terra vision judge).
Unlike ``judge_blender_binary_rubrics.py`` (a pure-vision pass that can only score what astatic render shows), this judge spawns a coding agent per task -- by default the sameGPT-5.6-terra model the render agent already uses, via the ``claude`` CLI pointed at theconfigured Anthropic-compatible endpoint -- that can OPEN THE SUBMITTED ``.blend`` WITH ``bpy``.This lets it verify rubrics whose ``evidence_type`` is ``scene_summary`` / ``either``(shape keys, drivers, Geometry-Nodes params, triangle budgets, UV layout, material nodegraphs, ``scene.unit_settings`` / ``render.engine`` / ``cycles.samples``, exact mmdimensions, physics setup) that the vision judge structurally cannot check, while stillusing the rendered PNGs for ``render``-type (visual) rubrics.
The agent emits, per rubric, two cross-check sub-verdicts (``bpy_check`` for the .blend internalsand ``visual_check`` for its own renders, each pass/fail/na) + method + evidence, and per dimension a1-10 impression plus a ``render_conflict`` flag. ALL scoring arithmetic (weighted rubric pass-rate,dimension score, the ``0.5*dim + 0.5*rubric`` fusion, and the uncapped fusion) is done herein Python, reusing the exact helpers from ``judge_blender_binary_rubrics.py``. Two worst-of-bothrules make the visible render authoritative: a rubric passes only if EVERY applicable sub-verdictpasses (so a correct bpy value cannot rescue a wrong-looking render), and any dimension the agentflags with ``render_conflict`` is clamped into the low band. Both are backward-compatible (agentoutputs lacking the new fields score exactly as before) and can be disabled via CLI. The top-levelper-task ``judgement.json`` and batch schema stay IDENTICAL to the vision judge (the new fields areadditive inside each ``rubric_scores``/``dimension_scores`` entry; the final per-rubric ``score`` isstill integer 0/1), so the Stage-7 aggregate in ``main.sh`` and downstream comparisons are unchanged.
Audit trail: the agent is required to persist ``agent_bpy_dump.json`` (the bpy query script+ its raw output) and ``agent_judgement_raw.json`` next to the judgement, so everyscene-metadata verdict is checkable after the fact."""
from __future__ import annotations
import argparseimport jsonimport osimport subprocessimport sysfrom concurrent.futures import ThreadPoolExecutor, as_completedfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any
# Reuse the vision judge's pure, model-agnostic helpers so the output schema and scoring# math stay bit-for-bit consistent between the two judges.from . import judge_blender_binary_rubrics as vjfrom . import evidence_checks
try: from json_repair import repair_jsonexcept Exception: # noqa: BLE001 def repair_json(s: str) -> str: return s
DEFAULT_OUTPUT_DIR = "evaluation/agent_judge_multiview_eval"DEFAULT_IMAGE_GLOB = "evaluation/multiview/*.png"RAW_NAME = "agent_judgement_raw.json"BPY_DUMP_NAME = "agent_bpy_dump.json"
# --------------------------------------------------------------------------------------# Agent output parsing# --------------------------------------------------------------------------------------def cli_api_error(path: Path) -> str: """Read the CLI's terminal API failure before attempting JSON output repair.""" if not path.exists(): return "" event, refused = evidence_checks.cli_log_status(path) if refused: return "agent_judge_upstream_content_policy_violation" if event: status = event.get("api_error_status") if event.get("is_error") is True and status: return f"agent judge API error {status}" return ""
def _coerce_binary(value: Any) -> int | None: if value in (0, "0", "0.0", False): return 0 if value in (1, "1", "1.0", True): return 1 return None
def _coerce_check(value: Any) -> str: """Normalize a per-rubric sub-verdict to ``pass`` / ``fail`` / ``na``.
Missing or unrecognized values collapse to ``na`` (not applicable), which makes the cross-check enforcement a no-op for that source and lets old outputs (with no ``bpy_check`` / ``visual_check`` keys) fall back to the model's self-reported ``score`` unchanged.""" if value is None: return "na" s = str(value).strip().lower() if s in ("pass", "passed", "ok", "yes", "true", "1", "1.0"): return "pass" if s in ("fail", "failed", "no", "false", "0", "0.0"): return "fail" return "na" # na / n/a / not_applicable / unknown / "" / anything else
def _truthy(value: Any) -> bool: """Loose truthiness for a model-emitted boolean flag (accepts true/1/yes/'true'...).""" if isinstance(value, bool): return value if value is None: return False if isinstance(value, (int, float)): return value != 0 return str(value).strip().lower() in ("true", "1", "1.0", "yes", "y")
def normalize_agent_rubrics( obj: dict[str, Any] | None, rubrics: list[dict[str, Any]], *, enforce_cross_check: bool = True,) -> tuple[bool, list[dict[str, Any]], str]: """Map the agent's per-rubric verdicts onto the canonical rubric_scores shape.
Mirrors ``vj.normalize_scores`` (id/score/evidence/source_views/confidence) and adds a ``method`` field (bpy|visual). Returns (ok, scores, error); ok is False if any rubric id is unanswered (build_score_summary still counts those as 0, matching the vision judge).
Cross-check enforcement (``enforce_cross_check``, default True): each verdict may carry two sub-verdicts, ``bpy_check`` (does the requirement hold in the .blend internals) and ``visual_check`` (does it hold in the agent's own renders), each ``pass``/``fail``/``na``. The final ``score`` is derived as 1 iff EVERY applicable (non-``na``) sub-verdict passes -- so a correct bpy value can never rescue a rubric whose render contradicts it (and vice-versa). When neither sub-verdict applies (both ``na``, or the keys are absent), we fall back to the model's self-reported ``score`` -- keeping old agent outputs bit-for-bit identical. The final ``score`` stays an integer 0/1 (relied on by ``vj.build_score_summary`` / ``vj.is_complete_judgement``); the sub-verdicts + ``model_score`` + ``cross_check_applied`` are stored as an audit trail.""" if not obj: return False, [], "agent output was not valid JSON" raw_scores = obj.get("rubric_scores") if not isinstance(raw_scores, list): return False, [], "missing rubric_scores list"
by_id: dict[str, dict[str, Any]] = {} for item in raw_scores: if not isinstance(item, dict): continue rid = str(item.get("id", "")).strip() if not rid: continue model_score = _coerce_binary(item.get("score")) bpy_check = _coerce_check(item.get("bpy_check")) visual_check = _coerce_check(item.get("visual_check")) applicable = [c for c in (bpy_check, visual_check) if c in ("pass", "fail")] if enforce_cross_check and applicable: score = 1 if all(c == "pass" for c in applicable) else 0 else: score = model_score if score is None: # No usable verdict (no valid score AND no applicable sub-check) -> treat as missing, # matching the pre-existing "score is None -> skip" behavior. continue by_id[rid] = { "id": rid, "score": score, "evidence": str(item.get("evidence", "")).strip(), "method": str(item.get("method", "")).strip() or "unknown", "bpy_check": bpy_check, "visual_check": visual_check, "model_score": model_score, "cross_check_applied": bool(applicable) and model_score is not None and score != model_score, "source_views": item.get("source_views") if isinstance(item.get("source_views"), list) else [], "confidence": str(item.get("confidence", "medium")).strip() or "medium", }
normalized: list[dict[str, Any]] = [] missing: list[str] = [] for rubric in rubrics: rid = str(rubric.get("id", "")).strip() if rid in by_id: normalized.append(by_id[rid]) else: missing.append(rid) if missing: return False, normalized, f"missing scores for ids: {missing[:10]}" return True, normalized, ""
def finalize_judgement( task_dir: Path, rubrics: list[dict[str, Any]], raw_obj: dict[str, Any] | None, cfg: dict[str, Any], *, render_images: list[Path] | None = None, extra_images: list[Path] | None = None, reference_images: list[Path] | None = None, extra_meta: dict[str, Any] | None = None,) -> dict[str, Any]: """Compute the canonical judgement object from the agent's raw verdicts.
Pure/deterministic given ``raw_obj``: reuses ``vj.build_score_summary`` / ``vj.score_dimensions`` and the same uncapped fusion logic as the vision judge (``judge_blender_binary_rubrics.py`` ~1636-1662). Unit-testable without spawning an agent.""" render_images = render_images or [] extra_images = extra_images or [] reference_images = reference_images or [] images = render_images + extra_images
ok, scores, error = normalize_agent_rubrics( raw_obj, rubrics, enforce_cross_check=bool(cfg.get("cross_check", True)) ) total = sum(item["score"] for item in scores) max_score = len(rubrics) score_summary = vj.build_score_summary(rubrics, scores)
rubric_score_0_100 = score_summary["weighted_score_0_100"] dim_result = vj.score_dimensions(raw_obj, vj.DIMENSIONS) if cfg.get("dimension_pass", True) else None if cfg.get("dimension_pass", True) and (not dim_result or not dim_result["ok"]): ok = False error = "; ".join(x for x in [error, "dimension judge failed"] if x)
# Worst-of-both for the 1-10 dimensions: if the agent flagged a dimension's .blend internals as # looking correct/better than what its renders actually show (`render_conflict`), the visible # result governs -- clamp that dimension into the low band. This mirrors the rubric cross-check # and runs before score fusion. The routed public protocol uses the VLM for dimensions. dim_conflict_cap = cfg.get("dimension_conflict_cap") if dim_result and dim_result.get("ok") and dim_conflict_cap is not None: raw_dims = (raw_obj or {}).get("dimensions") conflict_ids = { str(d.get("id", "")).strip() for d in (raw_dims if isinstance(raw_dims, list) else []) if isinstance(d, dict) and _truthy(d.get("render_conflict")) } conflict_ids.discard("") capped_any = False for row in dim_result.get("dimension_scores", []): if str(row.get("id", "")).strip() in conflict_ids: row["render_conflict"] = True if int(row.get("score", 0)) > dim_conflict_cap: row["original_score"] = row.get("score") row["score"] = dim_conflict_cap issues = row.get("issues") if not isinstance(issues, list): issues = [] issues.append( f"render conflicts with .blend internals; capped to <= {dim_conflict_cap}" ) row["issues"] = issues capped_any = True if capped_any: denom = 10 * len(vj.DIMENSIONS) total_dim = sum(int(r.get("score", 0)) for r in dim_result["dimension_scores"]) dim_result["dimension_score_0_100"] = (100.0 * total_dim / denom) if denom else 0.0
w = float(cfg.get("dimension_weight", 0.5)) if dim_result and dim_result["ok"]: dimension_score_0_100 = dim_result["dimension_score_0_100"] fused_score_0_100 = w * dimension_score_0_100 + (1.0 - w) * rubric_score_0_100 else: dimension_score_0_100 = None fused_score_0_100 = rubric_score_0_100 # fall back to rubric-only
cap_applied = False cap_reason = ""
obj: dict[str, Any] = { "created_at": datetime.now(timezone.utc).isoformat(), "task_dir": str(task_dir), "judge_kind": "agent", "model": cfg.get("model", ""), "reference_image_files": [vj.rel(p, task_dir) for p in reference_images], "image_files": [vj.rel(p, task_dir) for p in images], "rendered_image_files": [vj.rel(p, task_dir) for p in render_images], "extra_image_files": [vj.rel(p, task_dir) for p in extra_images], "rubric_count": len(rubrics), "score": total, "max_score": max_score, "normalized_score": (total / max_score) if max_score else 0.0, "raw_pass": score_summary["raw_pass"], "raw_total": score_summary["raw_total"], "raw_score_0_100": score_summary["raw_score_0_100"], "weighted_pass": score_summary["weighted_pass"], "weighted_total": score_summary["weighted_total"], "weighted_score_0_100": score_summary["weighted_score_0_100"], "score_summary": score_summary, "passed_count": total, "failed_count": max_score - total, "rubric_scores": scores, "overall_notes": str((raw_obj or {}).get("overall_notes", "")).strip(), # the agent judge does not run a separate blind pass "blind_pass": False, "blind_description": None, "blind_reference_description": None, "rubric_batch_size": 0, "rubric_chunk_count": 1, # --- holistic dimension scoring + fusion --- "dimension_pass": bool(cfg.get("dimension_pass", True)), "dimension_weight": w, "rubric_score_0_100": rubric_score_0_100, "dimension_score_0_100": dimension_score_0_100, "fused_score_0_100": fused_score_0_100, "cap_applied": cap_applied, "cap_reason": cap_reason, "dimension_scores": (dim_result or {}).get("dimension_scores", []), "core_objects_recognizable": (dim_result or {}).get("core_objects_recognizable"), "catastrophic_failure": (dim_result or {}).get("catastrophic_failure"), "dimension_missing": (dim_result or {}).get("missing_dimensions", []), "dimension_notes": str((raw_obj or {}).get("dimension_notes", (raw_obj or {}).get("overall_notes", ""))).strip(), "ok": ok, } if dim_result and not dim_result["ok"]: obj["dimension_error"] = dim_result.get("error", "") if not ok: obj["error"] = error if extra_meta: obj.update(extra_meta) if obj.get("agent_error"): obj["ok"] = False obj["error"] = obj["agent_error"] return obj
# --------------------------------------------------------------------------------------# Agent prompt + invocation# --------------------------------------------------------------------------------------def render_rubrics_for_agent(rubrics: list[dict[str, Any]]) -> str: lines = [] for item in rubrics: lines.append( json.dumps( { "id": item.get("id"), "category": item.get("category") or item.get("category_v2"), "evidence_type": item.get("evidence_type"), "criterion": item.get("criterion"), "pass_condition": item.get("pass_condition"), "fail_condition": item.get("fail_condition"), }, ensure_ascii=False, ) ) return "\n".join(lines)
def build_prompt( task_dir: Path, prompt_text: str, rubrics: list[dict[str, Any]], *, blend_files: list[Path], render_images: list[Path], extra_images: list[Path], reference_images: list[Path], blender_bin: str, output_rel: str, use_bpy: bool, render_required: bool = True,) -> str: def rels(paths: list[Path]) -> str: return "\n".join(f" - {vj.rel(p, task_dir)}" for p in paths) or " (none)"
inventory = evidence_checks.file_inventory(task_dir / ".eval_workspace") inventory_path = task_dir / output_rel / "submission_manifest.json" inventory_path.parent.mkdir(parents=True, exist_ok=True) inventory_path.write_text(json.dumps(inventory, ensure_ascii=False, indent=2), encoding="utf-8") # The full deterministic manifest stays available even for long sequences. inventory_preview = json.dumps({**inventory, "files": inventory["files"][:80]}, ensure_ascii=False) checks_script = str(Path(evidence_checks.__file__).resolve()) dims = "\n".join(f" - {d['id']}: {d['name']} — {d['desc']}" for d in vj.DIMENSIONS) raw_rel = f"{output_rel}/{RAW_NAME}" bpy_rel = f"{output_rel}/{BPY_DUMP_NAME}" renders_rel = f"{output_rel}/agent_renders"
# RENDERING POLICY (both modes): rendering is expensive and, in this headless GPU container, # EEVEE/Workbench silently degrade or fail — any scoring render MUST go through Cycles. When # render_required is False (evidence routing: this agent only owns structural / scene_summary # rubrics decided from the .blend internals) the agent should NOT render unless a specific # rubric genuinely cannot be settled from bpy. cycles_rule = ( "Whenever you render, you MUST use Cycles — never EEVEE/Workbench, which are unreliable " "headless here and degrade quality. In your render script set " "`scene.render.engine='CYCLES'`, select the GPU " "(`bpy.context.preferences.addons['cycles'].preferences.compute_device_type='OPTIX'` or " "`'CUDA'`, refresh devices, enable them, then `scene.cycles.device='GPU'`), and use enough " "samples (>=64) so the image is not noisy. Confirm the engine is actually CYCLES before " "trusting a render." ) export_scan_rule = ( "When a rubric concerns an EXPORTED deliverable (a PNG image, a rendered still, an " "animation/video such as .mp4/.mov/.gif/.webm, or a baked texture), verify its existence " "by scanning the WHOLE submission export tree — check `exports/`, `output/`, `renders/`, " "and the submission root recursively (e.g. `find . -type f \\( -iname '*.png' -o -iname " "'*.mp4' -o -iname '*.mov' -o -iname '*.gif' -o -iname '*.webm' \\)`). Do NOT assume one " "fixed folder; score such a rubric on whether the file actually exists somewhere under the " "export paths." ) if render_required: render_intro = ( "Author-delivered images are listed below. To judge any appearance/visual " "rubric inspect the relevant author file, or render targeted scene evidence in STEP 3 when needed. If you " "have neither inspected a relevant author image nor produced a relevant render, do not pass a visual rubric. " + cycles_rule ) step3 = ( "STEP 3 — Render MULTIPLE targeted images yourself, GUIDED by the rubric + prompt + " "dimensions. " + cycles_rule + " Open a COPY of the .blend and render as many views as " "you need — an overview PLUS the specific angles, close-ups and framings that expose what " "the rubrics and each dimension actually check (e.g. a close-up on a part a rubric names; " "an angle showing support/contact for `physics`; a wide shot for " "`layout_spatial`/`completeness`; a material close-up for `lighting_material`/`style_color`). " "You may adjust temporary cameras in your COPY. Preserve geometry, materials, lights, animation, visibility and color management. Save all images to " + renders_rel + "/ with descriptive names and note what each one shows." ) else: render_intro = ( "You are scoring STRUCTURAL / scene_summary rubrics that are decided from the .blend " "INTERNALS via bpy, NOT from appearance. You normally do NOT need to render anything, and " "you should NOT re-render unless a specific rubric genuinely cannot be settled from the " ".blend internals. " + cycles_rule ) step3 = ( "STEP 3 — Rendering is OPTIONAL for these rubrics and usually unnecessary. Do NOT render " "just to have an image. Render your OWN image(s) into " + renders_rel + "/ ONLY if a " "specific rubric truly requires visual confirmation that bpy cannot give; if you do, " + cycles_rule + " Preserve geometry, materials, lights, animation, visibility and color management. If no rubric needs a render, skip this step entirely (that is expected " "and not an error)." )
return f"""You are an AGENT-AS-JUDGE for a Blender scene-reconstruction benchmark. You are NOT solvingthe task. You SCORE an already-submitted result (a .blend) against a fixed rubric list and a set ofholistic dimensions. Unlike an image-only judge you can (a) open the submitted .blend to inspect the"original code" — its objects, modifiers, geometry-node graphs, shape keys, drivers, materials, scenesettings, and any embedded text/script data-blocks — AND (b) render your OWN targeted images from it.
# Task prompt given to the solver (the TARGET; the submission is what you judge){prompt_text}
# Submitted artifacts (paths relative to your working directory)Submitted .blend file(s) — the "original code" (READ-ONLY: work on a COPY; never edit/re-save the original):{rels(blend_files)}Reference / target image(s) (the goal; do NOT credit the submission for something only here):{rels(reference_images)}Author-delivered images already discovered (these are original files, not your renders):{rels(extra_images)}Original file inventory (first 80 records; includes PNG IHDR bit depth):{inventory_preview}Read the FULL inventory at `{vj.rel(inventory_path, task_dir)}` when needed. Inspect the whole `.eval_workspace/` tree, including root-level exports, nested frame sequences, FBX/EXR and accompanying textures. A configured absolute output path in the .blend may be stale: it is not evidence that a delivered file is absent. Do not count evaluator renders, input references or sampled video frames as author-delivered files. The hashes of supplied inputs are listed in `input_media_sha256.json` when present.Blender executable: {blender_bin}Read-only evidence helper: `{checks_script}`To inspect camera optics and rigid-body units, run the original file with autoexec disabled:`{blender_bin} --background <original.blend> --disable-autoexec --python {checks_script} -- --output <probe.json>`For a second-UV non-overlap condition add `--uv-layer <actual-layer-name>`. Inspect the relevant low-poly meshes; an incomplete scan is unknown, never proof of no overlap. The helper checks original mesh UVs; inspect evaluated geometry too when modifiers generate or alter the deliverable UVs.
{render_intro}
Work in this EXACT order:
STEP 1 — Plan. Read the task prompt above, EVERY rubric below (note each rubric's `evidence_type`),and the {len(vj.DIMENSIONS)} holistic dimensions with their descriptions. Decide which scene facts toextract from the .blend and which views / close-ups / angles will best reveal the rubric criteria andeach dimension.
STEP 2 — Inspect the .blend internals (the "original code") with bpy. Run Blender headless(`{blender_bin} --background <copy-of-blend> --python /tmp/probe.py`) to extract exactly what therubrics/dimensions need: object list & names, mesh triangle counts, modifiers / Geometry-Nodesnode-group inputs & values, shape-key/blendshape names & counts, drivers, object bounding-boxdimensions (mm), scene unit settings (`scene.unit_settings`), render engine/samples/resolution,material node graphs (Principled/SSS/IOR), UV layout & overlap, physics / rigid-body / Dynamic-Paintsettings, collections, and any embedded Text data-blocks (scripts). Save your probe script + rawoutput to `{bpy_rel}` (JSON) as an audit trail. DO NOT modify or re-save the original .blend.{export_scan_rule}
Evidence rules:- PNG bit depth comes from the original PNG IHDR, not Pillow's RGB/RGBA mode; Pillow commonly presents 16-bit RGB files as RGB. Use the manifest or evidence helper.- For alpha, inspect the actual channel and composite over a checkerboard. A black-looking RGB preview neither proves nor disproves transparency. Validate silhouettes in the actual alpha image.- Convert rigid-body substeps_per_frame using effective fps = fps/fps_base. For example, 10 substeps/frame at 24 fps equals 240 steps/second; record time_scale separately. Do not compare different units directly.- Camera downward pitch is measured from the world optical axis (local -Z) to the horizontal plane, not from Euler X. Euler X about 65 degrees can correspond to downward pitch about 25 degrees.- UV layer names do not prove non-overlap. Check positive-area triangle intersections within the requested layer, allowing shared boundaries. Check actual coordinates, not beauty renders or labels.- Preserve the original .blend as the source of settings. If using a copy for rendering, do not report changed render/world settings as original facts.- Final-image composition, focus, noise and required deliverable appearance must be checked against the designated author final file. Previews or your rerenders cannot replace that file. Scene existence/geometry can use targeted views.- Exact numerical facts, metadata and UV tests are structural checks: use visual_check=na where pixels cannot establish the numeric fact. A dimension that looks plausible is not an independent numeric measurement.
{step3}
STEP 4 — Score EVERY rubric by CROSS-CHECKING both evidence sources. Do NOT pick a single method andstop. For each rubric produce TWO independent sub-verdicts, each `pass` / `fail` / `na`:- `bpy_check`: does the requirement hold in the .blend INTERNALS (bpy)? Use `na` ONLY when the rubric has no structural/internal aspect (e.g. "reads as a real chair" — a purely visual judgment).- `visual_check`: does the requirement hold in YOUR rendered images? Use `na` ONLY when it is genuinely invisible in any render you could make (e.g. triangle-count / UV-overlap / a driver).At least one sub-verdict must be non-`na`. Whenever BOTH apply — colour, material, a part beingpresent AND correctly shaped, a dimension that is visible, layout — you MUST fill BOTH, and the rubricpasses ONLY if BOTH pass.
THE VISIBLE RENDER IS GROUND TRUTH for appearance. A correct internal value NEVER rescues a wrongappearance, and vice-versa. Concretely: if the Principled BSDF base colour is red in the node graph(`bpy_check`="pass") but the object renders grey/wrong (`visual_check`="fail"), the rubric FAILS —because the material is on the wrong slot, unassigned to the visible faces, overridden by emission /vertex colour, or the UVs are broken. Any such mismatch is a FAIL, not a pass.
Set the final `score`: 1 only if EVERY applicable (non-`na`) sub-verdict is `pass`, otherwise 0 (theharness re-derives this from your sub-verdicts, so make them consistent). Score what is ACTUALLYpresent in the submission (.blend + your renders), never what the prompt merely asked for. If trulyunverifiable even with bpy + targeted renders, score 0 and say why. Also set `method`="bpy" or"visual" for the source that was decisive, and give a short concrete `evidence` string that cites thebpy fact AND/OR the render file for each sub-verdict you made.
RUBRICS (one JSON object per line):{render_rubrics_for_agent(rubrics)}
STEP 5 — Rate these {len(vj.DIMENSIONS)} dimensions as integers 1-10, scored by WHAT THE RENDERVISIBLY ACHIEVES. The .blend internals may only CONFIRM or LOWER a dimension — a correct internalvalue can NEVER raise a dimension above the visible result. Be strict & calibrated: 9-10 only foressentially faithful results; 7-8 good with minor issues; 5-6 clear problems; 3-4 major failures;1-2 absent/broken. Do NOT cluster at 7-8. Each dimension needs concrete `reasons` (cite views) + an`issues` list.{dims}For EACH dimension also set a boolean `render_conflict`: true when the .blend internals lookcorrect/better than what the renders actually show, or the two disagree (e.g. materials/colours/partsthat are right in bpy but wrong or missing on screen). When `render_conflict` is true you MUST putthat dimension in the LOW band (the visible result governs; the harness additionally clamps suchdimensions).Also two booleans: `core_objects_recognizable` (main requested objects independently recognizable) and`catastrophic_failure` (scene fundamentally fails / unusable as requested).
STEP 6 — Write your verdict as a single JSON object to `{raw_rel}` (create the folder if needed),EXACTLY this shape and nothing else in the file:{{ "rubric_scores": [ {{"id": "R01", "score": 0 or 1, "bpy_check": "pass"/"fail"/"na", "visual_check": "pass"/"fail"/"na", "method": "bpy" or "visual", "evidence": "short reason"}} // one entry per rubric id above, all of them ], "dimensions": [ {{"id": "scene_fidelity", "score": 1-10, "render_conflict": true or false, "reasons": "...", "issues": ["..."]}} // one entry per dimension id above, all of them ], "core_objects_recognizable": true or false, "catastrophic_failure": true or false, "overall_notes": "short summary of the main strengths and failures"}}
Rules: include every rubric id and every dimension id exactly once; integer scores; each rubric's`score` must equal 1 iff every applicable (non-`na`) sub-verdict is `pass`; valid JSON (no trailingcommas/comments). When `{raw_rel}` is written you are done."""
def retry_preface(attempt: int, max_attempts: int, raw_rel: str, reason: str) -> str: """Preface prepended to the judge prompt on a retry.
Instead of silently dropping a non-conforming agent judgement to the VLM the moment it fails to parse, we re-tell the agent exactly why its previous ``agent_judgement_raw.json`` was rejected and ask it to re-emit a complete, valid JSON verdict.""" return ( f"RETRY {attempt}/{max_attempts}: your previous write to `{raw_rel}` was REJECTED because: " f"{reason}. Common causes: the file was not valid JSON, or some rubric ids were " f"missing/duplicated. Re-read EVERY rubric id listed below and re-emit the COMPLETE JSON " f"object exactly per the STEP 6 shape — include every rubric id and every dimension id " f"exactly once, integer scores, valid JSON only (no comments / no trailing commas), and " f"nothing else in the file. Overwrite `{raw_rel}` with the corrected JSON.\n\n" )
def run_one_task(result: dict[str, Any], cfg: dict[str, Any]) -> dict[str, Any] | None: task_dir = Path(str(result.get("task_dir") or "")).expanduser() rubrics = result.get("rubrics") or [] tname = task_dir.name # Under evidence_type routing this judge only scores a subset (e.g. scene_summary). Filter # immediately so is_complete/normalize/finalize all key off the same subset id-set, and the # VLM judge owns the rest. Empty set = score every rubric (legacy behavior). ev_types = cfg.get("agent_evidence_types") or set() if ev_types: rubrics = [r for r in rubrics if str(r.get("evidence_type") or "").strip().lower() in ev_types] if not rubrics: vj.log.info("[agent-judge] skip %s: no rubrics with evidence_type in %s", tname, sorted(ev_types)) return None if not task_dir.is_dir(): return {"task_dir": str(task_dir), "ok": False, "error": "task_dir not found", "rubric_scores": []} if not rubrics: return {"task_dir": str(task_dir), "ok": False, "error": "no rubrics", "rubric_scores": []}
out_path = vj.output_path(task_dir, cfg["output_dir"]) rubric_ids = {str(r.get("id")) for r in rubrics} if not cfg["overwrite"] and vj.is_complete_judgement(out_path, rubric_ids): vj.log.info("[agent-judge] skip complete %s", tname) return json.loads(out_path.read_text(encoding="utf-8"))
render_images = vj.find_render_images(task_dir, cfg["image_glob"], cfg["max_images"]) extra_images = vj.find_extra_submission_images(task_dir, cfg["extra_image_globs"], cfg["max_extra_images"]) reference_images = ( [] if cfg["no_reference_images"] else vj.find_reference_images(task_dir, cfg["reference_image_glob"], cfg["max_reference_images"]) ) # The public submission contract names the primary project explicitly. primary_project = task_dir / ".eval_workspace" / "final.blend" blend_files = [primary_project] if primary_project.is_file() else []
output_rel = Path(cfg["output_dir"]) output_rel = output_rel if not output_rel.is_absolute() else Path(tname) output_rel_str = output_rel.as_posix() (task_dir / output_rel).mkdir(parents=True, exist_ok=True) raw_path = task_dir / output_rel / RAW_NAME if cfg["overwrite"] and raw_path.exists(): raw_path.unlink()
# Renders are required only when this judge owns visual rubrics. Under evidence routing it owns # only scene_summary (structural, decided from bpy) → do NOT force a render (that render is # wasteful and, if it fails headless, would falsely error the whole scene_summary verdict). render_required = (not ev_types) or bool(ev_types & {"either", "render", "visual", "image"}) prompt = build_prompt( task_dir, str(result.get("prompt", "")), rubrics, blend_files=blend_files, render_images=render_images, extra_images=extra_images, reference_images=reference_images, blender_bin=cfg["blender_bin"], output_rel=output_rel_str, use_bpy=cfg["use_bpy"] and bool(blend_files), render_required=render_required, )
base_prompt = prompt raw_rel = f"{output_rel_str}/{RAW_NAME}" max_attempts = max(1, int(cfg.get("max_attempts", 3))) returncode: int | None = None agent_error = "" raw_obj: dict[str, Any] | None = None attempts_used = 0 last_reason = "" stdout_rel = f"{output_rel_str}/agent_judge_stdout.jsonl"
if cfg["dry_run"]: (task_dir / output_rel / "agent_judge_prompt.txt").write_text(base_prompt, encoding="utf-8") else: # Instead of dropping non-conforming agent output straight to the VLM, re-prompt the agent # with what was wrong and let it re-score, up to max_attempts. Only JSON-conformance misses # are retried; a timeout / missing-claude / spawn error is infrastructure, not the agent's # scoring, so we stop and let the VLM fallback (load_agent_verdicts guard) handle it. for attempt in range(1, max_attempts + 1): attempts_used = attempt if attempt == 1: prompt_n = base_prompt stdout_rel = f"{output_rel_str}/agent_judge_stdout.jsonl" else: prompt_n = retry_preface(attempt, max_attempts, raw_rel, last_reason) + base_prompt stdout_rel = f"{output_rel_str}/agent_judge_stdout.attempt{attempt}.jsonl" if raw_path.exists(): raw_path.unlink() # drop the previous bad file so it can't be misread as success cmd = [ "claude", "--verbose", "--max-turns", str(cfg["max_turns"]), "--output-format", "stream-json", "--allowedTools", "Bash", "Read", "Write", "Edit", "Glob", "Grep", "LS", "--disallowedTools", "WebFetch", "WebSearch", "-p", prompt_n, ] env = os.environ.copy() env["ANTHROPIC_BASE_URL"] = cfg["anthropic_base_url"] env.setdefault("ANTHROPIC_API_KEY", cfg["anthropic_api_key"]) env.setdefault("ANTHROPIC_AUTH_TOKEN", "") if cfg["model"]: env["ANTHROPIC_MODEL"] = cfg["model"] agent_error = "" try: with (task_dir / stdout_rel).open("w", encoding="utf-8") as stdout: completed = subprocess.run( cmd, cwd=str(task_dir), env=env, stdout=stdout, stderr=subprocess.STDOUT, text=True, timeout=cfg["timeout"], check=False, ) returncode = completed.returncode except subprocess.TimeoutExpired: returncode = 124 agent_error = f"agent judge timed out after {cfg['timeout']}s" except FileNotFoundError: returncode = 127 agent_error = "claude command not found" except Exception as exc: # noqa: BLE001 returncode = 1 agent_error = repr(exc)
# A terminal API failure is not a malformed judgement. In particular, an explicit # content refusal must stop here, without a JSON repair retry or VLM fallback. agent_error = agent_error or cli_api_error(task_dir / stdout_rel) if agent_error: break
# Parse this attempt's raw output (with json_repair fallback). raw_obj = None if raw_path.exists(): try: text = raw_path.read_text(encoding="utf-8") try: raw_obj = json.loads(text) except Exception: # noqa: BLE001 raw_obj = json.loads(repair_json(text)) except Exception as exc: # noqa: BLE001 raw_obj = None last_reason = f"could not parse {RAW_NAME}: {exc!r}" else: last_reason = f"agent did not write {RAW_NAME}"
# Conformance probe (reuses the same normalization finalize will apply): ok iff valid # JSON with a score for every rubric id. if raw_obj is not None: probe_ok, _, probe_reason = normalize_agent_rubrics( raw_obj, rubrics, enforce_cross_check=bool(cfg.get("cross_check", True)) ) if probe_ok: break # valid, complete scoring — done last_reason = probe_reason or "agent scoring incomplete"
if attempt < max_attempts: vj.log.info( "[agent-judge] task=%s attempt=%d/%d invalid (%s) — retrying", tname, attempt, max_attempts, last_reason, ) continue # Attempts exhausted, still non-conforming: flag the error so finalize records it and # load_agent_verdicts' guard falls back to VLM (the last resort). agent_error = f"agent output invalid after {max_attempts} attempts: {last_reason}"
# Enforce a self-render ONLY when this judge owns visual rubrics (render_required). Under # evidence routing it scores structural / scene_summary rubrics from bpy, so an empty # agent_renders/ is expected and must NOT be treated as an error. renders_dir = task_dir / output_rel / "agent_renders" agent_render_count = len(list(renders_dir.glob("*.png"))) if renders_dir.exists() else 0 if render_required and agent_render_count == 0 and not agent_error: agent_error = "agent produced no self-rendered images (agent_renders/ empty) — visual rubrics unverified"
extra_meta = { "agent_returncode": returncode, "agent_stdout_path": stdout_rel, "agent_raw_path": f"{output_rel_str}/{RAW_NAME}", "bpy_dump_path": f"{output_rel_str}/{BPY_DUMP_NAME}", "agent_renders_path": f"{output_rel_str}/agent_renders", "agent_render_count": agent_render_count, "agent_attempts": attempts_used, } if agent_error: extra_meta["agent_error"] = agent_error
obj = finalize_judgement( task_dir, rubrics, raw_obj, cfg, render_images=render_images, extra_images=extra_images, reference_images=reference_images, extra_meta=extra_meta, ) obj["output_path"] = str(out_path) vj.atomic_write_json(out_path, obj) vj.log.info( "[agent-judge] task=%s ok=%s fused=%.1f rubric=%.1f dim=%s self_renders=%d attempts=%d rc=%s", tname, obj.get("ok"), obj.get("fused_score_0_100") or 0.0, obj.get("weighted_score_0_100") or 0.0, obj.get("dimension_score_0_100"), agent_render_count, attempts_used, returncode, ) return obj
def parse_args() -> argparse.Namespace: p = argparse.ArgumentParser(description="Agent-as-Judge for Blender trajectory eval") p.add_argument("--rubrics-batch", required=True) p.add_argument("--output-dir", default=DEFAULT_OUTPUT_DIR) p.add_argument("--batch-output", default="") p.add_argument("--image-glob", default=DEFAULT_IMAGE_GLOB) p.add_argument("--extra-image-glob", action="append", default=[]) p.add_argument("--reference-image-glob", default="**/image_assets/*") p.add_argument("--no-reference-images", action="store_true") p.add_argument("--max-images", type=int, default=8) p.add_argument("--max-extra-images", type=int, default=4) p.add_argument("--max-reference-images", type=int, default=4) p.add_argument("--model", default=os.environ.get("AGENT_JUDGE_MODEL") or os.environ.get("MODEL", "")) p.add_argument("--max-turns", type=int, default=int(os.environ.get("AGENT_JUDGE_MAX_TURNS", "500"))) p.add_argument( "--max-attempts", type=int, default=int(os.environ.get("AGENT_JUDGE_MAX_ATTEMPTS", "3")), help="Max agent-judge attempts per task. When the agent produces non-conforming JSON " "(missing file / unparseable / missing rubric ids), it is re-prompted to re-score " "up to this many times before the VLM fallback is used as a last resort.", ) p.add_argument("--timeout", type=int, default=int(os.environ.get("AGENT_JUDGE_TIMEOUT", "14400"))) p.add_argument("--task-concurrency", type=int, default=int(os.environ.get("AGENT_JUDGE_TASK_CONCURRENCY", "2"))) p.add_argument("--dimension-weight", type=float, default=0.5) p.add_argument("--no-dimension-pass", action="store_true") p.add_argument("--dimension-conflict-cap", type=int, default=4, help="Clamp any dimension the agent flags with render_conflict=true to <= this " "1-10 value (worst-of-both; the visible render governs). Default 4.") p.add_argument("--no-dimension-conflict-cap", action="store_true", help="Disable the render_conflict dimension clamp.") p.add_argument("--no-rubric-cross-check", action="store_true", help="Disable conjunctive rubric scoring; fall back to the model's self-reported " "0/1 score (ignore bpy_check/visual_check).") p.add_argument("--blender-bin", default=os.environ.get("BLENDER_BIN", "blender")) p.add_argument("--no-bpy", action="store_true") p.add_argument("--anthropic-base-url", default=os.environ.get("ANTHROPIC_BASE_URL", "https://api.anthropic.com")) p.add_argument("--anthropic-api-key", default=os.environ.get("ANTHROPIC_API_KEY", "")) p.add_argument("--limit", type=int, default=0) p.add_argument("--overwrite", action="store_true") p.add_argument("--dry-run", action="store_true") p.add_argument( "--agent-evidence-types", default="", help=( "Comma list of evidence_type values this agent judge should score. Empty (default) " "means score every rubric (legacy behavior). Under evidence_type routing set this to " "'scene_summary' so the agent only judges those rubrics and the VLM handles the rest." ), ) return p.parse_args()
def main() -> int: args = parse_args() rubrics_batch = Path(args.rubrics_batch) results = vj.load_rubric_results(rubrics_batch) if args.limit > 0: results = results[: args.limit]
extra_globs = args.extra_image_glob or list(vj.DEFAULT_EXTRA_IMAGE_GLOBS) cfg = { "output_dir": args.output_dir, "image_glob": args.image_glob, "extra_image_globs": extra_globs, "reference_image_glob": args.reference_image_glob, "no_reference_images": args.no_reference_images, "max_images": args.max_images, "max_extra_images": args.max_extra_images, "max_reference_images": args.max_reference_images, "model": args.model, "max_turns": args.max_turns, "max_attempts": args.max_attempts, "timeout": args.timeout, "dimension_weight": args.dimension_weight, "dimension_pass": not args.no_dimension_pass, "dimension_conflict_cap": None if args.no_dimension_conflict_cap else args.dimension_conflict_cap, "cross_check": not args.no_rubric_cross_check, "blender_bin": args.blender_bin, "use_bpy": not args.no_bpy, "anthropic_base_url": args.anthropic_base_url, "anthropic_api_key": args.anthropic_api_key, "overwrite": args.overwrite, "dry_run": args.dry_run, "agent_evidence_types": vj.parse_type_set(args.agent_evidence_types), }
outputs: list[dict[str, Any]] = [] workers = max(1, int(args.task_concurrency)) if workers == 1: for result in results: out = run_one_task(result, cfg) if out is not None: outputs.append(out) else: with ThreadPoolExecutor(max_workers=workers) as pool: futures = {pool.submit(run_one_task, result, cfg): result for result in results} for fut in as_completed(futures): try: out = fut.result() except Exception as exc: # noqa: BLE001 r = futures[fut] out = {"task_dir": str(r.get("task_dir")), "ok": False, "error": repr(exc), "rubric_scores": []} if out is not None: outputs.append(out)
outputs.sort(key=lambda o: str(o.get("task_dir"))) batch_output = Path(args.batch_output) if args.batch_output else rubrics_batch.parent / "judge_agent_batch.json" ok_count = sum(1 for item in outputs if item.get("ok")) batch = { "created_at": datetime.now(timezone.utc).isoformat(), "rubrics_batch": str(rubrics_batch), "model": args.model, "judge_kind": "agent", "task_count": len(outputs), "ok_count": ok_count, "score_summary": vj.build_batch_score_summary(outputs), "results": outputs, } vj.atomic_write_json(batch_output, batch) vj.log.info("[agent-judge] wrote batch %s ok=%d/%d", batch_output, ok_count, len(outputs)) return 0 if ok_count == len(outputs) else 2
if __name__ == "__main__": sys.exit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205"""Export the frozen dataset as self-contained Harbor task packages."""from __future__ import annotations
import jsonimport importlib.metadataimport reimport shutilfrom pathlib import Path
from .data import RESOURCE_FIELDS, load_tasks, prepare, resolve, sha256, verify, write_jsonfrom .evaluation import PROTOCOLfrom . import __version__from .runtime import RUNTIME_VERSIONS, requirementsfrom .submissions import FORMAT, PROJECT
HARBOR_VERSION = "0.23.0"ASSETS = Path(__file__).with_name("harbor_assets")
def _harbor(): try: from harbor.models.dataset.manifest import DatasetManifest from harbor.models.task.task import Task from harbor.publisher.packager import Packager except ImportError as error: raise RuntimeError("Harbor export requires Python 3.12+ and pip install 'blenderworld[harbor]'") from error if importlib.metadata.version("harbor") != HARBOR_VERSION: raise RuntimeError(f"This exporter is validated with harbor=={HARBOR_VERSION}; install the pinned harbor extra") return DatasetManifest, Task, Packager
def _instruction(row): resources = [] for field in ("reference_images", "reference_videos", "attachments"): for entry in row[field]: resources.append(f"- `{field}`: `/workspace/inputs/{entry['task_relative_path']}`") return (f"# BlenderWorld {row['task_id']}\n\n" "## Task\n\n" + row["query"] + "\n\n" "## Inputs\n\nThe original request is also in `/workspace/inputs/query.txt`.\n\n" + ("\n".join(resources) if resources else "This task has no reference media or declared attachments.") + "\n\nRead the supplied specifications and inspect the reference media before modeling. " "Relative filenames in the request refer to the files listed above.\n\n" "## Deliverables\n\nSave the editable project as `/workspace/exports/final.blend`. " "Put all requested images, videos, model exports, and texture dependencies under " "`/workspace/exports/`. Pack textures into the project or keep relative paths inside " "this directory so the project can be opened in a fresh environment.\n\n" "## Tools\n\nBlender is installed as `blender`. A Blender MCP server is configured " "for agents that support task MCP servers; use its advertised tools to inspect the " "scene, execute Blender Python, and capture viewport images. The Blender Python CLI " "is also available. Use Blender 4.2.10, Node.js 22.17.0, Codex CLI 0.147.0 " "or Claude Code 2.1.220; do not upgrade these tools. " "Inspect your result and save your work before finishing.\n")
def _config(row, namespace, cpus, memory_mb, gpus, agent_timeout, verifier_timeout): quote = json.dumps gpu_line = f"gpus = {gpus}\n" if gpus else "" return f'''schema_version = "1.3"artifacts = ["/workspace/exports"]
[task]name = {quote(namespace + '/BlenderWorld-' + row['task_id'])}description = "BlenderWorld {row['task_id']} ({row['modality']})"keywords = ["blender", "3d", "{row['modality']}"]
[metadata]task_id = "{row['task_id']}"modality = "{row['modality']}"rubric_count = {row['rubric_count']}protocol_version = {PROTOCOL['version']}code_version = "{__version__}"blender_version = "{RUNTIME_VERSIONS['blender']}"node_version = "{RUNTIME_VERSIONS['node']}"codex_version = "{RUNTIME_VERSIONS['codex']}"claude_code_version = "{RUNTIME_VERSIONS['claude_code']}"submission_format = "{FORMAT}"submission_project = "{PROJECT}"
[agent]timeout_sec = {agent_timeout}
[environment]build_timeout_sec = 3600cpus = {cpus}memory_mb = {memory_mb}storage_mb = 102400{gpu_line}workdir = "/workspace"
[[environment.mcp_servers]]name = "blender"transport = "stdio"command = "/usr/local/bin/bw-blender-mcp"args = []
[verifier]timeout_sec = {verifier_timeout}environment_mode = "separate"
[verifier.environment]build_timeout_sec = 3600cpus = {cpus}memory_mb = {memory_mb}storage_mb = 102400{gpu_line}workdir = "/workspace"
[verifier.env]ANTHROPIC_BASE_URL = "${{BW_AGENT_JUDGE_ENDPOINT}}"ANTHROPIC_API_KEY = "${{BW_AGENT_JUDGE_API_KEY}}"JUDGE_API_ENDPOINT = "${{BW_VISION_JUDGE_ENDPOINT}}"JUDGE_API_KEY = "${{BW_VISION_JUDGE_API_KEY}}"RENDER_AGENT_MODEL = "${{BW_RENDER_MODEL:-gpt-5.6-terra}}"AGENT_JUDGE_MODEL = "${{BW_AGENT_JUDGE_MODEL:-gpt-5.6-terra}}"JUDGE_MODEL = "${{BW_VISION_JUDGE_MODEL:-gpt-5.6-terra}}"'''
def _copy_dataset_task(dataset, row, destination): task_root = destination / "tasks" / row["task_id"] task_root.mkdir(parents=True) write_json(task_root / "task.json", row) for key in ("query_file", "rubric_file"): target = resolve(destination, row[key]) target.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(resolve(dataset, row[key]), target) for field in RESOURCE_FIELDS: for entry in row[field]: target = resolve(destination, entry["path"]) target.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(resolve(dataset, entry["path"]), target) (destination / "dataset.jsonl").write_text(json.dumps(row, ensure_ascii=False) + "\n") rubric = json.loads(resolve(dataset, row["rubric_file"]).read_text()) write_json(destination / "rubrics.json", {"results": [rubric]})
def export_harbor(dataset, output, namespace="Qwen", task_ids=None, cpus=8, memory_mb=16384, gpus=0, agent_timeout=14400, verifier_timeout=28800): """Create a new export; the source dataset and existing task packages are never edited.""" Manifest, Task, Packager = _harbor() if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]*", namespace) or ".." in namespace: raise ValueError("Invalid Harbor organization namespace") if min(cpus, memory_mb, agent_timeout, verifier_timeout) <= 0 or gpus < 0: raise ValueError("Resources and timeouts must be positive; GPU count may be zero") dataset, output = Path(dataset).resolve(), Path(output).resolve() if output == dataset or output.is_relative_to(dataset): raise ValueError("Export directory must be outside the frozen dataset") verify(dataset) rows = load_tasks(dataset) if task_ids: selected = set(task_ids) rows = [r for r in rows if r["task_id"] in selected] if {r["task_id"] for r in rows} != selected: raise ValueError("Unknown task ID in selection") output.mkdir(parents=True, exist_ok=False) manifest_tasks, audit_tasks = [], [] code_root = Path(__file__).parent # Only Python runtime files go into the verifier, never into the agent image. code_files = sorted(code_root.rglob("*.py")) for row in rows: task = output / row["task_id"] env, tests = task / "environment", task / "tests" env.mkdir(parents=True) tests.mkdir() (task / "instruction.md").write_text(_instruction(row)) (task / "task.toml").write_text(_config(row, namespace, cpus, memory_mb, gpus, agent_timeout, verifier_timeout)) prepare(dataset, row["task_id"], env / "inputs") for name in ("Dockerfile.agent", "mcp_bridge.py", "blender_startup.py", "install_blender.sh", "requirements-tools.txt", "LICENSE"): shutil.copyfile(ASSETS / name, env / ("Dockerfile" if name == "Dockerfile.agent" else name)) for name in ("Dockerfile.verifier", "test.sh", "install_blender.sh", "requirements-verifier.txt", "LICENSE"): shutil.copyfile(ASSETS / name, tests / ("Dockerfile" if name == "Dockerfile.verifier" else name)) (tests / "test.sh").chmod(0o755) for path in code_files: relative = path.relative_to(code_root) if "harbor_assets" in relative.parts: continue target = tests / "blenderworld" / relative target.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(path, target) _copy_dataset_task(dataset, row, tests / "dataset") Task(task) # Validate with the same schema used by the installed Harbor release. digest, files = Packager.compute_content_hash(task) manifest_tasks.append({"name": f"{namespace}/BlenderWorld-{row['task_id']}", "digest": "sha256:" + digest}) audit_tasks.append({"task_id": row["task_id"], "modality": row["modality"], "digest": "sha256:" + digest, "files": len(files), "query_sha256": sha256(env / "inputs/query.txt"), "rubric_sha256": sha256(resolve(tests / "dataset", row["rubric_file"]))}) manifest = Manifest.model_validate({"dataset": {"name": f"{namespace}/BlenderWorld", "version": "1.2.0", "description": "BlenderWorld: 3D creation in Blender", "keywords": ["blender", "3d", "multimodal", "agent"]}, "tasks": manifest_tasks}) (output / "dataset.toml").write_text(manifest.to_toml()) for name in ("README.md", "verifier.env.example", "LICENSE"): shutil.copyfile(ASSETS / name, output / name) report = {"format": "blenderworld-harbor-v1", "harbor_version": HARBOR_VERSION, "code_version": __version__, "runtime_requirements": requirements(), "submission_format": FORMAT, "dataset_name": manifest.dataset.name, "task_count": len(rows), "dataset_digest": "sha256:" + manifest.compute_content_hash(), "source_dataset_sha256": sha256(dataset / "dataset.jsonl"), "protocol": PROTOCOL, "tasks": audit_tasks} write_json(output / "export_manifest.json", report) files = sorted(p for p in output.rglob("*") if p.is_file()) (output / "SHA256SUMS").write_text("".join(f"{sha256(p)} {p.relative_to(output).as_posix()}\n" for p in files)) return {k: v for k, v in report.items() if k != "tasks"}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980"""Harbor verifier entry point, backed by the standalone BlenderWorld evaluator."""from __future__ import annotations
import argparseimport jsonimport osimport shutilimport subprocessfrom pathlib import Pathfrom types import SimpleNamespace
from .data import load_tasks, sha256, write_jsonfrom .evaluation import PROTOCOL, evaluate, tree_hashesfrom .submissions import pack_submission
def run_verifier(dataset, submission, output): dataset, submission, output = map(lambda p: Path(p).resolve(), (dataset, submission, output)) if output == submission or output.is_relative_to(submission): raise ValueError("Verifier output must be outside the submission") output.mkdir(parents=True, exist_ok=True) reward = {"reward": 0.0, "rubric_score": 0.0, "dimension_score": 0.0} # A timeout/crash can never leave a previous successful reward behind. write_json(output / "reward.json", reward) result = {"ok": False, "status": "running", "score": 0.0, "protocol": PROTOCOL} write_json(output / "metrics.json", result) try: rows = load_tasks(dataset) if len(rows) != 1: raise ValueError("A Harbor verifier package must contain exactly one task") task_id = rows[0]["task_id"] result["task_id"] = task_id if submission.is_symlink() or any(p.is_symlink() for p in submission.rglob("*")): raise ValueError("Submission contains symbolic links") before = sha256(submission) if submission.is_file() else tree_hashes(submission) staging = output / "submissions" staging.mkdir(exist_ok=False) if submission.is_dir(): pack_submission(submission, task_id, staging / (task_id + ".zip")) elif submission.is_file(): shutil.copyfile(submission, staging / (task_id + ".zip")) options = SimpleNamespace( dataset=str(dataset), submissions=str(staging), output=str(output / "run"), task_id=[task_id], dry_run=False, resume=False, blender_bin=os.environ.get("BLENDER_BIN", "blender"), render_agent_model=os.environ.get("RENDER_AGENT_MODEL", "gpt-5.6-terra"), agent_judge_model=os.environ.get("AGENT_JUDGE_MODEL", "gpt-5.6-terra"), judge_model=os.environ.get("JUDGE_MODEL", "gpt-5.6-terra"), judge_api_endpoint=os.environ.get("JUDGE_API_ENDPOINT", "https://api.openai.com/v1/chat/completions")) evaluate(options) outcome = json.loads((output / "run/tasks" / task_id / "result.json").read_text()) after = sha256(submission) if submission.is_file() else tree_hashes(submission) if after != before: raise ValueError("Original submission changed during verification") result.update(outcome, status="scored" if outcome["ok"] else "failed") if outcome["ok"]: reward = {"reward": outcome["score"] / 100, "rubric_score": outcome["rubric_score"] / 100, "dimension_score": outcome["dimension_score"] / 100} except (OSError, ValueError, RuntimeError, subprocess.SubprocessError) as error: result.update(ok=False, status="failed", score=0.0, error=str(error)) write_json(output / "metrics.json", result) write_json(output / "reward.json", reward) return result
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--dataset", default="/tests/dataset") parser.add_argument("--submission", default="/workspace/exports", help="Harbor exports directory (packaged before scoring), or one submission ZIP") parser.add_argument("--output", default="/logs/verifier") args = parser.parse_args() result = run_verifier(args.dataset, args.submission, args.output) print(json.dumps(result, ensure_ascii=False)) return 0 if result["ok"] else 1
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130"""Adaptive eight-view evidence rendering using a configured coding agent."""from __future__ import annotations
import jsonimport osimport shutilimport subprocessfrom pathlib import Path
from PIL import Image
from .data import write_jsonfrom .evaluators.evidence_checks import cli_log_status
VIEW_COUNT = 8RESOLUTION = 1024SAMPLES = 64MAX_CORRECTIVE_RERENDERS = 2
def normalize_blender_path(value): """Resolve caller-relative paths before agents change their working directory.
A bare command may stay unresolved during a dry run without Blender installed. """ requested = os.path.expanduser(str(value)) found = shutil.which(requested) if found: return str(Path(found).resolve()) if os.sep in requested: return str(Path(requested).resolve()) return requested
def prompt_for(task, blender): return f"""You collect rendering evidence for BlenderWorld.Open the primary submitted project .eval_workspace/final.blend with {blender}. Read query.txt,rubric.json, and references/. These describe the target; they do not prove that thesubmission satisfies it. Render exactly {VIEW_COUNT} complementary views intoevaluation/multiview/. Start with the submitted camera when it shows the subject,then choose different wide views and at least two detail views relevant to the rubrics.Use short unique filenames ending in .png. Fit cameras to the subject, ignoringlarge background/floor planes. For interiors, position cameras inside enclosing walls.
Every view must use CYCLES, {RESOLUTION}x{RESOLUTION}, {SAMPLES} samples. Prefer OPTIX,then CUDA; use CPU if no supported GPU exists. Record the actual device. Retain thescene's denoising. Preserve geometry, materials, textures, object visibility, lighting,animation, and color management, including exposure and gamma. Never repair thesubmitted scene. Do not save over a .blend or any submitted file. The provided Blenderwrapper restores missing image paths only from this task's bundled workspace.
After each render, open and inspect the PNG. Correct evaluator camera/framing/clippingor incorrect evaluator render settings when necessary; allow at most{MAX_CORRECTIVE_RERENDERS} corrective re-renders per view (one initial render plustwo corrections, three total). Reuse the same filename. Dark or oddly coloredauthored scenes must remain that way. Do not alter lights or materials to improve them.Keep all Blender calls in the foreground and wait for completion. The runtime logsrender settings and rejects more than three attempts for the same view.
Write evaluation/multiview/render_agent_report.json with:{{"ok": true, "view_count": 8, "engine": "CYCLES", "device": "OPTIX|CUDA|CPU","image_files": ["view_01.png", "..."], "notes": "view selection and corrections"}}.All PNGs must be newly rendered from this submission. Do not copy author exports orreference images into the evaluator views. Do not write outside the task directory.
Task query:{task['query']}"""
def validate_views(task_dir): root = Path(task_dir) folder = root / "evaluation/multiview" images = sorted(folder.glob("*.png")) if len(images) != VIEW_COUNT: raise ValueError(f"Expected {VIEW_COUNT} fresh evaluator renders, found {len(images)}") report = json.loads((folder / "render_agent_report.json").read_text()) if report.get("ok") is not True or report.get("engine") != "CYCLES" or report.get("view_count") != VIEW_COUNT: raise ValueError("Invalid render-agent report") if sorted(report.get("image_files", [])) != [p.name for p in images]: raise ValueError("Render report does not list the actual views") attempts = json.loads((folder / "render_attempts.json").read_text()) for path in images: with Image.open(path) as image: if image.size != (RESOLUTION, RESOLUTION): raise ValueError(f"Incorrect resolution: {path.name}") image.verify() history = attempts.get(str(path.resolve()), []) if not history or len(history) > 1 + MAX_CORRECTIVE_RERENDERS: raise ValueError(f"Missing or excessive render attempts: {path.name}") final = history[-1] if final.get("engine") != "CYCLES" or final.get("samples") != SAMPLES: raise ValueError(f"Incorrect render settings: {path.name}") if final.get("completed") is not True: raise ValueError(f"No successful Blender render: {path.name}") return report
def run(task, task_dir, blender_bin, model, timeout=5400): root = Path(task_dir).resolve() folder = root / "evaluation/multiview" folder.mkdir(parents=True, exist_ok=False) real_blender = shutil.which(normalize_blender_path(blender_bin)) if not real_blender: raise FileNotFoundError(f"Blender not found: {blender_bin}") bootstrap = Path(__file__).with_name("blender_runtime.py").resolve() wrapper = root / "evaluation/blender" wrapper.write_text("#!/usr/bin/env python3\nimport os,sys\nos.execv(" + repr(real_blender) + ", [" + repr(real_blender) + ", '--background', '--python-exit-code', '2', '--python', " + repr(str(bootstrap)) + "] + sys.argv[1:])\n") wrapper.chmod(0o755) prompt = prompt_for(task, str(wrapper)) (root / "evaluation/render_prompt.txt").write_text(prompt) env = os.environ.copy() env.update(BLENDER_EVAL_ASSET_ROOT=str(root), BLENDER_EVAL_VIEW_ROOT=str(folder), BLENDER_EVAL_RUNTIME_AUDIT=str(root / "evaluation/blender_runtime.jsonl"), DISABLE_AUTOUPDATER="1") if model: env["ANTHROPIC_MODEL"] = model log_path = root / "evaluation/render_agent.jsonl" with log_path.open("w") as log: result = subprocess.run(["claude", "--verbose", "--output-format", "stream-json", "--max-turns", "500", "--allowedTools", "Bash", "Read", "Write", "Edit", "Glob", "Grep", "--disallowedTools", "WebFetch", "WebSearch", "-p", prompt], cwd=root, env=env, stdout=log, stderr=subprocess.STDOUT, timeout=timeout, check=False) event, refused = cli_log_status(log_path) if result.returncode or refused or not event or event.get("is_error"): raise RuntimeError("Render agent failed; see evaluation/render_agent.jsonl") return validate_views(root)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102"""Validate the release runtime before spending evaluator model calls."""from __future__ import annotations
import jsonimport osimport reimport shutilimport subprocessfrom pathlib import Path
from .data import sha256
class RuntimeValidationError(RuntimeError): """An evaluator installation error, not a failed agent submission."""
RUNTIME_VERSIONS = { "blender": "4.2.10", "node": "22.17.0", "claude_code": "2.1.220", "codex": "0.147.0",}
BLENDER_PROBE = '''import bpy, jsonbackends = []prefs = bpy.context.preferences.addons['cycles'].preferencesfor backend in ('OPTIX', 'CUDA'): try: prefs.compute_device_type = backend prefs.get_devices() devices = sorted({d.name for d in prefs.devices if d.type == backend}) if devices: backends.append({'backend': backend, 'devices': devices}) except Exception: passbuild = bpy.app.build_hashif isinstance(build, bytes): build = build.decode('ascii', errors='replace')print('BLENDERWORLD_RUNTIME=' + json.dumps({ 'version': '.'.join(map(str, bpy.app.version)), 'build_hash': build, 'gpu_backends': backends}))'''
def requirements(): return {"versions": dict(RUNTIME_VERSIONS), "evaluation_tools": ["blender", "node", "claude_code"], "generation_tools": ["blender", "node", "codex", "claude_code"]}
def _version(command, name): found = shutil.which(str(command)) if not found: raise RuntimeValidationError(f"BlenderWorld runtime requires {name} {RUNTIME_VERSIONS[name]}; executable not found: {command}") path = Path(found).resolve() try: result = subprocess.run([str(path), "--version"], capture_output=True, env={**os.environ, "DISABLE_AUTOUPDATER": "1"}, text=True, timeout=30, check=False) except (OSError, subprocess.SubprocessError) as error: raise RuntimeValidationError(f"Could not check {name} version: {error}") from error text = result.stdout.strip() match = re.search(r"\bv?(\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]+)?)\b", text) actual = match.group(1) if match else "unknown" if result.returncode or actual != RUNTIME_VERSIONS[name]: raise RuntimeValidationError(f"BlenderWorld runtime requires {name} {RUNTIME_VERSIONS[name]}, found {actual} at {path}") return {"path": str(path), "version": actual, "sha256": sha256(path)}
def inspect_runtime(blender_bin="blender"): """Pin evaluator tools; Codex is installed/checked by the rollout image.""" report = {"requirements": requirements()} report["blender"] = _version(blender_bin, "blender") report["node"] = _version("node", "node") report["claude_code"] = _version("claude", "claude_code") try: result = subprocess.run([report["blender"]["path"], "--background", "--factory-startup", "--python-exit-code", "2", "--python-expr", BLENDER_PROBE], capture_output=True, text=True, timeout=90, check=False) except (OSError, subprocess.SubprocessError) as error: raise RuntimeValidationError(f"Could not inspect Blender's Cycles runtime: {error}") from error lines = [s.removeprefix("BLENDERWORLD_RUNTIME=") for s in result.stdout.splitlines() if s.startswith("BLENDERWORLD_RUNTIME=")] if result.returncode or len(lines) != 1: raise RuntimeValidationError("Blender runtime inspection failed; check the Blender installation and GPU driver") try: details = json.loads(lines[0]) except ValueError as error: raise RuntimeValidationError("Invalid Blender runtime report") from error if details.get("version") != RUNTIME_VERSIONS["blender"]: raise RuntimeValidationError("Blender executable and bpy runtime versions disagree") report["blender"].update(details) return report
def record_runtime(output, report): path = Path(output) / "runtime.json" if path.exists() and json.loads(path.read_text()) != report: raise RuntimeValidationError("Runtime versions, executables, or GPU changed; start a new run") if not path.exists(): path.write_text(json.dumps(report, indent=2) + "\n")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211"""Public submission contract: one ZIP with final.blend at its root per task."""from __future__ import annotations
from contextlib import contextmanagerimport hashlibimport jsonimport osfrom pathlib import Path, PurePosixPathimport reimport shutilimport statimport tempfileimport zipfile
from .data import sha256
FORMAT = "blenderworld-submission-v1"PROJECT = "final.blend"MANIFEST = "submission.json"MAX_FILES = 100_000MAX_BYTES = 20 * 1024**3
def _name(name): if not name or "\\" in name or "\0" in name: raise ValueError("Invalid archive member path") path = PurePosixPath(name) if path.is_absolute() or ".." in path.parts or re.match(r"^[A-Za-z]:", name): raise ValueError("Archive member escapes its root") return path.as_posix().rstrip("/")
def _copy(source, destination, limit): total = 0 while block := source.read(1024 * 1024): total += len(block) if total > limit: raise ValueError("Submission file exceeds its declared size or size limit") destination.write(block) return total
@contextmanagerdef _archive(source): """Validate paths and file types before reading submitted files.""" try: with zipfile.ZipFile(source) as archive: members = archive.infolist() if len(members) > MAX_FILES: raise ValueError("Too many archive members") names, files, total = set(), {}, 0 for member in members: name = _name(member.orig_filename) directory = member.is_dir() if name == "." and directory: continue if name in names: raise ValueError("Duplicate archive member") names.add(name) kind = stat.S_IFMT(member.external_attr >> 16) if kind not in (0, stat.S_IFDIR if directory else stat.S_IFREG): raise ValueError("Archive links and special files are not supported") if not directory: total += member.file_size if member.file_size < 0 or total > MAX_BYTES: raise ValueError("Archive exceeds the uncompressed size limit") files[name] = (member.file_size, member) for name in names: if any(p.as_posix() in files for p in PurePosixPath(name).parents if p.as_posix() != "."): raise ValueError("Archive contains a file/directory path conflict") yield files, lambda name: archive.open(files[name][1]) except (zipfile.BadZipFile, EOFError, RuntimeError, NotImplementedError) as error: raise ValueError(f"Invalid submission ZIP: {type(error).__name__}") from error
@contextmanagerdef _directory(source): files, total = {}, 0 for path in sorted(source.rglob("*")): if path.is_symlink(): raise ValueError("Submission contains a symbolic link") if path.is_dir(): continue if not path.is_file(): raise ValueError("Submission contains a special file") size = path.stat().st_size total += size if total > MAX_BYTES or len(files) >= MAX_FILES: raise ValueError("Submission exceeds the size or file-count limit") files[_name(path.relative_to(source).as_posix())] = (size, path) yield files, lambda name: files[name][1].open("rb")
def _check_manifest(files, read, task_id): if MANIFEST not in files: return None if files[MANIFEST][0] > 16 * 1024**2: raise ValueError("Submission manifest is too large") with read(MANIFEST) as stream: manifest = json.load(stream) if not isinstance(manifest, dict) or manifest.get("format") != FORMAT or manifest.get("task_id") != task_id: raise ValueError("Submission manifest format or task_id does not match") expected = manifest.get("files") if not isinstance(expected, dict) or any(not isinstance(k, str) or not isinstance(v, str) or not re.fullmatch(r"[0-9a-f]{64}", v) for k, v in expected.items()): raise ValueError("Invalid submission file checksums") if set(expected) != set(files) - {MANIFEST}: raise ValueError("Submission manifest does not cover the delivered files") return expected
@contextmanagerdef _payload(source, task_id): source = Path(source) if source.is_symlink(): raise ValueError("Submission source must not be a symbolic link") if not source.is_dir() and not source.is_file(): raise ValueError("Submission source does not exist") reader = _directory(source) if source.is_dir() else _archive(source) with reader as (files, read): if PROJECT not in files: raise ValueError("Expected final.blend at the submission root; package the output directory's contents without a wrapping folder") if not files[PROJECT][0]: raise ValueError("Submitted final.blend is empty") expected = _check_manifest(files, read, task_id) selected = {n: info for n, info in files.items() if n != MANIFEST} yield selected, read, expected
def _task_id(task_id): if not re.fullmatch(r"bw_\d{4}", task_id): raise ValueError("Use the dataset's bw_XXXX task ID")
def pack_submission(source, task_id, output): """Package a model's output directory (or standard ZIP) with checksums.""" _task_id(task_id) source, output = Path(source), Path(output).absolute() if source.is_symlink(): raise ValueError("Submission source must not be a symbolic link") source = source.resolve() if output.suffix.lower() != ".zip" or output.exists(): raise ValueError("Output must be a new .zip file") if source.is_dir() and output.resolve().is_relative_to(source): raise ValueError("Write the submission ZIP outside the source directory") output.parent.mkdir(parents=True, exist_ok=True) with tempfile.NamedTemporaryFile(dir=output.parent, suffix=".zip", delete=False) as temporary: temp = Path(temporary.name) try: with _payload(source, task_id) as (files, read, expected): hashes = {} with zipfile.ZipFile(temp, "w", zipfile.ZIP_DEFLATED, compresslevel=6) as archive: for name, (size, _) in sorted(files.items()): digest = hashlib.sha256() with read(name) as stream, archive.open(name, "w", force_zip64=True) as target: written = 0 while block := stream.read(1024 * 1024): written += len(block) if written > size: raise ValueError("Source changed while packaging") digest.update(block) target.write(block) if written != size: raise ValueError("Truncated delivered file") hashes[name] = digest.hexdigest() if expected is not None and hashes != expected: raise ValueError("Submission checksum mismatch") archive.writestr(MANIFEST, json.dumps({"format": FORMAT, "task_id": task_id, "files": hashes}, indent=2) + "\n") inspect_submission(temp, task_id) # Publish atomically without overwriting another completed submission. os.link(temp, output) return {"task_id": task_id, "output": str(output), "format": FORMAT, "project": PROJECT, "files": len(hashes), "sha256": sha256(output)} finally: temp.unlink(missing_ok=True)
def inspect_submission(archive, task_id): _task_id(task_id) archive = Path(archive) if archive.is_symlink() or not archive.is_file(): raise ValueError("Expected a per-task submission ZIP") with _payload(archive, task_id) as (files, _, expected): return {"format": FORMAT, "project": PROJECT, "manifest_present": expected is not None, "files": len(files), "bytes": sum(size for size, _ in files.values()), "blend_files": sorted(n for n in files if n.lower().endswith(".blend"))}
def unpack_submission(archive, task_id, destination): """Extract submitted files into an evaluator-owned copy, preserving paths.""" archive, destination = Path(archive), Path(destination) details = inspect_submission(archive, task_id) destination.mkdir(parents=True, exist_ok=False) hashes = {} try: with _payload(archive, task_id) as (files, read, expected): for name, (size, _) in sorted(files.items()): path = destination / name path.parent.mkdir(parents=True, exist_ok=True) with read(name) as source, path.open("xb") as target: written = _copy(source, target, size) if written != size: raise ValueError("Truncated delivered file") hashes[name] = sha256(path) if expected is not None and hashes != expected: raise ValueError("Submission checksum mismatch") return {**details, "archive_sha256": sha256(archive), "file_sha256": hashes} except BaseException: shutil.rmtree(destination) raise1{"schema_version": 1, "task_id": "bw_0007", "modality": "image", "query": "Promo shot for a tree-care company: an arborist high in a tall pine with pruned branch stubs. The climber wears a red helmet, dark top, red-and-black protective trousers, rigged with harness and climbing ropes, chainsaw on his belt; dense forest, blue sky above, proportions estimated. Key point—worker and safety gear read clearly, not buried in foliage, woodland realistic but not stealing focus. Give bark, fabric and metal materials, daylight, camera and render; send a render and keep the .blend.", "query_file": "tasks/bw_0007/query.txt", "rubric_file": "tasks/bw_0007/rubric.json", "rubric_count": 7, "rubric_prompt_matches_query": true, "annotation_status": "ready", "attachments": [], "supplemental_attachments": [], "reference_images": [{"path": "tasks/bw_0007/references/image_01.jpg", "task_relative_path": "references/image_01.jpg", "bytes": 338209, "sha256": "1871e7c94f9b39d3bd6ab0bf1b70958585679f3cc392457b6e2154dfbd5c2eba"}], "reference_videos": [], "rubric_reference_images": [], "metadata": {"lang": "en", "category": "Nature & Landscapes", "subcategory": "Landscapes & Natural Environments", "domain": "outdoor_natural_scene", "persona": "intermediate", "length": "brief", "complexity": "hard", "ref_style": "recreate", "input_form": "image+text", "use_case": "realestate_marketing", "visual_focus": ["主体清楚、不被杂物盖住", "家具陈设真实但不抢主体"], "category_short": "Nature", "subcategory_short": "Natural scenes", "taxonomy_version": "taxonomy_223"}}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141{ "results": [ { "task_id": "bw_0007", "prompt": "Promo shot for a tree-care company: an arborist high in a tall pine with pruned branch stubs. The climber wears a red helmet, dark top, red-and-black protective trousers, rigged with harness and climbing ropes, chainsaw on his belt; dense forest, blue sky above, proportions estimated. Key point—worker and safety gear read clearly, not buried in foliage, woodland realistic but not stealing focus. Give bark, fabric and metal materials, daylight, camera and render; send a render and keep the .blend.", "lang": "en", "mode": "prompt_image", "attachments": [], "image_file": "references/image_01.jpg", "rubric_count": 7, "rubrics": [ { "id": "R01", "category": "layout", "importance": "major", "subject": "promotional_arborist_and_principal_pine_relationship", "requirement_source": "prompt_explicit", "evidence_type": "render", "criterion": "The completed image must establish a coherently scaled professional arborist working high on the dominant pine and make that work the promotional subject.", "pass_condition": "The final render clearly reads as a promotional tree-care image centered on a recognizable arborist working substantially high on and directly engaged with a dominant tall pine, rather than as a generic forest scene. The worker, pine, branch stubs, ropes, harness, chainsaw, and surrounding woodland have mutually coherent estimated proportions without requiring exact measurements.", "fail_condition": "The item fails if the image reads primarily as a generic forest, the worker is not recognizable as an arborist, the arborist is not substantially high on and directly engaged with a dominant tall pine, or any principal subject and equipment scales are mutually incoherent.", "category_v2": "layout", "importance_weight": 3, "score_type": "binary", "score_values": [ 0, 1 ] }, { "id": "R02", "category": "material", "importance": "major", "subject": "pruned_pine_trunk_system", "requirement_source": "prompt_explicit", "evidence_type": "render", "criterion": "The principal pine must combine clear pruning geometry with a convincing bark surface.", "pass_condition": "The principal pine shows multiple short projecting branch remnants with visibly blunt or cut-looking terminated ends, and its trunk reads as rough, naturally varied bark through earthy color variation plus ridges, plates, bumps, relief, or comparable bark cues rather than as a smooth untextured surface.", "fail_condition": "The item fails if the principal pine lacks multiple recognizable pruned branch stubs, their ends do not read as deliberately terminated or cut, or the trunk lacks a visibly rough and naturally varied bark response.", "category_v2": "material", "importance_weight": 3, "score_type": "binary", "score_values": [ 0, 1 ] }, { "id": "R03", "category": "material", "importance": "major", "subject": "arborist_protective_clothing_system", "requirement_source": "prompt_explicit", "evidence_type": "render", "criterion": "The arborist's protective clothing identities, specified colors, and fabric response must all be readable.", "pass_condition": "The climber visibly wears a recognizable hard-shell protective helmet that is predominantly red or red-orange, a black, charcoal, navy, or comparably dark upper garment, and protective trousers with substantial red areas plus black or comparably dark panels; the top and trousers also read as fabric through matte or woven response, folds, seams, wrinkles, or comparable textile cues.", "fail_condition": "The item fails if the protective helmet is absent, unrecognizable, or not predominantly red; the upper garment is not dark; the trousers do not visibly combine substantial red and dark sections; or the top and trousers do not read as fabric.", "category_v2": "material", "importance_weight": 3, "score_type": "binary", "score_values": [ 0, 1 ] }, { "id": "R04", "category": "function", "importance": "major", "subject": "complete_climbing_and_work_equipment_system", "requirement_source": "prompt_explicit", "evidence_type": "render", "criterion": "The climbing posture, harness, rope support, belt-hung chainsaw, gravity behavior, and practical metal hardware must form one visible and plausible arborist work rig.", "pass_condition": "The worker is viewed chiefly from behind or the side while facing the trunk in an active climbing posture with bent limbs and at least one foot or leg visibly braced against the bark; a recognizable harness is fitted around the waist, hips, or upper legs; and multiple distinct climbing-rope runs or segments are visibly associated with the climber, harness, and tree in a plausible support arrangement, with loaded sections supported or taut where appropriate and loose sections descending or curving naturally under gravity rather than floating. A recognizable chainsaw with a readable motor body and guide-bar form hangs naturally from the worker's belt, waist, or harness area, and at least one appropriate visible chainsaw, harness, connector, or climbing-hardware component has a credible painted, dark, polished, rough, weathered, or comparable metal response.", "fail_condition": "The item fails if the worker lacks the specified active rear-or-side trunk-bracing posture, no recognizable harness is visibly fitted, plural climbing-rope segments or plausible support behavior are absent, the ropes or equipment visibly float or route arbitrarily, no recognizable chainsaw hangs from the belt or harness area, or no suitable visible tool or rigging component reads as metal.", "category_v2": "function", "importance_weight": 3, "score_type": "binary", "score_values": [ 0, 1 ] }, { "id": "R05", "category": "space_layout", "importance": "major", "subject": "dense_layered_conifer_woodland", "requirement_source": "prompt_explicit", "evidence_type": "render", "criterion": "The surroundings must establish a dense, layered conifer woodland while retaining visible blue sky openings.", "pass_condition": "Numerous surrounding trees, branches, and abundant foliage establish dense forest beyond the principal pine; recognizable conifer branches with clustered needle-like foliage appear around the main tree and across more than one visible depth layer; and at least one clearly blue open-sky region remains visible above or through upper-canopy openings.", "fail_condition": "The item fails if the principal pine appears isolated or sparsely surrounded, recognizable conifer branches and clustered needle-like foliage are absent, the woodland reads as a single flat layer, or no clearly blue sky opening is visible above or through the canopy.", "category_v2": "space_layout", "importance_weight": 3, "score_type": "binary", "score_values": [ 0, 1 ] }, { "id": "R06", "category": "composition", "importance": "major", "subject": "author_final_promotional_render_presentation", "requirement_source": "prompt_explicit", "evidence_type": "render", "criterion": "The delivered render must use natural daylight and a height-emphasizing composition that keeps the worker and safety gear clear while making the realistic woodland subordinate.", "pass_condition": "The worker, red helmet, clothing, fitted harness, climbing ropes, and hanging chainsaw are clearly readable in the author-selected view and are not substantially obscured, buried in foliage, or lost through inadequate contrast, scale, or lighting; the woodland appears natural and convincing but remains visually subordinate to the arborist and safety equipment. The image visibly reads as naturally lit daytime through coherent sky, sun, and canopy illumination that keeps the principal subject readable. The composition broadly recreates the reference hierarchy with a dominant near-vertical trunk occupying the central image area, the elevated worker framed against it, and surrounding canopy plus sky supplying context, without requiring an identical crop, lens, aspect ratio, or pixel placement. The actual author-delivered final image opens successfully and is a completed camera render of the requested arborist, principal pine, and woodland scene rather than a viewport capture, setup screenshot, or unrelated image.", "fail_condition": "The item fails if any specified worker or safety-equipment element is not clearly readable or is substantially buried by foliage; the woodland is implausible or steals focus; the lighting does not read as natural daylight or leaves the subject unreadable; the composition lacks the dominant height-emphasizing trunk and elevated-worker hierarchy; or the author-delivered image is absent, cannot be opened, or is not a completed camera render of the requested scene.", "category_v2": "composition", "importance_weight": 3, "score_type": "binary", "score_values": [ 0, 1 ] }, { "id": "R07", "category": "function", "importance": "major", "subject": "native_blender_project_and_render_configuration", "requirement_source": "prompt_explicit", "evidence_type": "scene_summary", "criterion": "The native Blender project must be loadable, editable, scene-complete, camera-framed, and retain valid original lighting and render settings corresponding to the delivered shot.", "pass_condition": "The submitted native .blend opens successfully and contains editable geometry, assigned bark, fabric, and metal materials, daylight lighting, and scene contents corresponding to the delivered arborist shot; its retained camera has a valid projection and transform and frames the arborist, principal pine, and woodland as the core scene; and its original retained settings specify a valid render engine and usable render configuration capable of producing the scene without relying on evaluator-only temporary settings, while no particular engine, sample count, resolution, denoising method, or color-management preset is required.", "fail_condition": "The item fails if the native .blend is absent or cannot be opened, lacks editable scene contents corresponding to the delivered shot, lacks the assigned required material classes or daylight lighting, lacks a valid retained camera framing the core scene, or lacks a valid original render configuration.", "category_v2": "function", "importance_weight": 3, "score_type": "binary", "score_values": [ 0, 1 ] } ] } ]}1Promo shot for a tree-care company: an arborist high in a tall pine with pruned branch stubs. The climber wears a red helmet, dark top, red-and-black protective trousers, rigged with harness and climbing ropes, chainsaw on his belt; dense forest, blue sky above, proportions estimated. Key point—worker and safety gear read clearly, not buried in foliage, woodland realistic but not stealing focus. Give bark, fabric and metal materials, daylight, camera and render; send a render and keep the .blend.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137{ "task_id": "bw_0007", "prompt": "Promo shot for a tree-care company: an arborist high in a tall pine with pruned branch stubs. The climber wears a red helmet, dark top, red-and-black protective trousers, rigged with harness and climbing ropes, chainsaw on his belt; dense forest, blue sky above, proportions estimated. Key point—worker and safety gear read clearly, not buried in foliage, woodland realistic but not stealing focus. Give bark, fabric and metal materials, daylight, camera and render; send a render and keep the .blend.", "lang": "en", "mode": "prompt_image", "attachments": [], "image_file": "references/image_01.jpg", "rubric_count": 7, "rubrics": [ { "id": "R01", "category": "layout", "importance": "major", "subject": "promotional_arborist_and_principal_pine_relationship", "requirement_source": "prompt_explicit", "evidence_type": "render", "criterion": "The completed image must establish a coherently scaled professional arborist working high on the dominant pine and make that work the promotional subject.", "pass_condition": "The final render clearly reads as a promotional tree-care image centered on a recognizable arborist working substantially high on and directly engaged with a dominant tall pine, rather than as a generic forest scene. The worker, pine, branch stubs, ropes, harness, chainsaw, and surrounding woodland have mutually coherent estimated proportions without requiring exact measurements.", "fail_condition": "The item fails if the image reads primarily as a generic forest, the worker is not recognizable as an arborist, the arborist is not substantially high on and directly engaged with a dominant tall pine, or any principal subject and equipment scales are mutually incoherent.", "category_v2": "layout", "importance_weight": 3, "score_type": "binary", "score_values": [ 0, 1 ] }, { "id": "R02", "category": "material", "importance": "major", "subject": "pruned_pine_trunk_system", "requirement_source": "prompt_explicit", "evidence_type": "render", "criterion": "The principal pine must combine clear pruning geometry with a convincing bark surface.", "pass_condition": "The principal pine shows multiple short projecting branch remnants with visibly blunt or cut-looking terminated ends, and its trunk reads as rough, naturally varied bark through earthy color variation plus ridges, plates, bumps, relief, or comparable bark cues rather than as a smooth untextured surface.", "fail_condition": "The item fails if the principal pine lacks multiple recognizable pruned branch stubs, their ends do not read as deliberately terminated or cut, or the trunk lacks a visibly rough and naturally varied bark response.", "category_v2": "material", "importance_weight": 3, "score_type": "binary", "score_values": [ 0, 1 ] }, { "id": "R03", "category": "material", "importance": "major", "subject": "arborist_protective_clothing_system", "requirement_source": "prompt_explicit", "evidence_type": "render", "criterion": "The arborist's protective clothing identities, specified colors, and fabric response must all be readable.", "pass_condition": "The climber visibly wears a recognizable hard-shell protective helmet that is predominantly red or red-orange, a black, charcoal, navy, or comparably dark upper garment, and protective trousers with substantial red areas plus black or comparably dark panels; the top and trousers also read as fabric through matte or woven response, folds, seams, wrinkles, or comparable textile cues.", "fail_condition": "The item fails if the protective helmet is absent, unrecognizable, or not predominantly red; the upper garment is not dark; the trousers do not visibly combine substantial red and dark sections; or the top and trousers do not read as fabric.", "category_v2": "material", "importance_weight": 3, "score_type": "binary", "score_values": [ 0, 1 ] }, { "id": "R04", "category": "function", "importance": "major", "subject": "complete_climbing_and_work_equipment_system", "requirement_source": "prompt_explicit", "evidence_type": "render", "criterion": "The climbing posture, harness, rope support, belt-hung chainsaw, gravity behavior, and practical metal hardware must form one visible and plausible arborist work rig.", "pass_condition": "The worker is viewed chiefly from behind or the side while facing the trunk in an active climbing posture with bent limbs and at least one foot or leg visibly braced against the bark; a recognizable harness is fitted around the waist, hips, or upper legs; and multiple distinct climbing-rope runs or segments are visibly associated with the climber, harness, and tree in a plausible support arrangement, with loaded sections supported or taut where appropriate and loose sections descending or curving naturally under gravity rather than floating. A recognizable chainsaw with a readable motor body and guide-bar form hangs naturally from the worker's belt, waist, or harness area, and at least one appropriate visible chainsaw, harness, connector, or climbing-hardware component has a credible painted, dark, polished, rough, weathered, or comparable metal response.", "fail_condition": "The item fails if the worker lacks the specified active rear-or-side trunk-bracing posture, no recognizable harness is visibly fitted, plural climbing-rope segments or plausible support behavior are absent, the ropes or equipment visibly float or route arbitrarily, no recognizable chainsaw hangs from the belt or harness area, or no suitable visible tool or rigging component reads as metal.", "category_v2": "function", "importance_weight": 3, "score_type": "binary", "score_values": [ 0, 1 ] }, { "id": "R05", "category": "space_layout", "importance": "major", "subject": "dense_layered_conifer_woodland", "requirement_source": "prompt_explicit", "evidence_type": "render", "criterion": "The surroundings must establish a dense, layered conifer woodland while retaining visible blue sky openings.", "pass_condition": "Numerous surrounding trees, branches, and abundant foliage establish dense forest beyond the principal pine; recognizable conifer branches with clustered needle-like foliage appear around the main tree and across more than one visible depth layer; and at least one clearly blue open-sky region remains visible above or through upper-canopy openings.", "fail_condition": "The item fails if the principal pine appears isolated or sparsely surrounded, recognizable conifer branches and clustered needle-like foliage are absent, the woodland reads as a single flat layer, or no clearly blue sky opening is visible above or through the canopy.", "category_v2": "space_layout", "importance_weight": 3, "score_type": "binary", "score_values": [ 0, 1 ] }, { "id": "R06", "category": "composition", "importance": "major", "subject": "author_final_promotional_render_presentation", "requirement_source": "prompt_explicit", "evidence_type": "render", "criterion": "The delivered render must use natural daylight and a height-emphasizing composition that keeps the worker and safety gear clear while making the realistic woodland subordinate.", "pass_condition": "The worker, red helmet, clothing, fitted harness, climbing ropes, and hanging chainsaw are clearly readable in the author-selected view and are not substantially obscured, buried in foliage, or lost through inadequate contrast, scale, or lighting; the woodland appears natural and convincing but remains visually subordinate to the arborist and safety equipment. The image visibly reads as naturally lit daytime through coherent sky, sun, and canopy illumination that keeps the principal subject readable. The composition broadly recreates the reference hierarchy with a dominant near-vertical trunk occupying the central image area, the elevated worker framed against it, and surrounding canopy plus sky supplying context, without requiring an identical crop, lens, aspect ratio, or pixel placement. The actual author-delivered final image opens successfully and is a completed camera render of the requested arborist, principal pine, and woodland scene rather than a viewport capture, setup screenshot, or unrelated image.", "fail_condition": "The item fails if any specified worker or safety-equipment element is not clearly readable or is substantially buried by foliage; the woodland is implausible or steals focus; the lighting does not read as natural daylight or leaves the subject unreadable; the composition lacks the dominant height-emphasizing trunk and elevated-worker hierarchy; or the author-delivered image is absent, cannot be opened, or is not a completed camera render of the requested scene.", "category_v2": "composition", "importance_weight": 3, "score_type": "binary", "score_values": [ 0, 1 ] }, { "id": "R07", "category": "function", "importance": "major", "subject": "native_blender_project_and_render_configuration", "requirement_source": "prompt_explicit", "evidence_type": "scene_summary", "criterion": "The native Blender project must be loadable, editable, scene-complete, camera-framed, and retain valid original lighting and render settings corresponding to the delivered shot.", "pass_condition": "The submitted native .blend opens successfully and contains editable geometry, assigned bark, fabric, and metal materials, daylight lighting, and scene contents corresponding to the delivered arborist shot; its retained camera has a valid projection and transform and frames the arborist, principal pine, and woodland as the core scene; and its original retained settings specify a valid render engine and usable render configuration capable of producing the scene without relying on evaluator-only temporary settings, while no particular engine, sample count, resolution, denoising method, or color-management preset is required.", "fail_condition": "The item fails if the native .blend is absent or cannot be opened, lacks editable scene contents corresponding to the delivered shot, lacks the assigned required material classes or daylight lighting, lacks a valid retained camera framing the core scene, or lacks a valid original render configuration.", "category_v2": "function", "importance_weight": 3, "score_type": "binary", "score_values": [ 0, 1 ] } ]}123456789101112131415161718192021222324252627282930313233343536373839404142{ "schema_version": 1, "task_id": "bw_0007", "modality": "image", "query": "Promo shot for a tree-care company: an arborist high in a tall pine with pruned branch stubs. The climber wears a red helmet, dark top, red-and-black protective trousers, rigged with harness and climbing ropes, chainsaw on his belt; dense forest, blue sky above, proportions estimated. Key point—worker and safety gear read clearly, not buried in foliage, woodland realistic but not stealing focus. Give bark, fabric and metal materials, daylight, camera and render; send a render and keep the .blend.", "query_file": "tasks/bw_0007/query.txt", "rubric_file": "tasks/bw_0007/rubric.json", "rubric_count": 7, "rubric_prompt_matches_query": true, "annotation_status": "ready", "attachments": [], "supplemental_attachments": [], "reference_images": [ { "path": "tasks/bw_0007/references/image_01.jpg", "task_relative_path": "references/image_01.jpg", "bytes": 338209, "sha256": "1871e7c94f9b39d3bd6ab0bf1b70958585679f3cc392457b6e2154dfbd5c2eba" } ], "reference_videos": [], "rubric_reference_images": [], "metadata": { "lang": "en", "category": "Nature & Landscapes", "subcategory": "Landscapes & Natural Environments", "domain": "outdoor_natural_scene", "persona": "intermediate", "length": "brief", "complexity": "hard", "ref_style": "recreate", "input_form": "image+text", "use_case": "realestate_marketing", "visual_focus": [ "主体清楚、不被杂物盖住", "家具陈设真实但不抢主体" ], "category_short": "Nature", "subcategory_short": "Natural scenes", "taxonomy_version": "taxonomy_223" }}12345678910111213141516#!/bin/bashset -euo pipefailversion=4.2.10filename="blender-${version}-linux-x64.tar.xz"base_url="https://download.blender.org/release/Blender4.2"checksum=7b888b36cf5bd7e35d495eb9717f7a9b645ea5f2fb4fe9850991800b8f08d531curl --fail --location --retry 3 "${base_url}/${filename}" -o "/tmp/${filename}" || \ curl --fail --location --retry 3 "https://mirrors.ocf.berkeley.edu/blender/release/Blender4.2/${filename}" -o "/tmp/${filename}"cd /tmpprintf '%s %s\n' "$checksum" "$filename" | sha256sum --check -mkdir -p /opt/blendertar -xJf "$filename" --strip-components=1 -C /opt/blender/opt/blender/4.2/python/bin/python3.11 -m ensurepip/opt/blender/4.2/python/bin/python3.11 -m pip install --no-cache-dir requests==2.32.5rm "/tmp/${filename}"/opt/blender/blender --background --factory-startup --python-exit-code 2 --python-expr 'import bpy, requests; assert bpy.app.version == (4, 2, 10), bpy.app.version_string; print(bpy.app.version_string)'1234requests==2.32.5Pillow==11.3.0json-repair==0.50.1huggingface-hub==0.35.3123456#!/bin/bashset -euo pipefailexec python -m blenderworld.harbor_verify \ --dataset "${BW_HARBOR_DATASET:-/tests/dataset}" \ --submission "${BW_HARBOR_SUBMISSION:-/workspace/exports}" \ --output "${BW_HARBOR_OUTPUT:-/logs/verifier}"12345678910111213141516171819202122232425262728293031323334353637FROM node:22.17.0-bookworm-slim AS nodeFROM python:3.12-slim-bookworm
ENV DEBIAN_FRONTEND=noninteractive \ BLENDER_BIN=/opt/blender/blender \ BLENDER_MCP_ADDON_PATH=/opt/bw-mcp/addon.py \ BLENDERMCP_NO_UPDATE_CHECK=1 \ DISABLE_AUTOUPDATER=1 \ PATH=/opt/blender:/usr/local/bin:/usr/bin:/binRUN apt-get update && apt-get install -y --no-install-recommends \ bash ca-certificates curl xz-utils ffmpeg xvfb xauth procps \ libx11-6 libxi6 libxfixes3 libxrender1 libxxf86vm1 libxkbcommon0 \ libgl1 libegl1 libsm6 libice6 libdbus-1-3 libgomp1 libfontconfig1 \ fonts-dejavu-core && rm -rf /var/lib/apt/lists/*COPY install_blender.sh /opt/install_blender.shRUN bash /opt/install_blender.shCOPY --from=node /usr/local/bin/node /usr/local/bin/nodeCOPY --from=node /usr/local/lib/node_modules /usr/local/lib/node_modulesRUN ln -s /usr/local/lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm \ && ln -s /usr/local/lib/node_modules/npm/bin/npx-cli.js /usr/local/bin/npx \ && npm install --global @openai/codex@0.147.0 @anthropic-ai/claude-code@2.1.220 \ && test "$(node --version)" = "v22.17.0" \ && test "$(codex --version)" = "codex-cli 0.147.0" \ && test "$(claude --version)" = "2.1.220 (Claude Code)"COPY requirements-tools.txt /opt/requirements-tools.txtRUN python -m pip install --no-cache-dir -r /opt/requirements-tools.txtRUN python -m venv /opt/bw-mcp \ && /opt/bw-mcp/bin/pip install --no-cache-dir mcp-for-blender==2.1.3 mcp==1.30.0 \ && /opt/bw-mcp/bin/python -c "from importlib.resources import files; from pathlib import Path; Path('/opt/bw-mcp/addon.py').write_bytes(files('blender_mcp').joinpath('bundled/addon.py').read_bytes())"COPY mcp_bridge.py /usr/local/bin/bw-blender-mcpCOPY blender_startup.py /usr/local/bin/blender_startup.pyCOPY LICENSE /usr/local/share/licenses/BlenderWorld/LICENSERUN chmod 755 /usr/local/bin/bw-blender-mcp \ && mkdir -p /workspace/exports /logs/artifactsCOPY inputs/ /workspace/inputs/WORKDIR /workspaceCMD ["sleep", "infinity"]123456789101112131415161718192021MIT License
Copyright (c) 2026 BlenderWorld contributors
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123456789101112131415161718192021"""Start the bundled, versioned MCP addon in an interactive Blender session."""import importlib.utilimport osimport sys
import bpy
if bpy.app.version != (4, 2, 10): raise RuntimeError("BlenderWorld requires Blender 4.2.10")
os.environ["BLENDERMCP_NO_UPDATE_CHECK"] = "1"path = os.environ.get("BLENDER_MCP_ADDON_PATH", "/opt/bw-mcp/addon.py")spec = importlib.util.spec_from_file_location("blendermcp", path)addon = importlib.util.module_from_spec(spec)sys.modules[spec.name] = addonspec.loader.exec_module(addon)addon.register()bpy.context.scene.blendermcp_port = int(os.environ["BLENDER_PORT"])bpy.context.scene.blendermcp_auto_start_server = Truebpy.context.scene.blendermcp_use_polyhaven = Trueprint("BlenderWorld MCP addon registered", flush=True)123456789{ "task_id": "bw_0008", "query_file": "query.txt", "files": [ "references/image_01.jpg", "instruction.html", "reference_images.base64.json" ]}1我在给学生做一套设备安全操作的培训课件,想拿这张工业回收破碎压缩机组的渲染图当底本,把整套设备重建出来,再改几处方便讲解。设备我大概点几个关键的:左边那个独立立式控制柜(带一排按钮和指示灯)、后面架在钢结构支腿上的高位料仓(顶上的品牌标识和侧面那根弧形导料管留着)、中间的破碎压缩主机、右边那条倾斜进料输送带(白框架、绿带面带人字形防滑纹);主机侧面的圆柱形电机和底部脚轮这些也按图补齐。配色沿用原图的黄绿主色加深绿点缀。改造上:输送带倾角放缓一点,出料端和主机进料口之间加个过渡料斗把两头衔接上;控制柜换成不锈钢拉丝质感;主钢架做哑光漆面金属。尺寸不用精确,按图里相对比例估就行。重点是几种材质要分得出来、主机和各装备清清楚楚别被杂物盖住,学生一眼能看明白哪是操作台、料从哪进、哪有转动部件。保持干净的产品级观感:三点柔光棚、浅灰渐变背景、四分之三俯视把整机拍全。最后给我一张高分辨率渲染图,Blender 工程也留着,方便后面加标注、换角度。12345678910111213141516#!/bin/bashset -euo pipefailversion=4.2.10filename="blender-${version}-linux-x64.tar.xz"base_url="https://download.blender.org/release/Blender4.2"checksum=7b888b36cf5bd7e35d495eb9717f7a9b645ea5f2fb4fe9850991800b8f08d531curl --fail --location --retry 3 "${base_url}/${filename}" -o "/tmp/${filename}" || \ curl --fail --location --retry 3 "https://mirrors.ocf.berkeley.edu/blender/release/Blender4.2/${filename}" -o "/tmp/${filename}"cd /tmpprintf '%s %s\n' "$checksum" "$filename" | sha256sum --check -mkdir -p /opt/blendertar -xJf "$filename" --strip-components=1 -C /opt/blender/opt/blender/4.2/python/bin/python3.11 -m ensurepip/opt/blender/4.2/python/bin/python3.11 -m pip install --no-cache-dir requests==2.32.5rm "/tmp/${filename}"/opt/blender/blender --background --factory-startup --python-exit-code 2 --python-expr 'import bpy, requests; assert bpy.app.version == (4, 2, 10), bpy.app.version_string; print(bpy.app.version_string)'1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980#!/usr/local/bin/python"""Own a Blender session and expose its MCP server over clean stdio."""import osfrom pathlib import Pathimport signalimport socketimport subprocessimport sysimport time
def main(): env = os.environ.copy() env.setdefault("PATH", "/opt/blender:/usr/local/bin:/usr/bin:/bin") env["BLENDERMCP_NO_UPDATE_CHECK"] = "1" env["BLENDER_MCP_DISABLE_TELEMETRY"] = "1" env.setdefault("BLENDER_MCP_ADDON_PATH", "/opt/bw-mcp/addon.py") # Separate ports allow multiple MCP clients without borrowing another client's scene. with socket.socket() as reservation: reservation.bind(("127.0.0.1", 0)) port = reservation.getsockname()[1] env.update(BLENDER_HOST="127.0.0.1", BLENDER_PORT=str(port)) log = Path(env.get("BW_BLENDER_LOG", "/logs/artifacts/blender-mcp.log")) log.parent.mkdir(parents=True, exist_ok=True) blender = None server = None
def interrupted(signum, _frame): raise SystemExit(128 + signum)
for sig in (signal.SIGINT, signal.SIGTERM): signal.signal(sig, interrupted) try: with log.open("a") as stream: blender = subprocess.Popen( ["xvfb-run", "-a", env.get("BLENDER_BIN", "/opt/blender/blender"), "--factory-startup", "--python-exit-code", "1", "--python", str(Path(__file__).resolve().with_name("blender_startup.py"))], env=env, stdout=stream, stderr=subprocess.STDOUT, start_new_session=True) deadline = time.monotonic() + float(env.get("BW_MCP_STARTUP_TIMEOUT", "120")) while True: if blender.poll() is not None: raise RuntimeError(f"Blender exited during startup; see {log}") try: with socket.create_connection(("127.0.0.1", port), timeout=0.25): break except OSError: if time.monotonic() >= deadline: raise RuntimeError(f"Blender MCP startup timed out; see {log}") time.sleep(0.2) # stdin stays connected to the MCP client. Only this process writes to stdout. server = subprocess.Popen([env.get("BW_MCP_COMMAND", "/opt/bw-mcp/bin/mcp-for-blender")], env=env, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr, start_new_session=True) return server.wait() finally: for process in (server, blender): if process is None: continue # xvfb-run may exit before its descendants; terminate the owned process group. try: os.killpg(process.pid, signal.SIGTERM) except ProcessLookupError: pass try: process.wait(timeout=5) except subprocess.TimeoutExpired: try: os.killpg(process.pid, signal.SIGKILL) except ProcessLookupError: pass process.wait()
if __name__ == "__main__": try: raise SystemExit(main()) except (OSError, RuntimeError) as error: print(f"BlenderWorld MCP: {error}", file=sys.stderr) raise SystemExit(1)123456# Supporting tools from Appendix D.2. These package versions are release pins;# the paper specifies the tools but does not prescribe these package versions.numpy==2.2.6Pillow==11.3.0scipy==1.15.3imageio==2.37.0bw_0007/environment/LICENSEAdded+21
bw_0007/environment/blender_startup.pyAdded+21
bw_0007/environment/inputs/input.jsonAdded+9
bw_0007/environment/inputs/instruction.htmlAdded
bw_0007/environment/inputs/query.txtAdded+1
bw_0007/environment/inputs/reference_images.base64.jsonAdded
bw_0007/environment/inputs/references/image_01.jpgAdded

Large File Pointer Details
- SHA256: 1871e7c94f9b39d3bd6ab0bf1b70958585679f3cc392457b6e2154dfbd5c2eba
- Pointer size: 131 Bytes
- Size of remote file: 338 kB
bw_0007/environment/install_blender.shAdded+16
bw_0007/environment/mcp_bridge.pyAdded+80
bw_0007/environment/requirements-tools.txtAdded+6
bw_0007/instruction.mdAdded+25
bw_0007/task.tomlAdded+63
bw_0007/tests/DockerfileAdded+31
bw_0007/tests/LICENSEAdded+21
bw_0007/tests/blenderworld/__init__.pyAdded+2
bw_0007/tests/blenderworld/__main__.pyAdded+3
bw_0007/tests/blenderworld/blender_runtime.pyAdded+65
bw_0007/tests/blenderworld/cli.pyAdded+82
bw_0007/tests/blenderworld/data.pyAdded+127
bw_0007/tests/blenderworld/evaluation.pyAdded+270
bw_0007/tests/blenderworld/evaluators/__init__.pyAdded+1
bw_0007/tests/blenderworld/evaluators/asset_paths.pyAdded+163
bw_0007/tests/blenderworld/evaluators/evidence_checks.pyAdded+250
bw_0007/tests/blenderworld/evaluators/judge_blender_agent.pyAdded+878
bw_0007/tests/blenderworld/evaluators/judge_blender_binary_rubrics.pyAdded
bw_0007/tests/blenderworld/harbor_export.pyAdded+205
bw_0007/tests/blenderworld/harbor_verify.pyAdded+80
bw_0007/tests/blenderworld/render_agent.pyAdded+130
bw_0007/tests/blenderworld/runtime.pyAdded+102
bw_0007/tests/blenderworld/submissions.pyAdded+211
bw_0007/tests/dataset/dataset.jsonlAdded+1
bw_0007/tests/dataset/rubrics.jsonAdded+141
bw_0007/tests/dataset/tasks/bw_0007/query.txtAdded+1
bw_0007/tests/dataset/tasks/bw_0007/references/image_01.jpgAdded

Large File Pointer Details
- SHA256: 1871e7c94f9b39d3bd6ab0bf1b70958585679f3cc392457b6e2154dfbd5c2eba
- Pointer size: 131 Bytes
- Size of remote file: 338 kB
bw_0007/tests/dataset/tasks/bw_0007/rubric.jsonAdded+137
bw_0007/tests/dataset/tasks/bw_0007/task.jsonAdded+42
bw_0007/tests/install_blender.shAdded+16
bw_0007/tests/requirements-verifier.txtAdded+4
bw_0007/tests/test.shAdded+6
bw_0008/environment/DockerfileAdded+37
bw_0008/environment/LICENSEAdded+21
bw_0008/environment/blender_startup.pyAdded+21
bw_0008/environment/inputs/input.jsonAdded+9
bw_0008/environment/inputs/instruction.htmlAdded
bw_0008/environment/inputs/query.txtAdded+1
bw_0008/environment/inputs/reference_images.base64.jsonAdded
bw_0008/environment/inputs/references/image_01.jpgAdded

Large File Pointer Details
- SHA256: 1247858a045e8c47be79ff1b96e102f88dc99521a604c9909f0ebdc7528ad1ff
- Pointer size: 131 Bytes
- Size of remote file: 787 kB
bw_0008/environment/install_blender.shAdded+16
bw_0008/environment/mcp_bridge.pyAdded+80
bw_0008/environment/requirements-tools.txtAdded+6