update sessionID backend

This commit is contained in:
Pongsatorn 2025-08-23 18:38:50 +07:00
parent 5873945115
commit 07eddd3f0d
2 changed files with 137 additions and 81 deletions

60
app.py
View file

@ -293,12 +293,22 @@ async def detect(websocket: WebSocket):
subscription_parts = stream["subscriptionIdentifier"].split(';')
display_identifier = subscription_parts[0] if subscription_parts else None
# Create context for pipeline execution (session_id will be generated by pipeline)
# Get backend session ID if available
backend_session_id = session_ids.get(display_identifier)
# Create context for pipeline execution with backend sessionId
pipeline_context = {
"camera_id": camera_id,
"display_id": display_identifier
"display_id": display_identifier,
"backend_session_id": backend_session_id
}
if backend_session_id:
logger.info(f"🔥 USING BACKEND SESSION_ID: {backend_session_id} for camera {camera_id} (display: {display_identifier})")
logger.debug(f"Pipeline context includes backend session_id: {backend_session_id}")
else:
logger.debug(f"❌ No backend session_id available for display: {display_identifier} (session_ids: {session_ids})")
detection_result = run_pipeline(cropped_frame, model_tree, context=pipeline_context)
process_time = (time.time() - start_time) * 1000
logger.debug(f"Detection for camera {camera_id} completed in {process_time:.2f}ms")
@ -306,13 +316,17 @@ async def detect(websocket: WebSocket):
# Log the raw detection result for debugging
logger.debug(f"Raw detection result for camera {camera_id}:\n{json.dumps(detection_result, indent=2, default=str)}")
# Extract session_id from pipeline result (generated during database record creation)
# Extract session_id from pipeline result (uses backend sessionId)
session_id = None
if detection_result and isinstance(detection_result, dict):
# Check if pipeline generated a session_id (happens when Car+Frontal detected together)
# Check if pipeline used backend session_id for operations
if "session_id" in detection_result:
session_id = detection_result["session_id"]
logger.debug(f"Extracted session_id from pipeline result: {session_id}")
logger.debug(f"Pipeline used session_id: {session_id}")
elif backend_session_id:
# Use backend session_id even if pipeline didn't return it
session_id = backend_session_id
logger.debug(f"Using backend session_id for WebSocket response: {session_id}")
# Process detection result - run_pipeline returns the primary detection directly
if detection_result and isinstance(detection_result, dict) and "class" in detection_result:
@ -376,10 +390,13 @@ async def detect(websocket: WebSocket):
}
}
# Add session ID if available (generated by pipeline when Car+Frontal detected)
# Add session ID if available (from backend or pipeline operations)
if session_id is not None:
detection_data["sessionId"] = session_id
logger.info(f"📤 WEBSOCKET RESPONSE with sessionId: {session_id} for camera {camera_id}")
logger.debug(f"Added session_id to WebSocket response: {session_id}")
else:
logger.debug(f"📤 WebSocket response WITHOUT sessionId for camera {camera_id}")
if highest_confidence_detection.get("class") != "none":
confidence = highest_confidence_detection.get("confidence", 0.0)
@ -1131,14 +1148,41 @@ async def detect(websocket: WebSocket):
display_identifier = payload.get("displayIdentifier")
session_id = payload.get("sessionId")
logger.info(f"🆔 BACKEND SESSIONID RECEIVED: displayId={display_identifier}, sessionId={session_id}")
logger.debug(f"Full setSessionId payload: {payload}")
if display_identifier:
# Store session ID for this display
if session_id is None:
session_ids.pop(display_identifier, None)
logger.info(f"Cleared session ID for display {display_identifier}")
logger.info(f"🚫 BACKEND ENDED SESSION: Cleared session ID for display {display_identifier} - resetting tracking")
# Reset tracking state for all cameras associated with this display
with streams_lock:
for camera_id, stream in streams.items():
if stream["subscriptionIdentifier"].startswith(display_identifier + ";"):
# Import here to avoid circular import
from siwatsystem.pympta import reset_tracking_state
model_id = stream.get("modelId", "unknown")
reset_tracking_state(camera_id, model_id, "backend session ended")
logger.info(f"Reset tracking for camera {camera_id} (display: {display_identifier})")
else:
session_ids[display_identifier] = session_id
logger.info(f"Set session ID {session_id} for display {display_identifier}")
logger.info(f"✅ BACKEND SESSION STARTED: Set session ID {session_id} for display {display_identifier}")
logger.debug(f"Current session_ids dict: {session_ids}")
# Clear waiting state for cameras associated with this display
with streams_lock:
for camera_id, stream in streams.items():
if stream["subscriptionIdentifier"].startswith(display_identifier + ";"):
from siwatsystem.pympta import get_camera_stability_data
model_id = stream.get("modelId", "unknown")
stability_data = get_camera_stability_data(camera_id, model_id)
session_state = stability_data["session_state"]
if session_state.get("waiting_for_backend_session", False):
session_state["waiting_for_backend_session"] = False
session_state["wait_start_time"] = 0.0
logger.info(f"🚀 PIPELINE UNBLOCKED: Backend sessionId {session_id} received - camera {camera_id} can proceed with pipeline")
elif msg_type == "patchSession":
session_id = data.get("sessionId")