Generated banner for Amc Run Rtsp Calibration
Generated logo for Amc Run Rtsp Calibration

Amc Run Rtsp Calibration

NVIDIAOfficialCreated by Shubham AgrawalDistributed by NVIDIA

  • Skill
  • Workflow
  • Software development
  • Apache-2.0
  • Medium risk
  • Has scripts

From the author

Calibrate a new dataset from live RTSP camera streams via the AutoMagicCalib REST API. Use when the user provides RTSP URLs or asks to calibrate live cameras; VIOS records clips, AMC ingests them, then runs calibration.
— the description by Shubham Agrawal

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a structured workflow to calibrate camera systems using live RTSP streams. It integrates with the VIOS service to record video clips, which are then ingested into the AutoMagicCalib (AMC) microservice for processing. The workflow covers project creation, stream capture, data ingestion, configuration management, and the execution of the calibration pipeline. It includes robust error handling, polling mechanisms for long-running tasks, and support for optional VGGT refinement.

What it does

  • Connects to VIOS to record live RTSP camera streams for a specified duration.
  • Ingests recorded clips into an AutoMagicCalib project.
  • Supports uploading custom calibration settings, alignment data, and layout files.
  • Executes the calibration pipeline using either resnet or transformer detectors.
  • Provides polling mechanisms to track capture, ingestion, and calibration progress.
  • Offers optional post-calibration VGGT refinement.

When to use it

  • When you need to calibrate camera systems using live RTSP network streams.
  • When you have a running AMC microservice and a reachable VIOS instance.
  • When you want to automate the end-to-end process from stream capture to calibration results.
  • When you have specific calibration assets (settings, alignment, layout) to apply to a new scene.

Advantages

  • Automates the transition from live stream capture to calibrated output.
  • Provides a consistent, repeatable workflow for multi-camera calibration.
  • Integrates directly with existing AMC and VIOS infrastructure.
  • Supports flexible configuration through both API uploads and UI-based tuning.

Usage examples

“Calibrate my live cameras using RTSP URLs rtsp://cam0/stream and rtsp://cam1/stream.”
The agent will initiate the project creation, trigger the VIOS recording session, ingest the resulting clips, and guide you through the calibration process.
“Run AMC calibration on my RTSP streams for 180 seconds.”
The agent will configure the capture session with the specified duration and proceed with the automated ingestion and calibration workflow.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/nvidia/amc-run-rtsp-calibration/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip amc-run-rtsp-calibration.zip -d .agents/skills

Documentation by Shubham Agrawal

Skill: Calibrate from RTSP Streams

When to Use This Skill

Activate this skill when the user wants to calibrate from live RTSP camera streams. Typical prompts:

  • "calibrate RTSP streams" / "calibrate from live cameras"

  • "run AMC on RTSP"

  • The user provides one or more rtsp://... URLs

VIOS records fixed-duration clips from each stream, the AMC microservice ingests those clips into a project, then the workflow follows the same verification, calibration, polling, and results path as pre-recorded MP4 calibration.

Do not use this skill for local MP4 files already on disk; route those requests to skills/amc-run-video-calibration/SKILL.md. Do not use it for the bundled sample dataset; route that to skills/amc-run-sample-calibration/SKILL.md.

Never reuse files from the bundled sample dataset, extracted sample zip, assets/, or previous projects for RTSP calibration unless the user explicitly provides those paths for this RTSP scene. Similar camera names, stream counts, or cam_00/cam_01 ordering are not evidence that sample alignment, layout, GT, or detector settings apply.

Prerequisites

  • [ ] AMC microservice and UI running (follow skills/amc-setup-calibration-stack/SKILL.md if needed).

  • [ ] VIOS is running and reachable from the AMC microservice.

  • [ ] VIOS_BASE_URL is configured in the AMC microservice environment before capture starts.

  • [ ] RTSP URLs are reachable from the VIOS host.

  • [ ] Camera streams have enough moving people/objects for calibration; record at least 2-3 minutes when possible.

  • [ ] Python 3 with requests installed when using the bundled script.

Data Privacy

RTSP URLs may contain usernames, passwords, hostnames, or network topology. Do not print full RTSP URLs if credentials are embedded. This skill does not handle bearer credentials; if the VIOS deployment requires authentication, stop and hand the user to a manual admin-managed workflow instead of collecting or relaying secrets in chat, scripts, or logs.

What to Ask the User

Required
  1. RTSP URLs, one per camera.

  2. Camera names, one per stream. Use cam_00, cam_01, ... if the user does not provide names.

  3. Recording duration in seconds. Minimum is 60; prefer 120-180 or more when the scene has sparse motion.

  4. Microservice URL, for example http://<HOST_IP>:8000 or http://<HOST_IP>:8000/v1.

  5. Project name.

  6. Calibration asset source for this RTSP scene:

    • a local directory to scan, such as /data/my_rtsp_calib/;

    • explicit paths to settings, alignment, layout, and optional GT files; or

    • confirmation that the user will upload/tune settings and alignment in the AMC UI.

If the user does not provide a local asset source, stop and ask whether they want to provide a path or use UI upload. Give the UI link as http://<HOST_IP>:<AUTO_MAGIC_CALIB_UI_PORT>; the default UI port is 5000.

Auto-Detected or Asked

RTSP clips are recorded by VIOS, so there is no local videos directory to anchor file discovery. Only scan a directory the user explicitly provided for this RTSP scene. If the user provides a settings file path, use that file's directory as the scan directory. If the user provides a calibration asset directory, scan only that directory. Otherwise ask this question before planning uploads or calibration:

Do you have a local calibration asset directory or settings file for these RTSP streams, or should you upload/tune settings and alignment in the AMC UI at http://<HOST_IP>:<AUTO_MAGIC_CALIB_UI_PORT>?

