Events API

The Events API allows you to work with individual driving events detected in videos. This page documents both the REST API endpoints and the corresponding SDK methods.

Event Structure

Each detected event contains the following information:

{
  "time": 23.5,
  "type": "Traffic Violation",
  "severity": "medium",
  "description": "Running stop sign",
  "dmv_rule": "CVC 22450(a)",
  "metrics": {
    "confidence": 0.92,
    "speed": 15.7,
    "distance": 3.2,
    "acceleration": -2.1
  },
  "ai_analysis": "Vehicle approached stop sign at intersection and continued through without coming to a complete stop...",
  "recommendations": "Always come to a complete stop at stop signs, even if the intersection appears clear...",
  "frame_idx": 705,
  "objects_involved": [
    {
      "type": "vehicle",
      "position": {"x": 450, "y": 320},
      "bbox": {"x1": 420, "y1": 300, "x2": 480, "y2": 340},
      "track_id": 3
    },
    {
      "type": "stop_sign",
      "position": {"x": 520, "y": 280},
      "bbox": {"x1": 510, "y1": 270, "x2": 530, "y2": 290},
      "track_id": 7
    }
  ]
}

Event Types

NomadicML identifies several categories of driving events:

TypeDescriptionExamples
Traffic ViolationPotential violations of traffic lawsRunning stop signs, lane violations, speeding
Safety AlertSafety concernsNear misses, hard braking, unsafe following distance
Drive QualityIssues with driving techniquePoor lane positioning, jerky acceleration
DMV ComplianceRelevant to DMV testingImproper parallel parking, incorrect 3-point turns
Near CollisionClose calls with other objectsNear misses with pedestrians, vehicles, obstacles

Event Severity Levels

Events are categorized into three severity levels:

LevelDescription
lowMinor issues, no safety risk
mediumClear violations, potential safety concerns
highSerious safety issues, major violations

Get Video Events

Retrieve events detected in a specific video.

SDK Method

# Get all events from a video
events = client.video.get_video_events("video_id")

# Filter events by severity
high_severity_events = client.video.get_video_events(
    video_id="video_id",
    severity="high"
)

# Filter events by type
traffic_violations = client.video.get_video_events(
    video_id="video_id",
    event_type="Traffic Violation"
)

Method Parameters

ParameterTypeRequiredDescription
video_idstringYesID of the video
severitystringNoFilter by severity (“low”, “medium”, “high”)
event_typestringNoFilter by event type

Return Value

[
  {
    "time": 23.5,
    "type": "Traffic Violation",
    "severity": "medium",
    "description": "Running stop sign",
    "dmv_rule": "CVC 22450(a)",
    "metrics": {
      "confidence": 0.92,
      "speed": 15.7
    },
    "ai_analysis": "Vehicle approached stop sign at intersection and continued through without coming to a complete stop...",
    "recommendations": "Always come to a complete stop at stop signs, even if the intersection appears clear..."
  },
  // Additional events...
]

HTTP Request

GET /api/video/{video_id}/events

Headers:

X-API-Key: your_api_key

Query Parameters:

  • firebase_collection_name (string, required): Collection name (default: “videos”)
  • severity (string, optional): Filter by severity (“low”, “medium”, “high”)
  • event_type (string, optional): Filter by event type

Working with Events

The SDK provides methods to effectively work with event data:

Parsing Events

The SDK includes a helper method to parse events from the API response:

# Parse events from raw API response
events_list = client.video._parse_api_events(analysis_json)

Event Timeframes

Events include both timestamp and frame index information:

for event in events:
    print(f"Event at time {event['time']}s (frame {event['frame_idx']})")

Event Metrics

Extract detailed metrics from events:

for event in events:
    if 'metrics' in event:
        metrics = event['metrics']
        if 'speed' in metrics:
            print(f"Vehicle speed: {metrics['speed']} mph")
        if 'distance' in metrics:
            print(f"Distance: {metrics['distance']} feet")

Batch Processing Events

Process events across multiple videos:

# Get events from multiple videos
video_ids = ["video_id_1", "video_id_2", "video_id_3"]
all_events = []

for video_id in video_ids:
    try:
        # Get events for this video
        events = client.video.get_video_events(video_id)
        
        # Add video_id to each event for tracking
        for event in events:
            event['video_id'] = video_id
            
        all_events.extend(events)
    except Exception as e:
        print(f"Error getting events for video {video_id}: {e}")

# Sort all events by time
all_events.sort(key=lambda x: x['time'])

# Process events
for event in all_events:
    print(f"Video {event['video_id']}: {event['type']} at {event['time']}s - {event['description']}")

Analyzing Event Patterns

Extract patterns from events:

from collections import Counter

# Count event types
event_types = [event['type'] for event in events]
type_counter = Counter(event_types)
print("Event type distribution:")
for event_type, count in type_counter.most_common():
    print(f"  {event_type}: {count}")

# Count severity levels
severity_levels = [event['severity'] for event in events]
severity_counter = Counter(severity_levels)
print("\nSeverity distribution:")
for severity, count in severity_counter.most_common():
    print(f"  {severity}: {count}")

# Find common descriptions
descriptions = [event['description'] for event in events]
desc_counter = Counter(descriptions)
print("\nMost common events:")
for desc, count in desc_counter.most_common(5):
    print(f"  {desc}: {count}")

Event Sampling

For long videos with many events, you may want to sample events:

import random

# Get a random sample of 5 events
if len(events) > 5:
    sampled_events = random.sample(events, 5)
else:
    sampled_events = events

# Print the sampled events
for event in sampled_events:
    print(f"{event['type']} at {event['time']}s: {event['description']}")

Error Handling

The API returns standard HTTP status codes and the SDK raises specific exceptions:

from nomadicml.exceptions import NomadicMLError, APIError

try:
    events = client.video.get_video_events("video_id")
except APIError as e:
    print(f"API error: {e}")
except NomadicMLError as e:
    print(f"General error: {e}")

Next Steps