refactor: move get_derived_state function to top of file

This commit is contained in:
2025-08-01 17:03:24 +00:00
parent 20c433af2d
commit 2556858912

View File

@@ -34,6 +34,18 @@ PREDICTION_HISTORY_MAX_LENGTH = 3
PREVIOUS_STATE = "unknown"
LAST_OPEN_SAVE_TIME = None
def get_derived_state():
"""Derives the state from the prediction history."""
state = "unknown"
if len(PREDICTION_HISTORY) == PREDICTION_HISTORY_MAX_LENGTH:
if all(s == "open" for s in PREDICTION_HISTORY):
state = "open"
elif all(s == "closed" for s in PREDICTION_HISTORY):
state = "closed"
return state
# --- Model Inference ---
def get_prediction(model, image_bytes, device):
"""Run model inference on the provided image bytes."""
@@ -106,7 +118,7 @@ async def monitor_garage_door(app):
logging.info(f"Low confidence prediction: {prediction} ({confidence:.4f}). Saved for review: {filepath}")
else:
# High confidence, save to sorted
if prediction == 'open':
if get_derived_state() == 'open':
if LAST_OPEN_SAVE_TIME is None or (datetime.now() - LAST_OPEN_SAVE_TIME) > timedelta(minutes=5):
sorted_dir = os.path.join('data', 'sorted', 'open')
os.makedirs(sorted_dir, exist_ok=True)
@@ -115,7 +127,7 @@ async def monitor_garage_door(app):
f.write(image_bytes)
LAST_OPEN_SAVE_TIME = datetime.now()
logging.info(f"Saved high-confidence 'open' image: {filepath}")
elif prediction == 'closed':
elif get_derived_state() == 'closed':
open_dir = os.path.join('data', 'sorted', 'open')
closed_dir = os.path.join('data', 'sorted', 'closed')
os.makedirs(open_dir, exist_ok=True)
@@ -172,17 +184,6 @@ async def monitor_state_transitions(app):
# --- Web Server ---
def get_derived_state():
"""Derives the state from the prediction history."""
state = "unknown"
if len(PREDICTION_HISTORY) == PREDICTION_HISTORY_MAX_LENGTH:
if all(s == "open" for s in PREDICTION_HISTORY):
state = "open"
elif all(s == "closed" for s in PREDICTION_HISTORY):
state = "closed"
return state
async def handle_root(request):
"""Handler for the root GET request."""
return web.Response(text="hello world")