FileCandidate filenamesUI fallback
Calibration settingsExplicit user path, or settings.json, config.json, or calibration_config.json in the user-provided asset directoryUI Step 3: Parameters
Alignment JSONExplicit user path, or alignment_data.json in the user-provided asset directory/settings directoryUI Step 4: Alignment
Layout PNGExplicit user path, or layout.png in the user-provided asset directory/settings directoryUI Step 4: Alignment
Ground truth zipOptional explicit user path, or GT.zip/gt.zip in the user-provided asset directoryOmit metrics

Posting the settings file replaces UI Step 3 and may pin detector or detector_type. If it pins resnet or transformer, pass that same detector to /calibrate. If no settings file pins a detector, ask the user which detector to use; do not silently default to resnet.

Optional
  1. sensor_id per stream if the cameras are already registered in VIOS. Leave unset for auto-registration.

  2. Ground truth zip (GT.zip) for evaluation metrics.

  3. Focal lengths, one per camera.

  4. Whether to run VGGT refinement after AMC completes, only when the project reports vggt_state == "READY".

Instructions

The bundled script in scripts/run_rtsp_calibration.py implements this sequence end to end. Use the prose below for decisions, UI fallback, and troubleshooting.

Step 0 - Verify AMC and VIOS

Confirm the AMC microservice is reachable:

curl -sf http://<HOST_IP>:<MS_PORT>/v1/ready

Confirm VIOS is reachable before starting capture. Probe in this order and stop at the first working URL:

: "${REPO_ROOT:?set REPO_ROOT to the auto-magic-calib checkout. Run amc-setup-calibration-stack Step 0b first.}"
grep -q "AutoMagicCalib" "$REPO_ROOT/README.md" 2>/dev/null && grep -q "auto-magic-calib-ms" "$REPO_ROOT/compose/ms/compose.yml" 2>/dev/null || { echo "ERROR: REPO_ROOT is not an auto-magic-calib checkout: $REPO_ROOT" >&2; exit 1; }
VIOS_BASE_URL=""

# Default local VIOS port.
if curl -sf http://localhost:30888/vst/api/v1/sensor/list >/dev/null 2>&1; then
  VIOS_BASE_URL="http://localhost:30888"
  echo "VIOS detected at $VIOS_BASE_URL"
fi

# Running AMC microservice container environment.
if [ -z "$VIOS_BASE_URL" ]; then
  VIOS_BASE_URL=$(docker exec auto-magic-calib-ms-1 printenv VIOS_BASE_URL 2>/dev/null)
fi

if [ -n "$VIOS_BASE_URL" ]; then
  curl -sf "${VIOS_BASE_URL}/vst/api/v1/sensor/list" >/dev/null \
    && echo "VIOS up at $VIOS_BASE_URL" \
    || { echo "VIOS_BASE_URL=$VIOS_BASE_URL is set but not responding"; VIOS_BASE_URL=""; }
fi

[ -n "$VIOS_BASE_URL" ] || {
  echo "VIOS is not reachable. Export VIOS_BASE_URL=http://<VIOS_HOST>:30888 and relaunch the AMC microservice." >&2
  exit 1
}

If VIOS is not reachable, ask the user to deploy VIOS and provide the base URL. Do not start RTSP capture until ${VIOS_BASE_URL}/vst/api/v1/sensor/list returns 200.

If VIOS is reachable but the AMC microservice is missing VIOS_BASE_URL, do not edit checked-in compose files. Export the variable and relaunch the microservice with a temporary compose override:

cd "$REPO_ROOT/compose"
export VIOS_BASE_URL="http://<VIOS_HOST>:30888"
OVERRIDE_FILE="${TMPDIR:-/tmp}/amc-vios.override.yml"
cat > "$OVERRIDE_FILE" <<'YAML'
services:
  auto-magic-calib-ms:
    environment:
      - VIOS_BASE_URL=${VIOS_BASE_URL}
YAML

docker compose -f compose.yml -f "$OVERRIDE_FILE" up -d auto-magic-calib-ms
docker exec auto-magic-calib-ms-1 printenv VIOS_BASE_URL

A host-shell export alone is not enough after the container is already running; the microservice process must be restarted with VIOS_BASE_URL in its environment.

Step 1 - Create Project

POST /v1/create_project with form field project_name. Save the returned project_id.

Step 2 - Start RTSP Capture
POST /v1/rtsp/capture/<project_id>
Content-Type: application/json

{
  "streams": [
    {"rtsp_url": "rtsp://...", "camera_name": "cam_00", "sensor_id": null},
    {"rtsp_url": "rtsp://...", "camera_name": "cam_01", "sensor_id": null}
  ],
  "duration_seconds": 180,
  "ssl_verify": true
}

The response can nest session fields under session:

{"code": 0, "message": "...", "session": {"session_id": "...", "status": "STARTING"}}

Save session.session_id.

Step 3 - Poll Capture, Then Ingest

Poll every 10 seconds:

GET /v1/rtsp/capture/<project_id>/<session_id>

Session lifecycle:

STARTING -> RECORDING -> COMPLETED -> INGESTING -> INGESTED
                       -> ERROR
RECORDING -> CANCELLED

When capture reaches COMPLETED, ingest the recorded clips into the AMC project:

POST /v1/rtsp/capture/<project_id>/<session_id>/ingest

After ingest succeeds, the project has video files attached and the rest of the workflow matches the MP4 upload path.

Need to stop early: POST /v1/rtsp/capture/<project_id>/<session_id>/stop. A partial clip can still be ingested if VIOS produced one.

Other session endpoints:

  • GET /v1/rtsp/sessions/<project_id> - list sessions for a project.

Step 4 - Upload Settings, Alignment, Layout, and Optional Files

Resolve local files using the anchor-file pattern above. Upload resolved files:

FileEndpointNotes
Calibration settingsPOST /v1/config/<project_id>JSON body posted as-is; replaces UI Step 3
Alignment JSONPOST /v1/upload_alignment/<project_id>Multipart alignment_file
Layout PNGPOST /v1/upload_layout/<project_id>Multipart layout_file
Ground truth zipPOST /v1/upload_gt_file/<project_id>Optional
Focal lengthsPOST /v1/upload_focal_length/<project_id>Optional repeated focal_length values

Use only files from explicit user-provided paths or a user-provided calibration asset directory. Do not extract or scan sample data to find fallback settings, alignment, layout, or GT.

If settings are missing, direct the user to UI Step 3: Parameters at http://<HOST_IP>:<AUTO_MAGIC_CALIB_UI_PORT>, then ask which detector to use (resnet or transformer) before calibration. If alignment or layout is missing, direct the user to UI Step 4: Alignment for this project. For RTSP projects, videos are already ingested; do not re-upload videos in the UI fallback.

Before continuing after UI Step 4, verify:

PROJECT_ID=<project_id>
: "${REPO_ROOT:?set REPO_ROOT to the auto-magic-calib checkout. Run amc-setup-calibration-stack Step 0b first.}"
grep -q "AutoMagicCalib" "$REPO_ROOT/README.md" 2>/dev/null && grep -q "auto-magic-calib-ms" "$REPO_ROOT/compose/ms/compose.yml" 2>/dev/null || { echo "ERROR: REPO_ROOT is not an auto-magic-calib checkout: $REPO_ROOT" >&2; exit 1; }
HOST_PROJECTS="${PROJECTS_DIR:-$(cd "$REPO_ROOT" && realpath projects)}"
ls "$HOST_PROJECTS/project_${PROJECT_ID}/manual_adjustment/"
# Expected: alignment_data.json, layout.png

If the AMC stack stores project outputs outside the default projects/ directory, set PROJECTS_DIR explicitly before running the check above. Do not read compose/.env for project paths during this workflow.

Step 5 - Verify, Calibrate, Poll, and Fetch Results

Verify:

POST /v1/verify_project/<project_id>

The project must return project_state == "READY".

Confirm the plan before calibrating. Summarize:

  • Stream count and recording duration.

  • Detector: resnet or transformer.

  • Settings source: explicit uploaded settings file, user-provided asset directory, or UI Step 3.

  • Alignment/layout source: explicit uploaded files, user-provided asset directory, or UI manual adjustment.

  • Optional GT and focal-length overrides.

Start calibration:

POST /v1/calibrate/<project_id>
Content-Type: application/json

{"detector_type": "<resnet-or-transformer>"}

Poll:

GET /v1/get_project_info/<project_id>

Stop on COMPLETED or ERROR. On error, fetch GET /v1/amc/calibrate/<project_id>/log.

Fetch results:

GET /v1/result/<project_id>/evaluation_statistics

Only expect evaluation statistics when GT was uploaded.

Step 6 - Optional VGGT Refinement

After AMC calibration completes, read project_info.vggt_state from GET /v1/get_project_info/<project_id>.

  • If vggt_state == "READY", ask whether to run VGGT refinement.

  • If confirmed, call POST /v1/vggt/calibrate/<project_id>, poll vggt_state, then fetch GET /v1/vggt_results/<project_id>/evaluation_statistics.

  • If VGGT is not ready, skip it and explain that AMC calibration is complete.

Complete Python Script

Use the bundled script from the amc-run-rtsp-calibration skill package, not from the auto-magic-calib repo root. If the user points the agent at this skill folder directly instead of installing it, set AMC_RTSP_SKILL_DIR to the directory containing this SKILL.md, or run the command from that directory.

Common environment variables:

export BASE_URL=http://<HOST_IP>:8000
export PROJECT_NAME=rtsp_calibration_run
export RTSP_URLS='rtsp://user:pass@cam0/stream,rtsp://user:pass@cam1/stream'
export CAMERA_NAMES='cam_00,cam_01'
export DURATION_SECONDS=180
export VIOS_BASE_URL=http://<VIOS_HOST>:30888
export CALIB_ASSET_DIR=/path/to/rtsp-calibration-assets
# Or provide explicit CONFIG_FILE, ALIGNMENT_JSON, LAYOUT_PNG, and optional GT_ZIP.
export DETECTOR_TYPE=transformer  # Required when settings do not set detector/detector_type.
export AMC_UI_URL=http://<HOST_IP>:5000
export RUN_VGGT=false

# Optional but recommended: REPO_ROOT points to the auto-magic-calib checkout.
# PROJECTS_DIR can be set explicitly when project outputs live elsewhere.
if [ -z "${DEEPSTREAM_REPO_ROOT:-}" ] && [ -n "${REPO_ROOT:-}" ] && [ -d "$REPO_ROOT/../../skills/amc-run-rtsp-calibration" ]; then
  DEEPSTREAM_REPO_ROOT="$(cd "$REPO_ROOT/../.." && pwd)"
fi

SCRIPT_PATH=""
for candidate in \
  "${AMC_RTSP_SKILL_DIR:+$AMC_RTSP_SKILL_DIR/scripts/run_rtsp_calibration.py}" \
  "$PWD/scripts/run_rtsp_calibration.py" \
  "${DEEPSTREAM_REPO_ROOT:+$DEEPSTREAM_REPO_ROOT/skills/amc-run-rtsp-calibration/scripts/run_rtsp_calibration.py}" \
  "$PWD/skills/amc-run-rtsp-calibration/scripts/run_rtsp_calibration.py" \
  "$HOME/.claude/skills/amc-run-rtsp-calibration/scripts/run_rtsp_calibration.py" \
  "$HOME/.codex/skills/amc-run-rtsp-calibration/scripts/run_rtsp_calibration.py" \
  "$HOME/.cursor/skills/amc-run-rtsp-calibration/scripts/run_rtsp_calibration.py"; do
  if [ -f "$candidate" ]; then
    SCRIPT_PATH="$candidate"
    break
  fi
