"""CLEVR-specific immutable object-attribute interventions.""" from __future__ import annotations import copy from dataclasses import dataclass from typing import Literal from ..hashing import canonical_json_hash from ..sources.base import World from ..sources.world_ops import NODE_VISIBILITY_KEY, world_sha256 from .base import InterventionError ClevrAttribute = Literal["color", "material", "shape", "size"] ClevrMutationKind = Literal["CONTROL", "SUBSTITUTE", "MISSING"] ATTRIBUTE_DOMAINS: dict[ClevrAttribute, tuple[str, ...]] = { "color": ("blue", "brown", "cyan", "gray", "green", "purple", "red", "yellow"), "material": ("metal", "rubber"), "shape": ("cube", "cylinder", "sphere"), "size": ("large", "small"), } @dataclass(frozen=True) class ClevrMutation: """One deterministic, content-addressed CLEVR attribute edit.""" world: World kind: ClevrMutationKind target_node: str attribute: ClevrAttribute before: str after: str | None seed: int mutation_sha256: str def substitute_clevr_attribute( world: World, target_node: str, attribute: ClevrAttribute, value: str, *, seed: int, kind: Literal["CONTROL", "SUBSTITUTE"] = "SUBSTITUTE", ) -> ClevrMutation: """Return a new world with one typed CLEVR attribute changed.""" before = _current(world, target_node, attribute) if value not in ATTRIBUTE_DOMAINS[attribute]: raise InterventionError( f"CLEVR {attribute} substitute {value!r} is outside the official domain" ) if value == before: raise InterventionError( f"CLEVR {attribute} substitute for {target_node!r} must change the value" ) new = with_clevr_attribute(world, target_node, attribute, value) return _mutation( source=world, transformed=new, kind=kind, target_node=target_node, attribute=attribute, before=before, after=value, seed=seed, ) def redact_clevr_attribute( world: World, target_node: str, attribute: ClevrAttribute, *, seed: int, ) -> ClevrMutation: """Remove one observed attribute and hide the object's rendered pixels.""" before = _current(world, target_node, attribute) new = with_clevr_attribute(world, target_node, attribute, None) visibility = dict(new.get(NODE_VISIBILITY_KEY, {}) or {}) visibility[target_node] = "hidden" new[NODE_VISIBILITY_KEY] = visibility return _mutation( source=world, transformed=new, kind="MISSING", target_node=target_node, attribute=attribute, before=before, after=None, seed=seed, ) def with_clevr_attribute( world: World, target_node: str, attribute: ClevrAttribute, value: str | None, ) -> World: """Clone ``world`` and set one object attribute, preserving visibility.""" if attribute not in ATTRIBUTE_DOMAINS: raise InterventionError(f"unknown CLEVR attribute {attribute!r}") if value is not None and value not in ATTRIBUTE_DOMAINS[attribute]: raise InterventionError(f"invalid CLEVR {attribute} value {value!r}") new = copy.deepcopy(world) objects = new.get("objects") if not isinstance(objects, list): raise InterventionError("CLEVR world objects is not an array") for index, obj in enumerate(objects): if isinstance(obj, dict) and obj.get("id") == target_node: obj[attribute] = value objects[index] = obj return new raise InterventionError(f"CLEVR target {target_node!r} is not a world object") def object_ids(world: World) -> tuple[str, ...]: objects = world.get("objects") if not isinstance(objects, list): raise InterventionError("CLEVR world objects is not an array") ids = [ str(obj["id"]) for obj in objects if isinstance(obj, dict) and isinstance(obj.get("id"), str) ] if len(ids) != len(objects) or len(ids) != len(set(ids)): raise InterventionError("CLEVR world has missing or duplicate object ids") return tuple(sorted(ids)) def _current(world: World, target_node: str, attribute: ClevrAttribute) -> str: objects = world.get("objects") if not isinstance(objects, list): raise InterventionError("CLEVR world objects is not an array") for obj in objects: if isinstance(obj, dict) and obj.get("id") == target_node: value = obj.get(attribute) if not isinstance(value, str) or value not in ATTRIBUTE_DOMAINS[attribute]: raise InterventionError( f"CLEVR object {target_node!r} has invalid {attribute} {value!r}" ) return value raise InterventionError(f"CLEVR target {target_node!r} is not a world object") def _mutation( *, source: World, transformed: World, kind: ClevrMutationKind, target_node: str, attribute: ClevrAttribute, before: str, after: str | None, seed: int, ) -> ClevrMutation: digest = canonical_json_hash( { "kind": kind, "target_node": target_node, "attribute": attribute, "before": before, "after": after, "seed": seed, "source_world_sha256": world_sha256(source), "transformed_world_sha256": world_sha256(transformed), } ) return ClevrMutation( world=transformed, kind=kind, target_node=target_node, attribute=attribute, before=before, after=after, seed=seed, mutation_sha256=digest, ) __all__ = [ "ATTRIBUTE_DOMAINS", "ClevrAttribute", "ClevrMutation", "ClevrMutationKind", "object_ids", "redact_clevr_attribute", "substitute_clevr_attribute", "with_clevr_attribute", ]