Record first-zoom block reasons on PR7
#9
Open
YaroslavKartashov
wants to merge 1 commits from feature/ptz-pr7-zoom-block-reason into feature/ptz-zoom-threshold-diagnostics
@ -0,0 +1,71 @@
|
|||||||
|
--- a/postprocess.py
|
||||||
|
+++ b/postprocess.py
|
||||||
|
@@ -6640,6 +6640,28 @@
|
||||||
|
detector_conf=max(alarm_conf, identity_conf),
|
||||||
|
alarm_eligible=alarm_eligible, cam_idx=cam_idx)
|
||||||
|
alarms.ingest_detection(cam_idx, alarm_eligible)
|
||||||
|
+
|
||||||
|
+
|
||||||
|
+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=(",", ":")),
|
||||||
|
+ )
|
||||||
|
|
||||||
|
|
||||||
|
@visual_control.serialized_control
|
||||||
|
@@ -9844,6 +9866,39 @@
|
||||||
|
("brake", final_guard_active),
|
||||||
|
) if blocked)
|
||||||
|
zoom_decision = (source_seq, decision_request, zoom_zero_reason, "+".join(blockers) or "-")
|
||||||
|
+ 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)
|
||||||
|
dispatch_kwargs = {"force": force_track_ptz}
|
||||||
|
if zoom_decision is not None:
|
||||||
|
dispatch_kwargs["zoom_decision"] = zoom_decision
|
||||||
@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"before": "776b5b337e5f898e69770fec517c4459560f4cc6adeb951af40ac8f0b2178534",
|
||||||
|
"after": "a9315ef80ca1cc6064088acfba0e854ed4617f3594753663050b13f82dd3c8fa"
|
||||||
|
}
|
||||||
@ -0,0 +1,98 @@
|
|||||||
|
"""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()
|
||||||
@ -0,0 +1,90 @@
|
|||||||
|
"""Verify the pinned PR7 diagnostic patch, its counts and its observation-only hook."""
|
||||||
|
from hashlib import sha256
|
||||||
|
from pathlib import Path
|
||||||
|
from types import SimpleNamespace
|
||||||
|
from unittest.mock import Mock
|
||||||
|
import ast
|
||||||
|
import json
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
from prepare_pr7_diagnostics import BASE_SHA, OUT, SOURCE
|
||||||
|
|
||||||
|
|
||||||
|
def function(tree, name):
|
||||||
|
return next(x for x in tree.body if isinstance(x, ast.FunctionDef) and x.name == name)
|
||||||
|
|
||||||
|
|
||||||
|
def dump(node):
|
||||||
|
return ast.dump(node, include_attributes=False)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
pins = json.loads((OUT / "pr7_zoom_block_reason_pins.json").read_bytes())
|
||||||
|
patch = str(OUT / "pr7_zoom_block_reason.patch")
|
||||||
|
with tempfile.TemporaryDirectory(dir=OUT) as directory:
|
||||||
|
source = Path(directory)/"postprocess.py"
|
||||||
|
original = Path(sys.argv[1]) if len(sys.argv) > 1 else SOURCE
|
||||||
|
base = original.read_bytes()
|
||||||
|
assert sha256(base).hexdigest()==BASE_SHA
|
||||||
|
source.write_bytes(base)
|
||||||
|
git = ["git","-c","core.autocrlf=false","apply"]
|
||||||
|
subprocess.run([*git,"--whitespace=error",patch],cwd=directory,check=True)
|
||||||
|
after=source.read_bytes()
|
||||||
|
assert sha256(after).hexdigest()==pins["after"]
|
||||||
|
subprocess.run([*git,"-R",patch],cwd=directory,check=True)
|
||||||
|
assert source.read_bytes()==base
|
||||||
|
|
||||||
|
old, new = ast.parse(base), ast.parse(after)
|
||||||
|
proc = function(new,"postprocess_control")
|
||||||
|
control = function(old,"postprocess_control")
|
||||||
|
anchor = next(node for node in ast.walk(proc) if isinstance(node,ast.If)
|
||||||
|
and "ZOOM_BLOCK_DIAG_ENABLE" in dump(node.test))
|
||||||
|
# Removing the optional hook and its sole helper restores the entire AST.
|
||||||
|
for parent in ast.walk(proc):
|
||||||
|
for field,value in ast.iter_fields(parent):
|
||||||
|
if isinstance(value,list) and anchor in value:
|
||||||
|
value.remove(anchor)
|
||||||
|
new.body.remove(function(new,"_log_zoom_block_tick"))
|
||||||
|
assert dump(proc)==dump(control) and dump(old)==dump(new)
|
||||||
|
|
||||||
|
helper=function(ast.parse(after),"_log_zoom_block_tick")
|
||||||
|
log=Mock()
|
||||||
|
env={"json":json,"logger":log}
|
||||||
|
exec(compile(ast.Module(body=[helper],type_ignores=[]),"<diagnostics>","exec"),env)
|
||||||
|
report=env[helper.name]
|
||||||
|
st={"ptz_generation":4,"track_started_at":100.0}
|
||||||
|
state={
|
||||||
|
"config":SimpleNamespace(ZOOM_BLOCK_DIAG_ENABLE=False), "cam_idx":8, "st":st,
|
||||||
|
"source_seq":1,"zoom_cmd":0.,"final_guard_active":False,"near_edge":False,
|
||||||
|
"edge_recovery_active":False,"visual_control_stale":False,"visual_control_coast":False,
|
||||||
|
"zoom_rearm_ready":True,"raw_zoom_needed":True,"normal_size_hold":False,
|
||||||
|
"current_track_source":"visual","visual_zoom_validation_age":0.2,"zoom_quality_ok":True,
|
||||||
|
"followup_ready":True,"zoom_safe":True,"zoom_angular_safe":True,
|
||||||
|
"center_locked_for_zoom":False,"track_stable":False,"now":101.,
|
||||||
|
"zoom_zero_reason":"size_controller","_log_zoom_block_tick":report,
|
||||||
|
}
|
||||||
|
call=compile(ast.Module(body=[anchor],type_ignores=[]),"<hook>","exec")
|
||||||
|
exec(call,state)
|
||||||
|
assert "zoom_block_diag" not in st
|
||||||
|
state["config"].ZOOM_BLOCK_DIAG_ENABLE=True
|
||||||
|
st["visual_tracker_score"]=.8
|
||||||
|
exec(call,state)
|
||||||
|
assert st["zoom_block_diag"]["before_first"]=={"not_centered":1}
|
||||||
|
state.update(zoom_cmd=.10)
|
||||||
|
exec(call,state)
|
||||||
|
assert st["zoom_block_diag"]["first_positive"]
|
||||||
|
state.update(zoom_cmd=0.,zoom_zero_reason="final_brake",final_guard_active=True)
|
||||||
|
exec(call,state)
|
||||||
|
assert st["zoom_block_diag"]["total"]=={"not_centered":1,"final_brake":1}
|
||||||
|
assert st["zoom_block_diag"]["before_first"]=={"not_centered":1}
|
||||||
|
st.update(ptz_generation=5,track_started_at=103.0)
|
||||||
|
exec(call,state)
|
||||||
|
assert st["zoom_block_diag"]["before_first"]=={"final_brake":1}
|
||||||
|
assert log.info.call_count==3
|
||||||
|
print("Round-trip exact, control AST unchanged outside the hook, toggle/phase/owner/count checks passed.")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__=="__main__":
|
||||||
|
main()
|
||||||
Loading…
Reference in New Issue