Generated banner for Amc Run Video Calibration
Generated logo for Amc Run Video Calibration

Amc Run Video Calibration

NVIDIAOfficialCreated by Shubham AgrawalDistributed by NVIDIA

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

From the author

Calibrates pre-recorded `cam_*.mp4` datasets through the AutoMagicCalib REST API. Use for user-supplied local MP4s; route live RTSP streams to `amc-run-rtsp-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 for calibrating multi-camera systems using pre-recorded MP4 files. It handles the end-to-end process of project creation, video upload, configuration resolution, calibration execution, and optional VGGT refinement. Designed for integration with the AutoMagicCalib microservice, it supports both automated local file detection and interactive UI fallback for manual alignment tasks.

What it does

  • Creates and manages calibration projects via the AutoMagicCalib REST API.
  • Uploads and validates contiguous, time-synchronized MP4 video sequences.
  • Automatically resolves configuration, alignment, and layout files from local directories.
  • Executes the calibration pipeline and polls for completion status.
  • Provides optional VGGT refinement for improved calibration accuracy.
  • Retrieves evaluation metrics and logs upon successful completion.

When to use it

  • When you have a set of pre-recorded, time-synchronized MP4 files from multiple cameras.
  • When you need to perform camera calibration using the AutoMagicCalib microservice.
  • When you want to automate the calibration workflow for custom datasets.
  • When you need to integrate calibration results into downstream 3D tracking pipelines.

Advantages

  • Reduces manual effort by automating the multi-step calibration lifecycle.
  • Supports both fully automated and semi-automated (UI-assisted) workflows.
  • Provides clear status tracking and error reporting for calibration jobs.
  • Enables consistent calibration results through standardized API interactions.

Usage examples

“Calibrate my videos in /data/warehouse_session using the local AMC service.”
The agent initiates the calibration workflow, detects the video files, uploads them to the project, and proceeds through the calibration steps.
“Run a non-interactive calibration for project warehouse-batch with pre-supplied config and alignment files.”
The agent executes the calibration script using the provided paths for settings and alignment, confirming the plan and running the process to completion.

Install

  1. Download the skill as a ZIP:

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

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

Documentation by Shubham Agrawal

Skill: Calibrate from Video Files

When to Use This Skill

Activate this skill when the user has pre-recorded MP4 files and wants to calibrate them via the AMC REST API. Typical prompts:

  • "calibrate my videos" / "run AMC on these videos"

  • "calibrate from video files"

Drives calibration through the REST API on user-supplied pre-recorded MP4 files — no CLI scripts or Docker bind-mounts required, just a running microservice and your files.

Do not use this skill for live RTSP streams or rtsp://... URLs; route those requests to skills/amc-run-rtsp-calibration/SKILL.md.

Purpose

Guide the agent through project creation, sorted MP4 upload, local asset resolution, UI fallback only when necessary, project verification, calibration, polling, evaluation, and optional VGGT refinement for a user-provided multi-camera dataset.

Prerequisites

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

  • [ ] You know the microservice URL (use https://<HOST_IP>:<MS_PORT> for remote AMC, or http://localhost:<MS_PORT> on loopback) and UI URL

  • [ ] Video files locally as contiguous cam_00.mp4, cam_01.mp4, … time-synchronized, ~1920×1080

  • [ ] Python 3 with requests

  • [ ] If AMC stores project outputs outside the default projects/ directory, you know the host PROJECTS_DIR

Interaction Model

  • The "host's question mechanism" means the runtime's built-in prompt API for short user decisions, such as terminal stdin, an IDE ask tool, or an equivalent interactive dialog.

  • If that mechanism is unavailable, ask in chat and wait before any guarded step that requires user confirmation or a missing-file decision.

  • For unattended runs, the bundled script requires all non-UI inputs up front and exits before /calibrate unless CONFIRM_CALIBRATION=true is set. RUN_VGGT=true remains a separate opt-in for the optional VGGT step.

Data Privacy

Video files uploaded via this skill are transmitted to the AutoMagicCalib backend (REST endpoint). Only use this skill when the backend is deployed on a trusted platform / network.

Inputs

  • Required inputs: VIDEO_DIR, BASE_URL, and PROJECT_NAME.

  • Optional local inputs: CONFIG_FILE, ALIGNMENT_JSON, LAYOUT_PNG, GT_ZIP, FOCAL_LENGTHS, and DETECTOR_TYPE.

  • Optional control inputs: CONFIRM_CALIBRATION, RUN_VGGT, PROJECTS_DIR, CALIBRATION_TIMEOUT_SECONDS, and VGGT_TIMEOUT_SECONDS.

  • BASE_URL should use HTTPS for non-loopback hosts. Set ALLOW_INSECURE_HTTP=true only for trusted development setups that intentionally use remote plain HTTP.

  • Resolution precedence for settings, alignment, and layout: explicit path, single local auto-detected match, then UI fallback.

What to Ask the User

Required

(Video-file naming and the microservice URL are specified under Prerequisites above — collect the inputs below.)

  1. Videos directory — the folder the skill globs for cam_*.mp4, uploaded sorted alphabetically.

  2. Microservice URL

  3. Project name — short descriptive string

Auto-Detected (ask only if not found)

The script searches the videos dir, its first-level subdirectories, and its parent. If exactly one match is found, it is used; otherwise the script prints the searched locations and continues to explicit path or UI fallback:

FileCandidate filenamesUI fallback
Calibration settingssettings.json, config.json, calibration_config.jsonUI Step 3: Parameters
Alignment JSONalignment_data.jsonUI Step 4: Alignment
Layout PNGlayout.pngUI Step 4: Alignment

Posting the settings file replaces UI Step 3 and may pin the detector (resnet/transformer), which is passed to /calibrate separately — see Step 4.

Optional
  1. Ground truth zip — GT.zip with _World_Cameras_Camera_XX/ folders (enables evaluation metrics)

  2. Focal lengths — one per camera, e.g. 1269.0, 1099.5, 1099.5

  3. Detector type — resnet (default, fast) or transformer (slower, better under occlusion)

  4. Run VGGT refinement? — if VGGT is ready after AMC completes, ask the user whether to run refinement (see setup skill)

See root README.md "Custom Dataset" section for input-video guidelines and ground-truth format.


Available Scripts

ScriptPurposeKey inputs
run_video_calibration.pyExecutes create-project, upload, verify, calibrate, poll, evaluate, and optional VGGT refinement for a local MP4 dataset.Required: BASE_URL, PROJECT_NAME, VIDEO_DIR. Optional: CONFIG_FILE, ALIGNMENT_JSON, LAYOUT_PNG, GT_ZIP, FOCAL_LENGTHS, DETECTOR_TYPE, CONFIRM_CALIBRATION, RUN_VGGT, PROJECTS_DIR, CALIBRATION_TIMEOUT_SECONDS, VGGT_TIMEOUT_SECONDS, ALLOW_INSECURE_HTTP.

Instructions

All endpoints below are implemented end-to-end in the Complete Python Script — the prose is the workflow plus the decisions the agent must make; the script is the authoritative runnable.

Step 1 — Create Project

POST /v1/create_project (form field project_name) → save the returned project_id.

Step 2 — Upload Videos (required)

POST /v1/upload_video_files/<project_id> (multipart files). Upload sorted alphabetically — the server assigns camera indices by upload order. The bundled script rejects non-contiguous or non-zero-based camera sequences up front; the directory must contain cam_00.mp4, cam_01.mp4, ... with no gaps.

Step 3 — Resolve Local Files (Auto-Scan, Ask, or UI)

For each of calibration-settings, alignment, and layout, run this resolution:

Auto-use rule: if exactly one match is found, the script uses it automatically and prints the resolved path. No extra prompt occurs for that file.

  1. Auto-scan VIDEO_DIR, one level of subdirectories under VIDEO_DIR, and VIDEO_DIR.parent for the candidate filenames (table above).

  2. If exactly one match, use it and print what was found.

  3. If zero or multiple matches, print the searched locations, then ask the user for an explicit path using the host's question mechanism; if none is available, ask in chat and wait. If they don't have the file, mark it for UI fallback.

  4. UI fallback: tell the user to complete the corresponding UI step; wait for confirmation; then continue to Step 6 and treat verify_project as the source of truth for whether the UI-supplied alignment/layout data is complete.

Step 4 — Upload Resolved Files

Upload each file resolved locally:

FileEndpointNotes
Calibration settingsPOST /v1/config/<project_id> (JSON, posted as-is)Replaces UI Step 3 (rectification, bundle-adjustment, evaluation, detector, …). Non-2xx is surfaced — never silently fall back. Skip on the UI-fallback path.
AlignmentPOST /v1/upload_alignment/<project_id> (alignment_data.json)
LayoutPOST /v1/upload_layout/<project_id> (layout.png)
Ground truth (optional)POST /v1/upload_gt_file/<project_id> (GT.zip)Enables evaluation metrics
Focal lengths (optional)POST /v1/upload_focal_length/<project_id> (repeated focal_length=)Overrides GeoCalib estimates

Upload all resolved local files first, in any order. After the local uploads are complete, continue to Step 5 only for unresolved files, then run Step 6 exactly once to verify the assembled project.

After a successful settings POST, parse the file for "detector" / "detector_type" — if it's "resnet" or "transformer", use that value for the /calibrate call in Step 7 (detector is a separate API parameter, not consumed by /config).

Step 5 — UI Fallback (only for files the user doesn't have locally)

If any of settings / alignment / layout was not resolved in Step 3, direct the user to the appropriate UI step:

  • Settings missing → "Open UI project <project_id>, go to Step 3: Parameters, tune via the settings dialog (or accept defaults), click Save." Also: before the /calibrate call, ask the user which detector to use (resnet or transformer) using the host's question mechanism; if none is available, ask in chat and wait. UI Step 3 does not cover detector choice.

  • Alignment or layout missing → "Open UI project <project_id>, go to Step 4: Alignment, upload layout, mark correspondence points, click Save."

Wait for user confirmation. For non-interactive script runs, provide the needed files up front; the script exits with a clear message rather than waiting on input. Do not require local access to AMC's projects/ storage for the UI fallback; Step 6 is the canonical server-side verification step.

Step 6 — Verify Project

POST /v1/verify_project/<project_id> → must return {"project_state": "READY"} before calibrating.

Step 7 — Start Calibration

Confirm the plan before calibrating. Whether the settings file and detector were auto-detected or asked, present a short summary and get explicit user confirmation before POST /calibrate using the host's question mechanism; if none is available, ask in chat and wait. The resolved values are the defaults, so confirming is one click, but the user can switch the detector or skip an auto-detected settings file. The standalone Python script prompts when stdin is interactive; in non-interactive runs it exits before /calibrate unless CONFIRM_CALIBRATION=true is set. Summarize:

  • Detector — resnet or transformer (the value to be sent).

  • Calibration settings — the file being applied (path), or "defaults" if none.

  • Optional overrides — ground-truth zip and focal lengths, if any.

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

{"detector_type": "resnet"}
Step 8 — Poll for Completion

GET /v1/get_project_info/<project_id> every 10 s — project_info.project_state goes RUNNING → COMPLETED (or ERROR, pull the log). Typical time: 10–60 min depending on video length and detector. The bundled script defaults to a 90 minute cap through CALIBRATION_TIMEOUT_SECONDS=5400; raise that env var for longer runs instead of silently killing the process.

Step 9 — Get Results

GET /v1/result/<project_id>/evaluation_statistics (only if GT was uploaded; includes Average L2 distance(m) and Average reprojection error 0(px)), and GET /v1/amc/calibrate/<project_id>/log for the calibration log. If GT was uploaded and evaluation_statistics returns non-200, surface that HTTP error instead of treating it as a missing-GT case.

Status Fields from get_project_info

project_info.project_state is the AMC calibration lifecycle for the project: RUNNING → COMPLETED (or ERROR).

project_info.vggt_state is also per-project, a project-scoped VGGT refinement lifecycle rather than a direct global service or model-load status. A newly created project can report vggt_state: "INIT" even when the VGGT model is present and mounted. The expected VGGT lifecycle is INIT → READY after AMC calibration completes → RUNNING while VGGT refinement runs → COMPLETED (or ERROR).

Use vggt_state == "READY" only as the gate for optional VGGT refinement in Step 10. Interpret INIT on a new or uncalibrated project as normal project state. If AMC calibration is complete and the project remains in a non-ready VGGT state, confirm VGGT setup and model availability with the setup skill checks and service logs.

Step 10 — (Optional) VGGT Refinement

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

  • If the project reports vggt_state == "READY", ask the user whether to run VGGT refinement using the host's question mechanism; if none is available, ask in chat and wait.

  • If the user confirms, POST /v1/vggt/calibrate/<project_id>, poll vggt_state via get_project_info, then GET /v1/vggt_results/<project_id>/evaluation_statistics.

  • If VGGT is not ready, skip refinement and explain that the user can set up VGGT with amc-setup-calibration-stack and rerun this optional step later.

The standalone Python script prompts only when stdin is interactive. In non-interactive runs, set RUN_VGGT = True to opt in; otherwise the script prints that VGGT is ready and continues without blocking.


Complete Python Script

Use the bundled script from the amc-run-video-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_VIDEO_SKILL_DIR to the directory containing this SKILL.md, or run the command from that directory. Set BASE_URL, PROJECT_NAME, and VIDEO_DIR; optional env vars are CONFIG_FILE, ALIGNMENT_JSON, LAYOUT_PNG, GT_ZIP, FOCAL_LENGTHS, DETECTOR_TYPE, RUN_VGGT, REPO_ROOT, PROJECTS_DIR, CONFIRM_CALIBRATION, CALIBRATION_TIMEOUT_SECONDS, VGGT_TIMEOUT_SECONDS, and ALLOW_INSECURE_HTTP. The script implements AMC readiness checks, UI fallback, explicit confirmation gating, bounded polling, and refined statistics retrieval.

# 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-video-calibration" ]; then
  DEEPSTREAM_REPO_ROOT="$(cd "$REPO_ROOT/../.." && pwd)"
fi

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

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

python3 "$SCRIPT_PATH"

Examples

Interactive run with auto-detection for local settings/alignment/layout:

BASE_URL="http://localhost:8000/v1" \
PROJECT_NAME="warehouse-calibration" \
VIDEO_DIR="/data/warehouse_session" \
python3 "$SCRIPT_PATH"

Non-interactive run with all required local files supplied up front:

BASE_URL="http://localhost:8000/v1" \
PROJECT_NAME="warehouse-batch" \
VIDEO_DIR="/data/warehouse_session" \
CONFIG_FILE="/data/warehouse_session/settings.json" \
ALIGNMENT_JSON="/data/warehouse_session/alignment_data.json" \
LAYOUT_PNG="/data/warehouse_session/layout.png" \
CONFIRM_CALIBRATION=true \
RUN_VGGT=true \
python3 "$SCRIPT_PATH"

Success Criteria

  • project_state == "COMPLETED" after polling.

  • verify_project returned READY before calibration (including manual alignment/UI fallback paths).

  • If GT was uploaded: evaluation returns typical thresholds:

    • Average L2 distance(m) < 1.5

    • Average reprojection error 0(px) < 5

  • No ERROR state.

Key Output Files (on server)

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          # ← final calibration
└── calibration.log

Limitations

  • This skill only applies to local pre-recorded cam_*.mp4 datasets. Live RTSP streams and the bundled sample dataset are out of scope.

  • Unattended runs cannot rely on UI fallback; provide the required local files up front and set CONFIRM_CALIBRATION=true.

  • Reported server-side output paths depend on the correct host PROJECTS_DIR when AMC writes project outputs outside the default projects/ directory.

Troubleshooting

IssueFix
verify_project state not READYConfirm videos uploaded and alignment + layout are present (either via API or via UI manual alignment)
Manual alignment still not accepted after UI stepUser likely did not click Save or the UI data is incomplete; rerun verify_project and repeat UI Step 4
Calibration stuck RUNNING > 90 minGET /v1/amc/calibrate/<id>/log — usually insufficient tracklets (scene too static). See "Custom Dataset" guidelines in root README.
Immediate ERROR stateCheck video naming: must be cam_00.mp4, cam_01.mp4, … contiguous
Low L2 but high reprojectionProvide explicit focal_length override via Step 3
VGGT stays non-ready after AMC completesINIT is expected for a new project. After AMC calibration reaches COMPLETED, the project should transition to READY before optional VGGT refinement when VGGT is configured. If refinement is required and the state remains INIT or otherwise non-ready, confirm VGGT setup and model availability with setup skill Step 2 and MS logs.
Upload timeoutLarge videos — bump timeout=300 to e.g. 600 in the script

For Downstream Skills — MV3DT Export

A downstream Multi-View 3D Tracking skill fetches the MV3DT-format calibration directly from the microservice (this skill does not download it; it returns the project_id). After this skill reports COMPLETED:

  • GET /v1/result/{project_id}/mv3dt_result?result_type=amc → mv3dt_output.zip (contains transforms.yml).

  • If VGGT ran to COMPLETED (Step 10): ?result_type=vggt → vggt_mv3dt_output.zip.

  • skills/amc-setup-calibration-stack/SKILL.md — start MS + UI first.

  • skills/amc-run-sample-calibration/SKILL.md — verify the stack with the bundled sample before trying your own.

  • skills/amc-run-rtsp-calibration/SKILL.md — same calibration tail, but sourcing footage from live RTSP streams through VIOS.

Root README.md "Custom Dataset" and "Calibration Workflow (UI)" sections document input-video guidelines and the UI-driven alternative to this API flow.

<!-- signing marker -->

Files

scripts/run_video_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 for user-provided pre-recorded videos.

Usage:
    Set BASE_URL, PROJECT_NAME, and VIDEO_DIR, then run this module directly.

Environment arguments:
    Required: BASE_URL, PROJECT_NAME, VIDEO_DIR
    Optional: CONFIG_FILE, ALIGNMENT_JSON, LAYOUT_PNG, GT_ZIP, FOCAL_LENGTHS,
        DETECTOR_TYPE, RUN_VGGT, REPO_ROOT, PROJECTS_DIR,
        CONFIRM_CALIBRATION, CALIBRATION_TIMEOUT_SECONDS,
        VGGT_TIMEOUT_SECONDS

Output:
    Prints upload/progress status, project ID, evaluation metrics, and the
    server-side result locations to review in AMC.

Exit codes:
    0 for success, 1 for handled workflow failures, and 2 for unexpected
    runtime failures.
"""

import ipaddress
import json
import os
import sys
import time
from contextlib import ExitStack
from pathlib import Path
from urllib.parse import urlsplit, urlunsplit

try:
    import requests
except ModuleNotFoundError as exc:
    raise SystemExit(
        "This script requires Python 3 with the 'requests' package installed. "
        "Install it first, for example: python3 -m pip install requests"
    ) from exc


DEFAULT_TIMEOUT = (10, 120)
VIDEO_UPLOAD_TIMEOUT_SECONDS = 300
GT_UPLOAD_TIMEOUT_SECONDS = 120


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")


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


def _env_int(name, default):
    value = os.environ.get(name)
    if value is None:
        return default
    try:
        return int(value)
    except ValueError as exc:
        raise ValueError(f"{name} must be an integer, got {value!r}") from exc


def _is_loopback_host(hostname):
    if not hostname:
        return False
    if hostname == "localhost":
        return True
    try:
        return ipaddress.ip_address(hostname).is_loopback
    except ValueError:
        return False


def _normalize_base_url(value):
    parsed = urlsplit(value.rstrip("/"))
    if parsed.scheme not in ("http", "https") or not parsed.netloc:
        raise ValueError(
            "BASE_URL must be an absolute http:// or https:// URL, for example "
            "https://amc.example.com/v1 or http://localhost:8000/v1"
        )
    path = parsed.path.rstrip("/")
    normalized_path = path if path.endswith("/v1") else f"{path}/v1" if path else "/v1"
    if (
        parsed.scheme == "http"
        and not _is_loopback_host(parsed.hostname)
        and not _env_bool("ALLOW_INSECURE_HTTP", False)
    ):
        raise ValueError(
            "BASE_URL uses cleartext HTTP for a non-loopback host. Use HTTPS, "
            "tunnel the service to localhost, or set ALLOW_INSECURE_HTTP=true "
            "only for trusted development setups."
        )
    return urlunsplit(
        (parsed.scheme, parsed.netloc, normalized_path, parsed.query, parsed.fragment)
    )


def _response_detail(response):
    try:
        return response.json()
    except ValueError:
        text = response.text.strip()
        return text[:400] if text else "<empty response>"


def _response_json_object(response, label):
    try:
        payload = response.json()
    except ValueError as exc:
        raise RuntimeError(f"{label} did not return JSON: {_response_detail(response)}") from exc
    if not isinstance(payload, dict):
        raise TypeError(f"{label} returned an unexpected JSON payload: {payload!r}")
    return payload


def _require_field(payload, field_name, label):
    if field_name not in payload or payload[field_name] in (None, ""):
        raise RuntimeError(f"{label} response missing {field_name!r}: {payload}")
    return payload[field_name]


def _require_object_field(payload, field_name, label):
    value = _require_field(payload, field_name, label)
    if not isinstance(value, dict):
        raise TypeError(
            f"{label} field {field_name!r} must be a JSON object, got {value!r}"
        )
    return value


def _require_string_field(payload, field_name, label):
    value = _require_field(payload, field_name, label)
    if not isinstance(value, str):
        raise TypeError(
            f"{label} field {field_name!r} must be a string, got {value!r}"
        )
    return value


def _raise_for_status(response, label):
    try:
        response.raise_for_status()
    except requests.RequestException as exc:
        raise RuntimeError(
            f"{label} failed: HTTP {response.status_code}: {_response_detail(response)}"
        ) from exc


def _check_amc_ready(session, base_url):
    response = session.get(f"{base_url}/ready", timeout=DEFAULT_TIMEOUT)
    _raise_for_status(response, "AMC readiness probe")
    payload = _response_json_object(response, "AMC readiness probe")
    if payload.get("code") not in (None, 0, "0"):
        raise RuntimeError(f"AMC readiness probe returned non-zero code: {payload}")


def _resolve_local(override, candidate_names, scan_dirs, label):
    """Return a local file path if there is a single unambiguous match."""
    if override and override.exists():
        return override

    hits = []
    for scan_dir in scan_dirs:
        for name in candidate_names:
            candidate = scan_dir / name
            if candidate.exists():
                hits.append(candidate)

    if len(hits) == 1:
        print(f"    auto-detected {label}: {hits[0]}")
        return hits[0]

    searched = [str(scan_dir) for scan_dir in scan_dirs]
    if len(hits) > 1:
        print(
            f"    multiple {label} candidates found in {searched}: {hits}; "
            "use an explicit path or UI fallback"
        )
    else:
        print(
            f"    no {label} file auto-detected in {searched}; "
            "use an explicit path or UI fallback"
        )
    return None


def _parse_detector_from_config(config_file, current_detector):
    try:
        config_payload = json.loads(config_file.read_text())
    except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc:
        print(
            f"    warning: could not parse detector_type from {config_file}: {exc}; "
            f"continuing with DETECTOR_TYPE={current_detector}"
        )
        return current_detector

    if not isinstance(config_payload, dict):
        print(
            f"    warning: config file {config_file} did not parse to a JSON object; "
            f"continuing with DETECTOR_TYPE={current_detector}"
        )
        return current_detector

    detector = config_payload.get("detector") or config_payload.get("detector_type")
    if detector in ("resnet", "transformer"):
        print(f"    Detector overridden from config: {detector}")
        return detector
    if detector is not None:
        print(
            f"    warning: unsupported detector {detector!r} in {config_file}; "
            f"continuing with DETECTOR_TYPE={current_detector}"
        )
    return current_detector


def _get_project_info(session, base_url, project_id):
    response = session.get(
        f"{base_url}/get_project_info/{project_id}",
        timeout=DEFAULT_TIMEOUT,
    )
    _raise_for_status(response, "get_project_info")
    return _response_json_object(response, "get_project_info")


def _project_state(payload, label):
    project_info = _require_object_field(payload, "project_info", label)
    return _require_string_field(project_info, "project_state", f"{label}.project_info")


def _vggt_state(payload, label):
    project_info = _require_object_field(payload, "project_info", label)
    value = project_info.get("vggt_state", "INIT")
    if not isinstance(value, str):
        raise TypeError(
            f"{label}.project_info field 'vggt_state' must be a string, got {value!r}"
        )
    return value


def _statistics_payload(response, label):
    payload = _response_json_object(response, label)
    statistics = payload.get("statistics", payload)
    if not isinstance(statistics, dict):
        raise TypeError(f"{label} returned unexpected statistics payload: {payload!r}")
    return statistics


def _validate_video_files(video_files, video_dir):
    if not video_files:
        raise RuntimeError(
            f"No cam_*.mp4 files were found under {video_dir}. "
            "Provide a directory with contiguous cam_00.mp4, cam_01.mp4, ... files."
        )

    actual_names = [path.name for path in video_files]
    expected_names = [f"cam_{index:02d}.mp4" for index in range(len(video_files))]
    if actual_names != expected_names:
        raise RuntimeError(
            "VIDEO_DIR must contain a contiguous camera sequence named "
            "cam_00.mp4, cam_01.mp4, ... with no gaps. "
            f"Found {actual_names} under {video_dir}."
        )


def main():
    # Required env vars: BASE_URL, PROJECT_NAME, VIDEO_DIR. Optional file paths and
    # knobs use CONFIG_FILE, ALIGNMENT_JSON, LAYOUT_PNG, GT_ZIP, FOCAL_LENGTHS,
    # DETECTOR_TYPE, RUN_VGGT, REPO_ROOT, PROJECTS_DIR, CONFIRM_CALIBRATION,
    # CALIBRATION_TIMEOUT_SECONDS, and VGGT_TIMEOUT_SECONDS.
    base_url = _normalize_base_url(
        os.environ.get("BASE_URL", "http://<HOST_IP>:<MS_PORT>/v1")
    )
    project_name = os.environ.get("PROJECT_NAME", "my_calibration_run")
    video_dir = Path(os.environ.get("VIDEO_DIR", "/path/to/videos")).expanduser()
    config_file = _env_path("CONFIG_FILE")
    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", "resnet")
    run_vggt = _env_bool("RUN_VGGT", False)
    confirm_calibration = _env_bool("CONFIRM_CALIBRATION", False)
    calibration_timeout_seconds = _env_int("CALIBRATION_TIMEOUT_SECONDS", 5400)
    vggt_timeout_seconds = _env_int("VGGT_TIMEOUT_SECONDS", 900)

    repo_root = Path(os.environ.get("REPO_ROOT", Path.cwd())).expanduser()
    projects_dir = Path(os.environ.get("PROJECTS_DIR", repo_root / "projects")).expanduser()
    is_interactive = sys.stdin.isatty()

    for label, path in (
        ("VIDEO_DIR", video_dir),
        ("CONFIG_FILE", config_file),
        ("ALIGNMENT_JSON", alignment_json),
        ("LAYOUT_PNG", layout_png),
        ("GT_ZIP", gt_zip),
    ):
        if path and not path.exists():
            raise RuntimeError(f"{label} set but path not found: {path}")

    if not video_dir.is_dir():
        raise RuntimeError(f"VIDEO_DIR must point to a directory: {video_dir}")

    video_files = sorted(video_dir.glob("cam_*.mp4"))
    _validate_video_files(video_files, video_dir)

    first_level_dirs = sorted(
        (path for path in video_dir.iterdir() if path.is_dir()),
        key=lambda path: path.name,
    )
    scan_dirs = [video_dir, *first_level_dirs, video_dir.parent]
    config_file = _resolve_local(
        config_file,
        ["settings.json", "config.json", "calibration_config.json"],
        scan_dirs,
        "config",
    )
    alignment_json = _resolve_local(
        alignment_json,
        ["alignment_data.json"],
        scan_dirs,
        "alignment",
    )
    layout_png = _resolve_local(
        layout_png,
        ["layout.png"],
        scan_dirs,
        "layout",
    )

    session = requests.Session()
    _check_amc_ready(session, base_url)

    response = session.post(
        f"{base_url}/create_project",
        data={"project_name": project_name},
        timeout=DEFAULT_TIMEOUT,
    )
    _raise_for_status(response, "create_project")
    project_id = _require_field(
        _response_json_object(response, "create_project"),
        "project_id",
        "create_project",
    )
    print(f"[1] Created project: {project_id}")

    with ExitStack() as stack:
        files = []
        for video in video_files:
            handle = stack.enter_context(open(video, "rb"))
            files.append(("files", (video.name, handle, "video/mp4")))
        response = session.post(
            f"{base_url}/upload_video_files/{project_id}",
            files=files,
            timeout=VIDEO_UPLOAD_TIMEOUT_SECONDS,
        )
    _raise_for_status(response, "upload_video_files")
    print(f"[2] Uploaded {len(video_files)} videos")

    if config_file:
        response = session.post(
            f"{base_url}/config/{project_id}",
            data=config_file.read_bytes(),
            headers={"Content-Type": "application/json"},
            timeout=DEFAULT_TIMEOUT,
        )
        _raise_for_status(response, "upload config")
        print(f"[3] Applied calibration config from {config_file.name} (replaces UI Step 3)")
        detector_type = _parse_detector_from_config(config_file, detector_type)

    if alignment_json:
        with open(alignment_json, "rb") as handle:
            response = session.post(
                f"{base_url}/upload_alignment/{project_id}",
                files={"alignment_file": (alignment_json.name, handle, "application/json")},
                timeout=DEFAULT_TIMEOUT,
            )
        _raise_for_status(response, "upload_alignment")
        print(f"[3] Uploaded alignment: {alignment_json.name}")

    if layout_png:
        with open(layout_png, "rb") as handle:
            response = session.post(
                f"{base_url}/upload_layout/{project_id}",
                files={"layout_file": (layout_png.name, handle, "image/png")},
                timeout=DEFAULT_TIMEOUT,
            )
        _raise_for_status(response, "upload_layout")
        print(f"[3] Uploaded layout: {layout_png.name}")

    if gt_zip:
        with open(gt_zip, "rb") as handle:
            response = session.post(
                f"{base_url}/upload_gt_file/{project_id}",
                files={"gt_file": (gt_zip.name, handle, "application/zip")},
                timeout=GT_UPLOAD_TIMEOUT_SECONDS,
            )
        _raise_for_status(response, "upload_gt_file")
        print("[3] Uploaded GT zip")

    if focal_lengths:
        response = session.post(
            f"{base_url}/upload_focal_length/{project_id}",
            data={"focal_length": focal_lengths},
            timeout=DEFAULT_TIMEOUT,
        )
        _raise_for_status(response, "upload_focal_length")
        print(f"[3] 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.")

    if ui_tasks:
        print(f"\n[5] UI action required for project {project_id}:")
        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:
            print("    Continuing with verify_project to confirm the UI uploads.")

    response = session.post(
        f"{base_url}/verify_project/{project_id}",
        timeout=DEFAULT_TIMEOUT,
    )
    _raise_for_status(response, "verify_project")
    verify_payload = _response_json_object(response, "verify_project")
    project_state = _require_string_field(
        verify_payload,
        "project_state",
        "verify_project",
    )
    print(f"[6] Project state: {project_state}")
    if project_state != "READY":
        raise RuntimeError(
            f"verify_project returned {project_state!r}; expected 'READY'. "
            "Confirm videos, alignment, and layout were uploaded successfully."
        )

    print("\n[7] Calibration plan:")
    print(f"    Detector:             {detector_type}")
    print(
        f"    Calibration settings: "
        f"{config_file if config_file else 'UI Step 3 settings/defaults'}"
    )
    print(
        f"    Alignment JSON:       "
        f"{alignment_json if alignment_json else 'UI Step 4/manual_adjustment'}"
    )
    print(
        f"    Layout PNG:           "
        f"{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 RuntimeError("Stopped before calibration.")
    else:
        if not confirm_calibration:
            raise RuntimeError(
                "Non-interactive mode requires explicit confirmation. "
                "Set CONFIRM_CALIBRATION=true to proceed, or run interactively."
            )
        print(
            "    Non-interactive stdin detected; CONFIRM_CALIBRATION=true set; "
            "starting with the plan above."
        )

    response = session.post(
        f"{base_url}/calibrate/{project_id}",
        json={"detector_type": detector_type},
        timeout=DEFAULT_TIMEOUT,
    )
    _raise_for_status(response, "calibrate")
    print(f"[7] Calibration started (detector={detector_type})")

    print("[8] Polling (10-60 min typical)...")
    start_time = time.time()
    last_state = ""
    last_heartbeat = 0.0
    while time.time() - start_time < calibration_timeout_seconds:
        info = _get_project_info(session, base_url, project_id)
        project_state = _project_state(info, "get_project_info")
        minutes, seconds = divmod(int(time.time() - start_time), 60)
        if project_state != last_state or time.time() - last_heartbeat >= 60:
            print(f"    [{minutes:>3}m {seconds:02d}s] {project_state}", flush=True)
            last_state = project_state
            last_heartbeat = time.time()
        if project_state == "COMPLETED":
            print(f"[8] Done in {minutes}m {seconds:02d}s")
            break
        if project_state == "ERROR":
            try:
                response = session.get(
                    f"{base_url}/amc/calibrate/{project_id}/log",
                    timeout=DEFAULT_TIMEOUT,
                )
                _raise_for_status(response, "fetch calibration log")
                log_lines = response.text.splitlines()
                print("    --- last calibration log lines ---")
                for line in log_lines[-20:]:
                    print(f"    {line}")
            except RuntimeError as exc:
                print(f"    warning: {exc}")
            raise RuntimeError(
                f"Calibration entered ERROR state. Full log: "
                f"GET {base_url}/amc/calibrate/{project_id}/log"
            )
        time.sleep(10)
    else:
        raise RuntimeError(
            f"Calibration still running after {int((time.time() - start_time) // 60)} min. "
            "Increase CALIBRATION_TIMEOUT_SECONDS if needed, or inspect "
            f"GET {base_url}/amc/calibrate/{project_id}/log"
        )

    print("\n[9] Results:")
    response = session.get(
        f"{base_url}/result/{project_id}/evaluation_statistics",
        timeout=DEFAULT_TIMEOUT,
    )
    if response.status_code == 200:
        for key, value in _statistics_payload(response, "evaluation_statistics").items():
            print(f"    {key}: {value}")
    elif gt_zip is None:
        print(
            f"    Evaluation statistics unavailable (HTTP {response.status_code}). "
            "Ground truth was not uploaded, so this is expected."
        )
    else:
        raise RuntimeError(
            f"evaluation_statistics failed after GT upload: HTTP {response.status_code}: "
            f"{_response_detail(response)}"
        )

    info = _get_project_info(session, base_url, project_id)
    vggt_state = _vggt_state(info, "get_project_info")
    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")
        print(
            "     To run VGGT refinement later, set up the VGGT model with "
            "amc-setup-calibration-stack and rerun this optional step."
        )

    if run_vggt and vggt_state == "READY":
        response = session.post(
            f"{base_url}/vggt/calibrate/{project_id}",
            timeout=DEFAULT_TIMEOUT,
        )
        _raise_for_status(response, "vggt/calibrate")
        print("\n[10] VGGT started")
        vggt_start_time = time.time()
        while time.time() - vggt_start_time < vggt_timeout_seconds:
            info = _get_project_info(session, base_url, project_id)
            vggt_state = _vggt_state(info, "get_project_info")
            if vggt_state == "COMPLETED":
                print("     VGGT done")
                response = session.get(
                    f"{base_url}/vggt_results/{project_id}/evaluation_statistics",
                    timeout=DEFAULT_TIMEOUT,
                )
                if response.status_code == 200:
                    print("     VGGT evaluation statistics:")
                    for key, value in _statistics_payload(
                        response, "vggt evaluation_statistics"
                    ).items():
                        print(f"        {key}: {value}")
                else:
                    raise RuntimeError(
                        f"VGGT evaluation_statistics failed: HTTP {response.status_code}: "
                        f"{_response_detail(response)}"
                    )
                break
            if vggt_state == "ERROR":
                raise RuntimeError("VGGT refinement entered ERROR state")
            time.sleep(10)
        else:
            raise RuntimeError(
                f"VGGT refinement still running after {vggt_timeout_seconds // 60} min. "
                "Increase VGGT_TIMEOUT_SECONDS if needed and rerun the optional step."
            )

    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 to view the overlay"
    )
    print(
        f"    Final camera parameters: "
        f"{projects_dir}/project_{project_id}/output/multi_view_results/BA_output/"
        "results_ba/refined/camInfo_XX.yaml"
    )
    return 0


if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except requests.RequestException as exc:
        print(f"ERROR: network request failed: {exc}", file=sys.stderr)
        raise SystemExit(2) from exc
    except KeyboardInterrupt:
        print("ERROR: interrupted", file=sys.stderr)
        raise SystemExit(1) from None
    except (RuntimeError, TypeError, ValueError) as exc:
        print(f"ERROR: {exc}", file=sys.stderr)
        raise SystemExit(1) from None

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 Python

Security

What our scanner noticed· Medium risk

  • Large base64-encoded blobs
  • 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-video-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-video-calibration.zip