Skip to content

Official Codebase of 3DCodeVerse

Python
12.6 KB
Raw Blame
"""One dataset sample from one run: typed ``meta.json`` + folder layout."""

from __future__ import annotations

import shutil
from datetime import datetime
from pathlib import Path
from typing import Any

from codeverse3d.contracts.common import ENTRY_FILE, Language
from pydantic import BaseModel, Field

from c3d_flywheel import select
from c3d_flywheel.dataset.quality import (
    QualityTier,
    code_fingerprint,
    prompt_id,
    quality_tier,
)
from c3d_flywheel.legacy import LANGUAGE_LABEL, TRACK_LABEL, RoundRecord, RunRecord, code_file
from c3d_flywheel.record import git_history
from c3d_flywheel.record.deliverable import load_deliverable, round_outputs
from c3d_flywheel.record.record import effective_judgment, round_summary, stop_reason
from c3d_flywheel.runlayout import RunWorkspace

MAX_GLB_BYTES = 20 * 1024 * 1024
SOURCE_NAME = "3dcodeverse"
SAMPLE_LICENSE = "CC-BY-4.0"


class SampleError(RuntimeError):
    """The run cannot be turned into a sample (no code, no commit, ...)."""


class AcceptanceEntry(BaseModel):

    id: str
    text: str = ""
    how: str = ""
    priority: str = ""
    passed: bool | None = None


class SampleMeta(BaseModel):

    id: str
    key: str
    name: str
    type: str
    track: str
    language: str
    language_label: str
    entry: str
    multi_file: bool
    files: list[str] = Field(description="all files in the sample folder (relative)")
    renders: list[str] = Field(default_factory=list)
    environment: dict[str, str] = Field(default_factory=dict)
    source: str = SOURCE_NAME
    source_run: str = ""
    license: str = SAMPLE_LICENSE
    harness_version: str = Field(default="", description="the codeverse3d version that produced the run (record.environment)")
    prompt: str
    constraints: dict[str, Any] = Field(default_factory=dict)
    tags: list[str] = Field(default_factory=list)
    generator: str = ""
    planner: str = ""
    judge_backend: str = ""
    judge_rubric: str = ""
    score: float | None = None
    passed: bool | None = Field(default=None, description="the judge's own verdict for the exported round")
    baseline_score: float | None = None
    acceptance_results: dict[str, bool] = Field(default_factory=dict)
    acceptance: list[AcceptanceEntry] = Field(default_factory=list, description="plan checklist + verdicts")
    gate_errors: int = Field(default=0, description="error findings across all gates of the exported round")
    gate_summary: dict[str, int] = Field(default_factory=dict, description="gate name → error count")
    quality_tier: QualityTier = "D"
    complexity: float | None = Field(
        default=None, description="objective complexity index of the exported artifact (spatial/complexity.py)")
    complexity_band: str = Field(default="", description="trivial | simple | moderate | complex | intricate")
    rounds: int = 0
    round: int | None = Field(default=None, description="the exported round (addons/select's pick)")
    rounds_summary: list[dict[str, Any]] = Field(default_factory=list, description="compact per-round digest")
    stop_reason: str = ""
    code_commit: str = ""
    code_source: str = Field(default="commit", description="commit | deliverable | working_tree")
    code_fingerprint: str = Field(default="", description="sha256 of the normalised src/** tree")
    prompt_hash: str = ""
    status: str = ""
    cost_usd: float = 0.0
    usage: dict[str, Any] = Field(default_factory=dict)
    created_at: datetime
    finished_at: datetime | None = None
    has_captions: bool = False
    captioner: str = ""
    prompt_hashes: dict[str, str] = Field(default_factory=dict)
    telemetry: dict[str, Any] = Field(
        default_factory=dict,
        description="compact accounting digest from record.telemetry ({} when absent)")


def sample_key(ws: RunWorkspace) -> str:
    return ws.root.name


def sample_id(record: RunRecord, key: str) -> str:
    return f"{SOURCE_NAME}/{record.spec.track.value}/{record.spec.language.value}/{key}"


def sample_rel_dir(record: RunRecord, key: str) -> Path:
    return Path(record.spec.track.value) / record.spec.language.value / key


def exported_round(ws: RunWorkspace, record: RunRecord) -> RoundRecord | None:
    shown = select.summarise(ws.root, record=record).round
    return next((r for r in record.rounds if r.index == shown), record.rounds[-1] if record.rounds else None)


