TGraphX › Insights › Video Analysis JSON in Python: Validate, Query and Compare Results
← Back to Insights

Video Analysis JSON in Python: Validate, Query and Compare Results

Topic: Vision, multimodal and domain applications

A video analysis report is a file of model output with timestamps. Before a database, dashboard or test depends on it, check its structure, check that its parts agree with each other, load it into tables joined on the frame index, and store the run settings that the file leaves out. This tutorial does each of those steps in Python.

The reports come from AI-Powered Video Analyzer v1.1.0 (commit 313448a, observed on 2026-11-27). The analyzer publishes no schema of its own, so the one below was derived from what that version writes and is not an official contract.

Get a report

The command line writes <video name>_analysis.json into the output directory, together with a Markdown version and report.txt, a copy of the Markdown that the next run overwrites. JSON and Markdown cannot be switched off separately.

bash
ai-video-analyzer analyze video.mp4 --preset balanced \
    --no-captioning --no-audio-events --no-summarization -o results

One warning if you install it for this: the README's .[vision] install does not include PyTorch or Transformers, and a run then writes a well formed report with zero detections and exits successfully. Add both packages.

The tested commands are in analyzing a video locally from install to first report.

From Python, analyze_video(config) writes the same files and also returns a report object with to_dict(), to_json() and to_markdown(), so you can validate the data before it enters your own storage.

What a report contains

Structure of one analysis report

Report rootRunsettingsPer framerecordsdetectionscaptionsText andstatusBoxes perframeholds
The same diagram as a table
boxarrows todetail
Report rootRun settings; Per frame records; detections; captions; Text and statusOne JSON object per analyzed video.
Run settings—Path, duration, size, frame counts, backend, preset, strategy, model_ids, timings.
Per frame recordsBoxes per frame (holds)frame_observations: one record per sampled frame.
detections—Flat list of every box in the run.
captions—One sentence per captioned frame; may be empty.
Text and status—transcript, summary, audio_events, limitations.
Boxes per frame—The same box records, grouped by frame.

7 boxes and 6 arrows. No box is selected.

Step through the parts. Detections appear twice, nested under each frame and again as one flat list. A schematic drawn from the author's description: nothing is executed or measured.

All top level keys were present in every report examined; optional stages leave empty strings, lists or objects instead of removing keys.

Key Type Notes on presence
video_path, backend, preset, frame_strategy string always
duration_sec, fps number always
width, height, frame_count, sampled_frame_count integer always
model_ids object: detector, whisper, blip, ollama always
timings object: stage name to seconds keys depend on the stages that ran
transcript, transcript_language, summary string always; may be empty or unknown
audio_events object: name to list of strings always; may be {}
limitations array of strings always; often empty
frame_observations array frame_index, timestamp_sec, reason, scene_score, motion_score, detections
detections array label, score, bbox_xyxy (four numbers), frame_index, timestamp_sec, backend, model_id
captions array frame_index, timestamp_sec, caption

bbox_xyxy is [x1, y1, x2, y2] in pixels of the original frame.

A small real sample

So that every block below runs on its own, the first one rebuilds an excerpt of two real reports of the same 9 second test clip (three public domain or CC0 photographs with a synthetic narration). One used the balanced preset, the other quality. Only three of the nine sampled frames are kept; the boxes, scores and transcript are copied unchanged.

python
# Excerpt of two real reports (balanced and quality presets, same 9 s test clip):
# frames 0, 90 and 180 only. sampled_frame_count is set to 3 to match; timings are omitted.
FRAMES = {0: (0.0, "periodic", 0.0), 90: (3.0, "scene_change", 67.37), 180: (6.0, "scene_change", 54.09)}
BALANCED = {
    0: [("person", .9534, [53.4, .2, 503.3, 358.7]), ("bowl", .5727, [159.3, 154.0, 428.4, 356.0]),
        ("clock", .4821, [159.3, 154.0, 428.4, 356.0])],
    90: [("cat", .9674, [.3, .3, 638.6, 359.3])],
    180: [("diningtable", .8674, [-.1, .7, 640.1, 357.7]), ("spoon", .739, [389.3, 61.3, 510.4, 358.9]),
          ("cup", .7193, [205.4, 2.5, 494.0, 334.0]), ("spoon", .5779, [389.2, 61.1, 510.5, 359.0]),
          ("spoon", .4866, [206.3, 144.4, 319.4, 353.6]), ("spoon", .468, [233.7, 254.3, 315.3, 354.3]),
          ("bowl", .4051, [206.0, 2.9, 491.3, 268.8]), ("spoon", .3903, [390.5, 198.4, 486.6, 359.1])]}
