sidrefresh's picture
Add files using upload-large-folder tool
2e7de11 verified
Raw History Blame Contribute Delete
22 kB
"""T29 provisional offline rendered-reference diagnostics.
Uses NumPy, OpenCV and ffmpeg; no model or network calls. No native editability
claim is made. Essential behavior is only partially covered by these visual
proxies until the category-specific event/trajectory checks are implemented.
"""
import argparse
import hashlib
import json
import subprocess
import tempfile
from pathlib import Path
import cv2
import numpy as np
VERSION = "t29-rendered-progress-v0.3"
W, H, ANIM_H, FRAMES = 384, 216, 180, 300
GOOEY = {"dot-gathering", "dot-hourglass", "dot-overtaking", "dot-shuttle"}
def sha(path):
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def probe(path):
r = subprocess.run(["ffprobe", "-v", "error", "-show_streams", "-show_format",
"-of", "json", str(path)], capture_output=True, text=True)
if r.returncode:
raise ValueError("Video probe failed: " + r.stderr[-1000:])
return json.loads(r.stdout)
def decode(path, size=(W, H), expected_size=None):
info = probe(path)
streams = [s for s in info["streams"] if s["codec_type"] == "video"]
if len(streams) != 1:
raise ValueError("Expected one video stream")
v = streams[0]
if expected_size and (v["width"], v["height"]) != expected_size:
raise ValueError(f"Expected {expected_size}, got {(v['width'], v['height'])}")
if v["avg_frame_rate"] != "30/1" or abs(float(info["format"]["duration"])-10) > .04:
raise ValueError("Expected 10 seconds at 30 fps")
if v["codec_name"] != "h264":
raise ValueError("Expected H.264")
if any(s["codec_type"] == "audio" for s in info["streams"]):
raise ValueError("Expected no audio")
timestamps = json.loads(subprocess.check_output(
["ffprobe", "-v", "error", "-select_streams", "v:0",
"-show_entries", "frame=best_effort_timestamp_time", "-of", "json", str(path)]))
pts = [float(f["best_effort_timestamp_time"]) for f in timestamps.get("frames", [])
if "best_effort_timestamp_time" in f]
if len(pts) != FRAMES or max(abs(t-i/30) for i, t in enumerate(pts)) > .001:
raise ValueError("Expected 300 frames with uniform timestamps starting at zero")
# Output dimensions and duration are bounded before buffering raw frames.
frame_bytes = size[0]*size[1]*3
gray = np.empty((FRAMES, size[1], size[0]), np.uint8)
chroma_sum, bright_count, count = 0.0, 0, 0
with tempfile.TemporaryFile() as errors:
process = subprocess.Popen(
["ffmpeg", "-nostdin", "-v", "error", "-i", str(path), "-an",
"-vf", f"scale={size[0]}:{size[1]}:flags=area", "-frames:v", "301",
"-pix_fmt", "rgb24", "-f", "rawvideo", "-"],
stdout=subprocess.PIPE, stderr=errors)
try:
while True:
raw = process.stdout.read(frame_bytes)
if not raw:
break
if len(raw) != frame_bytes or count >= FRAMES:
raise ValueError("Unexpected decoded frame count/size")
rgb = np.frombuffer(raw, dtype=np.uint8).reshape(size[1], size[0], 3)
bright = rgb.max(axis=-1) > 32
chroma = rgb.max(axis=-1).astype(np.int16)-rgb.min(axis=-1)
chroma_sum += float(chroma[bright].sum())
bright_count += int(bright.sum())
gray[count] = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY)
count += 1
code = process.wait()
errors.seek(0)
error_text = errors.read().decode(errors="replace")
if code:
raise ValueError("Video decode failed: " + error_text[-1000:])
finally:
if process.poll() is None:
process.kill()
process.wait()
process.stdout.close()
if count != FRAMES:
raise ValueError("Expected exactly 300 fully decoded frames")
chroma_mean = chroma_sum/max(bright_count, 1)/255
return gray, info, chroma_mean
def bridge_masks(frames):
"""Find narrow visible material between local distance-transform peaks.
A reference-only proxy for gooey neck regions, not an identity tracker.
Ambiguous or absent peaks yield no mask and must be reported as uncovered.
"""
masks = np.zeros(frames[:, :ANIM_H].shape, np.uint8)
kernel = np.ones((7, 7), np.uint8)
yy, xx = np.indices((ANIM_H, W))
for fi, frame in enumerate(frames[:, :ANIM_H]):
binary = (frame >= 96).astype(np.uint8)
dist = cv2.distanceTransform(binary, cv2.DIST_L2, 5)
local = ((dist >= cv2.dilate(dist, kernel)-.01) & (dist >= 4)).astype(np.uint8)
n, labels, stats, centers = cv2.connectedComponentsWithStats(local, 8)
components = cv2.connectedComponents(binary, 8)[1]
peaks = []
for k in range(1, n):
x, y = centers[k]
x, y = int(round(x)), int(round(y))
peaks.append((x, y, float(dist[y, x]), int(components[y, x])))
for i, (ax, ay, ar, ac) in enumerate(peaks):
for bx, by, br, bc in peaks[i+1:]:
length = np.hypot(bx-ax, by-ay)
if not ac or ac != bc or length < max(ar, br) or length > 1.8*(ar+br):
continue
dx, dy = bx-ax, by-ay
t = ((xx-ax)*dx+(yy-ay)*dy)/(length*length)
perp = np.abs((xx-ax)*dy-(yy-ay)*dx)/length
region = ((t > .25) & (t < .75) & (perp < max(1.5, min(ar, br)*.25))
& (np.hypot(xx-ax, yy-ay) > .85*ar)
& (np.hypot(xx-bx, yy-by) > .85*br) & (binary > 0))
masks[fi][region] = 1
return masks
def window_max(values, width=15):
return float(np.convolve(values, np.ones(width)/width, mode="valid").max())
def progress_credit(value, tolerance):
"""Full inside the disclosed band, linear credit to zero at twice it."""
if value is None:
return None
if tolerance == 0:
return float(value == 0)
return float(np.clip(2-value/tolerance, 0, 1))
def curve_measurements(a, b):
"""Observable whole-region curves; no invented identities through merges."""
def curves(frames):
mass = frames.sum(axis=(1, 2))
yy, xx = np.indices(frames.shape[1:])
valid = mass >= 16
cx = (frames*xx).sum(axis=(1, 2))/np.maximum(mass, 1)
cy = (frames*yy).sum(axis=(1, 2))/np.maximum(mass, 1)
sx = np.sqrt((frames*(xx-cx[:, None, None])**2).sum(axis=(1, 2))/np.maximum(mass, 1))
sy = np.sqrt((frames*(yy-cy[:, None, None])**2).sum(axis=(1, 2))/np.maximum(mass, 1))
area = (frames >= .5).sum(axis=(1, 2))
return mass, area, cx, cy, sx, sy, valid
ac, bc = curves(a), curves(b)
valid = ac[6] & bc[6]
# Missing visible content loses that frame; reference disappearance is valid.
missing = bc[6] & ~ac[6]
def spatial(index, band):
errors = np.abs(ac[index][valid]-bc[index][valid])/band
return float((np.clip(errors-1, 0, 1).sum()+missing.sum())/max(bc[6].sum(), 1))
mass_scale = max(float(np.percentile(bc[0], 95)), 16)
area_scale = max(float(np.percentile(bc[1], 95)), 16)
return {
"position_curve_error": (spatial(2, 3)+spatial(3, 3))/2,
"size_curve_error": (spatial(4, 2)+spatial(5, 2))/2,
"brightness_curve_error": float(np.mean(np.abs(ac[0]-bc[0]))/mass_scale),
"area_curve_error": float(np.mean(np.abs(ac[1]-bc[1]))/area_scale),
}
def label_text_check(frames, expected):
"""Read wording only. OCR failure is unmeasured, never a font mismatch."""
import re
import shutil
if shutil.which("tesseract") is None:
raise RuntimeError("Tesseract is required for label wording verification")
def normalize(text):
# Ignore whitespace and typographic hyphens, but retain every letter.
return re.sub(r"[\s\-\u2010-\u2015\u2212]+", "", text.casefold())
readings = []
with tempfile.TemporaryDirectory(prefix="t29-label-") as directory:
path = Path(directory)/"label.png"
for index in (0, 149, 299):
crop = frames[index, ANIM_H:]
if not np.any(crop > 32):
readings.append("")
continue
for pixels in (255-crop, np.where(crop > 64, 0, 255).astype(np.uint8)):
image = cv2.resize(pixels, None, fx=6, fy=6, interpolation=cv2.INTER_CUBIC)
image = cv2.copyMakeBorder(image, 30, 30, 30, 30, cv2.BORDER_CONSTANT, value=255)
cv2.imwrite(str(path), image)
result = subprocess.run(["tesseract", str(path), "stdout", "--psm", "7", "-l", "eng"],
capture_output=True, text=True, timeout=20)
if result.returncode:
raise RuntimeError("Label OCR failed: " + result.stderr[-300:])
readings.append(normalize(result.stdout.strip()))
expected_text = normalize(expected)
correct = sum(r == expected_text for r in readings)
if correct >= 2:
return 0.0, {"status": "recognized", "readings": readings, "expected": expected}
# Blank crop is observable absence; unreadable occupied crop is uncertainty.
wrong = [r for r in readings if r and r != expected_text]
if readings.count("") == 3 and not np.any(frames[:, ANIM_H:] > 32):
return 1.0, {"status": "missing", "readings": readings, "expected": expected}
if any(wrong.count(r) >= 2 for r in wrong):
return 1.0, {"status": "recognized mismatch", "readings": readings, "expected": expected,
"limitation": "Consistent OCR errors require detector calibration"}
return None, {"status": "OCR uncertain", "readings": readings, "expected": expected}
def compare(candidate, reference, config, bridges=None, candidate_chroma=0.0, expected_label=None):
if candidate.shape != reference.shape or candidate.shape != (FRAMES, H, W):
raise ValueError("Comparison requires aligned 300x216x384 arrays")
a = candidate[:, :ANIM_H].astype(np.float32)/255
b = reference[:, :ANIM_H].astype(np.float32)/255
union = (a > 32/255) | (b > 32/255)
# Average normalized foreground error per frame; black canvas is excluded.
frame_error = np.abs(a-b).sum(axis=(1, 2))/np.maximum(b.sum(axis=(1, 2)), 16)
soft_error = float(frame_error.mean())
ious = {}
for threshold in [32, 128, 224]:
am, bm = a >= threshold/255, b >= threshold/255
counts = (am | bm).sum(axis=(1, 2))
iou = np.divide((am & bm).sum(axis=(1, 2)), counts,
out=np.ones(FRAMES), where=counts > 0)
ious[str(threshold)] = {"mean": float(iou.mean()),
"p05": float(np.percentile(iou, 5))}
# Pool before differencing so compression/antialias flicker has less weight.
pa = np.stack([cv2.resize(f, (96, 45), interpolation=cv2.INTER_AREA) for f in a])
pb = np.stack([cv2.resize(f, (96, 45), interpolation=cv2.INTER_AREA) for f in b])
da, db = np.diff(pa, axis=0), np.diff(pb, axis=0)
motion_energy = float(np.abs(db).sum())
temporal_error = float(np.abs(da-db).sum()/max(motion_energy, 1))
# Reference-changing pixels isolate moving/fading satellites from static cores.
dynamic = np.ptp(b, axis=0) > .12
dynamic_error = float(np.abs(a[:, dynamic]-b[:, dynamic]).sum()
/max(float(b[:, dynamic].sum()), 16)) if dynamic.any() else None
xp = float(np.abs(a.sum(axis=1)-b.sum(axis=1)).sum()/max(float(b.sum()), 16))
yp = float(np.abs(a.sum(axis=2)-b.sum(axis=2)).sum()/max(float(b.sum()), 16))
# Observability-based spatial envelope is an auxiliary invariant, not a
# stand-alone horizontal-motion pass: stationary objects can satisfy it.
envelope = (b > 32/255).any(axis=0).astype(np.uint8)
envelope = cv2.dilate(envelope, np.ones((3, 3), np.uint8))
off_envelope = float(a[:, envelope == 0].sum()/max(float(a.sum()), 16))
bridge_error = None
bridge_frames = 0
if bridges is not None:
active = bridges.astype(bool)
bridge_frames = int(active.any(axis=(1, 2)).sum())
if active.sum() >= 20 and bridge_frames >= 3:
bridge_error = float(np.abs(a[active]-b[active]).sum()/max(float(b[active].sum()), 1))
label_error, label_evidence = (label_text_check(candidate, expected_label)
if expected_label else
(None, {"status": "not requested for this comparison"}))
metrics = {
"foreground_luma_error": soft_error,
"worst_half_second_error": window_max(frame_error),
"temporal_change_error": temporal_error,
"dynamic_region_error": dynamic_error,
"x_projection_error": xp, "y_projection_error": yp,
"outside_reference_envelope": off_envelope,
"bridge_region_error": bridge_error,
"label_text_error": label_error,
"foreground_chroma": candidate_chroma,
}
metrics.update(curve_measurements(a, b))
content_present = bool(np.any(candidate[:, :ANIM_H] > 32))
checks = []
for key, rule in config["checks"].items():
if key == "label_text_error" and expected_label is None:
continue
value = metrics[key]
if key == "bridge_region_error" and bridges is None:
continue
credit = progress_credit(value, rule["max"])
if key != "label_text_error" and not content_present:
credit = 0.0
checks.append({"id": key, "measured": value, "limit": rule["max"],
"credit": credit,
"passed": None if value is None else value <= rule["max"],
"role": rule["role"], "weight": rule["weight"],
"status": "unmeasurable" if value is None else "measured"})
available = [c for c in checks if c["measured"] is not None]
quality_checks = [c for c in checks if c["id"] != "label_text_error"]
denom = sum(c["weight"] for c in quality_checks)
partial = sum(c["weight"]*(c["credit"] or 0) for c in quality_checks)/denom if denom else 0
activity_ratio = float(np.abs(da).sum()/max(motion_energy, 1))
# Preserve appearance progress, but a still image cannot earn most animation credit.
motion_factor = .25 + .75*min(activity_ratio, 1)
partial *= motion_factor
return {
"metrics": metrics, "checks": checks, "label_evidence": label_evidence,
"visual_proxy_partial": partial,
"animation_quality": partial, "content_present": content_present,
"motion_activity_ratio": activity_ratio, "motion_factor": motion_factor,
"proxy_checks_pass": bool(available) and all(c["passed"] is True for c in checks),
"category_visual_pass": None,
"essential_semantics_fully_implemented": False,
"unimplemented": ["Explicit per-dot trajectories/identities where observable",
"Category-specific event order and turning-point checks",
"Broad label OCR/font calibration",
"Native project replay and editability"],
"foreground_iou": ious, "bridge_reference_frames": bridge_frames,
"reference_motion_energy": motion_energy,
"coverage": len(available)/max(len(checks), 1),
"worst_frames": np.argsort(frame_error)[-6:].tolist(),
"warning": "Rendered progress score; broad recreation calibration and explicit event identities remain unavailable."
}
def evaluate(root, out, reference_dir):
root, out, reference_dir = Path(root), Path(out), Path(reference_dir)
out.mkdir(parents=True, exist_ok=True)
for name in ["reward.txt", "reward.json", "evaluation-error.json"]:
(out/name).unlink(missing_ok=True)
config_path = reference_dir/"diagnostic-config.json"
config = json.loads(config_path.read_text())
bundle = reference_dir/"reference-frames.npz"
if sha(bundle) != config["bundle_sha256"]:
raise RuntimeError("Private reference bundle hash mismatch")
data = np.load(bundle, allow_pickle=False)
names = config["category_order"]
report = {"version": VERSION, "mode": "rendered animation progress reward",
"config_sha256": sha(config_path), "reference_hash": config["supplied_reference_sha256"],
"categories": [], "delivery": [], "native_validity": "unverified",
"overall_task_pass": None}
gallery_path = root/"Desktop/final.mp4"
gallery = None
if gallery_path.exists():
try:
gallery, _, gallery_chroma = decode(gallery_path, size=(1920, 1080), expected_size=(1920, 1080))
report["gallery_foreground_chroma"] = gallery_chroma
report["delivery"].append({"path": str(gallery_path), "passed": True})
except ValueError as exc:
report["delivery"].append({"path": str(gallery_path), "passed": False, "reason": str(exc)})
else:
report["delivery"].append({"path": str(gallery_path), "passed": False, "reason": "missing"})
for i, name in enumerate(names):
entry = {"name": name, "individual": None, "gallery": None, "assembly_consistency": None}
candidate = root/"Desktop/individual"/(name+".mp4")
ref = data[name]
bridges = data[name+"__bridges"] if name in GOOEY else None
frames = None
if candidate.exists():
try:
frames, _, chroma = decode(candidate, expected_size=(960, 540))
entry["individual"] = compare(frames, ref, config, bridges, chroma, expected_label=name)
entry["candidate_sha256"] = sha(candidate)
report["delivery"].append({"path": str(candidate), "passed": True})
except ValueError as exc:
entry["visual_state"] = "unmeasurable"
report["delivery"].append({"path": str(candidate), "passed": False, "reason": str(exc)})
else:
entry["visual_state"] = "unmeasurable: missing export"
report["delivery"].append({"path": str(candidate), "passed": False, "reason": "missing"})
if gallery is not None:
row, col = i//5, i%5
crop = gallery[:, row*270+27:row*270+243, col*384:(col+1)*384]
entry["gallery"] = compare(crop, ref, config, bridges, expected_label=name)
if frames is not None:
entry["assembly_consistency"] = compare(crop, frames, config)
project = root/"edit/individual"/(name+".friction")
report["delivery"].append({"path": str(project), "passed": project.is_file() and project.stat().st_size > 0,
"limitation": "presence only; not native validity"})
report["categories"].append(entry)
combined = root/"edit/combined.friction"
report["delivery"].append({"path": str(combined), "passed": combined.is_file() and combined.stat().st_size > 0,
"limitation": "presence only; not native validity"})
scored = [c["individual"] for c in report["categories"] if c["individual"] is not None]
report["individual_visual_coverage"] = len(scored)/len(names)
report["individual_proxy_sum_over_all_required_categories"] = sum(c["visual_proxy_partial"] for c in scored)/len(names)
report["delivery_fraction"] = sum(c["passed"] for c in report["delivery"])/len(report["delivery"])
def mean_quality(field):
return sum(c[field]["animation_quality"] if c[field] else 0 for c in report["categories"])/len(names)
label_total = 0
consistency = 0
for c in report["categories"]:
for field in ("individual", "gallery"):
measured = c[field]
if measured:
uncertain = [x["id"] for x in measured["checks"] if x["credit"] is None]
if uncertain:
raise RuntimeError(f"Detector uncertainty for {c['name']} {field}: {uncertain}")
label_total += float(measured["metrics"]["label_text_error"] == 0)
if c["assembly_consistency"]:
# Two empty or wrong renders must not earn consistency credit alone.
consistency += (c["assembly_consistency"]["animation_quality"] *
min(c["individual"]["animation_quality"], c["gallery"]["animation_quality"]))
weights = config["reward_weights"]
sections = {"delivery": report["delivery_fraction"],
"individual_animation": mean_quality("individual"),
"gallery_animation": mean_quality("gallery"),
"label_wording": label_total/(2*len(names)),
"assembly_consistency": consistency/len(names)}
report["reward_sections"] = {k: {"score": v, "weight": weights[k], "contribution": v*weights[k]}
for k, v in sections.items()}
report["reward"] = sum(v*weights[k] for k, v in sections.items())
(out/"visual-diagnostics.json").write_text(json.dumps(report, indent=2)+"\n")
(out/"reward.txt").write_text(str(report["reward"])+"\n")
(out/"reward.json").write_text(json.dumps({"reward": report["reward"]})+"\n")
return report
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--root", default="/root")
parser.add_argument("--out", default="/logs/verifier")
parser.add_argument("--reference-dir", default=str(Path(__file__).parent/"reference"))
args = parser.parse_args()
try:
evaluate(args.root, args.out, args.reference_dir)
except Exception as exc:
out = Path(args.out)
out.mkdir(parents=True, exist_ok=True)
for name in ["reward.txt", "reward.json"]:
(out/name).unlink(missing_ok=True)
(out/"evaluation-error.json").write_text(json.dumps({"error": type(exc).__name__, "message": str(exc)}))
raise