def code_files_for_round(ws: RunWorkspace, rnd: RoundRecord | None) -> tuple[dict[str, bytes], str]:
    """The round's code at its commit; a packaged ``deliverable/`` only when its manifest names that round."""
    if rnd is None:
        return git_history.read_working_tree(ws), "working_tree"
    if rnd.commit and ws.has_commit(rnd.commit):
        return git_history.read_tree_at(ws, rnd.commit), "commit"
    manifest = load_deliverable(ws)
    if manifest is not None and manifest.round == rnd.index and manifest.commit == rnd.commit:
        return _deliverable_code(ws), "deliverable"
    raise SampleError(f"round {rnd.index}: commit {rnd.commit[:10] or '(none)'} is unavailable and deliverable/ holds "
                      + (f"round {manifest.round}" if manifest is not None else "no manifest"))


def _deliverable_code(ws: RunWorkspace) -> dict[str, bytes]:
    files: dict[str, bytes] = {}
    for root in git_history.CODE_ROOTS:
        base = ws.deliverable / root
        if not base.is_dir():
            continue
        for p in sorted(base.rglob("*")):
            if p.is_file():
                files[p.relative_to(ws.deliverable).as_posix()] = p.read_bytes()
    return files


def write_code_tree(dest: Path, files: dict[str, bytes], language: Language) -> tuple[str, list[str]]:
    written: list[str] = []
    for rel, data in sorted(files.items()):
        p = dest / rel
        p.parent.mkdir(parents=True, exist_ok=True)
        p.write_bytes(data)
        written.append(rel)
    entry_src = ENTRY_FILE[language]
    code_name = code_file(language)
    if entry_src in files:
        (dest / code_name).write_bytes(files[entry_src])
        written.append(code_name)
    if language is Language.URDF_BLENDER and "src/robot.urdf" in files:
        (dest / "robot.urdf").write_bytes(files["src/robot.urdf"])
        written.append("robot.urdf")
    return code_name, written


def copy_renders(ws: RunWorkspace, rnd: RoundRecord | None, dest: Path) -> list[str]:
    out: list[str] = []
    rdir = dest / "renders"
    rdir.mkdir(parents=True, exist_ok=True)

    def _cp(src: Path | None, name: str) -> None:
        if src is None:
            return
        shutil.copy2(src, rdir / name)
        out.append(f"renders/{name}")

    if rnd is not None and rnd.renders is not None:
        names = [v.name for v in rnd.renders.views]
        by_stem = len(set(names)) != len(names)
        for v in rnd.renders.views:
            src = ws.rebase(v.path)
            if not src.is_file():
                continue
            name = f"view_{src.stem if by_stem else v.name}{src.suffix or '.png'}"
            i = 2
            while f"renders/{name}" in out:
                name = f"view_{src.stem}_{i}{src.suffix or '.png'}"
                i += 1
            _cp(src, name)
        sheet = ws.rebase(rnd.renders.contact_sheet or "")
        if sheet.is_file():
            _cp(sheet, f"sheet{sheet.suffix or '.png'}")
    if not any(o.startswith("renders/sheet") for o in out):
        packaged = ws.deliverable / "sheet.png"
        _cp(packaged if packaged.is_file() else None, "sheet.png")
    for name in ("object.glb", "preview.gif"):
        src = select.round_file(ws, rnd, name)
        if src is not None and src.stat().st_size < MAX_GLB_BYTES:
            _cp(src, name)
    return out


def copy_link_meshes(ws: RunWorkspace, rnd: RoundRecord | None, dest: Path) -> list[str]:
    out_dir = round_outputs(ws, rnd)
    src = out_dir / "meshes" if out_dir is not None else None
    if src is None or not src.is_dir():
        return []
    out: list[str] = []
    total = 0
    for p in sorted(src.glob("*.glb")):
        total += p.stat().st_size
        if total > MAX_GLB_BYTES:
            break
        (dest / "meshes").mkdir(parents=True, exist_ok=True)
        shutil.copy2(p, dest / "meshes" / p.name)
        out.append(f"meshes/{p.name}")
    return out