done

[ -n "$SCRIPT_PATH" ] || {
  echo "ERROR: could not find amc-run-rtsp-calibration/scripts/run_rtsp_calibration.py" >&2
  echo "Set AMC_RTSP_SKILL_DIR to the amc-run-rtsp-calibration skill directory, or run this block from that directory." >&2
  exit 1
}

python3 "$SCRIPT_PATH"

Alternative stream input:

export STREAMS_JSON='[
  {"rtsp_url":"rtsp://cam0/stream","camera_name":"cam_00","sensor_id":null},
  {"rtsp_url":"rtsp://cam1/stream","camera_name":"cam_01","sensor_id":null}
]'

Optional env vars are CALIB_ASSET_DIR, CONFIG_FILE, ALIGNMENT_JSON, LAYOUT_PNG, GT_ZIP, FOCAL_LENGTHS, DETECTOR_TYPE, AMC_UI_URL, SSL_VERIFY, RUN_VGGT, REPO_ROOT, and PROJECTS_DIR. SSL_VERIFY defaults to true; only set SSL_VERIFY=false for loopback testing. If the VIOS deployment requires bearer authentication, stop and use a manual admin-managed capture flow instead of routing credentials through this skill.

Success Criteria

  • VIOS health probe returns 200.

  • Capture session reaches COMPLETED.

  • Ingest returns success and project info shows the expected video files.

  • verify_project returns READY.

  • AMC calibration reaches project_state == "COMPLETED".

  • If GT was uploaded, evaluation statistics are returned.

  • No RTSP credentials, bearer tokens, NGC keys, or HuggingFace tokens are printed or persisted by the agent.

Key Output Files

Results persist on the AMC server under:

