diff --git "a/bw_0221/tests/blenderworld/evaluators/judge_blender_binary_rubrics.py" "b/bw_0221/tests/blenderworld/evaluators/judge_blender_binary_rubrics.py" new file mode 100644--- /dev/null +++ "b/bw_0221/tests/blenderworld/evaluators/judge_blender_binary_rubrics.py" @@ -0,0 +1,2574 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Judge Blender multi-view renders against binary rubrics with gpt-5.6-terra. + +Inputs: + - binary_rubrics_batch.json generated by gen_blender_binary_rubrics.py + - per-task reference images, by default image_assets/* + - per-task rendered PNGs, by default evaluation/multiview/*_views/*.png + +Outputs: + - per-task judgement.json files, written atomically for resume safety + - a combined batch judgement JSON + +Resume behavior: + Existing per-task judgement.json files are skipped when they are complete + unless --overwrite is passed. This makes interrupted runs restartable. +""" + +from __future__ import annotations + +import argparse +import asyncio +import base64 +import email.utils +import hashlib +import hmac +import io +import json +import logging +import mimetypes +import os +import re +import sys +import time +import urllib.parse +from datetime import datetime, timezone +from pathlib import Path +from typing import Any, Callable + +import requests + +try: + from PIL import Image, ImageFile + + ImageFile.LOAD_TRUNCATED_IMAGES = True +except Exception: # noqa: BLE001 + Image = None # type: ignore[assignment] + +try: + from json_repair import repair_json +except Exception: # noqa: BLE001 + def repair_json(s: str) -> str: + return s + + +logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") +log = logging.getLogger("judge_blender_binary_rubrics") + + +DEFAULT_API_KEY_ENV = "JUDGE_API_KEY" +_DASH_ENDPOINT = os.environ.get("JUDGE_API_ENDPOINT", "https://api.openai.com/v1/chat/completions") +DEFAULT_MODEL = os.environ.get("JUDGE_MODEL", "gpt-5.6-terra") +MAX_IMAGE_BYTES = int(1.5 * 1024 * 1024) +MAX_IMAGE_DIMENSION = 8000 +# Bound encoded image payloads for compatible gateways. +MAX_REQUEST_BODY_BYTES = 9 * 1024 * 1024 + +VIEW_ORDER = [ + "submitted_camera", + "front_context", + "left_oblique", + "right_oblique", + "high_isometric", + "top_overview", + "ceiling_cutaway", +] +IMAGE_SUFFIXES = {".png", ".jpg", ".jpeg", ".webp"} +DEFAULT_EXTRA_IMAGE_GLOBS = [ + ".eval_workspace/exports/**/*.png", + ".eval_workspace/output/**/*.png", +] +# Time-ordered frames sampled upstream (by main.sh Stage 4, via ffmpeg) from the +# model's OWN exported animation video. Judged as a temporal sequence so that +# motion/timing/turntable rubrics are not auto-failed on static stills. +DEFAULT_ANIM_FRAME_GLOBS = [ + ".eval_workspace/anim_frames/**/*.png", +] + + +JUDGE_SYSTEM = """\ +You are a strict visual judge for Blender scene reconstruction tasks. + +You will receive: +1. The original task prompt. +2. The original reference image(s), when available. +3. Multi-view rendered screenshots and additional exported images from one + submitted Blender artifact, and — for animation/video tasks — time-ordered + frames sampled from the model's own exported animation video. +4. A list of binary rubrics. Each rubric must be scored exactly 0 or 1. +5. A BLIND DESCRIPTION of the rendered screenshots, written by a separate viewer + who was NOT shown the prompt or reference. Treat it as independent evidence of + what the renders actually communicate on their own. +6. A BLIND DESCRIPTION of the reference image(s), when a reference exists, + written by a separate viewer who was NOT shown the prompt or the renders. + Treat it as an independent inventory of what the target scene should contain. + +Core principle: +Score what the submitted images actually SHOW, not what the prompt says they +should contain. The prompt describes the intended scene; it is NEVER evidence +that an object is present, recognizable, or correct. + +Scoring rules: +- Score 1 only when the submitted images provide clear, unambiguous visual + evidence that the pass_condition is satisfied. +- Score 0 when the condition is absent, contradicted, too ambiguous, or visible + only as a vague/partial hint. When genuinely in doubt, score 0. +- Use all provided views together. Do not require every view to show the same + element; one clear view is enough for object-presence rubrics. +- Both standardized multi-view renders and exported/agent camera images can + have weaknesses. Do not require all submitted images to be high quality or + mutually complete. For scene-feature rubrics, one relevant view or a small + set may establish compliance. Final-deliverable criteria are restricted below. +- Use the reference image(s) and prompt only to understand the target scene's + intent, layout, proportions, materials, and details. Do not score the + reference image itself, and do not give credit for the prompt alone. +- If a view is blank, clipped, noisy, or from a bad angle, rely on the other + views; unresolved uncertainty means score 0. + + +Evidence provenance (applies before any general "use any view" guidance): +- Group A consists of EVALUATOR rerenders. Group B contains original AUTHOR + files, including possible previews. .eval_workspace/exports is an extracted + author directory, not newly generated evaluator output. +- When a condition concerns the final image's composition, focus, noise, + background or finished appearance, cite the designated author final image. + Do not satisfy it with a preview, or fail it solely because an evaluator + camera reveals off-frame staging, clips the subject or produces noise. +- Use Group A for actual scene geometry and layout. Rendering faults such as + blank/obstructed evaluator views are not author-final-image defects. Explain + evidence conflicts without transferring a preview's defects to the final. +- Transparent author images are displayed over a neutral checkerboard; that + checkerboard is a viewing aid, not an authored scene/background defect. +- Blind descriptions are fallible observations. Check claims against actual + images before treating a missing mention as proof that an object is absent. + +Submission image guidance: +- The submitted images may include both standardized multi-view renders and + exported/agent camera PNGs. The file name is shown immediately before each + image; use those names when citing evidence. +- In this evaluation, "standardized multi-view renders" are middle-layer + Claude/Sonnet renders produced from the submitted .blend. "Exported images" + are upstream PNGs produced alongside that same .blend artifact. +- Standardized multi-view renders are best for global layout, scale, support, + spatial relationships, and whether the Blender scene is coherent. +- Exported images under exports/, output/, .eval_workspace/exports, or + .eval_workspace/output often preserve the agent's intended camera angle or + close-up details. For material, texture, ornament, small-object, and + fine-detail rubrics, inspect these exported images carefully and do not + penalize solely because an overview render is distant. +- If a close-up exported image clearly shows a required detail while a standard + render is too far away or washed out, credit the detail based on the close-up. +- Conversely, do not require every exported image or standardized multi-view + render to be high quality. If some images are blurry, clipped, distant, or + from a weak angle, rely on any other submitted image that clearly supports or + refutes the rubric. +- If views conflict, state which file/view is decisive in the evidence. +- Some submissions include a THIRD group, "Group C": evenly-spaced frames + sampled in time order (first -> last) from the model's OWN exported animation + video. When Group C frames are present, read them AS A TIME SEQUENCE and use + them to judge motion, animation, turntable, rotation, timing, playback, and + sequence rubrics. Do NOT auto-fail such a rubric merely because a single still + cannot show motion; if the ordered frames demonstrate the described motion or + coverage (e.g. the object rotates through the frames, a part moves, the camera + orbits), score that rubric 1. For a rotationally near-symmetric subject (a + plain cylinder, sphere, or a bottle with a blank/uniform label), a correctly + working turntable can look nearly identical from frame to frame — inspect the + ASYMMETRIC cues (a spout, handle, seam, logo, or the way shadows/highlights + sweep across the surface) to confirm rotation, and do NOT declare the animation + broken solely because the overall frame appears unchanged. +- Missing Group C alone does not prove missing video (sampling may fail or + the author may deliver an image sequence). Judge animation-specific rubrics + on the available temporal evidence, and do NOT + give benefit of the doubt for motion that no submitted image actually shows. + +Identity and anti-blob rules (critical): +- A rubric about an object's identity, presence, type, or proportions may be + scored 1 only if that object is independently recognizable in the renders as + that specific object, i.e. its defining features are actually visible. +- Cross-check with the BLIND DESCRIPTION: if the blind viewer did not recognize + the expected object, or saw only a featureless box, slab, plane, or blob + where that object is expected, score its identity, proportion, and quality + rubrics 0. A shape indistinguishable from a plain box does NOT satisfy + "looks like a bed / desk / chair / shelf / etc.". +- Support and physics rubrics (not floating, rests on the floor, no + intersection, has thickness) are trivially satisfied by any solid box. Judge + them on their own terms, but they NEVER imply the object is the correct thing + and must not compensate for an unrecognizable object. + +Reference comparison rules (only when a reference blind description is provided): +- Treat the two blind descriptions as independent inventories: one of the target + (reference), one of the submission (renders). Compare them object by object. +- If the reference blind description lists an object, material, color, or layout + feature that the render blind description lacks, or describes very differently, + the submission failed to reproduce it: score the matching presence, fidelity, + or quality rubric 0. +- Never credit the render for something that appears only in the reference and + not in the render blind description. Presence must be evidenced in the renders. +- If no reference blind description is provided (e.g. text-only tasks), ignore + these rules and judge from the renders plus the render blind description. + +Evidence discipline: +- Each rubric's "evidence" must be a concrete visual observation grounded in the + named views (what is actually seen, and where). Do NOT restate or paraphrase + the pass_condition as the evidence. + +Output constraints: +- Every rubric id from the input must appear exactly once in the output. +- Each score must be integer 0 or 1. + +Return ONLY a JSON object of this exact shape: +{ + "rubric_scores": [ + { + "id": "R01", + "score": 0, + "evidence": "Concise evidence grounded in the submitted images.", + "source_views": ["submitted_camera", "front_context"], + "confidence": "high|medium|low" + } + ], + "overall_notes": "Short summary of the artifact's main strengths and failures." +} +""" + + +JUDGE_USER_TEMPLATE = """\ +# Task Prompt +{prompt} + +# Reference Image Names +{reference_names} + +# Submitted Image Names +{view_names} + +# Blind Description Of The Rendered Views +The following description was written by a separate viewer who saw ONLY the +rendered views, with no access to the task prompt or reference. Use it as +independent evidence of what the renders communicate on their own. If it did not +recognize an object the prompt expects (or saw only a featureless box/blob), +score that object's identity, proportion, and quality rubrics 0. + +{blind_description} + +# Blind Description Of The Reference Image(s) +The following description was written by a separate viewer who saw ONLY the +reference image(s), with no access to the task prompt or the rendered views. Use +it as an independent inventory of what the target scene should contain. Compare +it against the blind description of the renders above: any object, material, or +layout that the reference clearly has but the renders lack or badly distort must +make the corresponding rubric score 0. + +{blind_reference_description} + +# Binary Rubrics To Score +{rubrics} + +Score every rubric strictly as 0 or 1. Reference images show the target; submitted rendered views show the artifact being judged. +""" + + +BLIND_SYSTEM = """\ +You are a neutral describer of 3D renders. You are given only multi-view +rendered screenshots of one 3D scene. You are NOT told what the scene is +supposed to be: there is no task prompt and no reference image. + +Report only what is actually visible, making no assumptions about intent. + +- Enumerate every distinct object or element you can see across the views. +- For each, give the plainest name you would naturally use for it, and list its + defining visible features (shape, parts, how it rests in the scene). +- Rate how confidently you can identify it: clear | ambiguous | unidentifiable. +- If something is only a featureless box, slab, plane, or blob that you cannot + confidently name as a specific object, say so explicitly and label it e.g. + "unidentified white box". Do NOT guess a purpose for it. +- Flag anything that looks physically wrong: floating or unsupported parts, + intersecting/overlapping bodies, paper-thin surfaces, missing room structure + (e.g. an open box with no ceiling), or washed-out / foggy / low-contrast + rendering that hides detail. +- Describe only. Do not score anything and do not reference any rubric. + +Return concise plain text; a short list is fine. Do not invent objects you +cannot actually see. + +The file name before each image is part of the evidence. If some images are +close-up/exported views and others are standardized overview renders, describe +details visible in the close-up exports and use overview renders for spatial +layout. +""" + + +BLIND_USER = """\ +Describe what is visible in these rendered multi-view screenshots. Name each +object with your natural first guess, note your identification confidence, and +flag any featureless blobs or physical problems. Do not assume what the scene is +meant to be. +""" + + +BLIND_USER_REF = """\ +Describe what is visible in this reference image (or images) of a target scene. +List every distinct object/element, name each with your natural first guess, and +note its key visible features, colors, materials, and rough layout. Do not +assume anything beyond what is shown. +""" + + +# Holistic dimension scoring: each dimension scored 1-10, equal weight by default. +DIMENSIONS = [ + { + "id": "scene_fidelity", + "name": "场景还原 / scene fidelity", + "desc": "Overall, do the renders reproduce the target scene (from the " + "reference image and/or query) as a whole: right kind of scene, " + "the main objects present, the overall arrangement recognizable.", + }, + { + "id": "physics", + "name": "物理合理性 / physical plausibility", + "desc": "Support, connection and structure: objects rest on the floor or " + "are properly attached, no floating/unsupported parts, no " + "interpenetration, parts join into real structures, room shell is " + "coherent (floor/walls/ceiling), surfaces have thickness.", + }, + { + "id": "style_color", + "name": "样式与颜色 / object style & color", + "desc": "Each object's shape/silhouette actually reads as the intended " + "object (not a featureless box), and its colors match the target.", + }, + { + "id": "realism", + "name": "overall realism", + "desc": "As one image, is it believable and coherent, with acceptable " + "render quality? (Avoid washed-out, foggy, low-contrast issues. " + "Appropriate stylistic simplification for engineering parts or " + "sketchs is acceptable as long as objects do not lose their " + "identity).", + }, + { + "id": "layout_spatial", + "name": "布局与空间关系 / layout & spatial relations", + "desc": "Relative positions, orientations and spacing of objects match " + "the reference/query (what is next to / on / in front of what).", + }, + { + "id": "proportion_scale", + "name": "比例与尺度 / proportion & scale", + "desc": "Size ratios are sensible: object-to-object and object-to-room " + "proportions look right, nothing miniature or oversized.", + }, + { + "id": "lighting_material", + "name": "光照与材质质感 / lighting & material", + "desc": "Lighting, shadows and material appearance look plausible for the " + "intended surface. A clean matte / flat finish that matches the " + "intended object is acceptable; do not penalize non-photorealistic " + "or matte materials.", + }, + { + "id": "completeness", + "name": "物件完整性 / completeness", + "desc": "Every object the query/reference requires is actually present, " + "in roughly the right count; nothing important is missing.", + }, +] + + +DIMENSION_SYSTEM = """\ +You are a strict holistic judge for Blender scene reconstruction tasks. Instead +of tiny binary checks, you rate the submission on a few broad dimensions. + +You will receive: +1. The task prompt / query (the user's intent). +2. The reference image(s) of the target scene, when available. +3. Submission images in up to three groups: evaluator-generated + multi-view renders from the submitted .blend, upstream exported images + produced alongside that same .blend artifact, and — for animation/video + tasks — time-ordered frames sampled from the model's own exported animation. +4. A BLIND DESCRIPTION of the rendered views, written by a viewer who saw ONLY + the renders (no prompt, no reference). +5. A BLIND DESCRIPTION of the reference image(s), when a reference exists, + written by a viewer who saw ONLY the reference. + +Core principle: +Score what the renders actually SHOW, not what the prompt says. The prompt and +reference define the TARGET; the renders are the SUBMISSION being judged. Never +credit the submission for something that is only in the prompt/reference but not +visible in the renders. + +Use the two blind descriptions as independent evidence: +- If the render blind viewer only saw featureless boxes/blobs where an object is + expected, the object is NOT successfully modeled — penalize style_color, + scene_fidelity and realism accordingly. +- Compare the reference blind inventory against the render blind inventory: + objects/materials/layout present in the reference but missing or badly + distorted in the renders are reconstruction failures — penalize completeness, + scene_fidelity, layout_spatial. +- When there is no reference (text-only tasks), judge fidelity against the query. + + +Evidence provenance (applies before any general "use any view" guidance): +- Group A consists of EVALUATOR rerenders. Group B contains original AUTHOR + files, including possible previews. .eval_workspace/exports is an extracted + author directory, not newly generated evaluator output. +- When a condition concerns the final image's composition, focus, noise, + background or finished appearance, cite the designated author final image. + Do not satisfy it with a preview, or fail it solely because an evaluator + camera reveals off-frame staging, clips the subject or produces noise. +- Use Group A for actual scene geometry and layout. Rendering faults such as + blank/obstructed evaluator views are not author-final-image defects. Explain + evidence conflicts without transferring a preview's defects to the final. +- Transparent author images are displayed over a neutral checkerboard; that + checkerboard is a viewing aid, not an authored scene/background defect. +- Blind descriptions are fallible observations. Check claims against actual + images before treating a missing mention as proof that an object is absent. + +Submission image guidance: +- Use the evaluator-generated multi-view renders primarily for scene + layout, scale, support, and spatial relationships. +- Use upstream exported/agent camera PNGs under exports/, output/, + .eval_workspace/exports, or .eval_workspace/output primarily for close-up + appearance, material, texture, ornament, and small-object details. +- Do not mark a detail/material failure solely because an overview render loses + detail if an exported close-up image clearly shows the required feature. +- Conversely, do not require every exported image to be high quality. If an + exported image is blurry, clipped, or from a weak angle, rely on any other + submitted image that clearly supports or refutes the rubric. +- When a "Group C" set of time-ordered animation frames is present, read it as a + time sequence and let it inform dimensions that depend on motion/animation + (e.g. whether a requested turntable/animation actually plays through). Do not + penalize animation quality for lack of motion evidence when Group C clearly + shows the motion; conversely, if no Group C frames exist, do not credit motion + that no submitted image shows. For a rotationally near-symmetric subject + (plain cylinder/sphere/bottle with a blank label), a working turntable may look + nearly identical across frames — read the asymmetric cues (spout, handle, seam, + logo, sweeping shadow/highlight) rather than concluding the motion failed just + because the whole frame looks unchanged. +- Cite the decisive file/view when explaining a score. + +Score EACH dimension as an integer from 1 to 10 using this scale: +- 9-10: essentially matches the target; only trivial flaws. +- 7-8: good; recognizable and mostly correct with minor issues. +- 5-6: acceptable but with clear, obvious problems. +- 3-4: poor; major failures, only loosely resembles the target. +- 1-2: absent, broken, or unrecognizable. + +Also make two overall judgments: +- core_objects_recognizable: true only if the main objects the query/reference + asks for are independently recognizable in the renders as those objects. +- catastrophic_failure: true ONLY if the STATIC scene/object fundamentally fails + — the main object(s) cannot be recognized (only boxes/blobs), the target + subject is not reproduced at all, or the result is unusable as the requested + subject. This judgment concerns the static geometry/material/scene ONLY. NEVER + set catastrophic_failure because of animation, motion, turntable, rotation, + timing, or playback problems — those are scored per-rubric and per-dimension, + not here. If the core object(s) are clearly recognizable and correctly + rendered, the result is NOT catastrophic even when the animation is absent, + static, or its motion is imperceptible in the sampled frames. + +Rules: +- Be strict and calibrated; do not cluster everything at 7-8. Reserve 9-10 for + genuinely faithful results and use low scores when warranted. +- Each dimension needs a concrete "reasons" grounded in the views, plus an + "issues" list of specific problems you observed (empty if none). + +Return ONLY a JSON object of this exact shape: +{ + "dimensions": [ + {"id": "scene_fidelity", "score": 7, "reasons": "concrete, view-grounded", "issues": ["..."]} + ], + "core_objects_recognizable": true, + "catastrophic_failure": false, + "overall_notes": "Short summary of main strengths and failures." +} +Include every dimension id exactly once. +""" + + +DIMENSION_USER_TEMPLATE = """\ +# Task Prompt / Query +{prompt} + +# Reference Image Names +{reference_names} + +# Submitted Image Names +{view_names} + +# Blind Description Of The Submitted Images +{blind_description} + +# Blind Description Of The Reference Image(s) +{blind_reference_description} + +# Dimensions To Score (integer 1-10 each) +{dimensions} + +Score every dimension 1-10 based strictly on the submitted images. Reference +images and query define the target; the submitted images are the submission being judged. +""" + + +def _clamp_dimensions(image: Any, max_dim: int = MAX_IMAGE_DIMENSION) -> Any: + width, height = image.size + if width <= max_dim and height <= max_dim: + return image + scale = min(max_dim / width, max_dim / height) + return image.resize((int(width * scale), int(height * scale)), Image.LANCZOS) + + +def _compress_image_to_jpeg_bytes( + image: Any, + max_bytes: int = MAX_IMAGE_BYTES, + max_dim: int = MAX_IMAGE_DIMENSION, + quality_ladder: tuple[int, ...] = (90, 80, 70, 60, 45, 30), + scale_ladder: tuple[float, ...] = (0.75, 0.5, 0.35, 0.25), +) -> bytes: + """Encode a PIL image to JPEG bytes fitting max_bytes. Walks quality_ladder at + full (clamped) resolution first and returns the highest quality that fits; only + if none fit does it fall back to scale_ladder downscaling. Callers that must + preserve resolution (e.g. the media-OSS presigned path) pass a huge max_dim and + a high-quality ladder so downscaling is an effectively unreachable last resort.""" + if image.mode == "P" and "transparency" in image.info: + image = image.convert("RGBA") + if image.mode in ("RGBA", "LA"): + rgba = image.convert("RGBA") + if rgba.getchannel("A").getextrema()[0] < 255: + # Display the original alpha over a neutral checkerboard before JPEG + # encoding. Dropping alpha silently turns transparency into black. + from PIL import ImageDraw + background = Image.new("RGBA", rgba.size, (224, 224, 224, 255)) + draw = ImageDraw.Draw(background) + cell = max(8, max(rgba.size) // 32) + for y in range(0, rgba.height, cell): + for x in range(0, rgba.width, cell): + if (x // cell + y // cell) % 2: + draw.rectangle((x, y, x + cell - 1, y + cell - 1), fill=(160, 160, 160, 255)) + image = Image.alpha_composite(background, rgba).convert("RGB") + else: + image = rgba.convert("RGB") + elif image.mode == "P": + image = image.convert("RGB") + image = _clamp_dimensions(image, max_dim=max_dim) + + for quality in quality_ladder: + buffer = io.BytesIO() + image.save(buffer, format="JPEG", quality=quality, optimize=True) + if buffer.tell() <= max_bytes: + return buffer.getvalue() + + for scale in scale_ladder: + resized = image.resize((max(1, int(image.width * scale)), max(1, int(image.height * scale))), Image.LANCZOS) + buffer = io.BytesIO() + resized.save(buffer, format="JPEG", quality=60, optimize=True) + if buffer.tell() <= max_bytes: + return buffer.getvalue() + + buffer = io.BytesIO() + image.resize((max(1, image.width // 4), max(1, image.height // 4)), Image.LANCZOS).save( + buffer, + format="JPEG", + quality=30, + optimize=True, + ) + return buffer.getvalue() + + +def _compress_image_to_base64(image: Any, max_bytes: int = MAX_IMAGE_BYTES) -> str: + return base64.b64encode(_compress_image_to_jpeg_bytes(image, max_bytes=max_bytes)).decode("ascii") + + +def image_to_data_url(path: Path, max_bytes: int = MAX_IMAGE_BYTES) -> str | None: + if not path.exists(): + return None + if Image is not None: + try: + b64 = _compress_image_to_base64(Image.open(path), max_bytes=max_bytes) + return f"data:image/jpeg;base64,{b64}" + except Exception as exc: # noqa: BLE001 + log.warning("failed to compress image %s: %s; falling back to raw data URL", path, exc) + try: + raw = path.read_bytes() + except OSError: + return None + if len(raw) > max_bytes: + log.warning( + "skipping image %s because Pillow is unavailable/failed and raw size %.1f MB exceeds %.1f MB", + path, + len(raw) / 1024 / 1024, + max_bytes / 1024 / 1024, + ) + return None + mime = mimetypes.guess_type(str(path))[0] or "image/png" + b64 = base64.b64encode(raw).decode("ascii") + return f"data:{mime};base64,{b64}" + + +# --------------------------------------------------------------------------- +# Media OSS pre-signed URL offload. +# +# the configured gateway (the judge's upstream, JUDGE_BASE_URL) enforces a request-body cap +# that oversized video-task payloads (up to 32 inline base64 images, ~14-21MB) +# blow past, forcing lossy recompression in shrink_messages_to_fit. When media +# OSS is configured (same bucket the render-agent proxy uses), upload each image +# to OSS at FULL resolution and hand the configured gateway a short-lived pre-signed GET URL +# instead of an inline data: URL. Proven to work: the render-agent's own requests +# to the same the configured gateway + gpt-5.6-terra backend already carry exactly these URLs. +# Body then shrinks to a few KB, images stay lossless, and shrink_messages_to_fit +# never fires. Any upload failure falls back to inline base64 so judging still +# proceeds. Signing is Aliyun OSS V1 query-string auth (matches the render-agent +# URL format: OSSAccessKeyId / Expires / Signature). +# --------------------------------------------------------------------------- + +_MEDIA_OSS_URL_EXPIRY_SECONDS = 12 * 3600 +_MEDIA_OSS_PUT_TIMEOUT = 60 +_MEDIA_OSS_CONTENT_TYPES = { + ".png": "image/png", + ".jpg": "image/jpeg", + ".jpeg": "image/jpeg", + ".webp": "image/webp", +} +_media_oss_uploaded_keys: set[str] = set() # content-hash of images already PUT this process + +# Per-image budget for the media-OSS presigned-URL path. the configured gateway downloads each +# presigned URL and rejects any single image over its per-image size limit with +# "Image size exceeds the limit" — a deterministic 400 on full-resolution 4K hero +# PNGs (~37MB) that zeroes the whole judge (rubric_batch_size=0 -> missing scores). +# The upstream limit is ~20MB, so we keep images comfortably under it WITHOUT +# reducing resolution: an image already within budget uploads byte-for-byte +# (untouched, lossless); an oversized one is re-encoded PNG->JPEG at FULL +# resolution and the highest quality that fits (the VLM downsamples to ~1536px +# internally, so full-res JPEG q95 is lossless for judging). Resolution is only +# reduced as an unreachable last resort (full-res q80 still over budget). Tunable +# via JUDGE_MEDIA_OSS_MAX_MB (default 15MB, a safe margin below the ~20MB cap). +_MEDIA_OSS_MAX_IMAGE_BYTES = int(float(os.environ.get("JUDGE_MEDIA_OSS_MAX_MB", "15") or 15) * 1024 * 1024) +_MEDIA_OSS_JPEG_QUALITY_LADDER = (95, 92, 90, 88, 85, 82, 80) +_MEDIA_OSS_LASTRESORT_SCALES = (0.85, 0.7, 0.55, 0.4) +_MEDIA_OSS_NO_DIM_CLAMP = 10_000_000 # effectively disable dimension downscaling on the JPEG path + + +def _media_oss_config() -> dict[str, str] | None: + if str(os.environ.get("MEDIA_OSS_ENABLED", "")).strip().lower() not in ("1", "true", "yes", "on"): + return None + bucket = os.environ.get("MEDIA_OSS_BUCKET", "").strip() + endpoint = os.environ.get("MEDIA_OSS_ENDPOINT", "").strip() + akid = os.environ.get("MEDIA_OSS_ACCESS_KEY_ID", "").strip() + secret = os.environ.get("MEDIA_OSS_ACCESS_KEY_SECRET", "").strip() + if not (bucket and endpoint and akid and secret): + return None + endpoint = endpoint.replace("https://", "").replace("http://", "").strip("/") + prefix = os.environ.get("MEDIA_OSS_OBJECT_PREFIX", "").strip().strip("/") + return {"bucket": bucket, "endpoint": endpoint, "akid": akid, "secret": secret, "prefix": prefix} + + +def _oss_sign(secret: str, string_to_sign: str) -> str: + digest = hmac.new(secret.encode("utf-8"), string_to_sign.encode("utf-8"), hashlib.sha1).digest() + return base64.b64encode(digest).decode("ascii") + + +def _oss_presigned_get_url(cfg: dict[str, str], key: str, expiry: int = _MEDIA_OSS_URL_EXPIRY_SECONDS) -> str: + expires = int(time.time()) + expiry + string_to_sign = f"GET\n\n\n{expires}\n/{cfg['bucket']}/{key}" + signature = _oss_sign(cfg["secret"], string_to_sign) + path = urllib.parse.quote(key, safe="/") + query = urllib.parse.urlencode({"OSSAccessKeyId": cfg["akid"], "Expires": expires, "Signature": signature}) + return f"https://{cfg['bucket']}.{cfg['endpoint']}/{path}?{query}" + + +def _oss_put_object(cfg: dict[str, str], key: str, data: bytes, content_type: str) -> None: + date = email.utils.formatdate(timeval=time.time(), usegmt=True) + string_to_sign = f"PUT\n\n{content_type}\n{date}\n/{cfg['bucket']}/{key}" + signature = _oss_sign(cfg["secret"], string_to_sign) + path = urllib.parse.quote(key, safe="/") + url = f"https://{cfg['bucket']}.{cfg['endpoint']}/{path}" + headers = { + "Date": date, + "Content-Type": content_type, + "Authorization": f"OSS {cfg['akid']}:{signature}", + } + resp = requests.put(url, data=data, headers=headers, timeout=_MEDIA_OSS_PUT_TIMEOUT) + resp.raise_for_status() + + +def _media_oss_upload_image(path: Path) -> str | None: + cfg = _media_oss_config() + if cfg is None: + return None + try: + raw = path.read_bytes() + except OSError as exc: + log.warning("media-oss: cannot read %s: %s", path, exc) + return None + if not raw: + return None + + ext = path.suffix.lower() + if ext not in _MEDIA_OSS_CONTENT_TYPES: + ext = ".png" + data = raw + # Keep the image under the configured gateway's per-image download limit WITHOUT touching its + # resolution. In-budget images upload byte-for-byte (untouched, lossless); an + # oversized one is re-encoded PNG->JPEG at FULL resolution (no downscale except + # as an unreachable last resort), which turns a ~37MB 4K PNG into a ~5-8MB + # full-res JPEG the VLM cannot distinguish from the original at its ~1536px + # working resolution. Falls back to uploading the raw bytes if Pillow is missing + # or re-encoding fails, so judging still proceeds. + if len(raw) > _MEDIA_OSS_MAX_IMAGE_BYTES and Image is not None: + try: + with Image.open(io.BytesIO(raw)) as im: + width, height = im.size + data = _compress_image_to_jpeg_bytes( + im, + max_bytes=_MEDIA_OSS_MAX_IMAGE_BYTES, + max_dim=_MEDIA_OSS_NO_DIM_CLAMP, + quality_ladder=_MEDIA_OSS_JPEG_QUALITY_LADDER, + scale_ladder=_MEDIA_OSS_LASTRESORT_SCALES, + ) + ext = ".jpg" + log.info( + "media-oss: re-encoded oversized %s (%.1fMB PNG %dx%d) -> %.2fMB full-res JPEG (<=%.0fMB budget)", + path.name, len(raw) / 1024 / 1024, width, height, + len(data) / 1024 / 1024, _MEDIA_OSS_MAX_IMAGE_BYTES / 1024 / 1024, + ) + except Exception as exc: # noqa: BLE001 + log.warning("media-oss: re-encode failed for %s: %s; uploading original bytes", path, exc) + data = raw + ext = path.suffix.lower() + if ext not in _MEDIA_OSS_CONTENT_TYPES: + ext = ".png" + elif len(raw) > _MEDIA_OSS_MAX_IMAGE_BYTES: + log.warning( + "media-oss: %s is %.1fMB and Pillow is unavailable; uploading raw (may exceed the limit)", + path, len(raw) / 1024 / 1024, + ) + + content_type = _MEDIA_OSS_CONTENT_TYPES[ext] + digest = hashlib.sha1(data).hexdigest()[:24] + key = "/".join(p for p in (cfg["prefix"], "judge", f"{digest}{ext}") if p) + retries = max(1, int(os.environ.get("MEDIA_OSS_IMAGE_URL_MAX_RETRIES", "3") or 3)) + if digest not in _media_oss_uploaded_keys: + last_exc: Exception | None = None + for _attempt in range(retries): + try: + _oss_put_object(cfg, key, data, content_type) + _media_oss_uploaded_keys.add(digest) + last_exc = None + break + except Exception as exc: # noqa: BLE001 + last_exc = exc + if last_exc is not None: + log.warning( + "media-oss: upload failed for %s after %d attempt(s): %s; falling back to base64", + path, retries, last_exc, + ) + return None + return _oss_presigned_get_url(cfg, key) + + +def image_to_attach_url(path: Path, max_bytes: int = MAX_IMAGE_BYTES) -> str | None: + """Value for image_url.url: a media-OSS pre-signed URL (full-resolution, + lossless) when media OSS is configured, else an inline base64 data URL. + + Media OSS avoids the configured gateway's request-body cap entirely, so no recompression is + needed. On any upload failure we fall back to base64 so judging still runs. + """ + if not path.exists(): + return None + if _media_oss_config() is not None: + url = _media_oss_upload_image(path) + if url: + return url + # upload failed -> fall through to base64 so judging still proceeds + return image_to_data_url(path, max_bytes=max_bytes) + + +def _iter_image_parts(messages: list[dict[str, Any]]): + """Yield (content_list, index, part) for every inline data: image_url part.""" + for message in messages: + content = message.get("content") + if not isinstance(content, list): + continue + for idx, part in enumerate(content): + if not isinstance(part, dict) or part.get("type") != "image_url": + continue + url = (part.get("image_url") or {}).get("url", "") + if isinstance(url, str) and url.startswith("data:"): + yield content, idx, part + + +def _request_body_size(messages: list[dict[str, Any]]) -> int: + """Approximate the byte size of the eventual POST body. + + call_gpt55 sends ``requests.post(json={"model", "messages", ...})`` which serializes with + ensure_ascii=True; base64 image data (which dominates the payload) is ASCII so ensure_ascii + is size-neutral for it. Add a fixed slack for the wrapper keys so the measurement matches + the Content-Length the configured gateway actually enforces. + """ + return len(json.dumps({"messages": messages}, ensure_ascii=False).encode("utf-8")) + 8192 + + +def shrink_messages_to_fit(messages: list[dict[str, Any]], max_body: int = MAX_REQUEST_BODY_BYTES) -> list[dict[str, Any]]: + if next(_iter_image_parts(messages), None) is None: + return messages + + size = _request_body_size(messages) + if size <= max_body: + return messages + + if Image is None: + log.warning( + "Pillow unavailable; cannot shrink oversized request body (%.1f MB > %.1f MB cap)", + size / 1024 / 1024, + max_body / 1024 / 1024, + ) + return messages + + log.warning( + "request body %.1f MB exceeds %.1f MB cap; recompressing %d image(s)", + size / 1024 / 1024, + max_body / 1024 / 1024, + sum(1 for _ in _iter_image_parts(messages)), + ) + + # Iteratively recompress every oversized image, tightening the per-image budget each round + # until the whole body fits. The per-image budget is derived from the images that remain, + # so a single pass usually suffices; the loop is a convergence guard for the case where + # many images already sit below budget and only a few dominate. + for iteration in range(6): + parts = [(part, (part.get("image_url") or {}).get("url", "")) for _c, _i, part in _iter_image_parts(messages)] + n = len(parts) + if n == 0: + break + squeeze = 0.85 ** iteration + per_image_b64 = max(1, int(((max_body - 8192) // n) * squeeze)) + per_image_raw = max(1, int(per_image_b64 * 3 / 4)) + for part, url in parts: + _, _, b64_data = url.partition(",") + try: + raw = base64.b64decode(b64_data) + if len(raw) <= per_image_raw: + continue + b64 = _compress_image_to_base64(Image.open(io.BytesIO(raw)), max_bytes=per_image_raw) + part["image_url"]["url"] = f"data:image/jpeg;base64,{b64}" + except Exception as exc: # noqa: BLE001 + log.warning("failed to shrink image in request body: %s", exc) + size = _request_body_size(messages) + if size <= max_body: + log.warning( + "recompress pass %d -> %.1f MB (under %.1f MB cap)", + iteration + 1, + size / 1024 / 1024, + max_body / 1024 / 1024, + ) + return messages + + # Recompression alone did not fit (e.g. Pillow could not squeeze far enough). Last resort: + # drop trailing image_url parts together with their immediately-preceding label text. Images + # are appended hero-renders/references first and animation-frames/extras last, so trailing + # drops shed the least-critical frames first. + dropped = 0 + while size > max_body: + tail = None + for content, idx, part in _iter_image_parts(messages): + tail = (content, idx) + if tail is None: + break + content, idx = tail + del content[idx] + if idx - 1 >= 0 and isinstance(content[idx - 1], dict) and content[idx - 1].get("type") == "text": + del content[idx - 1] + dropped += 1 + size = _request_body_size(messages) + if dropped: + log.warning( + "dropped %d trailing image(s) to fit request under %.1f MB cap -> %.1f MB", + dropped, + max_body / 1024 / 1024, + size / 1024 / 1024, + ) + return messages + + +def rel(path: Path, root: Path) -> str: + try: + return path.resolve().relative_to(root.resolve()).as_posix() + except ValueError: + return path.resolve().as_posix() + + +def image_label(path: Path, root: Path | None = None) -> str: + if root is not None: + return rel(path, root) + return path.name + + +def append_labeled_images( + content: list[dict[str, Any]], + paths: list[Path], + *, + role: str, + label_root: Path | None = None, +) -> int: + attached = 0 + for path in paths: + url = image_to_attach_url(path) + if not url: + continue + content.append({"type": "text", "text": f"{role} image file: {image_label(path, label_root)}"}) + content.append({"type": "image_url", "image_url": {"url": url}}) + attached += 1 + return attached + + +def append_labeled_image_groups( + content: list[dict[str, Any]], + groups: list[tuple[str, str, list[Path]]], + *, + label_root: Path | None = None, +) -> int: + attached = 0 + for title, role, paths in groups: + if not paths: + content.append({"type": "text", "text": f"{title}: (none found)"}) + continue + content.append({"type": "text", "text": f"{title}:"}) + attached += append_labeled_images(content, paths, role=role, label_root=label_root) + return attached + + +def _clean_json(raw: str | None) -> str: + text = (raw or "").strip() + if text.startswith("```"): + text = text.strip("`") + if text.lower().startswith("json"): + text = text[4:] + return text.strip() + + +def _extract_first_json_object(text: str) -> str | None: + start = text.find("{") + if start < 0: + return None + depth = 0 + in_string = False + escape = False + for idx in range(start, len(text)): + ch = text[idx] + if in_string: + if escape: + escape = False + elif ch == "\\": + escape = True + elif ch == '"': + in_string = False + continue + if ch == '"': + in_string = True + elif ch == "{": + depth += 1 + elif ch == "}": + depth -= 1 + if depth == 0: + return text[start: idx + 1] + return text[start:] if start >= 0 else None + + +def parse_json_obj(raw: str | None) -> dict[str, Any] | None: + text = _clean_json(raw) + candidates = [text] + extracted = _extract_first_json_object(text) + if extracted and extracted not in candidates: + candidates.append(extracted) + for candidate in candidates: + for repaired in (candidate, repair_json(candidate)): + try: + obj = json.loads(repaired) + except Exception: + continue + if isinstance(obj, dict): + return obj + return None + + +def raw_preview(raw: str | None, limit: int = 1200) -> str: + text = (raw or "").strip().replace("\r", "") + return text[:limit] + ("..." if len(text) > limit else "") + + +def parse_stream_response(response: requests.Response) -> dict[str, Any]: + result_content = "" + stop_reason = None + usage = None + has_data = False + for line in response.iter_lines(decode_unicode=True): + if not line or not line.startswith("data: "): + continue + data_str = line[6:].strip() + if data_str == "[DONE]": + break + try: + chunk = json.loads(data_str) + except json.JSONDecodeError: + log.warning("failed to parse stream chunk: %s", data_str[:200]) + continue + has_data = True + choices = chunk.get("choices") or [] + if choices: + delta = choices[0].get("delta") or {} + content = delta.get("content") or "" + if content: + result_content += content + finish = choices[0].get("finish_reason") + if finish: + stop_reason = finish + if chunk.get("usage"): + usage = chunk["usage"] + if not has_data: + raise ValueError("No chunks in stream response") + return { + "choices": [{"message": {"content": result_content}, "finish_reason": stop_reason}], + "usage": usage, + } + + +def post_sync(endpoint: str, api_key: str, body: dict[str, Any], timeout: int) -> dict[str, Any]: + auth = api_key if api_key.lower().startswith("bearer ") else f"Bearer {api_key}" + headers = {"Content-Type": "application/json", "Authorization": auth} + stream = bool(body.get("stream")) + response = requests.post(endpoint, headers=headers, json=body, timeout=timeout, stream=stream) + if response.status_code != 200: + raise requests.HTTPError(f"{response.status_code}: {response.text[:2000]}", response=response) + if stream: + return parse_stream_response(response) + return response.json() + + +def extract_openai(obj: dict[str, Any]) -> str | None: + choices = obj.get("choices") if isinstance(obj, dict) else None + if not choices: + return None + return (choices[0].get("message") or {}).get("content") + + +async def call_gpt55( + user_text: str, + reference_image_paths: list[Path], + rendered_image_paths: list[Path], + model: str, + api_key: str, + max_tokens: int, + timeout: int, + retries: int, + sem: asyncio.Semaphore, + image_detail: str, + api_endpoint: str = _DASH_ENDPOINT, + system_prompt: str = JUDGE_SYSTEM, + rendered_caption: str = "Submitted rendered multi-view image(s) to score:", + label_root: Path | None = None, + rendered_image_groups: list[tuple[str, str, list[Path]]] | None = None, +) -> str | None: + content: list[dict[str, Any]] = [] + + content.append({"type": "text", "text": user_text}) + if reference_image_paths: + content.append({"type": "text", "text": "Reference image(s) for the target scene:"}) + append_labeled_images(content, reference_image_paths, role="Reference", label_root=label_root) + content.append({"type": "text", "text": rendered_caption}) + if rendered_image_groups is not None: + attached_submission_images = append_labeled_image_groups( + content, + rendered_image_groups, + label_root=label_root, + ) + else: + attached_submission_images = append_labeled_images( + content, + rendered_image_paths, + role="Submission", + label_root=label_root, + ) + if rendered_image_paths and attached_submission_images == 0: + log.warning("no submission images could be attached after compression/filtering") + return None + messages = shrink_messages_to_fit( + [ + {"role": "system", "content": system_prompt}, + {"role": "user", "content": content}, + ] + ) + body = { + "model": model, + "messages": messages, + "stream": True, + "reasoning_effort": "xhigh", + "max_output_tokens": max_tokens, + } + for attempt in range(retries): + async with sem: + try: + obj = await asyncio.to_thread(post_sync, api_endpoint, api_key, body, timeout) + # Counters only: never persist the request, API key or signed URLs. + usage_log = os.environ.get("JUDGE_USAGE_LOG") + if usage_log and obj.get("usage"): + with open(usage_log, "a", encoding="utf-8") as handle: + handle.write(json.dumps({"type": "api_usage", "model": model, "usage": obj["usage"]}) + "\n") + out = extract_openai(obj) + if out: + return out + log.warning("empty model output attempt=%d: %s", attempt + 1, json.dumps(obj)[:300]) + except Exception as exc: # noqa: BLE001 + log.warning("judge call failed attempt=%d: %s", attempt + 1, exc) + await asyncio.sleep(1 + attempt) + return None + + +def validate_rubric_json(obj: dict[str, Any] | None, rubrics: list[dict[str, Any]]) -> str: + ok, _, error = normalize_scores(obj, rubrics) + return "" if ok else error + + +def validate_dimension_json(obj: dict[str, Any] | None) -> str: + result = score_dimensions(obj, DIMENSIONS) + return "" if result["ok"] else str(result.get("error") or "invalid dimension JSON") + + +async def call_json_gpt55( + *, + user_text: str, + reference_image_paths: list[Path], + rendered_image_paths: list[Path], + model: str, + api_key: str, + max_tokens: int, + timeout: int, + retries: int, + json_retries: int, + sem: asyncio.Semaphore, + image_detail: str, + api_endpoint: str, + validate: Callable[[dict[str, Any] | None], str], + system_prompt: str = JUDGE_SYSTEM, + rendered_caption: str = "Submitted rendered multi-view image(s) to score:", + label_root: Path | None = None, + rendered_image_groups: list[tuple[str, str, list[Path]]] | None = None, + kind: str = "judge", +) -> tuple[str | None, dict[str, Any] | None, dict[str, Any]]: + attempts = max(1, json_retries) + invalid_attempts: list[dict[str, Any]] = [] + prompt = user_text + last_raw: str | None = None + last_parsed: dict[str, Any] | None = None + + for attempt in range(attempts): + raw = await call_gpt55( + user_text=prompt, + reference_image_paths=reference_image_paths, + rendered_image_paths=rendered_image_paths, + model=model, + api_key=api_key, + max_tokens=max_tokens, + timeout=timeout, + retries=retries, + sem=sem, + image_detail=image_detail, + api_endpoint=api_endpoint, + system_prompt=system_prompt, + rendered_caption=rendered_caption, + label_root=label_root, + rendered_image_groups=rendered_image_groups, + ) + last_raw = raw + last_parsed = parse_json_obj(raw) + error = validate(last_parsed) + if not error: + return raw, last_parsed, { + "kind": kind, + "json_ok": True, + "json_attempts": attempt + 1, + "invalid_json_attempts": invalid_attempts, + } + + invalid_attempts.append( + { + "attempt": attempt + 1, + "error": error, + "raw_preview": raw_preview(raw), + } + ) + log.warning("%s JSON invalid attempt=%d/%d: %s", kind, attempt + 1, attempts, error) + prompt = ( + user_text + + "\n\n# Output Correction\n" + + f"Your previous {kind} answer was invalid: {error}.\n" + + "Return ONLY one valid JSON object matching the required schema. " + + "Do not include markdown fences, commentary, or trailing text. " + + "Include every required id exactly once." + ) + + return last_raw, last_parsed, { + "kind": kind, + "json_ok": False, + "json_attempts": attempts, + "invalid_json_attempts": invalid_attempts, + } + + +async def describe_blind( + image_paths: list[Path], + model: str, + api_key: str, + max_tokens: int, + timeout: int, + retries: int, + sem: asyncio.Semaphore, + image_detail: str, + api_endpoint: str = _DASH_ENDPOINT, + user_text: str = BLIND_USER, + caption: str = "Rendered multi-view image(s) to describe:", + image_groups: list[tuple[str, str, list[Path]]] | None = None, + label_root: Path | None = None, +) -> str | None: + """Prompt-free pass: describe the given images with no access to prompt/reference/rubric.""" + return await call_gpt55( + user_text=user_text, + reference_image_paths=[], + rendered_image_paths=image_paths, + model=model, + api_key=api_key, + max_tokens=max_tokens, + timeout=timeout, + retries=retries, + sem=sem, + image_detail=image_detail, + api_endpoint=api_endpoint, + system_prompt=BLIND_SYSTEM, + rendered_caption=caption, + label_root=label_root, + rendered_image_groups=image_groups, + ) + + +def load_rubric_results(path: Path) -> list[dict[str, Any]]: + obj = json.loads(path.read_text(encoding="utf-8")) + results = obj.get("results") + if not isinstance(results, list): + raise ValueError(f"missing results list in {path}") + return results + + +def task_name(task_dir: Path) -> str: + return task_dir.name.rstrip("/") + + +def find_reference_images(task_dir: Path, pattern: str, max_images: int) -> list[Path]: + images = [p for p in task_dir.glob(pattern) if p.is_file()] + images = sorted(images, key=lambda path: str(path)) + if max_images > 0: + images = images[:max_images] + return images + + +def find_render_images(task_dir: Path, pattern: str, max_images: int) -> list[Path]: + images = [p for p in task_dir.glob(pattern) if p.is_file() and p.suffix.lower() in IMAGE_SUFFIXES] + + def key(path: Path) -> tuple[int, str]: + stem = path.stem + try: + rank = VIEW_ORDER.index(stem) + except ValueError: + rank = len(VIEW_ORDER) + return rank, str(path) + + images = sorted(images, key=key) + if max_images > 0: + images = images[:max_images] + return images + + +def dedupe_paths(paths: list[Path]) -> list[Path]: + seen: set[str] = set() + out: list[Path] = [] + for path in paths: + key = str(path.resolve()) + if key in seen: + continue + seen.add(key) + out.append(path) + return out + + +def parse_glob_list(value: str | list[str] | tuple[str, ...]) -> list[str]: + # Repeated --extra-image-glob flags arrive as a list, and each flag may + # itself contain comma-separated patterns (as main.sh passes them). + values = [value] if isinstance(value, str) else value + return [part.strip() for item in values for part in item.split(",") if part.strip()] + + +# Directories whose images are texture / material / thumbnail / cache assets, +# i.e. inputs or intermediates, not deliverable scene renders. +AUX_DIR_NAMES = { + "_tex", "tex", "texture", "textures", "_textures", "tex_maps", "texmaps", + "maps", "_maps", "matcap", "matcaps", "material", "materials", + "thumb", "thumbs", "thumbnail", "thumbnails", "_thumbnails", + "cache", "_cache", "bake", "_bake", "baked", "hdri", "_hdri", "hdris", + "lightmaps", "uv", "uvs", "mask", "masks", "alpha", "alphas", + "preview", "previews", "_preview", "_previews", +} +# Filename prefixes that indicate PBR texture maps rather than scene renders. +AUX_NAME_PREFIXES = ("tex_", "texture_", "mat_", "material_", "uv_", "mask_") +AUX_NAME_TOKENS = { + "albedo", "ambientocclusion", "ao", "basecolor", "base_color", "bump", + "diffuse", "displacement", "disp", "emission", "gloss", "height", + "metallic", "metalness", "normal", "normalgl", "normaldx", "opacity", + "roughness", "specular", "transmission", "uv", "uvmap", +} +# Filename tokens that mark denoise / render-debug DIAGNOSTIC images +# (e.g. `_cycles_diag.png`, `_cycles_oidn_volume_diag.png`): intermediate +# noise/denoise debug renders, never scene deliverables, so they must never +# consume an extra-image slot. Kept deliberately narrow so real deliverable names +# are unaffected: no generic engine words like "cycles", and NO ordinary scene +# words. In particular "noisy" (e.g. noisy_market_4k.png) and "aov" (aov_beauty.png) +# were dropped — they are plausible descriptive deliverable names and matched as +# exact tokens, so they risked filtering real heroes; the debug renders they +# targeted are already "_"-prefixed and demoted by is_intermediate_name anyway. +# The retained tokens describe OpenImageDenoise/AOV-debug passes specifically. +AUX_DIAGNOSTIC_TOKENS = {"diag", "oidn", "denoise"} +# Absolute ceiling on extra submission images even when a task exports more real +# deliverables than max_images (adaptive-cap safety valve): keeps the VLM prompt +# bounded while guaranteeing every hero deliverable of a normal submission is shown. +EXTRA_IMAGE_HARD_CEILING = 10 +# A same-directory numeric run this long or longer is treated as an animation +# sequence and down-sampled, so its earliest frames cannot fill the cap and +# crowd out the real deliverable (e.g. the final assembled frame). +SEQUENCE_MIN_LEN = 8 +# Representative frames kept per large sequence (evenly spaced, always including +# the first and the last / final-result frame). Chosen so a borderline sequence +# keeps about as many frames as the old first-N cap while still surfacing the +# final result rather than only the opening frames. +SEQUENCE_SAMPLE = 6 + + +def is_auxiliary_image(path: Path, root: Path) -> bool: + """True for texture/material/thumbnail/cache assets that are not renders.""" + try: + rel_parts = path.relative_to(root).parts + except ValueError: + rel_parts = path.parts + for part in rel_parts[:-1]: + if part.lower() in AUX_DIR_NAMES: + return True + name = path.name.lower() + if name.startswith(AUX_NAME_PREFIXES): + return True + stem = path.stem.lower() + tokens = {part for part in re.split(r"[^a-z0-9]+", stem) if part} + if tokens & AUX_NAME_TOKENS: + return True + # Denoise / render-debug diagnostic intermediates (e.g. `_cycles_diag`, + # `_cycles_oidn_volume_diag`) are never scene deliverables. + return bool(tokens & AUX_DIAGNOSTIC_TOKENS) + + +def sequence_key(path: Path) -> tuple[str, int] | None: + """For a frame like frame_0007, return (group_id, 7); else None. group_id + ties frames sharing a directory and stem prefix (frame_0001..frame_0185).""" + stem = path.stem + i = len(stem) + while i > 0 and stem[i - 1].isdigit(): + i -= 1 + if i == len(stem): + return None + try: + num = int(stem[i:]) + except ValueError: + return None + return (str(path.parent) + "::" + stem[:i], num) + + +def sample_indices(n: int, k: int) -> list[int]: + """Evenly spaced indices over [0, n-1], inclusive of first and last.""" + if k >= n: + return list(range(n)) + if k <= 1: + return [n - 1] + return sorted({round(i * (n - 1) / (k - 1)) for i in range(k)}) + + +def is_intermediate_name(path: Path) -> bool: + """True for render-agent intermediates/previews that use the leading-underscore + convention (e.g. `_preview_autumn.png`, `_cycles_diag.png`). These are real (or + degraded/preview) images but must rank BELOW proper deliverables so they can + never crowd a hero render out of a capped extra-image slot. A leading `_` is the + render agents' consistent marker for hidden/intermediate outputs; genuine + deliverables are letter-prefixed (autumn_main_4k, dragon_treasure_cave_preview), + so this deliberately keys on the PREFIX, not a `preview`/`diag` substring.""" + return path.name.startswith("_") + + +def extra_image_sort_key(path: Path) -> tuple[int, int, int, str, int]: + """Sort order for extra submission images (most-important first): + 1. priority — real deliverables (0) before `_`-prefixed intermediates (1). + 2. depth — shallower paths first. + 3. kind — standalone renders (0) before sequence samples (1), so a lone + hero deliverable can never be pushed past sampled frames. + 4. tie-break — alphabetical path (standalone) or sequence group id. + 5. frame no. — numeric-aware ordering within a sequence. + The leading priority tier is what stops `_`-prefixed previews and denoise + diagnostics from sorting ahead of hero deliverables under a plain alphabetical + tie (ASCII `_` (0x5F) < letters), which previously let them fill every capped + slot and exclude the real *_main_4k renders.""" + priority = 1 if is_intermediate_name(path) else 0 + seq = sequence_key(path) + depth = len(path.parts) + if seq is not None: + return (priority, depth, 1, seq[0], seq[1]) + return (priority, depth, 0, str(path).lower(), -1) + + +def find_extra_submission_images(task_dir: Path, patterns: str | list[str], max_images: int) -> list[Path]: + images: list[Path] = [] + for pattern in parse_glob_list(patterns): + images.extend( + path + for path in task_dir.glob(pattern) + if path.is_file() and path.suffix.lower() in IMAGE_SUFFIXES + ) + images = dedupe_paths(images) + input_manifest = task_dir / "input_media_sha256.json" + if input_manifest.exists(): + input_hashes = set(json.loads(input_manifest.read_text())) + images = [p for p in images if hashlib.sha256(p.read_bytes()).hexdigest() not in input_hashes] + if not images: + return [] + + # Keep deliverable renders; input textures are not author-rendered evidence. + filtered = [path for path in images if not is_auxiliary_image(path, task_dir)] + + if max_images <= 0: + return dedupe_paths(sorted(filtered, key=extra_image_sort_key)) + + # Collapse large numeric frame sequences to evenly-spaced representatives + # (always including the final frame) so early frames cannot crowd out the + # real deliverable when the cap is applied. + groups: dict[str, list[Path]] = {} + standalone: list[Path] = [] + for path in filtered: + seq = sequence_key(path) + if seq is None: + standalone.append(path) + else: + groups.setdefault(seq[0], []).append(path) + + selected: list[Path] = list(standalone) + for members in groups.values(): + members.sort(key=lambda path: sequence_key(path)[1]) + if len(members) >= SEQUENCE_MIN_LEN: + selected.extend(members[i] for i in sample_indices(len(members), SEQUENCE_SAMPLE)) + else: + selected.extend(members) + + # Deliverables first, `_`-prefixed intermediates/previews after; then cap. + # Adaptive cap: guarantee every real deliverable (priority-0, non-underscore) + # is kept even if there are more of them than max_images, so a multi-hero + # submission (e.g. autumn/winter/close-up 4K renders) is never truncated below + # its deliverable count. Intermediates and sequence samples then fill any + # remaining slots, all bounded by EXTRA_IMAGE_HARD_CEILING. + selected = dedupe_paths(sorted(selected, key=extra_image_sort_key)) + # max_images > 0 is guaranteed here (the <= 0 case returned early above). + deliverable_count = sum(1 for path in selected if not is_intermediate_name(path)) + effective_max = min(EXTRA_IMAGE_HARD_CEILING, max(max_images, deliverable_count)) + selected = selected[:effective_max] + return selected + + +def find_animation_frames(task_dir: Path, patterns: str | list[str], max_images: int) -> list[Path]: + """Collect time-ordered animation frames (sampled upstream by main.sh from the + model's exported video) under .eval_workspace/anim_frames. Unlike + find_extra_submission_images these are NOT re-downsampled — main.sh already + picked an evenly-spaced set — they are only ordered by (group, frame number) + via extra_image_sort_key and capped at max_images.""" + images: list[Path] = [] + for pattern in parse_glob_list(patterns): + images.extend( + path + for path in task_dir.glob(pattern) + if path.is_file() and path.suffix.lower() in IMAGE_SUFFIXES + ) + images = dedupe_paths(images) + if not images: + return [] + images = sorted(images, key=extra_image_sort_key) + if max_images > 0: + images = images[:max_images] + return images + + +def output_path(task_dir: Path, output_dir: str) -> Path: + out = Path(output_dir) + if out.is_absolute(): + return out / task_name(task_dir) / "judgement.json" + return task_dir / out / "judgement.json" + + +def is_complete_judgement(path: Path, rubric_ids: set[str]) -> bool: + if not path.exists(): + return False + try: + obj = json.loads(path.read_text(encoding="utf-8")) + except Exception: + return False + if not obj.get("ok"): + return False + scores = obj.get("rubric_scores") + if not isinstance(scores, list): + return False + seen = {str(item.get("id")) for item in scores if isinstance(item, dict)} + if seen != rubric_ids: + return False + return all(item.get("score") in (0, 1) for item in scores if isinstance(item, dict)) + + +def render_rubrics(rubrics: list[dict[str, Any]]) -> str: + lines = [] + for item in rubrics: + lines.append( + json.dumps( + { + "id": item.get("id"), + "category": item.get("category"), + "criterion": item.get("criterion"), + "pass_condition": item.get("pass_condition"), + "fail_condition": item.get("fail_condition"), + "score_values": [0, 1], + }, + ensure_ascii=False, + ) + ) + return "\n".join(lines) + + +def render_dimensions(dimensions: list[dict[str, Any]]) -> str: + lines = [] + for item in dimensions: + lines.append( + json.dumps( + { + "id": item.get("id"), + "name": item.get("name"), + "description": item.get("desc"), + "score_range": [1, 10], + }, + ensure_ascii=False, + ) + ) + return "\n".join(lines) + + +def rubric_chunks(rubrics: list[dict[str, Any]], chunk_size: int) -> list[list[dict[str, Any]]]: + if chunk_size <= 0 or len(rubrics) <= chunk_size: + return [rubrics] + return [rubrics[i: i + chunk_size] for i in range(0, len(rubrics), chunk_size)] + + +def parse_type_set(value: str) -> set[str]: + """Parse a comma list of evidence_type values into a lowercased set.""" + return {p.strip().lower() for p in str(value or "").split(",") if p.strip()} + + +class AgentContentRefusal(RuntimeError): + """The agent's explicit upstream rejection must not fall back to another judge.""" + + +def load_agent_verdicts(task_dir: Path, agent_verdict_dir: str) -> dict[str, int]: + """Read a prior agent-as-judge ``judgement.json`` into ``{rubric_id: 0/1}``. + + Returns an empty dict on any miss (file absent, unparseable, or no rubric_scores) + so callers can gracefully fall back to VLM scoring for the affected rubrics.""" + path = output_path(task_dir, agent_verdict_dir) + if not path.exists(): + return {} + try: + obj = json.loads(path.read_text(encoding="utf-8")) + except Exception: # noqa: BLE001 + return {} + if obj.get("agent_error") == "agent_judge_upstream_content_policy_violation": + raise AgentContentRefusal(obj["agent_error"]) + # Post-check: never trust (leak) the verdicts of an agent-as-judge run that did not cleanly + # complete. `ok` is False when any scored rubric id is missing/unparseable; `agent_error` is + # set on timeout / crash / no-raw / parse-failure / (in visual mode) no-render. In either case + # drop ALL of this run's verdicts so the affected rubrics fall back to VLM scoring instead of + # being silently forced to a stale/partial 0/1. + if not obj.get("ok", False): + log.warning( + "[evidence-routing] agent judgement %s not ok (%s) — dropping its verdicts; " + "rubrics fall back to VLM", path, str(obj.get("error") or "")[:200] + ) + return {} + agent_err = str(obj.get("agent_error") or "").strip() + if agent_err: + log.warning( + "[evidence-routing] agent judgement %s has agent_error (%s) — dropping its verdicts; " + "rubrics fall back to VLM", path, agent_err[:200] + ) + return {} + out: dict[str, int] = {} + for item in (obj.get("rubric_scores") or []): + if not isinstance(item, dict): + continue + rid = str(item.get("id", "")).strip() + if not rid: + continue + score = item.get("score") + if score in (0, "0", "0.0", False): + out[rid] = 0 + elif score in (1, "1", "1.0", True): + out[rid] = 1 + return out + + +def render_submission_inventory( + task_dir: Path, + render_images: list[Path], + extra_images: list[Path], + anim_frames: list[Path] | None = None, +) -> str: + lines = ["Group A - evaluator-generated multi-view renders from the submitted .blend:"] + if render_images: + lines.extend(f"- {path.stem}: {rel(path, task_dir)}" for path in render_images) + else: + lines.append("- (none found)") + + lines.append("Group B - upstream exported images produced alongside the same .blend artifact:") + if extra_images: + lines.extend(f"- {path.stem}: {rel(path, task_dir)}" for path in extra_images) + else: + lines.append("- (none found)") + + if anim_frames: + lines.append( + "Group C - time-ordered frames sampled from the model's exported animation video (first -> last):" + ) + lines.extend(f"- {path.stem}: {rel(path, task_dir)}" for path in anim_frames) + return "\n".join(lines) + + +def build_rubric_user_text( + *, + result: dict[str, Any], + task_dir: Path, + reference_images: list[Path], + render_images: list[Path], + extra_images: list[Path], + anim_frames: list[Path] | None = None, + blind_description: str, + blind_reference_description: str, + rubrics: list[dict[str, Any]], +) -> str: + return JUDGE_USER_TEMPLATE.format( + prompt=result.get("prompt", ""), + reference_names=( + "\n".join(f"- reference_{idx + 1}: {rel(path, task_dir)}" for idx, path in enumerate(reference_images)) + if reference_images else + "(no reference images found)" + ), + view_names=render_submission_inventory(task_dir, render_images, extra_images, anim_frames), + blind_description=blind_description, + blind_reference_description=blind_reference_description, + rubrics=render_rubrics(rubrics), + ) + + +def score_dimensions( + obj: dict[str, Any] | None, + dimensions: list[dict[str, Any]], +) -> dict[str, Any]: + """Parse the dimension-judge output into normalized scores and flags.""" + result: dict[str, Any] = { + "ok": False, + "error": "", + "dimension_scores": [], + "dimension_score_0_100": 0.0, + "core_objects_recognizable": None, + "catastrophic_failure": None, + "missing_dimensions": [], + } + if not obj: + result["error"] = "dimension output was not valid JSON" + return result + raw = obj.get("dimensions") + if not isinstance(raw, list): + result["error"] = "missing dimensions list" + return result + + by_id: dict[str, dict[str, Any]] = {} + for item in raw: + if not isinstance(item, dict): + continue + did = str(item.get("id", "")).strip() + if not did: + continue + try: + score = int(round(float(item.get("score")))) + except (TypeError, ValueError): + continue + if score < 1 or score > 10: + score = max(1, min(10, score)) + by_id[did] = { + "id": did, + "score": score, + "reasons": str(item.get("reasons", "")).strip(), + "issues": item.get("issues") if isinstance(item.get("issues"), list) else [], + } + + scores: list[dict[str, Any]] = [] + missing: list[str] = [] + total = 0 + for dim in dimensions: + did = str(dim.get("id", "")).strip() + row = by_id.get(did) + if row is None: + missing.append(did) + scores.append({"id": did, "score": 0, "reasons": "", "issues": [], "missing": True}) + else: + row["name"] = dim.get("name") + scores.append(row) + total += row["score"] + + denom = 10 * len(dimensions) + result.update( + { + "ok": not missing, + "error": "missing dimensions: " + ", ".join(missing) if missing else "", + "dimension_scores": scores, + "dimension_score_0_100": (100.0 * total / denom) if denom else 0.0, + "core_objects_recognizable": bool(obj.get("core_objects_recognizable")) + if obj.get("core_objects_recognizable") is not None else None, + "catastrophic_failure": bool(obj.get("catastrophic_failure")) + if obj.get("catastrophic_failure") is not None else None, + "missing_dimensions": missing, + } + ) + return result + + +def normalize_scores(obj: dict[str, Any] | None, rubrics: list[dict[str, Any]]) -> tuple[bool, list[dict[str, Any]], str]: + if not obj: + return False, [], "model 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 + score = item.get("score") + if score in ("0", "0.0"): + score = 0 + elif score in ("1", "1.0"): + score = 1 + if score not in (0, 1): + continue + by_id[rid] = { + "id": rid, + "score": int(score), + "evidence": str(item.get("evidence", "")).strip(), + "source_views": item.get("source_views") if isinstance(item.get("source_views"), list) else [], + "confidence": str(item.get("confidence", "medium")).strip() or "medium", + } + + normalized = [] + missing = [] + 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 build_score_summary(rubrics: list[dict[str, Any]], scores: list[dict[str, Any]]) -> dict[str, Any]: + score_by_id = {str(item.get("id")): int(item.get("score", 0)) for item in scores} + raw_pass = 0 + raw_total = 0 + weighted_pass = 0.0 + weighted_total = 0.0 + missing_scores: list[str] = [] + extra_scores = sorted(set(score_by_id) - {str(r.get("id")) for r in rubrics}) + + by_category: dict[str, dict[str, float]] = {} + by_importance: dict[str, dict[str, float]] = {} + + for rubric in rubrics: + rid = str(rubric.get("id", "")).strip() + raw_total += 1 + if rid in score_by_id: + score = 1 if score_by_id[rid] else 0 + else: + score = 0 + missing_scores.append(rid) + raw_pass += score + + weight = float(rubric.get("importance_weight") or 1) + weighted_pass += score * weight + weighted_total += weight + + for table, key in ( + (by_category, str(rubric.get("category") or rubric.get("category_v2") or "unknown")), + (by_importance, str(rubric.get("importance") or "unknown")), + ): + row = table.setdefault( + key, + {"raw_pass": 0.0, "raw_total": 0.0, "weighted_pass": 0.0, "weighted_total": 0.0}, + ) + row["raw_pass"] += score + row["raw_total"] += 1 + row["weighted_pass"] += score * weight + row["weighted_total"] += weight + + def finalize(table: dict[str, dict[str, float]]) -> dict[str, dict[str, float]]: + out: dict[str, dict[str, float]] = {} + for key, row in sorted(table.items()): + raw_total_row = row["raw_total"] + weighted_total_row = row["weighted_total"] + out[key] = { + **row, + "raw_score_0_100": (100.0 * row["raw_pass"] / raw_total_row) if raw_total_row else 0.0, + "weighted_score_0_100": ( + 100.0 * row["weighted_pass"] / weighted_total_row + ) if weighted_total_row else 0.0, + } + return out + + return { + "raw_pass": raw_pass, + "raw_total": raw_total, + "raw_score_0_100": (100.0 * raw_pass / raw_total) if raw_total else 0.0, + "weighted_pass": weighted_pass, + "weighted_total": weighted_total, + "weighted_score_0_100": (100.0 * weighted_pass / weighted_total) if weighted_total else 0.0, + "missing_scores": missing_scores, + "extra_scores": extra_scores, + "by_category": finalize(by_category), + "by_importance": finalize(by_importance), + } + + +def atomic_write_json(path: Path, obj: dict[str, Any]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.with_suffix(path.suffix + ".tmp") + tmp.write_text(json.dumps(obj, ensure_ascii=False, indent=2), encoding="utf-8") + tmp.replace(path) + + +async def judge_one(result: dict[str, Any], cfg: dict[str, Any], api_sem: asyncio.Semaphore) -> dict[str, Any]: + task_dir = Path(result["task_dir"]).resolve() + rubrics = result.get("rubrics") or [] + rubric_ids = {str(item.get("id")) for item in rubrics} + out_path = output_path(task_dir, cfg["output_dir"]) + + # --- evidence_type routing: scene_summary → agent-as-judge verdicts, {either,render} → VLM --- + # When routing is off, vlm_rubrics == rubrics and agent_scored is empty, so the code path below + # is byte-for-byte identical to the non-routed behavior. + routing = bool(cfg.get("evidence_routing")) + agent_scored: dict[str, int] = {} + if routing: + vlm_types = cfg.get("vlm_evidence_types") or {"either", "render"} + try: + agent_verdicts = load_agent_verdicts( + task_dir, cfg.get("agent_verdict_dir") or "evaluation/agent_judge_multiview_eval" + ) + except AgentContentRefusal as exc: + obj = { + "task_dir": str(task_dir), "ok": False, "error": str(exc), + "rubric_scores": [], "output_path": str(out_path), + } + atomic_write_json(out_path, obj) + return obj + vlm_rubrics: list[dict[str, Any]] = [] + fallback_ss = 0 + for item in rubrics: + ev = str(item.get("evidence_type") or "").strip().lower() + rid = str(item.get("id")) + if ev in vlm_types: + vlm_rubrics.append(item) + elif rid in agent_verdicts: + agent_scored[rid] = agent_verdicts[rid] + else: + obj = {"task_dir": str(task_dir), "ok": False, + "error": f"missing structural verdict: {rid}", "rubric_scores": []} + atomic_write_json(out_path, obj) + return obj + log.info( + "[evidence-routing] task=%s total=%d vlm=%d agent_scene_summary=%d fallback_to_vlm=%d", + task_name(task_dir), len(rubrics), len(vlm_rubrics), len(agent_scored), fallback_ss, + ) + else: + vlm_rubrics = rubrics + + if not cfg["overwrite"] and is_complete_judgement(out_path, rubric_ids): + existing = json.loads(out_path.read_text(encoding="utf-8")) + existing["skipped_existing"] = True + score_summary = build_score_summary(rubrics, existing.get("rubric_scores") or []) + existing.update(score_summary) + return existing + + render_images = find_render_images(task_dir, cfg["image_glob"], cfg["max_images"]) + extra_images = find_extra_submission_images( + task_dir, + cfg["extra_image_glob"], + cfg["max_extra_images"], + ) + anim_frames = find_animation_frames( + task_dir, + cfg["anim_frame_glob"], + cfg["max_anim_frames"], + ) + images = dedupe_paths(render_images + extra_images) + reference_images = [] if cfg["no_reference_images"] else find_reference_images( + task_dir, + cfg["reference_image_glob"], + cfg["max_reference_images"], + ) + if cfg["dry_run"]: + obj = { + "created_at": datetime.now(timezone.utc).isoformat(), + "task_dir": str(task_dir), + "output_path": str(out_path), + "reference_image_files": [rel(path, task_dir) for path in reference_images], + "image_files": [rel(path, task_dir) for path in images], + "rendered_image_files": [rel(path, task_dir) for path in render_images], + "extra_image_files": [rel(path, task_dir) for path in extra_images], + "anim_frame_files": [rel(path, task_dir) for path in anim_frames], + "rubric_count": len(rubrics), + "ok": True, + "dry_run": True, + "rubric_scores": [], + } + atomic_write_json(out_path, obj) + return obj + + if not render_images: + obj = { + "created_at": datetime.now(timezone.utc).isoformat(), + "task_dir": str(task_dir), + "output_path": str(out_path), + "ok": False, + "error": f"no evaluator renders matched {cfg['image_glob']}", + "rubric_count": len(rubrics), + "rubric_scores": [], + } + atomic_write_json(out_path, obj) + return obj + + submission_image_groups = [ + ( + "Group A - evaluator-generated multi-view renders from the submitted .blend", + "Middle-layer multi-view render", + render_images, + ), + ( + "Group B - upstream exported images produced alongside the same .blend artifact", + "Upstream .blend co-produced image", + extra_images, + ), + ] + # Animation/video tasks only: a third, time-ordered group so motion/timing + # rubrics are judged on the actual sequence instead of auto-failed on stills. + if anim_frames: + submission_image_groups.append(( + "Group C - time-ordered frames sampled from the model's OWN exported animation video (first -> last)", + "Animation frame (time-ordered)", + anim_frames, + )) + submission_caption = ( + "Submitted image evidence to score. Group A images are middle-layer " + "Claude/Sonnet multi-view renders from the submitted .blend. Group B " + "images are upstream PNGs produced alongside that same .blend artifact. " + "Group C (when present) are time-ordered frames sampled from the model's " + "own exported animation video — read them as a sequence for motion/timing. " + "Consider all provided groups together, using the group labels when citing evidence:" + ) + + render_blind = None + reference_blind = None + if cfg["blind_pass"]: + blind_calls = [ + describe_blind( + image_paths=images, + model=cfg["model"], + api_key=cfg["api_key"], + max_tokens=cfg["blind_max_tokens"], + timeout=cfg["timeout"], + retries=cfg["retries"], + sem=api_sem, + image_detail=cfg["image_detail"], + api_endpoint=cfg["api_endpoint"], + user_text=BLIND_USER, + caption=( + "Submission images to describe. Group A images are " + "evaluator-generated multi-view renders from the " + "submitted .blend. Group B images are upstream PNGs produced " + "alongside that same .blend artifact:" + ), + image_groups=submission_image_groups, + label_root=task_dir, + ) + ] + if reference_images: + blind_calls.append( + describe_blind( + image_paths=reference_images, + model=cfg["model"], + api_key=cfg["api_key"], + max_tokens=cfg["blind_max_tokens"], + timeout=cfg["timeout"], + retries=cfg["retries"], + sem=api_sem, + image_detail=cfg["image_detail"], + api_endpoint=cfg["api_endpoint"], + user_text=BLIND_USER_REF, + caption="Reference image(s) to describe:", + ) + ) + blind_results = await asyncio.gather(*blind_calls) + render_blind = blind_results[0] + if reference_images: + reference_blind = blind_results[1] + + render_blind_block = (render_blind or "").strip() or ( + "(blind description unavailable; judge the renders on their own visual evidence)" + ) + reference_blind_block = (reference_blind or "").strip() or ( + "(no reference image provided; nothing to compare against)" + ) + + dimension_user_text = DIMENSION_USER_TEMPLATE.format( + prompt=result.get("prompt", ""), + reference_names=( + "\n".join(f"- reference_{idx + 1}: {rel(path, task_dir)}" for idx, path in enumerate(reference_images)) + if reference_images else + "(no reference images found)" + ), + view_names=render_submission_inventory(task_dir, render_images, extra_images, anim_frames), + blind_description=render_blind_block, + blind_reference_description=reference_blind_block, + dimensions=render_dimensions(DIMENSIONS), + ) + + chunk_size = int(cfg.get("rubric_batch_size") or 0) + chunks = rubric_chunks(vlm_rubrics, chunk_size) + if routing and not vlm_rubrics: + # All rubrics resolved from agent verdicts — skip the VLM rubric pass entirely + # (dimension pass, when enabled, still runs below). + chunks = [] + rubric_calls = [] + for idx, chunk in enumerate(chunks, start=1): + user_text = build_rubric_user_text( + result=result, + task_dir=task_dir, + reference_images=reference_images, + render_images=render_images, + extra_images=extra_images, + blind_description=render_blind_block, + blind_reference_description=reference_blind_block, + rubrics=chunk, + anim_frames=anim_frames, + ) + rubric_calls.append( + call_json_gpt55( + user_text=user_text, + reference_image_paths=reference_images, + rendered_image_paths=images, + model=cfg["model"], + api_key=cfg["api_key"], + max_tokens=cfg["max_tokens"], + timeout=cfg["timeout"], + retries=cfg["retries"], + json_retries=cfg["json_retries"], + sem=api_sem, + image_detail=cfg["image_detail"], + api_endpoint=cfg["api_endpoint"], + validate=lambda obj, chunk=chunk: validate_rubric_json(obj, chunk), + rendered_caption=submission_caption, + label_root=task_dir, + rendered_image_groups=submission_image_groups, + kind=( + f"rubric judge chunk {idx}/{len(chunks)}" + if len(chunks) > 1 else + "rubric judge" + ), + ) + ) + + judge_calls = [ + *rubric_calls, + ] + if cfg["dimension_pass"]: + judge_calls.append( + call_json_gpt55( + user_text=dimension_user_text, + reference_image_paths=reference_images, + rendered_image_paths=images, + model=cfg["model"], + api_key=cfg["api_key"], + max_tokens=cfg["dimension_max_tokens"], + timeout=cfg["timeout"], + retries=cfg["retries"], + json_retries=cfg["json_retries"], + sem=api_sem, + image_detail=cfg["image_detail"], + api_endpoint=cfg["api_endpoint"], + validate=validate_dimension_json, + system_prompt=DIMENSION_SYSTEM, + rendered_caption=submission_caption, + label_root=task_dir, + rendered_image_groups=submission_image_groups, + kind="dimension judge", + ) + ) + judge_results = await asyncio.gather(*judge_calls) + + chunk_results = judge_results[:len(rubric_calls)] + combined_scores: list[dict[str, Any]] = [] + combined_notes: list[str] = [] + combined_raw: list[str | None] = [] + chunk_errors: list[str] = [] + chunk_meta: list[dict[str, Any]] = [] + for idx, (chunk, chunk_result) in enumerate(zip(chunks, chunk_results), start=1): + raw_chunk, parsed_chunk, meta_chunk = chunk_result + combined_raw.append(raw_chunk) + ok_chunk, scores_chunk, error_chunk = normalize_scores(parsed_chunk, chunk) + combined_scores.extend(scores_chunk) + notes = str((parsed_chunk or {}).get("overall_notes", "")).strip() + if notes: + combined_notes.append(f"chunk {idx}: {notes}") + meta = { + **meta_chunk, + "chunk_index": idx, + "chunk_count": len(chunks), + "rubric_ids": [str(item.get("id")) for item in chunk], + "ok": ok_chunk, + } + if error_chunk: + meta["error"] = error_chunk + chunk_errors.append(f"chunk {idx}: {error_chunk}") + chunk_meta.append(meta) + + # Merge scene_summary verdicts from the agent-as-judge pass into the combined scores. + # These ids are excluded from vlm_rubrics, so there is no collision with VLM output. + for rid, agent_score in agent_scored.items(): + combined_scores.append({ + "id": rid, + "score": int(agent_score), + "evidence": "agent-as-judge verdict (evidence_type=scene_summary)", + "source_views": [], + "confidence": "high", + "method": "agent", + }) + + parsed = { + "rubric_scores": combined_scores, + "overall_notes": "\n".join(combined_notes), + } + raw = "\n\n".join(raw for raw in combined_raw if raw) + rubric_json_meta = { + "kind": "rubric judge", + "chunked": len(chunks) > 1, + "rubric_batch_size": chunk_size, + "chunk_count": len(chunks), + "json_ok": not chunk_errors, + "chunks": chunk_meta, + } + if chunk_errors: + rubric_json_meta["errors"] = chunk_errors + + if cfg["dimension_pass"]: + dim_raw, dim_parsed, dimension_json_meta = judge_results[len(rubric_calls)] + else: + dim_raw, dim_parsed, dimension_json_meta = None, None, None + + ok, scores, error = normalize_scores(parsed, rubrics) + if chunk_errors and not error: + error = "; ".join(chunk_errors) + total = sum(item["score"] for item in scores) + max_score = len(rubrics) + score_summary = build_score_summary(rubrics, scores) + + # --- dimension scoring + uncapped 50/50 fusion --- + rubric_score_0_100 = score_summary["weighted_score_0_100"] + dim_result = score_dimensions(dim_parsed, DIMENSIONS) if cfg["dimension_pass"] else None + if cfg["dimension_pass"] and (not dim_result or not dim_result["ok"]): + ok = False + error = "; ".join(x for x in [error, "dimension judge failed"] if x) + + w = cfg["dimension_weight"] + 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 = { + "created_at": datetime.now(timezone.utc).isoformat(), + "task_dir": str(task_dir), + "output_path": str(out_path), + "model": cfg["model"], + "reference_image_files": [rel(path, task_dir) for path in reference_images], + "image_files": [rel(path, task_dir) for path in images], + "rendered_image_files": [rel(path, task_dir) for path in render_images], + "extra_image_files": [rel(path, task_dir) for path 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((parsed or {}).get("overall_notes", "")).strip(), + "blind_pass": cfg["blind_pass"], + "blind_description": render_blind, + "blind_reference_description": reference_blind, + "rubric_batch_size": chunk_size, + "rubric_chunk_count": len(chunks), + # --- holistic dimension scoring + fusion --- + "dimension_pass": cfg["dimension_pass"], + "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((dim_parsed or {}).get("overall_notes", "")).strip(), + "json_repair": rubric_json_meta, + "dimension_json_repair": dimension_json_meta, + "ok": ok, + } + if routing: + obj["evidence_routing"] = True + obj["agent_scored_ids"] = sorted(agent_scored) + if dim_result and not dim_result["ok"]: + obj["dimension_error"] = dim_result.get("error", "") + if not ok: + obj["error"] = error + obj["raw_output"] = raw + if cfg["save_raw"]: + if raw is not None: + obj["raw_output"] = raw + if dim_raw is not None: + obj["dimension_raw_output"] = dim_raw + atomic_write_json(out_path, obj) + return obj + + +async def run_all(results: list[dict[str, Any]], cfg: dict[str, Any]) -> list[dict[str, Any]]: + api_sem = asyncio.Semaphore(cfg["concurrency"]) + task_sem = asyncio.Semaphore(cfg["task_concurrency"]) + done = {"n": 0, "fail": 0, "skip": 0} + outputs: list[dict[str, Any]] = [] + + async def worker(item: dict[str, Any]) -> None: + async with task_sem: + out = await judge_one(item, cfg, api_sem) + outputs.append(out) + done["n"] += 1 + if out.get("skipped_existing"): + done["skip"] += 1 + if not out.get("ok"): + done["fail"] += 1 + log.info( + "task=%s ok=%s rubric=%s/%s rubric100=%.1f dim100=%s fused=%.1f%s progress=%d/%d skipped=%d failed=%d", + Path(item["task_dir"]).name, + out.get("ok"), + out.get("score"), + out.get("max_score"), + float(out.get("rubric_score_0_100") or out.get("weighted_score_0_100") or 0.0), + ("%.1f" % out["dimension_score_0_100"]) if isinstance(out.get("dimension_score_0_100"), (int, float)) else "NA", + float(out.get("fused_score_0_100") or 0.0), + " CAP" if out.get("cap_applied") else "", + done["n"], + len(results), + done["skip"], + done["fail"], + ) + + await asyncio.gather(*(worker(item) for item in results)) + return outputs + + +def build_batch_score_summary(outputs: list[dict[str, Any]]) -> dict[str, Any]: + scored = [item for item in outputs if item.get("ok") and "weighted_score_0_100" in item] + raw_pass = sum(float(item.get("raw_pass", item.get("score", 0))) for item in scored) + raw_total = sum(float(item.get("raw_total", item.get("max_score", 0))) for item in scored) + weighted_pass = sum(float(item.get("weighted_pass", 0.0)) for item in scored) + weighted_total = sum(float(item.get("weighted_total", 0.0)) for item in scored) + return { + "scoring_method": ( + "weighted_score_0_100=100*sum(binary_score*importance_weight)/sum(importance_weight); " + "raw_score_0_100=100*sum(binary_score)/rubric_count" + ), + "scored_task_count": len(scored), + "raw_pass": raw_pass, + "raw_total": raw_total, + "raw_micro_score_0_100": (100.0 * raw_pass / raw_total) if raw_total else 0.0, + "weighted_pass": weighted_pass, + "weighted_total": weighted_total, + "weighted_micro_score_0_100": (100.0 * weighted_pass / weighted_total) if weighted_total else 0.0, + "raw_macro_score_0_100": ( + sum(float(item.get("raw_score_0_100", 0.0)) for item in scored) / len(scored) + ) if scored else 0.0, + "weighted_macro_score_0_100": ( + sum(float(item.get("weighted_score_0_100", 0.0)) for item in scored) / len(scored) + ) if scored else 0.0, + "dimension_macro_score_0_100": ( + _mean([item.get("dimension_score_0_100") for item in scored]) + ), + "fused_macro_score_0_100": ( + _mean([item.get("fused_score_0_100") for item in scored]) + ), + "cap_applied_count": sum(1 for item in scored if item.get("cap_applied")), + } + + +def _mean(values: list[Any]) -> float | None: + nums = [float(v) for v in values if isinstance(v, (int, float))] + return (sum(nums) / len(nums)) if nums else None + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description="Judge Blender multi-view renders against binary rubrics using gpt-5.6-terra.") + parser.add_argument( + "--rubrics-batch", + required=True, + ) + parser.add_argument("--output-dir", default="evaluation/judge_vlm") + parser.add_argument("--batch-output", default="", help="Combined judgement JSON. Defaults next to rubrics batch.") + parser.add_argument("--image-glob", default="evaluation/multiview/*.png") + parser.add_argument("--max-images", type=int, default=8) + parser.add_argument( + "--extra-image-glob", + action="append", + default=[], + help=( + "Additional submission image glob(s), relative to each task dir. " + "Defaults to .eval_workspace/exports/**/*.png and .eval_workspace/output/**/*.png." + ), + ) + parser.add_argument( + "--max-extra-images", + type=int, + default=4, + help="Maximum upstream exported final-product images to include; 0 means no count cap.", + ) + parser.add_argument( + "--anim-frame-glob", + action="append", + default=[], + help=( + "Glob(s) for time-ordered animation frames sampled upstream from the model's own " + "exported video, relative to each task dir. Defaults to " + ".eval_workspace/anim_frames/**/*.png. Attached to the VLM as a dedicated Group C " + "so motion/timing rubrics are judged on the sequence instead of a single still." + ), + ) + parser.add_argument( + "--max-anim-frames", + type=int, + default=16, + help="Maximum time-ordered animation frames to attach; 0 means no count cap.", + ) + parser.add_argument("--reference-image-glob", default="image_assets/*") + parser.add_argument("--max-reference-images", type=int, default=4) + parser.add_argument("--no-reference-images", action="store_true") + parser.add_argument("--model", default=DEFAULT_MODEL) + parser.add_argument("--api-key", default="", help=f"Judge API key; overrides {DEFAULT_API_KEY_ENV}.") + parser.add_argument("--api-endpoint", default=_DASH_ENDPOINT, help="OpenAI-compatible chat/completions endpoint.") + parser.add_argument("--concurrency", type=int, default=4, help="Max simultaneous HTTP calls.") + parser.add_argument("--task-concurrency", type=int, default=4, help="Max simultaneous tasks.") + parser.add_argument("--retries", type=int, default=10) + parser.add_argument( + "--json-retries", + type=int, + default=3, + help="Retry judge calls when the model output is not valid/complete JSON.", + ) + parser.add_argument( + "--rubric-batch-size", + type=int, + default=int(os.environ.get("JUDGE_RUBRIC_BATCH_SIZE", "0") or 0), + help=( + "If >0, split each task's binary rubrics into chunks of this size " + "and judge each chunk separately before merging. Default 0 keeps " + "the original single-call per-task behavior." + ), + ) + parser.add_argument("--timeout", type=int, default=300) + parser.add_argument("--max-tokens", type=int, default=20000) + parser.add_argument( + "--no-blind-pass", + action="store_true", + help="Disable the prompt-free blind description pass (blind pass is on by default).", + ) + parser.add_argument( + "--blind-max-tokens", + type=int, + default=4000, + help="Max tokens for the blind description pass.", + ) + parser.add_argument( + "--no-dimension-pass", + action="store_true", + help="Disable holistic dimension scoring (on by default; fused with rubric).", + ) + parser.add_argument( + "--dimension-weight", + type=float, + default=0.5, + help="Weight of dimension score in the fused score (rubric gets 1-weight). Default 0.5.", + ) + parser.add_argument( + "--dimension-max-tokens", + type=int, + default=8000, + help="Max tokens for the dimension scoring pass.", + ) + parser.add_argument("--image-detail", choices=["low", "high", "auto"], default="high") + parser.add_argument("--limit", type=int, default=0) + parser.add_argument("--overwrite", action="store_true") + parser.add_argument("--save-raw", action="store_true") + parser.add_argument("--dry-run", action="store_true") + parser.add_argument( + "--evidence-routing", + action="store_true", + help=( + "Route rubrics by evidence_type: scene_summary verdicts are read from a prior " + "agent-as-judge pass; other types are scored by this VLM. Off by default (all " + "rubrics scored by VLM, byte-identical to legacy behavior)." + ), + ) + parser.add_argument( + "--vlm-evidence-types", + default="either,render", + help="Comma list of evidence_type values this VLM scores. Default 'either,render'.", + ) + parser.add_argument( + "--agent-verdict-dir", + default="evaluation/agent_judge_multiview_eval", + help=( + "Per-task dir (relative to each task_dir) holding the agent-as-judge judgement.json " + "whose scene_summary verdicts are merged in when --evidence-routing is set." + ), + ) + return parser.parse_args() + + +def main() -> int: + args = parse_args() + if args.api_key: + os.environ[DEFAULT_API_KEY_ENV] = args.api_key + api_key = os.environ.get(DEFAULT_API_KEY_ENV, "") + if not args.dry_run and not api_key: + log.error("no API key: pass --api-key or set %s", DEFAULT_API_KEY_ENV) + return 1 + + rubrics_batch = Path(args.rubrics_batch).resolve() + results = load_rubric_results(rubrics_batch) + if args.limit: + results = results[: args.limit] + cfg = { + "output_dir": args.output_dir, + "image_glob": args.image_glob, + "max_images": args.max_images, + "extra_image_glob": args.extra_image_glob or DEFAULT_EXTRA_IMAGE_GLOBS, + "max_extra_images": args.max_extra_images, + "anim_frame_glob": args.anim_frame_glob or DEFAULT_ANIM_FRAME_GLOBS, + "max_anim_frames": args.max_anim_frames, + "reference_image_glob": args.reference_image_glob, + "max_reference_images": args.max_reference_images, + "no_reference_images": args.no_reference_images, + "model": args.model, + "api_key": api_key, + "api_endpoint": args.api_endpoint, + "concurrency": args.concurrency, + "task_concurrency": args.task_concurrency, + "retries": args.retries, + "json_retries": args.json_retries, + "rubric_batch_size": args.rubric_batch_size, + "timeout": args.timeout, + "max_tokens": args.max_tokens, + "blind_pass": not args.no_blind_pass, + "blind_max_tokens": args.blind_max_tokens, + "dimension_pass": not args.no_dimension_pass, + "dimension_weight": args.dimension_weight, + "dimension_max_tokens": args.dimension_max_tokens, + "image_detail": args.image_detail, + "overwrite": args.overwrite, + "save_raw": args.save_raw, + "dry_run": args.dry_run, + "evidence_routing": args.evidence_routing, + "vlm_evidence_types": parse_type_set(args.vlm_evidence_types), + "agent_verdict_dir": args.agent_verdict_dir, + } + log.info( + "loaded %d tasks from %s model=%s concurrency=%d task_concurrency=%d reference_images=%s blind_pass=%s dimension_pass=%s dim_weight=%.2f rubric_batch_size=%d dry_run=%s evidence_routing=%s vlm_evidence_types=%s", + len(results), + rubrics_batch, + args.model, + args.concurrency, + args.task_concurrency, + not args.no_reference_images, + not args.no_blind_pass, + not args.no_dimension_pass, + args.dimension_weight, + args.rubric_batch_size, + args.dry_run, + args.evidence_routing, + sorted(parse_type_set(args.vlm_evidence_types)) if args.evidence_routing else "-", + ) + outputs = asyncio.run(run_all(results, cfg)) + + if args.batch_output: + batch_output = Path(args.batch_output) + else: + batch_output = rubrics_batch.parent / "judge_vlm_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, + "rubric_batch_size": args.rubric_batch_size, + "task_count": len(outputs), + "ok_count": ok_count, + "score_summary": build_batch_score_summary(outputs), + "results": outputs, + } + atomic_write_json(batch_output, batch) + log.info("wrote batch output %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())