def acceptance_entries(record: RunRecord, rnd: RoundRecord | None) -> list[AcceptanceEntry]:
    j = effective_judgment(rnd) if rnd is not None else None
    verdicts = dict(j.acceptance_results) if j is not None else {}
    items = list(getattr(record.plan, "acceptance", []) or []) if record.plan is not None else []
    out = [AcceptanceEntry(id=a.id, text=a.text, how=a.how, priority=a.priority, passed=verdicts.get(a.id)) for a in items]
    known = {a.id for a in items}
    out += [AcceptanceEntry(id=k, passed=v) for k, v in verdicts.items() if k not in known]
    return out


def gate_error_summary(rnd: RoundRecord | None) -> dict[str, int]:
    return {g.gate: len(g.errors) for g in rnd.gates} if rnd is not None else {}


def build_meta(
    ws: RunWorkspace, record: RunRecord, *, key: str, entry: str, files: list[str], renders: list[str],
    rnd: RoundRecord | None, code_source: str, code: dict[str, bytes] | None = None,
    captions: dict[str, Any] | None = None,
) -> SampleMeta:
    spec = record.spec
    j = effective_judgment(rnd) if rnd is not None else None
    caps = captions if captions is not None else (record.extra.get("captions") or {})
    code_files = [f for f in files if f.startswith("src/")]
    gates = gate_error_summary(rnd)
    n_gate_errors = sum(gates.values())
    cx = select.round_complexity_block(rnd)
    name = ""
    if record.plan is not None:
        name = getattr(record.plan, "object_name", "") or getattr(record.plan, "title", "")
    return SampleMeta(
        id=sample_id(record, key),
        key=key,
        name=name,
        type=TRACK_LABEL[spec.track],
        track=spec.track.value,
        language=spec.language.value,
        language_label=LANGUAGE_LABEL[spec.language],
        entry=entry,
        multi_file=len(code_files) > 1,
        files=sorted(files),
        renders=sorted(renders),
        environment=dict(record.environment),
        harness_version=str(record.environment.get("codeverse3d", "")),
        source_run=str(ws.root),
        prompt=spec.prompt,
        constraints=spec.constraints.model_dump(mode="json", exclude_none=True),
        tags=list(spec.tags),
        generator=spec.backends.generator,
        planner=spec.backends.planner,
        judge_backend=(j.judge_backend if j else "") or spec.backends.judge,
        judge_rubric=j.rubric if j else "",
        score=j.overall if j else None,
        passed=j.passed if j else None,
        baseline_score=select.summarise(ws.root, record=record).baseline_score,
        acceptance_results=dict(j.acceptance_results) if j else {},
        acceptance=acceptance_entries(record, rnd),
        gate_errors=n_gate_errors,
        gate_summary=gates,
        quality_tier=quality_tier(passed=j.passed if j else None, gate_errors=n_gate_errors, score=j.overall if j else None),
        complexity=cx.get("index") if cx else None,
        complexity_band=str(cx.get("band") or "") if cx else "",
        rounds=len(record.rounds),
        round=rnd.index if rnd is not None else None,
        rounds_summary=[round_summary(r) for r in record.rounds],
        stop_reason=stop_reason(record),
        code_commit=rnd.commit if rnd is not None else "",
        code_source=code_source,
        code_fingerprint=code_fingerprint(code) if code else "",
        prompt_hash=prompt_id(spec.prompt),
        status=record.status.value,
        cost_usd=round(record.total_usage.cost_usd, 6),
        usage=record.total_usage.model_dump(mode="json"),
        created_at=spec.created_at,
        finished_at=record.finished_at,
        has_captions=bool(caps.get("detailed")),
        captioner=str((caps.get("provenance") or {}).get("captioner", "")),
        prompt_hashes=dict(record.prompt_hashes),
        telemetry=telemetry_digest(record),
    )


def telemetry_digest(record: RunRecord) -> dict[str, Any]:
    tele = record.telemetry
    if tele is None:
        return {}
    out: dict[str, Any] = {}
    if tele.cost is not None:
        out.update({
            "total_usd": tele.cost.total_usd,
            "minutes": record.minutes,
            "n_calls": tele.cost.n_calls,
            "by_stage": {s.stage: s.cost_usd for s in tele.cost.by_stage},
            "by_model": dict(tele.cost.by_model),
        })
    if tele.settings is not None:
        out.update({
            "models": {r.role: r.model for r in tele.settings.roles},
            "thinking": {r.role: r.thinking for r in tele.settings.roles if r.thinking},
            "rubric_hash": tele.settings.rubric_hash,
            "price_table_version": tele.settings.price_table_version,
        })
    return out