QUALITY = {
    0: [("person", .928, [45.7, .1, 508.9, 359.5]), ("baseball bat", .3072, [554.9, -0.0, 614.8, 349.2])],
    90: [("cat", .9392, [.2, .2, 635.4, 359.7]), ("cat", .3201, [.5, .3, 640.5, 359.6]),
         ("bed", .3083, [.5, .3, 640.5, 359.6])],
    180: [("cup", .9669, [205.7, 2.4, 490.8, 353.0]), ("spoon", .9615, [390.3, 61.4, 510.8, 358.6]),
          ("diningtable", .9011, [.3, -.1, 640.0, 358.7])]}


def sample_report(boxes, preset, model):
    frames = []
    for index, (t, reason, change) in FRAMES.items():
        found = [{"label": label, "score": score, "bbox_xyxy": box, "frame_index": index,
                  "timestamp_sec": t, "backend": "visionservex", "model_id": model}
                 for label, score, box in boxes[index]]
        frames.append({"frame_index": index, "timestamp_sec": t, "reason": reason,
                       "scene_score": change, "motion_score": change, "detections": found})
    return {
        "video_path": "cc0_slides.mp4", "duration_sec": 9.0, "fps": 30.0, "width": 640,
        "height": 360, "frame_count": 270, "sampled_frame_count": len(frames),
        "backend": "visionservex",
        "model_ids": {"detector": model, "whisper": "base", "blip": "disabled", "ollama": "disabled"},
        "preset": preset, "frame_strategy": "adaptive", "timings": {},
        "transcript": " This is a synthetic narration, first departure, then a cat, and finally a cup of coffee.",
        "transcript_language": "en", "audio_events": {}, "frame_observations": frames,
        "detections": [d for f in frames for d in f["detections"]],
        "captions": [], "summary": "", "limitations": []}


balanced = sample_report(BALANCED, "balanced", "dfine-s")
quality = sample_report(QUALITY, "quality", "dfine-m")

Validate the structure

JSON Schema Draft 2020-12 describes types and required keys. The code uses the jsonschema package (pip install jsonschema; version 4.26.0 here) and writes the schema to a file, so that other programs can share it.

python
import json

from jsonschema import Draft202012Validator


def record(**properties):
    return {"type": "object", "additionalProperties": False,
            "required": list(properties), "properties": properties}


def array(items, **extra):
    return {"type": "array", "items": items, **extra}


text = {"type": "string"}
number = {"type": "number", "minimum": 0}
count = {"type": "integer", "minimum": 0}
detection = record(
    label=text, score={"type": "number", "minimum": 0, "maximum": 1},
    bbox_xyxy=array({"type": "number"}, minItems=4, maxItems=4),
    frame_index=count, timestamp_sec=number, backend=text, model_id=text)
frame = record(
    frame_index=count, timestamp_sec=number,
    reason={"enum": ["uniform", "periodic", "scene_change", "motion", "max_interval_fallback"]},
    scene_score=number, motion_score=number, detections=array(detection))
SCHEMA = {"$schema": "https://json-schema.org/draft/2020-12/schema", **record(
    video_path=text, duration_sec=number, fps={"type": "number", "exclusiveMinimum": 0},
    width=count, height=count, frame_count=count, sampled_frame_count=count, backend=text,
    model_ids=record(detector=text, whisper=text, blip=text, ollama=text),
    preset=text, frame_strategy=text, timings={"type": "object", "additionalProperties": number},
    transcript=text, transcript_language=text,
    audio_events={"type": "object", "additionalProperties": array(text)},
    frame_observations=array(frame), detections=array(detection),
    captions=array(record(frame_index=count, timestamp_sec=number, caption=text)),
    summary=text, limitations=array(text))}

