Skip to content
Interlatent/Documentation
Ivy/Technical reference/Python recipes & ffmpeg

Python recipes & ffmpeg

Run repeatable measurements and video transformations with annotate(clip, ctx), then save outputs for review.

How a recipe runs

An annotation recipe is a Python function named annotate(clip, ctx). Ivy runs the same function for each selected clip. The clip provides recording metadata; ctx provides frame access, model operations, annotation helpers, and artifact output. Ask your agent to read get_annotation_sdk for the current API before writing a recipe.

  1. Define the required inputs, camera, interval, and outputs.
  2. Read the SDK and author one recipe for that task.
  3. Use estimate_annotation with the selected clip IDs and script.
  4. Start the estimated job with run_annotation, then poll get_job with kind="annotation".
  5. Inspect the resulting tracks and artifacts. Retry failed clips only.

Example: measure brightness

This deterministic recipe samples frames and writes mean grayscale brightness as a scalar track. It requires no vision-model calls. Values are in the 0–255 grayscale range; this measures image brightness, not task success or image quality.

Brightness recipepython
def annotate(clip, ctx):
    times, values = ctx.brightness(every_n=5)
    return {
        "tracks": [{
            "name": "mean_brightness",
            "kind": "scalar",
            "times": [float(t) for t in times],
            "values": [float(v) for v in values],
        }],
        "summary": "Mean grayscale brightness, every fifth frame.",
    }

Frames, intervals, and camera selection

ctx.frames yields a timestamp in seconds and an OpenCV BGR frame. Set camera explicitly when the task depends on a particular view. An integer every_n strides through source frames; every_n=None with max_frames spreads a finite set across the requested interval. Report this sampling when interpreting a result.

Frame samplingpython
# Inside annotate(clip, ctx). Choose a name from ctx.cameras.
camera = ctx.cameras[0]
for t, frame_bgr in ctx.frames(
    camera=camera,
    t0=0,
    t1=min(10.0, clip.duration_s),
    every_n=None,
    max_frames=8,
):
    # Compute a deterministic measurement from this frame.
    pass

Example: create a separate excerpt

ctx.trim creates a frame-exact H.264 MP4 artifact by default. The end of the interval is exclusive. Name the output so you can find it in the clip’s artifact list. Reusing that name replaces the artifact produced under that name.

Trim recipepython
def annotate(clip, ctx):
    start = 12.0
    end = min(24.0, clip.duration_s)
    if end <= start:
        raise ValueError("This recording has no frames after 12 seconds")

    ctx.trim(start, end, name="excerpt_12_24", in_place=False)
    return {
        "summary": f"Created an excerpt from {start:.2f} to {end:.2f}s."
    }

Example: render timestamps onto a view

ctx.render_video calls a frame-processing function and saves the returned frames as a separate video view. Output dimensions must remain constant. The example renders only the first ten seconds and uses each frame’s source timestamp for the text.

Timestamp overlay recipepython
import cv2

def annotate(clip, ctx):
    def draw_timestamp(t, frame_bgr):
        output = frame_bgr.copy()
        cv2.putText(
            output, f"{t:.2f}s", (20, 36),
            cv2.FONT_HERSHEY_SIMPLEX, 0.8,
            (255, 255, 255), 2, cv2.LINE_AA,
        )
        return output

    ctx.render_video(
        "timestamp_preview", draw_timestamp,
        every_n=1, t0=0, t1=min(10.0, clip.duration_s),
    )
    return {"summary": "Rendered source timestamps on a separate view."}

ffmpeg on a downloaded video

The following shell command runs in your own terminal or coding-agent environment after you download the input video. It extracts source seconds 12–24, resizes to 640 pixels wide, re-encodes H.264, removes audio, and writes a browser-playable MP4. Re-encoding avoids the keyframe-boundary limitations of stream-copy cuts.

ffmpeg excerpt commandshell
ffmpeg -n -i input.mp4 -ss 12 -t 12 \
  -vf "scale=640:-2" \
  -c:v libx264 -crf 20 -preset medium \
  -pix_fmt yuv420p -movflags +faststart -an \
  excerpt.mp4

