"""Prepare an opt-in observation-only patch for the pinned PR7 controller.""" from hashlib import sha256 from pathlib import Path import difflib import json import sys OUT = Path(__file__).resolve().parent SOURCE = OUT.parent / "ptz_zoom_threshold_maintenance_20261111/postprocess.py" BASE_SHA = "776b5b337e5f898e69770fec517c4459560f4cc6adeb951af40ac8f0b2178534" HELPER = '''def _log_zoom_block_tick(st, cam, source_seq, zoom, reason, blockers): """Count TRACK decisions without taking part in actuator authorization.""" owner = (st.get("ptz_generation"), st.get("track_started_at")) record = st.get("zoom_block_diag") if record is None or record["owner"] != owner: record = {"owner": owner, "first_positive": False, "total": {}, "before_first": {}} st["zoom_block_diag"] = record if zoom > 0.0: record["first_positive"] = True return before_first = not record["first_positive"] for key in ("total", "before_first") if before_first else ("total",): counts = record[key] counts[reason] = counts.get(reason, 0) + 1 logger.info( "[ZOOM BLOCK] cam=%s gen=%s track=%s frame=%s zoom_block_reason=%s " "before_first_positive_decision=%s blockers=%s counts=%s", cam, owner[0], owner[1], source_seq, reason, before_first, "+".join(blockers) or "-", json.dumps(record["total"], separators=(",", ":")), ) ''' HOOK = ''' if (bool(getattr(config, "ZOOM_BLOCK_DIAG_ENABLE", False)) and cam_idx in getattr(config, "ZOOM_BLOCK_DIAG_CAM_IDS", (8, 10))): if zoom_cmd > 0.0: _log_zoom_block_tick(st, cam_idx, source_seq, zoom_cmd, "", ()) else: diagnostic_flags = tuple(name for name, active in ( ("gimbal_brake", final_guard_active), ("edge_margin_low", near_edge or edge_recovery_active), ("stale_visual", visual_control_stale), ("visual_coast", visual_control_coast), ("geometry_rearm", not zoom_rearm_ready), ("size_controller", not raw_zoom_needed or normal_size_hold), ("low_tracker_score", current_track_source == "visual" and float(st.get("visual_tracker_score", 0.0) or 0.0) < float(getattr(config, "VISUAL_TRACKER_ZOOM_SCORE", 0.42))), ("waiting_yolo", current_track_source == "visual" and not zoom_quality_ok and visual_zoom_validation_age > float(getattr(config, "VISUAL_TRACKER_ZOOM_MAX_UNVALIDATED_SEC", 1.0))), ("quality_or_validation", not zoom_quality_ok), ("fov_cooldown", not followup_ready), ("framing", not zoom_safe), ("angular_limit", not zoom_angular_safe), ("not_centered", not center_locked_for_zoom), ("track_history", not track_stable), ("focus_settle", now < float(st.get("focus_settle_until", 0.0) or 0.0)), ) if active) # size_controller is initialized before any gate is evaluated. # Prefer a specific stop stage when one was actually recorded. diagnostic_reason = zoom_zero_reason if diagnostic_reason in ("size_controller", "permission") and diagnostic_flags: diagnostic_reason = diagnostic_flags[0] _log_zoom_block_tick(st, cam_idx, source_seq, zoom_cmd, diagnostic_reason, diagnostic_flags) ''' def build(path): raw = path.read_bytes() if sha256(raw).hexdigest() != BASE_SHA: raise ValueError("Expected pinned PR7 postprocess.py") old = raw.decode() marker = "@visual_control.serialized_control\ndef postprocess_control(" anchor = ' dispatch_kwargs = {"force": force_track_ptz}\n' if old.count(marker) != 1 or old.count(anchor) != 1: raise ValueError("Unexpected integration point") new = old.replace(marker, HELPER+marker).replace(anchor,HOOK+anchor) return old,new def main(): source = Path(sys.argv[1]) if len(sys.argv) > 1 else SOURCE old,new = build(source) compile(new,"postprocess.py","exec") patch = "".join(difflib.unified_diff(old.splitlines(True),new.splitlines(True), "a/postprocess.py","b/postprocess.py")) (OUT/"pr7_zoom_block_reason.patch").write_bytes(patch.encode()) (OUT/"pr7_zoom_block_reason_pins.json").write_text( json.dumps({"before":BASE_SHA,"after":sha256(new.encode()).hexdigest()},indent=2)+"\n", encoding="utf-8") print("Prepared diagnostic patch and hashes") if __name__=="__main__": main()