Draft202012Validator.check_schema(SCHEMA)
with open("video-report.schema.json", "w", encoding="utf-8") as fh:
    json.dump(SCHEMA, fh, indent=2)                    # keep this file under version control
validator = Draft202012Validator(SCHEMA)


def schema_errors(report):
    return [f"{'/'.join(map(str, e.absolute_path))}: {e.message}" for e in validator.iter_errors(report)]


print("balanced:", schema_errors(balanced))
broken = {**balanced, "sampled_frame_count": "3", "device": "cuda"}
broken.pop("limitations")
for message in sorted(schema_errors(broken)):
    print(message)
text
balanced: []
: 'limitations' is a required property
: Additional properties are not allowed ('device' was unexpected)
sampled_frame_count: '3' is not of type 'integer'

additionalProperties: false is a deliberate choice. When a later version adds a key, validation fails and you decide what to do, instead of silently ignoring something that may change the meaning of other fields. All 32 report files collected from test runs of v1.1.0 validated against this schema. None of those runs had populated sound labels, so treat the audio_events part as the least tested.

Add the rules a schema cannot express

Some parts of the contract relate fields to each other: the frame count to the number of frame records, the flat detection list to the nested one, caption indices to sampled frames. A few lines of Python cover them. The second function deals with two fields whose text is not always what the name suggests.

python
def integrity_errors(r):
    """Rules that relate one field to another, which JSON Schema does not express."""
    errors, frames = [], r["frame_observations"]
    if len(frames) != r["sampled_frame_count"]:
        errors.append("sampled_frame_count differs from the number of frame records")
    if [d for f in frames for d in f["detections"]] != r["detections"]:
        errors.append("nested and flat detections differ")
    indices = [f["frame_index"] for f in frames]
    if indices != sorted(set(indices)):
        errors.append("frame indices are not strictly increasing")
    if any(c["frame_index"] not in indices for c in r["captions"]):
        errors.append("a caption refers to a frame that was not sampled")
    if any(x2 <= x1 or y2 <= y1 for x1, y1, x2, y2 in (d["bbox_xyxy"] for d in r["detections"])):
        errors.append("empty or inverted box")
    return errors


def clean_text_fields(r):
    """Sound labels and summary with status markers removed."""
    events = {name: times for name, times in r["audio_events"].items() if times}
    summary = r["summary"]
    if not summary or summary.startswith("LLM summarization unavailable") or "\x1b" in summary:
        summary = None
    return events, summary


print(integrity_errors(balanced))
damaged = {**balanced, "detections": balanced["detections"][:-1], "sampled_frame_count": 4}
print(schema_errors(damaged), integrity_errors(damaged))
failed = {**balanced, "audio_events": {"error": []},
          "summary": "LLM summarization unavailable. Install and start Ollama."}
print(schema_errors(failed), clean_text_fields(failed))
text
[]
[] ['sampled_frame_count differs from the number of frame records', 'nested and flat detections differ']
[] ({}, None)

The damaged copy passes the schema and fails the integrity rules. All 32 files passed both. The last line shows why validity is not success: a run whose sound stage and summary both failed is still schema-valid. At v1.1.0:

  • audio_events can hold model_not_found, unavailable, silence or error with an empty list. The audio-event stage returns no real sound labels in this version (checked 2026-11-27), so keep only keys that have times. Seven of the 32 files held such a status key.
  • A failed language model call stores a sentence beginning LLM summarization unavailable. in summary.
  • With Ollama 0.20.5, a stored summary contained terminal escape sequences and repeated word fragments. Removing the codes alone leaves the fragments, so the function discards such a summary.
  • Most stage failures are not listed in limitations. An empty list there does not mean that everything ran. Three of the 32 files had a detector configured and no detections.

Load the reports into SQLite

