File size: 5,281 Bytes
517154b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | """InsightUX developer calibration optimizer.
Runs repeated calibration/validation cycles and keeps the best calibration.
Each cycle is intentionally interactive: the operator must look at every
calibration dot and every validation target.
Typical use:
python calibration_optimizer.py --runs 5 --developer
For every run:
1. Launch calibrate.py.
2. Operator completes the 16-point calibration.
3. Launch validate.py.
4. Operator completes the 9 validation targets.
5. Parse mean pixel error and store the run.
6. If it is the best result so far, copy calibration.pkl and the fine-tuned
model into calibration_optimal/.
Lower mean validation pixel error is the primary definition of "better".
Quality diagnostics are still recorded, but they do not override a real
validation measurement.
"""
from __future__ import annotations
import argparse
import json
import os
import re
import subprocess
import sys
from pathlib import Path
PROJECT_ROOT = Path(__file__).resolve().parent.parent
if str(PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(PROJECT_ROOT))
from calibration.calibration_quality import record_run, compare_to_optimal
VAL_PATTERNS = {
"mean_error_px": re.compile(r"Mean pixel error\s*:\s*([0-9.]+)\s*px", re.I),
"mean_error_pct": re.compile(r"Mean error vs screen\s*:\s*([0-9.]+)%", re.I),
"zone_hit_rate": re.compile(r"Zone hit rate.*?\(([0-9.]+)%\)", re.I),
}
def run_script(script: str, env: dict, log_path: Path) -> str:
print(f"\n===== Running {script} =====")
proc = subprocess.run(
[sys.executable, script],
env=env,
cwd=Path(__file__).resolve().parent,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
output = proc.stdout or ""
log_path.write_text(output, encoding="utf-8", errors="replace")
print(output)
if proc.returncode != 0:
raise RuntimeError(f"{script} exited with code {proc.returncode}")
return output
def parse_validation(output: str) -> dict:
out = {}
for key, pat in VAL_PATTERNS.items():
m = pat.search(output)
if m:
out[key] = float(m.group(1))
if "mean_error_px" not in out:
raise RuntimeError("Could not find 'Mean pixel error' in validate.py output.")
return out
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--runs", type=int, default=5,
help="Number of calibration+validation cycles.")
ap.add_argument("--developer", action="store_true",
help="Promote the best run to calibration_optimal/.")
ap.add_argument("--calibrate", default="calibration/calibrate.py")
ap.add_argument("--validate", default="calibration/validate.py")
ap.add_argument("--history", default="calibration_quality_history.json")
ap.add_argument("--logs-dir", default="calibration_benchmark_logs")
args = ap.parse_args()
if args.runs < 1:
raise SystemExit("--runs must be >= 1")
root = PROJECT_ROOT
logs = root / args.logs_dir
logs.mkdir(parents=True, exist_ok=True)
env = dict(os.environ)
summary = []
for i in range(1, args.runs + 1):
print(f"\n\n################ CALIBRATION RUN {i}/{args.runs} ################")
cal_log = logs / f"run_{i:02d}_calibration.txt"
val_log = logs / f"run_{i:02d}_validation.txt"
calibrate_script = Path(args.calibrate)
validate_script = Path(args.validate)
if not calibrate_script.is_absolute():
calibrate_script = root / calibrate_script
if not validate_script.is_absolute():
validate_script = root / validate_script
run_script(str(calibrate_script), env, cal_log)
val_output = run_script(str(validate_script), env, val_log)
val = parse_validation(val_output)
metrics = {
"benchmark_run": i,
"validation_error_px": val["mean_error_px"],
"validation_error_pct": val.get("mean_error_pct"),
"zone_hit_rate": val.get("zone_hit_rate"),
}
comparison = compare_to_optimal(metrics, args.history)
result = record_run(
metrics,
history_path=args.history,
calibration_path=str(root / "calibration.pkl"),
model_path=str(root / "gaze_cnn_v4_finetuned.onnx"),
developer_mode=args.developer,
)
row = {
"run": i,
"mean_error_px": val["mean_error_px"],
"mean_error_pct": val.get("mean_error_pct"),
"zone_hit_rate": val.get("zone_hit_rate"),
"promoted": result["promoted"],
"comparison": comparison,
}
summary.append(row)
print("\n--- RUN RESULT ---")
print(json.dumps(row, indent=2))
best = min(summary, key=lambda r: r["mean_error_px"])
print("\n================ BENCHMARK COMPLETE ================")
print(json.dumps({"runs": summary, "best_run": best}, indent=2))
print("=====================================================")
if __name__ == "__main__":
main()
|