projects/project_<project_id>/
|-- manual_adjustment/
|   |-- alignment_data.json
|   `-- layout.png
|-- output/
|   |-- single_view_results/cam_XX/
|   |   |-- camInfo_hyper_XX.yaml
|   |   `-- trajDump_Stream_0_3d.txt
|   `-- multi_view_results/BA_output/results_ba/
|       |-- initial/camInfo_XX.yaml
|       `-- refined/camInfo_XX.yaml
`-- calibration.log

Troubleshooting

IssueFix
VIOS /vst/api/v1/sensor/list returns connection refusedVIOS is not running or not reachable from this host. Ask the user to deploy VIOS or provide the reachable base URL.
Capture endpoint returns 503 or "VIOS not configured"Export VIOS_BASE_URL, relaunch the microservice with the temporary compose override from Step 0, then retry capture.
Session stuck in STARTINGVIOS accepted the request but sensors may not be online. Check ${VIOS_BASE_URL}/vst/api/v1/sensor/list and wait 20-30 seconds after sensor restarts.
Session stuck in RECORDING past duration_secondsCall POST /v1/rtsp/capture/<project_id>/<session_id>/stop, then ingest the partial clip if available.
Ingest fails with "No clip available"The recording window may not overlap the VIOS timeline. Wait for sensors to become online, then start a new capture.
400 "empty streams"Pass at least one stream object with rtsp_url and camera_name.
400 "duration too short"Use duration_seconds >= 60.
404 on /v1/rtsp/capture/<project_id>Create the project first with /v1/create_project.
verify_project is not READY after ingestCheck project info and confirm expected videos, alignment, and layout are attached.
Calibration reaches ERRORFetch GET /v1/amc/calibrate/<project_id>/log; common causes are insufficient tracklets, static scenes, or incorrect alignment.
  • skills/amc-setup-calibration-stack/SKILL.md - start AMC microservice and UI first.

  • skills/amc-run-video-calibration/SKILL.md - calibrate from local pre-recorded MP4 files.

  • skills/amc-run-sample-calibration/SKILL.md - verify the stack with the bundled sample dataset.

<!-- signing marker -->

Files

scripts/run_rtsp_calibration.py

#!/usr/bin/env python3
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Run AMC calibration from live RTSP streams recorded through VIOS."""
import ipaddress
import json
import os
import sys
import time
from pathlib import Path
from urllib.parse import urlsplit, urlunsplit

import requests


def _env_path(name):
    value = os.environ.get(name)
    return Path(value).expanduser() if value else None


def _env_bool(name, default=False):
    value = os.environ.get(name)
    if value is None:
        return default
    return value.strip().lower() in ("1", "true", "yes", "y", "on")


def _env_float_list(name):
    value = os.environ.get(name)
    if not value:
        return None
    return [float(x.strip()) for x in value.split(",") if x.strip()]


def _csv(name):
    value = os.environ.get(name, "")
    return [x.strip() for x in value.split(",") if x.strip()]


def _normalize_base_url(value):
    base = value.rstrip("/")
    return base if base.endswith("/v1") else f"{base}/v1"


def _url_scheme(value):
    try:
        return urlsplit(value).scheme.lower()
    except (AttributeError, TypeError, ValueError):
        return ""


def _url_host(value):
    try:
        return urlsplit(value).hostname or ""
    except (AttributeError, TypeError, ValueError):
        return ""


def _is_loopback_url(value):
    host = _url_host(value)
    if host == "localhost":
        return True
    try:
        return ipaddress.ip_address(host).is_loopback
    except ValueError:
        return False


def _redact_rtsp_url(url):
    try:
        parts = urlsplit(url)
        if "@" not in parts.netloc:
            return url
        host = parts.hostname or ""
        port = f":{parts.port}" if parts.port else ""
        return urlunsplit((parts.scheme, f"<redacted>@{host}{port}", parts.path, parts.query, parts.fragment))
    except (AttributeError, TypeError, ValueError):
        return "<redacted-rtsp-url>"


def _parse_streams():
    streams_json = os.environ.get("STREAMS_JSON")
    if streams_json:
        streams = json.loads(streams_json)
        if not isinstance(streams, list):
            raise SystemExit("STREAMS_JSON must be a JSON list of stream objects.")
    else:
        urls = _csv("RTSP_URLS")
        if not urls:
            raise SystemExit("Set RTSP_URLS or STREAMS_JSON before running.")
        names = _csv("CAMERA_NAMES") or [f"cam_{i:02d}" for i in range(len(urls))]
        sensor_ids = _csv("SENSOR_IDS")
        if len(names) != len(urls):
            raise SystemExit("CAMERA_NAMES must have the same count as RTSP_URLS.")
        if sensor_ids and len(sensor_ids) != len(urls):
            raise SystemExit("SENSOR_IDS must have the same count as RTSP_URLS when set.")
        streams = []
        for idx, url in enumerate(urls):
            sensor_id = sensor_ids[idx] if sensor_ids else None
            streams.append({"rtsp_url": url, "camera_name": names[idx], "sensor_id": sensor_id or None})

    normalized = []
    for idx, stream in enumerate(streams):
        if not isinstance(stream, dict):
            raise SystemExit(f"Stream entry {idx} must be an object.")
        rtsp_url = stream.get("rtsp_url")
        camera_name = stream.get("camera_name") or f"cam_{idx:02d}"
        if not rtsp_url or not str(rtsp_url).startswith("rtsp://"):
            raise SystemExit(f"Stream entry {idx} must include an rtsp:// URL.")
        normalized.append({
            "rtsp_url": rtsp_url,
            "camera_name": camera_name,
            "sensor_id": stream.get("sensor_id"),
        })
    return normalized


def _resolve_local(override, candidate_names, scan_dir, label):
    if override and Path(override).exists():
        return Path(override)
    if scan_dir is None:
        return None
    hits = [scan_dir / name for name in candidate_names if (scan_dir / name).exists()]
    if len(hits) == 1:
        print(f"    auto-detected {label}: {hits[0]}")
        return hits[0]
    if len(hits) > 1:
        print(f"    multiple {label} candidates in {scan_dir}: {hits}; use an explicit path or UI fallback")
    return None


def _json_response(response, label):
    response.raise_for_status()
    payload = response.json()
    code = payload.get("code")
    if code not in (None, 0, "0"):
        raise RuntimeError(f"{label} returned code={code}: {payload}")
    return payload


def _session_from_payload(payload):
    session = payload.get("session") or payload
    if "session_id" not in session:
        raise RuntimeError(f"RTSP capture response did not include session_id: {payload}")
    return session


def _check_amc_ready(session, base_url):
    try:
        response = session.get(f"{base_url}/ready", timeout=10)
        response.raise_for_status()
    except requests.RequestException as exc:
        raise SystemExit(f"AMC microservice is not reachable at {base_url}/ready: {exc}") from exc


def _check_vios_ready(base_url):
    response = requests.get(f"{base_url.rstrip('/')}/vst/api/v1/sensor/list", timeout=10)
    response.raise_for_status()


def _default_ui_url(base_url):
    explicit = os.environ.get("AMC_UI_URL") or os.environ.get("UI_URL")
    if explicit:
        return explicit.rstrip("/")
    try:
        parts = urlsplit(base_url.rstrip("/"))
        host = parts.hostname or "<HOST_IP>"
        return f"{parts.scheme or 'http'}://{host}:5000"
    except (AttributeError, TypeError, ValueError):
        return "http://<HOST_IP>:5000"


def _detector_from_config(path):
    if not path or not path.exists():
        return None
    try:
        cfg = json.loads(path.read_text())
    except (OSError, UnicodeDecodeError, json.JSONDecodeError):
        return None
    det = cfg.get("detector") or cfg.get("detector_type")
    return det if det in ("resnet", "transformer") else None


def _require_detector(current):
    if current in ("resnet", "transformer"):
        return current
    if not IS_INTERACTIVE:
        raise RuntimeError(
            "Detector type is required before calibration. Set DETECTOR_TYPE=resnet or "
            "DETECTOR_TYPE=transformer, or provide CONFIG_FILE with detector/detector_type."
        )
    while True:
        answer = input("    Detector type for calibration [resnet/transformer]: ").strip().lower()
        if answer in ("resnet", "transformer"):
            return answer
        print("    Enter 'resnet' or 'transformer'.")


# Required env vars: RTSP_URLS or STREAMS_JSON. BASE_URL and PROJECT_NAME have
# defaults for easy editing but should normally be set by the caller.
BASE_URL = _normalize_base_url(os.environ.get("BASE_URL", "http://<HOST_IP>:<MS_PORT>/v1"))
PROJECT_NAME = os.environ.get("PROJECT_NAME", "rtsp_calibration_run")
STREAMS = _parse_streams()
DURATION_SECONDS = int(os.environ.get("DURATION_SECONDS", "180"))
if DURATION_SECONDS < 60:
    raise SystemExit("DURATION_SECONDS must be at least 60.")

CONFIG_FILE = _env_path("CONFIG_FILE")
CALIB_ASSET_DIR = _env_path("CALIB_ASSET_DIR")
ALIGNMENT_JSON = _env_path("ALIGNMENT_JSON")
LAYOUT_PNG = _env_path("LAYOUT_PNG")
GT_ZIP = _env_path("GT_ZIP")
FOCAL_LENGTHS = _env_float_list("FOCAL_LENGTHS")
DETECTOR_TYPE = os.environ.get("DETECTOR_TYPE")
RUN_VGGT = _env_bool("RUN_VGGT", False)
SSL_VERIFY = _env_bool("SSL_VERIFY", True)
VIOS_BASE_URL = os.environ.get("VIOS_BASE_URL", "").rstrip("/")
REQUIRE_VIOS_HEALTH = _env_bool("REQUIRE_VIOS_HEALTH", True)

REPO_ROOT = Path(os.environ.get("REPO_ROOT", Path.cwd()))
PROJECTS_DIR = Path(os.environ.get("PROJECTS_DIR", REPO_ROOT / "projects"))
IS_INTERACTIVE = sys.stdin.isatty()
AMC_UI_URL = _default_ui_url(BASE_URL)

for label, path in (
    ("CONFIG_FILE", CONFIG_FILE),
    ("CALIB_ASSET_DIR", CALIB_ASSET_DIR),
    ("ALIGNMENT_JSON", ALIGNMENT_JSON),
    ("LAYOUT_PNG", LAYOUT_PNG),
    ("GT_ZIP", GT_ZIP),
):
    if path and not path.exists():
        raise SystemExit(f"{label} set but path not found: {path}")
if CALIB_ASSET_DIR and not CALIB_ASSET_DIR.is_dir():
    raise SystemExit(f"CALIB_ASSET_DIR must be a directory: {CALIB_ASSET_DIR}")
if not SSL_VERIFY and not _is_loopback_url(BASE_URL):
    raise SystemExit(
        "SSL_VERIFY=false is only allowed for loopback AMC endpoints. Use HTTPS with certificate "
        "verification enabled for remote services."
    )

CONFIG_FILE = _resolve_local(
    CONFIG_FILE,
    ["settings.json", "config.json", "calibration_config.json"],
    CALIB_ASSET_DIR,
    "calibration settings",
)
_scan_dir = CALIB_ASSET_DIR or (CONFIG_FILE.parent if CONFIG_FILE else None)
ALIGNMENT_JSON = _resolve_local(ALIGNMENT_JSON, ["alignment_data.json"], _scan_dir, "alignment")
LAYOUT_PNG = _resolve_local(LAYOUT_PNG, ["layout.png"], _scan_dir, "layout")
GT_ZIP = _resolve_local(GT_ZIP, ["GT.zip", "gt.zip"], _scan_dir, "ground truth")

config_detector = _detector_from_config(CONFIG_FILE)
if config_detector:
    DETECTOR_TYPE = config_detector

local_asset_source = any([CONFIG_FILE, ALIGNMENT_JSON, LAYOUT_PNG])
if not local_asset_source:
    print(
        "[0] No local calibration asset source was provided for these RTSP streams.\n"
        "    Provide CALIB_ASSET_DIR or explicit CONFIG_FILE/ALIGNMENT_JSON/LAYOUT_PNG,\n"
        f"    or use AMC UI upload/tuning at {AMC_UI_URL}.\n"
        "    Do not reuse sample dataset assets unless they are explicitly intended for this RTSP scene."
    )
    if not IS_INTERACTIVE:
        raise SystemExit(
            "No local calibration asset source was provided. Run interactively for UI upload, "
            "or set CALIB_ASSET_DIR / CONFIG_FILE / ALIGNMENT_JSON / LAYOUT_PNG."
        )
    answer = input("    Continue and complete settings/alignment in the AMC UI after capture? [y/N]: ").strip().lower()
    if answer not in ("y", "yes"):
        raise SystemExit("Stopped before capture; provide a local asset path or use the AMC UI.")

s = requests.Session()
s.verify = SSL_VERIFY

if not SSL_VERIFY:
    print("[0] WARNING: SSL certificate verification is disabled for loopback AMC access only.")

print("[0] Checking AMC microservice")
_check_amc_ready(s, BASE_URL)

print("[0] Checking VIOS")
if VIOS_BASE_URL:
    try:
        _check_vios_ready(VIOS_BASE_URL)
        print(f"    VIOS reachable at {VIOS_BASE_URL}")
    except requests.RequestException as exc:
        raise SystemExit(f"VIOS_BASE_URL is set but not reachable: {exc}") from exc
else:
    try:
        _check_vios_ready("http://localhost:30888")
        VIOS_BASE_URL = "http://localhost:30888"
        print("    VIOS reachable at http://localhost:30888")
    except requests.RequestException as exc:
        if REQUIRE_VIOS_HEALTH:
            raise SystemExit(
                "VIOS health check failed. Set VIOS_BASE_URL to a reachable VIOS endpoint, "
                "or set REQUIRE_VIOS_HEALTH=false only if the AMC microservice has already "
                "been verified with VIOS_BASE_URL configured."
            ) from exc
        print("    VIOS health check skipped; ensure the AMC microservice has VIOS_BASE_URL configured.")

print("\n[1] RTSP capture plan:")
print(f"    Project:              {PROJECT_NAME}")
print(f"    Stream count:         {len(STREAMS)}")
print(f"    Duration seconds:     {DURATION_SECONDS}")
print(f"    AMC UI:               {AMC_UI_URL}")
print(f"    Calibration assets:   {CALIB_ASSET_DIR if CALIB_ASSET_DIR else 'explicit files or UI'}")
print(f"    Calibration settings: {CONFIG_FILE if CONFIG_FILE else 'UI Step 3 settings/defaults'}")
print(f"    Alignment JSON:       {ALIGNMENT_JSON if ALIGNMENT_JSON else 'UI Step 4/manual_adjustment'}")
print(f"    Layout PNG:           {LAYOUT_PNG if LAYOUT_PNG else 'UI Step 4/manual_adjustment'}")
print(f"    Detector:             {DETECTOR_TYPE if DETECTOR_TYPE else 'ask before calibration'}")
for idx, stream in enumerate(STREAMS):
    sensor_state = "provided" if stream.get("sensor_id") else "auto"
    print(f"    Stream {idx}:           {stream['camera_name']} {sensor_state} {_redact_rtsp_url(stream['rtsp_url'])}")
if IS_INTERACTIVE:
    answer = input("    Start RTSP capture? [y/N]: ").strip().lower()
    if answer not in ("y", "yes"):
        raise SystemExit("Stopped before capture.")
else:
    print("    Non-interactive stdin detected; starting with the plan above.")

# Step 1 -- Create project.
r = s.post(f"{BASE_URL}/create_project", data={"project_name": PROJECT_NAME})
project_id = _json_response(r, "create_project")["project_id"]
print(f"\n[2] Created project: {project_id}")

# Step 2 -- Start RTSP capture.
capture_body = {
    "streams": STREAMS,
    "duration_seconds": DURATION_SECONDS,
    "ssl_verify": SSL_VERIFY,
}
r = s.post(f"{BASE_URL}/rtsp/capture/{project_id}", json=capture_body, timeout=30)
payload = _json_response(r, "rtsp capture")
session_info = _session_from_payload(payload)
session_id = session_info["session_id"]
print(f"[3] Capture session: {session_id}")

# Step 3 -- Poll capture until the recording is complete, then ingest.
print(f"[4] Polling capture status (timeout {DURATION_SECONDS + 600}s)")
start = time.time()
last_state = ""
while time.time() - start < DURATION_SECONDS + 600:
    r = s.get(f"{BASE_URL}/rtsp/capture/{project_id}/{session_id}", timeout=30)
    payload = _json_response(r, "rtsp capture status")
    sess = payload.get("session") or payload
    state = (sess.get("status") or sess.get("state") or "").upper()
    elapsed = int(time.time() - start)
    if state != last_state:
        print(f"    [{elapsed:>4}s] {state}", flush=True)
        last_state = state
    if state in ("COMPLETED", "INGESTED"):
        break
    if state in ("ERROR", "CANCELLED"):
        raise RuntimeError(f"Capture {state}: {payload}")
    time.sleep(10)
else:
    raise RuntimeError("RTSP capture polling timed out.")

if last_state != "INGESTED":
    r = s.post(f"{BASE_URL}/rtsp/capture/{project_id}/{session_id}/ingest", timeout=120)
    _json_response(r, "rtsp ingest")
    print("[4] Ingested recorded clips into the project")
else:
    print("[4] Capture session was already ingested")

# Step 4 -- Upload settings, alignment, layout, and optional files.
if CONFIG_FILE and CONFIG_FILE.exists():
    r = s.post(
        f"{BASE_URL}/config/{project_id}",
        data=CONFIG_FILE.read_bytes(),
        headers={"Content-Type": "application/json"},
        timeout=60,
    )
    r.raise_for_status()
    print(f"[5] Applied calibration config from {CONFIG_FILE.name} (replaces UI Step 3)")
    det = _detector_from_config(CONFIG_FILE)
    if det:
        DETECTOR_TYPE = det
        print(f"    Detector overridden from config: {DETECTOR_TYPE}")

if ALIGNMENT_JSON and ALIGNMENT_JSON.exists():
    with open(ALIGNMENT_JSON, "rb") as f:
        s.post(
            f"{BASE_URL}/upload_alignment/{project_id}",
            files={"alignment_file": (ALIGNMENT_JSON.name, f, "application/json")},
            timeout=60,
        ).raise_for_status()
    print(f"[5] Uploaded alignment: {ALIGNMENT_JSON.name}")

if LAYOUT_PNG and LAYOUT_PNG.exists():
    with open(LAYOUT_PNG, "rb") as f:
        s.post(
            f"{BASE_URL}/upload_layout/{project_id}",
            files={"layout_file": (LAYOUT_PNG.name, f, "image/png")},
            timeout=60,
        ).raise_for_status()
    print(f"[5] Uploaded layout: {LAYOUT_PNG.name}")

if GT_ZIP and GT_ZIP.exists():
    with open(GT_ZIP, "rb") as f:
        s.post(
            f"{BASE_URL}/upload_gt_file/{project_id}",
            files={"gt_file": (GT_ZIP.name, f, "application/zip")},
            timeout=120,
        ).raise_for_status()
    print("[5] Uploaded GT zip")

if FOCAL_LENGTHS:
    s.post(
        f"{BASE_URL}/upload_focal_length/{project_id}",
        data={"focal_length": FOCAL_LENGTHS},
        timeout=60,
    ).raise_for_status()
    print(f"[5] Uploaded focal lengths: {FOCAL_LENGTHS}")

ui_tasks = []
if not CONFIG_FILE:
    ui_tasks.append("Step 3 (Parameters): tune settings or accept defaults, then Save.")
if not ALIGNMENT_JSON or not LAYOUT_PNG:
    ui_tasks.append("Step 4 (Alignment): upload layout, mark correspondence points, then Save. Do not re-upload videos.")
if ui_tasks:
    print(f"\n[5] UI action required for project {project_id}:")
    print(f"    Open AMC UI: {AMC_UI_URL}")
    for task in ui_tasks:
        print(f"    - {task}")
    if not IS_INTERACTIVE:
        raise RuntimeError(
            "UI action is required before continuing. Run interactively, or provide "
            "CONFIG_FILE, ALIGNMENT_JSON, and LAYOUT_PNG so the script can run unattended."
        )
    input("    Press Enter when done...")
    if not ALIGNMENT_JSON or not LAYOUT_PNG:
        manual_dir = PROJECTS_DIR / f"project_{project_id}" / "manual_adjustment"
        assert (manual_dir / "alignment_data.json").exists() and (manual_dir / "layout.png").exists(), (
            f"Alignment files missing under {manual_dir}. Re-check UI Step 4 and click Save."
        )
        print(f"    Alignment files verified at {manual_dir}")

# Step 5 -- Verify, confirm, calibrate, poll, and fetch results.
DETECTOR_TYPE = _require_detector(DETECTOR_TYPE)

r = s.post(f"{BASE_URL}/verify_project/{project_id}", timeout=60)
r.raise_for_status()
verify_payload = r.json()
state = verify_payload.get("project_state") or verify_payload.get("project_info", {}).get("project_state")
print(f"\n[6] Project state: {state}")
assert state == "READY", f"Expected READY, got {state}"

print("\n[7] Calibration plan:")
print(f"    Detector:             {DETECTOR_TYPE}")
print(f"    Stream count:         {len(STREAMS)}")
print(f"    Duration seconds:     {DURATION_SECONDS}")
print(f"    AMC UI:               {AMC_UI_URL}")
print(f"    Calibration settings: {CONFIG_FILE if CONFIG_FILE else 'UI Step 3 settings/defaults'}")
print(f"    Alignment JSON:       {ALIGNMENT_JSON if ALIGNMENT_JSON else 'UI Step 4/manual_adjustment'}")
print(f"    Layout PNG:           {LAYOUT_PNG if LAYOUT_PNG else 'UI Step 4/manual_adjustment'}")
print(f"    Ground truth zip:     {GT_ZIP if GT_ZIP else 'not provided'}")
print(f"    Focal lengths:        {FOCAL_LENGTHS if FOCAL_LENGTHS else 'not provided'}")
if IS_INTERACTIVE:
    answer = input("    Start calibration? [y/N]: ").strip().lower()
    if answer not in ("y", "yes"):
        raise SystemExit("Stopped before calibration.")
else:
    print("    Non-interactive stdin detected; starting with the plan above.")

s.post(f"{BASE_URL}/calibrate/{project_id}", json={"detector_type": DETECTOR_TYPE}, timeout=60).raise_for_status()
print(f"[7] Calibration started (detector={DETECTOR_TYPE})")

print("[8] Polling calibration (10-60 min typical)")
start, last_state, last_beat = time.time(), "", 0.0
while time.time() - start < 5400:
    info = s.get(f"{BASE_URL}/get_project_info/{project_id}", timeout=30).json()
    st = info["project_info"]["project_state"]
    mins, secs = divmod(int(time.time() - start), 60)
    if st != last_state or time.time() - last_beat >= 60:
        print(f"    [{mins:>3}m {secs:02d}s] {st}", flush=True)
        last_state, last_beat = st, time.time()
    if st == "COMPLETED":
        print(f"[8] Done in {mins}m {secs:02d}s")
        break
    if st == "ERROR":
        try:
            log_lines = s.get(f"{BASE_URL}/amc/calibrate/{project_id}/log", timeout=30).text.splitlines()
            print("    --- last calibration log lines ---")
            for line in log_lines[-20:]:
                print(f"    {line}")
        except requests.RequestException as exc:
            print(f"    warning: could not fetch calibration log tail: {exc}")
        raise RuntimeError(f"ERROR state -- full log: GET {BASE_URL}/amc/calibrate/{project_id}/log")
    time.sleep(10)
else:
    raise RuntimeError(
        f"Calibration still running after {int((time.time() - start) // 60)} min -- "
        f"inspect GET {BASE_URL}/amc/calibrate/{project_id}/log"
    )

print("\n[9] Results:")
r = s.get(f"{BASE_URL}/result/{project_id}/evaluation_statistics", timeout=30)
if r.status_code == 200:
    for key, value in (r.json().get("statistics") or r.json()).items():
        print(f"    {key}: {value}")
else:
    print("    No GT provided -- skipping evaluation_statistics")

info = s.get(f"{BASE_URL}/get_project_info/{project_id}", timeout=30).json()
vggt_state = info.get("project_info", {}).get("vggt_state", "INIT")
if vggt_state == "READY" and not RUN_VGGT:
    if IS_INTERACTIVE:
        answer = input("\n[10] VGGT is READY. Run VGGT refinement now? [y/N]: ").strip().lower()
        RUN_VGGT = answer in ("y", "yes")
    else:
        print("\n[10] VGGT is READY. Set RUN_VGGT=true to run VGGT refinement in non-interactive runs.")
elif vggt_state != "READY":
    print(f"\n[10] VGGT not ready (state={vggt_state}) -- skipping")

if RUN_VGGT and vggt_state == "READY":
    s.post(f"{BASE_URL}/vggt/calibrate/{project_id}", timeout=60).raise_for_status()
    print("\n[10] VGGT started")
    t0 = time.time()
    while time.time() - t0 < 900:
        vs = s.get(f"{BASE_URL}/get_project_info/{project_id}", timeout=30).json() \
            .get("project_info", {}).get("vggt_state", "INIT")
        if vs == "COMPLETED":
            print("     VGGT done")
            r = s.get(f"{BASE_URL}/vggt_results/{project_id}/evaluation_statistics", timeout=30)
            if r.status_code == 200:
                print("     VGGT evaluation statistics:")
                for key, value in (r.json().get("statistics") or r.json()).items():
                    print(f"        {key}: {value}")
            else:
                print(f"     VGGT evaluation statistics unavailable (HTTP {r.status_code})")
            break
        if vs == "ERROR":
            raise RuntimeError("VGGT failed")
        time.sleep(10)

print(f"\nProject: {project_id}")
print("Review the calibration:")
print(f"    UI:                open project {project_id} in the AMC web UI, then the Results page")
print(f"    Final parameters:  projects/project_{project_id}/output/multi_view_results/BA_output/results_ba/refined/camInfo_XX.yaml")

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs network access, Needs a command-line tool, Needs Python

Security

What our scanner noticed· Medium risk

  • Large base64-encoded blobs
  • Instructions that use the network
  • Scripts that your agent may run

This skill includes scripts that your agent may run. Read them before you use it.

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
Shubham Agrawal
Publisher
NVIDIA (Official)
Distributed by
NVIDIA
Source
NVIDIA/skills · skills/amc-run-rtsp-calibration · commit fce3cca
Licence
Apache License 2.0 (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE-APACHE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Shubham Agrawal or NVIDIA.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download amc-run-rtsp-calibration.zip