SQLite ships with Python. Use one table for runs and one per record type, and join on (run, frame_index). Do not join on timestamp_sec: frame and detection times are rounded to milliseconds, caption times are not. The loader refuses a report that fails either check, and each report goes in as one transaction.

python
import sqlite3

db = sqlite3.connect(":memory:")                       # use a file path to keep it
db.executescript("""
    CREATE TABLE runs(run TEXT PRIMARY KEY, video TEXT, preset TEXT, model TEXT,
                      strategy TEXT, sampled INTEGER, summary TEXT);
    CREATE TABLE frames(run TEXT, frame_index INTEGER, t REAL, reason TEXT,
                        PRIMARY KEY (run, frame_index));
    CREATE TABLE detections(run TEXT, frame_index INTEGER, label TEXT, score REAL,
                            x1 REAL, y1 REAL, x2 REAL, y2 REAL);
""")


def load(db, run, r):
    errors = schema_errors(r) or integrity_errors(r)
    if errors:
        raise ValueError(f"{run}: {errors}")
    with db:                                           # one transaction per report
        db.execute("INSERT INTO runs VALUES (?,?,?,?,?,?,?)",
                   (run, r["video_path"], r["preset"], r["model_ids"]["detector"],
                    r["frame_strategy"], r["sampled_frame_count"], clean_text_fields(r)[1]))
        db.executemany("INSERT INTO frames VALUES (?,?,?,?)",
                       [(run, f["frame_index"], f["timestamp_sec"], f["reason"])
                        for f in r["frame_observations"]])
        db.executemany("INSERT INTO detections VALUES (?,?,?,?,?,?,?,?)",
                       [(run, d["frame_index"], d["label"], d["score"], *d["bbox_xyxy"])
                        for d in r["detections"]])


load(db, "balanced", balanced)
load(db, "quality", quality)

window = """SELECT f.t, d.label, d.score FROM frames f
            JOIN detections d ON d.run = f.run AND d.frame_index = f.frame_index
            WHERE f.run = ? AND f.t >= ? AND f.t < ? AND d.score >= 0.5
            ORDER BY f.t, d.score DESC"""
print(db.execute(window, ("balanced", 3.0, 7.0)).fetchall())

best = """SELECT d.label, f.t, MAX(d.score) FROM detections d
          JOIN frames f ON f.run = d.run AND f.frame_index = d.frame_index
          WHERE d.run = ? AND d.score >= ? GROUP BY d.label ORDER BY f.t, d.label"""
print(db.execute(best, ("balanced", 0.5)).fetchall())

across = """SELECT r.preset, r.model, COUNT(*) AS boxes,
                   COUNT(DISTINCT d.frame_index) AS frames_with_boxes
            FROM runs r JOIN detections d ON d.run = r.run
            WHERE d.score >= ? GROUP BY r.run ORDER BY r.preset"""
print(db.execute(across, (0.5,)).fetchall())
text
[(3.0, 'cat', 0.9674), (6.0, 'diningtable', 0.8674), (6.0, 'spoon', 0.739), (6.0, 'cup', 0.7193), (6.0, 'spoon', 0.5779)]
[('bowl', 0.0, 0.5727), ('person', 0.0, 0.9534), ('cat', 3.0, 0.9674), ('cup', 6.0, 0.7193), ('diningtable', 6.0, 0.8674), ('spoon', 6.0, 0.739)]
[('balanced', 'dfine-s', 7, 3), ('quality', 'dfine-m', 5, 3)]

The three queries answer different questions: what was detected between 3 and 7 seconds; which sampled frame is the best scoring example of each label, a handy index of representative moments (SQLite takes the other columns from the row that holds the MAX); and how two runs differ in total. The last one counts boxes and frames with boxes. Neither is a number of objects, because the analyzer does not track anything from one frame to the next.

On the full balanced report (nine frames, not the excerpt) the boxes distribute like this:

Boxes per label over nine sampled frames, split by score

Stacked bars of box counts per label, split at a score of one half. Spoon has twelve boxes, mostly below it; bowl has five; person, clock, cat, dining table and cup have three each; refrigerator has two, both below it.

1. score >= 0.52. score < 0.5

spoon: 12 boxes ×1.00

