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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
from __future__ import annotations

import hashlib
import json
import math
import os
import subprocess
import uuid
from collections.abc import Sequence
from pathlib import Path
from typing import Any, Literal, Protocol

from PIL import Image, ImageDraw, ImageFont
from pydantic import BaseModel, ConfigDict, Field, model_validator

from packages.asset_registry.certification_models import (
    CardinalAxis,
    FrontAxis,
    FrontEvidence,
    SymmetryType,
)
from packages.core.files import atomic_write_text

TURN_TABLE_AXES = (
    "+X",
    "+X+Y",
    "+Y",
    "-X+Y",
    "-X",
    "-X-Y",
    "-Y",
    "+X-Y",
)
OPPOSITE: dict[CardinalAxis, CardinalAxis] = {
    "+X": "-X",
    "-X": "+X",
    "+Y": "-Y",
    "-Y": "+Y",
}


def sha256_file(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(4 * 1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


class _StrictModel(BaseModel):
    model_config = ConfigDict(extra="forbid", validate_assignment=True)


class TurntableView(_StrictModel):
    index: int = Field(ge=0, le=7)
    camera_side: str
    image_uri: str
    image_sha256: str = Field(pattern=r"^[0-9a-f]{64}$")


class TurntableManifest(_StrictModel):
    schema_version: Literal["1.0"] = "1.0"
    asset_id: str
    asset_uri: str
    asset_sha256: str = Field(pattern=r"^[0-9a-f]{64}$")
    render_uri: str | None = None
    render_sha256: str | None = Field(default=None, pattern=r"^[0-9a-f]{64}$")
    render_repair: str | None = None
    geometry_identity_preserved: Literal[True] | None = None
    renderer: str
    material_aware: Literal[True] = True
    canonical_transform: tuple[float, ...] | None = None
    canonical_transform_sha256: str | None = Field(default=None, pattern=r"^[0-9a-f]{64}$")
    views: list[TurntableView] = Field(min_length=8, max_length=8)
    contact_sheet_uri: str
    contact_sheet_sha256: str = Field(pattern=r"^[0-9a-f]{64}$")

    @model_validator(mode="after")
    def validate_view_order(self) -> TurntableManifest:
        if [item.index for item in self.views] != list(range(8)):
            raise ValueError("turntable views must be ordered 0..7")
        if tuple(item.camera_side for item in self.views) != TURN_TABLE_AXES:
            raise ValueError("turntable camera-side labels differ from the canonical order")
        if (self.canonical_transform is None) != (self.canonical_transform_sha256 is None):
            raise ValueError("canonical transform and its hash must be present together")
        if self.canonical_transform is not None:
            if len(self.canonical_transform) != 16 or not all(
                math.isfinite(value) for value in self.canonical_transform
            ):
                raise ValueError("canonical transform must contain 16 finite values")
            digest = hashlib.sha256(
                json.dumps(list(self.canonical_transform), separators=(",", ":")).encode()
            ).hexdigest()
            if digest != self.canonical_transform_sha256:
                raise ValueError("canonical transform hash differs")
        runtime_fields = (
            self.render_uri,
            self.render_sha256,
            self.geometry_identity_preserved,
        )
        if any(value is not None for value in runtime_fields) and not all(
            value is not None for value in runtime_fields
        ):
            raise ValueError("render derivative fields must be present together")
        return self


class AutonomousFrontVote(_StrictModel):
    schema_version: Literal["1.0"] = "1.0"
    visual_front_axis: FrontAxis
    functional_front_axis: FrontAxis
    back_axis: FrontAxis
    symmetry_type: SymmetryType
    confidence: float = Field(ge=0.0, le=1.0)
    decisive_view_indices: list[int] = Field(default_factory=list)
    visible_cues: list[str] = Field(default_factory=list)
    reasoning: str

    @model_validator(mode="after")
    def validate_axes(self) -> AutonomousFrontVote:
        cardinal = {"+X", "-X", "+Y", "-Y"}
        if (
            self.functional_front_axis in cardinal
            and self.back_axis
            != OPPOSITE[
                self.functional_front_axis  # type: ignore[index]
            ]
        ):
            raise ValueError("back_axis must oppose a cardinal functional_front_axis")
        if any(index < 0 or index > 7 for index in self.decisive_view_indices):
            raise ValueError("decisive view indices must be in 0..7")
        return self


class ImageAnalysisClient(Protocol):
    def analyze_image(self, source: Path, prompt: str) -> str: ...


def _contact_sheet(view_paths: Sequence[Path], output: Path, asset_id: str) -> None:
    if len(view_paths) != 8:
        raise ValueError("eight turntable images are required")
    tile = 320
    label_height = 34
    sheet = Image.new("RGB", (4 * tile, 2 * (tile + label_height)), (244, 244, 242))
    draw = ImageDraw.Draw(sheet)
    font = ImageFont.load_default()
    for index, (path, camera_side) in enumerate(zip(view_paths, TURN_TABLE_AXES, strict=True)):
        row, column = divmod(index, 4)
        x = column * tile
        y = row * (tile + label_height)
        with Image.open(path) as source:
            image = source.convert("RGB")
            image.thumbnail((tile - 8, tile - 8))
        sheet.paste(image, (x + (tile - image.width) // 2, y + (tile - image.height) // 2))
        draw.rectangle((x, y, x + tile - 1, y + tile - 1), outline=(70, 70, 70), width=2)
        draw.text(
            (x + 6, y + tile + 7),
            f"view {index}: camera on {camera_side}",
            fill=(20, 20, 20),
            font=font,
        )
    draw.text((8, 4), asset_id[:100], fill=(10, 10, 10), font=font)
    sheet.save(output, format="PNG", optimize=True)


def render_material_turntable(
    *,
    asset_id: str,
    asset_path: Path,
    asset_sha256: str,
    output_dir: Path,
    blender: Path,
    renderer_script: Path | None = None,
    canonical_transform: Sequence[float] | None = None,
    render_path: Path | None = None,
    render_sha256: str | None = None,
    render_repair: str | None = None,
) -> TurntableManifest:
    """Render an immutable eight-view, material-aware turntable in Blender."""

    asset_path = asset_path.resolve()
    output_dir = output_dir.resolve()
    blender = blender.resolve()
    script = (
        renderer_script
        or Path(__file__).resolve().parents[2] / "scripts" / "blender_render_asset_turntable.py"
    ).resolve()
    if output_dir.exists():
        raise FileExistsError(f"refusing to overwrite turntable output: {output_dir}")
    if not asset_path.is_file() or not blender.is_file() or not script.is_file():
        missing = [str(path) for path in (asset_path, blender, script) if not path.is_file()]
        raise FileNotFoundError(f"turntable input is missing: {missing}")
    if asset_path.suffix.casefold() in {".glb", ".gltf"} and canonical_transform is None:
        raise ValueError("GLB/GLTF turntables require the descriptor canonical transform")
    canonical_values = (
        tuple(float(value) for value in canonical_transform)
        if canonical_transform is not None
        else None
    )
    if canonical_values is not None and (
        len(canonical_values) != 16 or not all(math.isfinite(value) for value in canonical_values)
    ):
        raise ValueError("canonical transform must contain 16 finite values")
    actual_asset_sha256 = sha256_file(asset_path)
    if actual_asset_sha256 != asset_sha256:
        raise ValueError(f"asset hash differs: {actual_asset_sha256} != {asset_sha256}")
    runtime_path = render_path.resolve() if render_path is not None else asset_path
    if not runtime_path.is_file():
        raise FileNotFoundError(runtime_path)
    actual_render_sha256 = sha256_file(runtime_path)
    if render_path is not None:
        if render_sha256 is None:
            raise ValueError("render derivative requires its SHA-256")
        if actual_render_sha256 != render_sha256:
            raise ValueError("render derivative hash differs")
    elif render_sha256 is not None or render_repair is not None:
        raise ValueError("render derivative metadata was supplied without a path")

    output_dir.parent.mkdir(parents=True, exist_ok=True)
    staging = output_dir.parent / f".{output_dir.name}.tmp-{uuid.uuid4().hex[:12]}"
    staging.mkdir(parents=False, exist_ok=False)
    command = [
        str(blender),
        "--background",
        "--factory-startup",
        "--python",
        str(script),
        "--",
        "--asset",
        str(runtime_path),
        "--output",
        str(staging),
    ]
    if canonical_values is not None:
        command.extend(
            [
                "--canonical-transform-json",
                json.dumps(list(canonical_values), separators=(",", ":")),
            ]
        )
    completed = subprocess.run(command, capture_output=True, text=True, check=False)
    atomic_write_text(
        staging / "blender.log",
        completed.stdout + ("\n[stderr]\n" + completed.stderr if completed.stderr else ""),
    )
    if completed.returncode:
        raise RuntimeError(
            f"Blender turntable failed with code {completed.returncode}; "
            f"log={staging / 'blender.log'}"
        )
    renderer_report_path = staging / "renderer_report.json"
    report = json.loads(renderer_report_path.read_text(encoding="utf-8"))
    view_paths = [staging / f"view_{index:02d}.png" for index in range(8)]
    if any(not path.is_file() for path in view_paths):
        raise RuntimeError("Blender did not produce all eight canonical views")
    contact_sheet = staging / "contact_sheet.png"
    _contact_sheet(view_paths, contact_sheet, asset_id)
    views = [
        TurntableView(
            index=index,
            camera_side=TURN_TABLE_AXES[index],
            image_uri=path.name,
            image_sha256=sha256_file(path),
        )
        for index, path in enumerate(view_paths)
    ]
    manifest = TurntableManifest(
        asset_id=asset_id,
        asset_uri=str(asset_path),
        asset_sha256=asset_sha256,
        render_uri=(str(runtime_path) if render_path is not None else None),
        render_sha256=(actual_render_sha256 if render_path is not None else None),
        render_repair=render_repair,
        geometry_identity_preserved=(True if render_path is not None else None),
        renderer=f"Blender/{report['blender_version']} material-turntable-v1",
        canonical_transform=canonical_values,
        canonical_transform_sha256=(
            hashlib.sha256(
                json.dumps(list(canonical_values), separators=(",", ":")).encode()
            ).hexdigest()
            if canonical_values is not None
            else None
        ),
        views=views,
        contact_sheet_uri=contact_sheet.name,
        contact_sheet_sha256=sha256_file(contact_sheet),
    )
    atomic_write_text(
        staging / "turntable_manifest.json",
        manifest.model_dump_json(indent=2) + "\n",
    )
    if output_dir.exists():
        raise FileExistsError(f"turntable destination appeared during render: {output_dir}")
    os.replace(staging, output_dir)
    return manifest


def _json_object(raw: str) -> dict[str, Any]:
    candidate = raw.strip()
    if candidate.startswith("```"):
        lines = candidate.splitlines()
        candidate = "\n".join(lines[1:-1]).strip()
    decoder = json.JSONDecoder()
    for index, character in enumerate(candidate):
        if character != "{":
            continue
        try:
            value, _ = decoder.raw_decode(candidate[index:])
        except json.JSONDecodeError:
            continue
        if isinstance(value, dict):
            return value
    raise ValueError("multimodal response contains no JSON object")


def parse_front_vote(raw: str) -> AutonomousFrontVote:
    return AutonomousFrontVote.model_validate(_json_object(raw))


def front_vote_prompt(*, category: str, definition: str) -> str:
    return (
        "You are certifying the usable front of one immutable 3D asset from an "
        "eight-view material-aware turntable.\n"
        f"Category: {category}\n"
        f"Category-specific definition: {definition}\n\n"
        "The sheet labels camera positions, not viewing directions: a camera on +Y "
        "shows the asset's +Y side. Cardinal answers must be one of +X, -X, +Y, "
        "-Y. Use NONE only when the category truly has no directional front; use "
        "AMBIGUOUS when evidence is insufficient. For cabinets, refrigerators, "
        "drawers, and appliances, functional_front_axis is the side with doors, "
        "drawers, handles, controls, or other operation affordances. back_axis must "
        "be the exact opposite of a cardinal functional front. Inspect materials "
        "and small cues rather than relying on silhouette alone.\n\n"
        "Return exactly one JSON object with these keys and no markdown: "
        'schema_version="1.0", visual_front_axis, functional_front_axis, back_axis, '
        "symmetry_type (NONE, ROTATIONAL, MIRROR, ROTATIONAL_AND_MIRROR, or "
        "UNKNOWN), confidence (0..1), decisive_view_indices (array of 0..7), "
        "visible_cues (array of short strings), reasoning (short string). Do not "
        "invent a front when cues conflict."
    )


def analyze_turntable_front(
    *,
    manifest: TurntableManifest,
    turntable_root: Path,
    category: str,
    definition: str,
    client: ImageAnalysisClient,
    output_dir: Path,
) -> AutonomousFrontVote:
    if output_dir.exists():
        raise FileExistsError(f"refusing to overwrite autonomous front analysis: {output_dir}")
    sheet = (turntable_root / manifest.contact_sheet_uri).resolve()
    if sha256_file(sheet) != manifest.contact_sheet_sha256:
        raise ValueError("turntable contact sheet hash differs from its manifest")
    raw = client.analyze_image(sheet, front_vote_prompt(category=category, definition=definition))
    vote = parse_front_vote(raw)
    output_dir.mkdir(parents=True, exist_ok=False)
    atomic_write_text(output_dir / "vlm_raw_response.txt", raw.rstrip() + "\n")
    atomic_write_text(output_dir / "front_vote.json", vote.model_dump_json(indent=2) + "\n")
    atomic_write_text(
        output_dir / "analysis_provenance.json",
        json.dumps(
            {
                "schema_version": "1.0",
                "asset_id": manifest.asset_id,
                "asset_sha256": manifest.asset_sha256,
                "turntable_manifest_sha256": sha256_file(
                    turntable_root / "turntable_manifest.json"
                ),
                "contact_sheet_sha256": manifest.contact_sheet_sha256,
                "human_review_used": False,
                "adjudication": "automatic_vlm_material_turntable_v1",
            },
            indent=2,
            sort_keys=True,
        )
        + "\n",
    )
    return vote


def evidence_from_front_vote(
    manifest: TurntableManifest,
    vote: AutonomousFrontVote,
    *,
    analysis_uri: str,
) -> list[FrontEvidence]:
    note = "; ".join(vote.visible_cues[:6]) or vote.reasoning
    evidence = [
        FrontEvidence(
            evidence_id=f"turntable:{manifest.asset_sha256}:functional",
            kind="multiview",
            target="functional_front",
            axis=vote.functional_front_axis,
            source_uri=analysis_uri,
            source_hash=manifest.contact_sheet_sha256,
            confidence=vote.confidence,
            note=note,
        ),
        FrontEvidence(
            evidence_id=f"vlm:{manifest.asset_sha256}:functional",
            kind="vlm_vote",
            target="functional_front",
            axis=vote.functional_front_axis,
            source_uri=analysis_uri,
            source_hash=manifest.contact_sheet_sha256,
            confidence=vote.confidence,
            note=note,
        ),
        FrontEvidence(
            evidence_id=f"turntable:{manifest.asset_sha256}:visual",
            kind="multiview",
            target="visual_front",
            axis=vote.visual_front_axis,
            source_uri=analysis_uri,
            source_hash=manifest.contact_sheet_sha256,
            confidence=vote.confidence,
            note=note,
        ),
        FrontEvidence(
            evidence_id=f"turntable:{manifest.asset_sha256}:back",
            kind="multiview",
            target="back_axis",
            axis=vote.back_axis,
            source_uri=analysis_uri,
            source_hash=manifest.contact_sheet_sha256,
            confidence=vote.confidence,
            note=note,
        ),
    ]
    if vote.functional_front_axis == "NONE" or vote.symmetry_type in {
        SymmetryType.ROTATIONAL,
        SymmetryType.ROTATIONAL_AND_MIRROR,
    }:
        evidence.append(
            FrontEvidence(
                evidence_id=f"turntable:{manifest.asset_sha256}:symmetry",
                kind="symmetry",
                target="symmetry",
                axis="NONE",
                source_uri=analysis_uri,
                source_hash=manifest.contact_sheet_sha256,
                confidence=vote.confidence,
                note=note,
            )
        )
    return evidence