"""Execution verifiers -- the OBJECTIVE half of the reward. For modalities Handicate can produce as code/markup, we don't just ask the judge's opinion -- we actually RUN/parse the artifact and check it works. That hard signal is what lets reinforcement learning improve real capability (working 3D, valid SVG, code that runs) instead of just plausible-looking text. Verifiers return a float in 0..1 (1 = works). They run generated code in a subprocess with a timeout -- safe on the ephemeral HF Job container; locally only run on trusted input. """ import re import subprocess import sys import tempfile from pathlib import Path def extract_block(text, langs=("python", "")): for lang in langs: m = re.search(rf"```{lang}\s*\n(.*?)```", text, re.DOTALL | re.IGNORECASE) if m: return m.group(1).strip() # fall back to any fenced block m = re.search(r"```\s*\n(.*?)```", text, re.DOTALL) return m.group(1).strip() if m else text.strip() def _run(code, prelude="", timeout=15): with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False, encoding="utf-8") as f: f.write(prelude + "\n" + code) path = f.name try: r = subprocess.run([sys.executable, path], capture_output=True, text=True, timeout=timeout) return r.returncode == 0, (r.stdout + r.stderr) except subprocess.TimeoutExpired: return False, "timeout" except Exception as e: return False, str(e) finally: Path(path).unlink(missing_ok=True) def verify_python(text): """Code must run without error.""" ok, _ = _run(extract_block(text, ("python", ""))) return 1.0 if ok else 0.0 def verify_3d(text): """Generated code must build a valid mesh (a `mesh` trimesh with faces, or save an OBJ).""" code = extract_block(text, ("python", "")) check = ("\n_m = globals().get('mesh', None)\n" "assert _m is not None, 'no mesh variable'\n" "assert len(getattr(_m, 'faces', [])) > 0 and len(getattr(_m, 'vertices', [])) > 0\n" "print('MESH_OK', len(_m.vertices), len(_m.faces))\n") ok, out = _run(code + check, prelude="import trimesh, numpy as np") return 1.0 if (ok and "MESH_OK" in out) else 0.0 def verify_svg(text): """SVG must parse and contain at least one drawable shape.""" import xml.etree.ElementTree as ET m = re.search(r"", text, re.DOTALL | re.IGNORECASE) if not m: return 0.0 try: root = ET.fromstring(m.group(0)) except Exception: return 0.0 shapes = ("path", "rect", "circle", "ellipse", "line", "polyline", "polygon") found = any(el.tag.split("}")[-1] in shapes for el in root.iter()) return 1.0 if found else 0.3 def verify_bash(text): """Syntax-check only (no execution): bash -n on a temp file (portable, unix newlines).""" code = extract_block(text, ("bash", "sh", "")) import os with tempfile.NamedTemporaryFile("w", suffix=".sh", delete=False, newline="\n", encoding="utf-8") as f: f.write(code) path = f.name try: r = subprocess.run(["bash", "-n", path], capture_output=True, text=True, timeout=10) return 1.0 if r.returncode == 0 else 0.0 except Exception: return 0.0 finally: Path(path).unlink(missing_ok=True)