bowl: 5 boxes ×0.42

person: 3 boxes ×0.25

clock: 3 boxes ×0.25

cat: 3 boxes ×0.25

diningtable: 3 boxes ×0.25

cup: 3 boxes ×0.25

refrigerator: 2 boxes ×0.17

Each × compares with spoon. Shown: total.

Values (boxes)
barscore >= 0.5score < 0.5total
spoon4812
bowl325
person303
clock213
cat303
diningtable303
cup303
refrigerator022

Showing the totals: spoon 12 boxes; bowl 5 boxes; person 3 boxes; clock 3 boxes; cat 3 boxes; diningtable 3 boxes; cup 3 boxes; refrigerator 2 boxes. Ratios are to spoon.

These are boxes summed over sampled frames, not objects. Measured values, as recorded by the author: Analyzer v1.1.0, balanced preset (dfine-s), VisionServeX 3.23.0, 9 s clip of three public domain or CC0 stills, 9 sampled frames. The figure only displays and compares them. Bars start at zero; totals and ratios are computed from the values.

A timeline built from the full balanced report

Sampled framespersonbowlclockcatcup and diningtable02468seconds
What each lane holds at the selected time
laneholds
Sampled framesa sampled frame
personperson
bowlbowl
clockclock
catnothing
cup and diningtablenothing
Events, with the sampled frames inside each visual event
eventlanetimeSampled frames
personperson0 s—
personperson1 s—
personperson2 s—
bowlbowl0 s—
bowlbowl1 s—
bowlbowl2 s—
bowlbowl6 s—
bowlbowl7 s—
clockclock0 s—
clockclock1 s—
clockclock2 s—
catcat3 s—
catcat4 s—
catcat5 s—
bothcup and diningtable6 s—
bothcup and diningtable7 s—
bothcup and diningtable8 s—

Sampled frames: 9 frames in 9 s (1 per second).

At 0 s. Sampled frames: a sampled frame. person: person. bowl: bowl. clock: clock. cat: nothing. cup and diningtable: nothing.

Each point is a sampled frame that holds the label. Nothing is known between the points. Measured times and events, as recorded by the author: frame_observations of the same balanced report; analyzer v1.1.0, dfine-s, confidence 0.3. The figure only displays and compares them.

The first slide is a portrait with no clock and no bowl in it. The chart and the timeline faithfully show what the detector reported, which is not the same as what was there.

Export to CSV and WebVTT

CSV suits spreadsheets and data frames. WebVTT lets a video player show text at given times. A cue has a start and a later end, which can be written as HH:MM:SS.mmm --> HH:MM:SS.mmm. Cue text must escape & and < and must not contain -->; escaping > as well takes care of the last rule.

python
import csv


def write_csv(r, path):
    names = ["frame_index", "timestamp_sec", "label", "score", "x1", "y1", "x2", "y2", "model_id"]
    with open(path, "w", newline="", encoding="utf-8") as fh:
        out = csv.DictWriter(fh, fieldnames=names, extrasaction="ignore")
        out.writeheader()
        for d in r["detections"]:
            out.writerow({**d, **dict(zip(("x1", "y1", "x2", "y2"), d["bbox_xyxy"]))})


def vtt_time(seconds):
    ms = round(seconds * 1000)
    hours, ms = divmod(ms, 3_600_000)
    minutes, ms = divmod(ms, 60_000)
    secs, ms = divmod(ms, 1000)
    return f"{hours:02d}:{minutes:02d}:{secs:02d}.{ms:03d}"


def to_webvtt(r, min_score=0.5):
    frames = r["frame_observations"]
    captions = {c["frame_index"]: c["caption"] for c in r["captions"]}
    lines = ["WEBVTT", ""]
    for n, f in enumerate(frames):
        start = f["timestamp_sec"]
        end = frames[n + 1]["timestamp_sec"] if n + 1 < len(frames) else r["duration_sec"]
        labels = dict.fromkeys(d["label"] for d in f["detections"] if d["score"] >= min_score)
        body = captions.get(f["frame_index"]) or ", ".join(labels)
        if body and end > start:
            body = " ".join(body.split())
            body = body.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
            lines += [f"{vtt_time(start)} --> {vtt_time(end)}", body, ""]
    return "\n".join(lines)


