"""Strict JSON I/O and validation shared by the runner and standalone SFT builder.""" import hashlib import json import math from pathlib import Path import re import tempfile import os # A normal answer conclusion is not a reference to private supervision. PRIVATE = re.compile(r"\b(?:hint|ground[ -]?truth|human[ -]verified|secret mission|private supervision)\b", re.I) FIELDS = { "grounding": {"recognized_objects", "scene_description", "question_relevant_entities", "relevant_interactions"}, "state": {"target_entity", "transition_status", "state_before", "motion_or_interaction", "observed_state", "state_after", "state_change"}, "report": {"report", "answer", "confidence"}, } def dumps(value, **kwargs): return json.dumps(value, ensure_ascii=False, allow_nan=False, **kwargs) def loads(text): def constant(value): raise ValueError(f"Non-finite JSON constant: {value}") def pairs(items): result = {} for key, value in items: if key in result: raise ValueError(f"Duplicate JSON key: {key}") result[key] = value return result return json.loads(text, parse_constant=constant, object_pairs_hook=pairs) def read(path): return loads(Path(path).read_text(encoding="utf-8")) def atomic_text(path, text): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) fd, name = tempfile.mkstemp(prefix="." + path.name, dir=path.parent) try: with os.fdopen(fd, "w", encoding="utf-8") as stream: stream.write(text) os.replace(name, path) finally: if Path(name).exists(): Path(name).unlink() def write(path, value): atomic_text(path, dumps(value, indent=2) + "\n") def digest(value): return hashlib.sha256(dumps(value, sort_keys=True).encode()).hexdigest() def file_hash(path): sha = hashlib.sha256() with open(path, "rb") as stream: for chunk in iter(lambda: stream.read(1024 * 1024), b""): sha.update(chunk) return sha.hexdigest() def no_private(text): if PRIVATE.search(text): raise ValueError("Response refers to private supervision; sample must not be exported") def unwrap(text): no_private(text) match = re.fullmatch(r"\s*(.*?)\s*(.*?)\s*", text, re.S) if not match or not match[1].strip() or not match[2].strip(): raise ValueError("Expected followed by with no outside text") if re.search(r"", match[1] + match[2]): raise ValueError("Unexpected nested protocol tags") return match[2].strip() def validate(value, stage, num_options=None): if not isinstance(value, dict) or set(value) != FIELDS[stage]: raise ValueError(f"Invalid {stage} fields; expected {sorted(FIELDS[stage])}") no_private(dumps(value)) def string(item, nullable=False): if nullable and item is None: return if not isinstance(item, str) or not item.strip(): raise ValueError("Expected a nonempty string") if stage == "grounding": string(value["scene_description"]) for key in FIELDS[stage] - {"scene_description"}: if not isinstance(value[key], list): raise ValueError(f"Expected string list: {key}") for item in value[key]: string(item) if not value["recognized_objects"]: raise ValueError("Empty recognized object list") elif stage == "state": string(value["target_entity"]) gate = value["transition_status"] if gate not in {"explicit", "partial", "none"}: raise ValueError("Invalid transition_status") for key in FIELDS[stage] - {"target_entity", "transition_status"}: string(value[key], nullable=True) endpoints = [value[key] for key in ("state_before", "state_after", "state_change")] if gate == "explicit" and any(item is None for item in endpoints): raise ValueError("Explicit transition requires before, after, and change") if gate == "none" and any(item is not None for item in endpoints): raise ValueError("No transition requires null before, after, and change") if gate == "partial" and not (value["motion_or_interaction"] or value["state_change"]): raise ValueError("Partial transition requires supported motion or change") else: string(value["report"]) answer, confidence = value["answer"], value["confidence"] if answer is not None and (type(answer) is not int or num_options is None or not 0 <= answer < num_options): raise ValueError("Invalid zero-based answer index") if type(confidence) not in (int, float) or not math.isfinite(confidence) or not 0 <= confidence <= 1: raise ValueError("Invalid confidence") return value def public(value): if isinstance(value, dict): return {key: public(item) for key, item in value.items() if key not in {"severity", "raw_response", "answer_idx", "private_hint"}} if isinstance(value, list): return [public(item) for item in value] return value