Skip to main content

Python SDK for NomadicML's DriveMonitor API

Project description

NomadicML Python SDK

A Python client library for the NomadicML DriveMonitor API, allowing you to upload and analyze driving videos programmatically.

Installation

From PyPI (for users)

pip install nomadicml

For Development (from source)

To install the package in development mode, where changes to the code will be immediately reflected without reinstallation:

# Clone the repository
git clone https://github.com/nomadic-ml/drivemonitor.git
cd sdk

# For development: Install in editable mode
pip install -e .

With this installation, any changes you make to the code will be immediately available when you import the package.

Quick Start

from nomadicml import NomadicML

# Initialize the client with your API key
client = NomadicML(api_key="your_api_key")

# Upload a video and analyze it in one step
result = client.video.upload_and_analyze("path/to/your/video.mp4")

# Print the detected events
for event in result["events"]:
    print(f"Event: {event['type']} at {event['time']}s - {event['description']}")
#For a batch upload

videos_list = [.....]#list of video paths
batch_results = client.video.upload_and_analyze_videos(videos_list, wait_for_completion=False)

    
video_ids = [
    res.get("video_id")
    for res in batch_results
    if res                                         # safety for None
    ]

    
full_results = client.video.wait_for_analyses(video_ids)

Authentication

You need an API key to use the NomadicML API. You can get one by:

  1. Log in to your DriveMonitor account
  2. Go to Profile > API Key
  3. Generate a new API key

Then use this key when initializing the client:

client = NomadicML(api_key="your_api_key")

Video Upload and Analysis

Upload a video

# Upload a local video file
result = client.video.upload_video(
    source="file",
    file_path="path/to/video.mp4"
)

# Or upload from YouTube
result = client.video.upload_video(
    source="youtube",
    youtube_url="https://www.youtube.com/watch?v=VIDEO_ID"
)

# Get the video ID from the response
video_id = result["video_id"]

Analyze a video

# Start analysis
client.video.analyze_video(video_id)

# Wait for analysis to complete
status = client.video.wait_for_analysis(video_id)

# Get analysis results
analysis = client.video.get_video_analysis(video_id)

# Get detected events
events = client.video.get_video_events(video_id)

Upload and analyze in one step

# Upload and analyze a video, waiting for results
analysis = client.video.upload_and_analyze("path/to/video.mp4")

# Or just start the process without waiting
result = client.video.upload_and_analyze("path/to/video.mp4", wait_for_completion=False)

Advanced Usage

Filter events by severity or type

# Get only high severity events
high_severity_events = client.video.get_video_events(
    video_id=video_id,
    severity="high"
)

# Get only traffic violation events
traffic_violations = client.video.get_video_events(
    video_id=video_id,
    event_type="Traffic Violation"
)

Custom timeout and polling interval

# Wait for analysis with a custom timeout and polling interval
client.video.wait_for_analysis(
    video_id=video_id,
    timeout=1200,  # 20 minutes
    poll_interval=10  # Check every 10 seconds
)

Batch analyses across many videos

When you provide a list of video IDs to client.video.analyze(...), the SDK now creates a backend batch automatically (for both Asking Agent and Edge Agent pipelines) and keeps polling the /batch/{batch_id}/status endpoint until the orchestrator finishes. The return value is a dictionary with two keys:

  • batch_metadata — contains the batch_id, a fully-qualified batch_viewer_url pointing at the Batch Results Viewer, and a batch_type flag ("ask" or "agent").
  • results — the list of per-video analysis dictionaries (exactly the same schema you would get from calling analyze() on a single video).

BEFORE DEPLOYIN RUN THIS: Running SDK integration tests locally

The integration suite is tagged with calls_api and exercises the live backend endpoints. Make sure you have a valid API key and a backend domain reachable from your environment, then run:

cd sdk
export NOMADICML_API_KEY=YOUR_API_KEY
export VITE_BACKEND_DOMAIN=http://127.0.0.1:8099
python -u -m pytest -m calls_api -vvs -rPfE --durations=0 --capture=no tests/test_integration.py

The command disables pytest's output capture so you can follow streaming logs while the long-running tests execute.

from nomadicml.video import AnalysisType, CustomCategory

batch = client.video.analyze(
    ["video_1", "video_2", "video_3"],
    analysis_type=AnalysisType.ASK,
    custom_event="Did the driver stop before the crosswalk?",
    custom_category=CustomCategory.DRIVING,
)

print(batch["batch_metadata"])
for item in batch["results"]:
    print(item["video_id"], item["analysis_id"], len(item.get("events", [])))

Custom API endpoint

If you're using a custom deployment of the DriveMonitor backend:

# Connect to a local or custom deployment
client = NomadicML(
    api_key="your_api_key",
    base_url="http://localhost:8099"
)

Search across videos

Run a semantic search on several of your videos at once:

results = client.video.search_videos(
    "red pickup truck overtaking",
    ["vid123", "vid456"]
)
for match in results["matches"]:
    print(match["videoId"], match["eventIndex"], match["similarity"])

Error Handling

The SDK provides specific exceptions for different error types:

from nomadicml import NomadicMLError, AuthenticationError, VideoUploadError

try:
    client.video.upload_and_analyze("path/to/video.mp4")
except AuthenticationError:
    print("API key is invalid or expired")
except VideoUploadError as e:
    print(f"Failed to upload video: {e}")
except NomadicMLError as e:
    print(f"An error occurred: {e}")

Development

Setup

Clone the repository and install development dependencies:

git clone https://github.com/nomadicml/nomadicml-python.git
cd nomadicml-python
pip install -e ".[dev]"

Running tests

pytest

License

MIT License. See LICENSE file for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

nomadicml-0.1.21.tar.gz (44.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

nomadicml-0.1.21-py3-none-any.whl (43.1 kB view details)

Uploaded Python 3

File details

Details for the file nomadicml-0.1.21.tar.gz.

File metadata

  • Download URL: nomadicml-0.1.21.tar.gz
  • Upload date:
  • Size: 44.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.7

File hashes

Hashes for nomadicml-0.1.21.tar.gz
Algorithm Hash digest
SHA256 72499ea9e023c0412e6a7f6e620b74325d1b87154d60be2faf8a60097fb90c67
MD5 37a070804aeb37121910fa1e6c83cd31
BLAKE2b-256 04ce3033feb27326b53b4424dcb46a8e83f4d38688e9d5421e8110c88cf3da56

See more details on using hashes here.

File details

Details for the file nomadicml-0.1.21-py3-none-any.whl.

File metadata

  • Download URL: nomadicml-0.1.21-py3-none-any.whl
  • Upload date:
  • Size: 43.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.7

File hashes

Hashes for nomadicml-0.1.21-py3-none-any.whl
Algorithm Hash digest
SHA256 88e9e17723dc11f3283e6a3513d73fc4693adae2a8c0ac52ba7ca90c5e613ef2
MD5 16dc73e1bacf1072f5c7fbcbd3b0a805
BLAKE2b-256 33fee1c2fb22b7287895cdf6fe664a4b668229383d486d5628468d4ffbffac0a

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page