write_csv(balanced, "detections.csv")
with open("detections.csv", encoding="utf-8") as fh:
    print("".join(fh.readlines()[:3]))
print(to_webvtt(balanced))
text
frame_index,timestamp_sec,label,score,x1,y1,x2,y2,model_id
0,0.0,person,0.9534,53.4,0.2,503.3,358.7,dfine-s
0,0.0,bowl,0.5727,159.3,154.0,428.4,356.0,dfine-s

WEBVTT

00:00:00.000 --> 00:00:03.000
person, bowl

00:00:03.000 --> 00:00:06.000
cat

00:00:06.000 --> 00:00:09.000
diningtable, spoon, cup

The end of each cue is the time of the next sample. That is a display convention, not a finding: the report says nothing about what was visible in between. If you show these cues to people, say that they come from sampled frames.

Format Written by Good for What it drops or distorts
JSON analyzer programs, archiving holds everything the report object holds
Markdown, report.txt analyzer reading boxes; keeps the top 20 labels and first 15 captions
SQLite your code queries across runs fields you do not load
CSV your code spreadsheets nesting, run settings
WebVTT your code viewing alongside the video boxes and scores; implies continuity

Compare two runs

Comparing presets, thresholds or versions by total box count hides where they differ. Match boxes instead, frame by frame, by label and overlap. Intersection over union of two boxes is:

text
IoU(a, b) = area(a ∩ b) / area(a ∪ b)

The function below takes the boxes of the first run from the highest score down and pairs each with the unused box of the same label that overlaps it most, if the IoU is at least 0.5. It refuses runs that sampled different frames, because then the differences would mix sampling with detection.

python
from collections import Counter


def iou(a, b):
    width = min(a[2], b[2]) - max(a[0], b[0])
    height = min(a[3], b[3]) - max(a[1], b[1])
    overlap = max(width, 0) * max(height, 0)
    union = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - overlap
    return overlap / union if union > 0 else 0.0


def compare(a, b, min_score=0.0, min_iou=0.5):
    fa = {f["frame_index"]: f["detections"] for f in a["frame_observations"]}
    fb = {f["frame_index"]: f["detections"] for f in b["frame_observations"]}
    if fa.keys() != fb.keys():
        raise ValueError("the two runs sampled different frames")
    matched, only_a, only_b = 0, Counter(), Counter()
    for index in sorted(fa):
        left = sorted((d for d in fa[index] if d["score"] >= min_score), key=lambda d: -d["score"])
        right = [d for d in fb[index] if d["score"] >= min_score]
        for d in left:
            same = [e for e in right if e["label"] == d["label"]]
            best = max(same, key=lambda e: iou(d["bbox_xyxy"], e["bbox_xyxy"]), default=None)
            if best is not None and iou(d["bbox_xyxy"], best["bbox_xyxy"]) >= min_iou:
                matched += 1
                right.remove(best)
            else:
                only_a[d["label"]] += 1
        only_b.update(e["label"] for e in right)
    return matched, dict(only_a), dict(only_b)


for threshold in (0.0, 0.5):
    matched, only_balanced, only_quality = compare(balanced, quality, min_score=threshold)
    print(f"score >= {threshold}: matched {matched}")
    print("   only balanced:", only_balanced)
    print("   only quality: ", only_quality)
text
score >= 0.0: matched 5
   only balanced: {'bowl': 2, 'clock': 1, 'spoon': 4}
   only quality:  {'baseball bat': 1, 'cat': 1, 'bed': 1}
score >= 0.5: matched 5
   only balanced: {'bowl': 1, 'spoon': 1}
   only quality:  {}

On the two full reports, balanced had 34 boxes and quality 21, of which 15 matched. Only balanced had 9 spoon, 5 bowl, 3 clock and 2 refrigerator boxes; only quality had 2 spoon, 2 bed, 1 baseball bat and 1 cat. With a minimum score of 0.5 on both sides, all 15 quality boxes found a partner and 6 balanced boxes did not.

