Technical reference
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.
- Define the required inputs, camera, interval, and outputs.
- Read the SDK and author one recipe for that task.
- Use estimate_annotation with the selected clip IDs and script.
- Start the estimated job with run_annotation, then poll get_job with kind="annotation".
- 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.
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.
# 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.
passExample: 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.
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.
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 -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.mp4Run 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.
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.