Run ffmpeg inside a recipe

For a transformation beyond the video helpers, a Python recipe can invoke ffmpeg on the clip’s available media and save the result with ctx.save_file. The example creates a one-frame-per-second preview and saves it as a downloadable clip artifact. Use ctx.render_video when you need a processed video registered as a selectable view.

ffmpeg preview recipepython
from pathlib import Path
import subprocess
import tempfile

def annotate(clip, ctx):
    with tempfile.TemporaryDirectory() as directory:
        output = Path(directory) / "preview.mp4"
        subprocess.run([
            "ffmpeg", "-n", "-loglevel", "error",
            "-i", str(clip.path), "-t", "10",
            "-vf", "fps=1,scale=640:-2",
            "-c:v", "libx264", "-pix_fmt", "yuv420p",
            "-movflags", "+faststart", "-an", str(output),
        ], check=True, capture_output=True, timeout=240)
        ctx.save_file("preview.mp4", output.read_bytes())
    return {"summary": "Saved a 1 fps preview of the first 10 seconds."}

Return tracks and save files

Return scalar tracks for measurements, span tracks for labeled intervals, and events for instants. ctx.save_file saves JSON, text, bytes, or supported image arrays as clip artifacts. ctx.read_file reads files supplied through the project’s Files panel. After the job finishes, inspect annotations and request artifact links; a file on a temporary path is not a delivered result.

Start hereQuickstartImport a Hugging Face dataset and analyze an episode with Ivy.Start hereConnect an agentOfficial setup for Interlatent’s Ivy at interlatent.com. Connect your agent to shared visual data, hosted compute, and saved analysis through Ivy.Start hereTrain vision models with an agentUse Ivy by Interlatent for vision model training and evaluation. Training access is gated; contact team@interlatent.com to request access.User manualImport a datasetImport public or private Hugging Face datasets, video files, or recordings from connected storage.User manualAccess datasets from a coding agentDescribe the dataset you want, ask questions about its recordings, and turn the answers into a selection for vision model work with your MCP-compatible coding agent.User manualAmazon S3Connect a bucket, import a small recording collection, and verify that it is ready for analysis.User manualGoogle DriveShare a folder with Ivy, review the import plan, and bring the recordings into a project.User manualGoogle Cloud StorageGrant bucket access, verify the connection, and import recordings from a gs:// path.User manualFiles & video linksImport a single video, a direct download link, or a local recording directory.User manualFind & tag videosFind recordings by their visual content, save a selection as tags, and reuse it in later analysis.User manualObject trackingDetect objects, track their masks with SAM, and inspect the result before measuring motion or counting passages.User manualModels & analysisChoose the method for your question: actions, object locations, masks, or classifications.User manualSubtask segmentation & semantic trimmingPrompt Ivy to divide a video into meaningful steps, steer the boundaries and labels, and export selected sections as video clips.User manualTrim & process videoTrim video by timestamps or meaningful action sections, create processed views, and keep source and output times clear.User manualRun your first experimentsRun action labeling and object tracking on a small sample, then compare and apply the results.User manualReview & exportInspect annotations, correct errors, and export a Dataset snapshot.Technical referenceCore conceptsProjects, recordings, annotations, pipelines, and Dataset snapshots.Technical referencePython recipes & ffmpegRun repeatable measurements and video transformations with annotate(clip, ctx), then save outputs for review.Technical referenceQueries & tag operationsQuery saved annotations and recorded per-frame data with SQL, then use the matching clip IDs for tagging or export.Technical referenceSource connectionsConnection states, cloud permissions, import tools, and recovery for source workflows.Technical referenceTool referencePublic MCP tools grouped by task. Your connected agent provides the current schemas and availability.Technical referenceTroubleshootingResolve common connection, import, analysis, and access errors.ResourcesRights & data FAQAnswers about private video data, vision model ownership, provider handling, evaluation, and trial pricing with Interlatent.