Agreement is not accuracy. Neither run is a reference: two models can agree on a mistake. To measure accuracy you need labelled boxes, with those as the second "run" and precision and recall computed from the same matching.

Use the comparison as a regression check

Do not compare two reports with exact equality, even when you expect the same result. In test runs of the balanced preset on the same clip, installing torchvision changed scores by up to 0.0032 and box edges by up to 0.3 pixels, and running on the CPU instead of the GPU changed scores by up to 0.0085 and edges by up to 0.2 pixels. In both pairs the files differed, while compare(old, new, min_iou=0.9) matched all 34 boxes and left nothing over.

That suggests a simple test for an upgrade of the analyzer or of its libraries: run a fixed clip before and after, then require both difference counters to be empty.

python
matched, only_old, only_new = compare(balanced, balanced, min_iou=0.9)
print(matched, "matched; unmatched:", only_old, only_new)
assert not only_old and not only_new
text
12 matched; unmatched: {} {}

Replace the two arguments with your stored report and the new one. A box scoring very close to the 0.3 floor can still appear on one machine and not on another, so decide beforehand whether to compare above a slightly higher min_score. The check says that behaviour did not change, not that it is correct.

Record what the report does not

The report has no schema version, run date, device, library or checkpoint revision, confidence threshold, sampler parameters or frame budget. Two files with the same preset can therefore differ for reasons you cannot recover from them. Write a sidecar file at the moment of the run:

python
import hashlib
import json
import platform
from datetime import datetime, timezone
from importlib import metadata
from pathlib import Path


def sha256(path):
    return hashlib.sha256(Path(path).read_bytes()).hexdigest()


def installed(name):
    try:
        return metadata.version(name)
    except metadata.PackageNotFoundError:
        return None


def write_manifest(report_path, video_path, settings):
    manifest = {
        "report_sha256": sha256(report_path),
        "video_sha256": sha256(video_path),
        "recorded_utc": datetime.now(timezone.utc).isoformat(timespec="seconds"),
        "python": platform.python_version(),
        "packages": {n: installed(n) for n in (
            "ai-powered-video-analyzer", "visionservex", "torch", "transformers",
            "opencv-python-headless", "openai-whisper")},
        "settings": settings,
    }
    Path(report_path).with_suffix(".manifest.json").write_text(json.dumps(manifest, indent=2))
    return manifest


Path("run_analysis.json").write_text(json.dumps(balanced))
Path("video.bin").write_bytes(b"stand-in for the video file")
manifest = write_manifest("run_analysis.json", "video.bin", {
    "preset": "balanced", "confidence": 0.3, "frame_strategy": "adaptive", "target_fps": 1.0,
    "scene_threshold": 30.0, "motion_threshold": 5.0, "max_frames": 2000, "device": "cuda"})
print(sorted(manifest))

Record the settings you actually passed, and for the device the one you requested: an unavailable device falls back to the CPU without being recorded. The hash ties the sidecar to one video even if files are renamed. Note also that video_path is stored exactly as you gave it, so a report can reveal local directory names, and it contains the transcript. Review both before sharing a report.

Common interpretation errors

Error Why it is wrong Do instead
Counting boxes as objects no tracking; one object can get several boxes in a frame report frames that contain the label
Comparing counts between videos the sampler takes more frames where there is motion divide by sampled frames, and state the sampling
Reading an empty list as "nothing there" stages can fail silently check that each stage you rely on produced something
Treating every audio_events key as a sound some are status keys filter them out
Showing summary as it is stored may be a placeholder or contain escape codes discard it in either case
Assuming times are presentation times they are frame index divided by frame rate for variable frame rate, map indices through ffprobe
Assuming boxes lie inside the image they are not clipped clip before cropping

For what the gaps between samples allow you to claim, see how AI analyzes an entire video.

To turn these records into a cited, windowed summary with a local model, see summarizing a video with timestamped evidence.

The same habit of keeping settings next to results applies to model experiments; designing a graph experiment report works through it for graph learning.

References