TGraphX › Insights › Local Video Summarization with Ollama: Building Timestamped Evidence
← Back to Insights

Local Video Summarization with Ollama: Building Timestamped Evidence

Topic: Vision, multimodal and domain applications

A text model served by Ollama does not watch your video. It rewrites whatever text you hand it. To summarize a video locally in a way you can check, build that text deliberately: short evidence records with identifiers and times, in windows that fit the model's context, with a rule that every sentence of the answer must cite records. Then reject answers that break the rule, and remember that a valid citation makes a sentence checkable, not true.

This article builds such a summarizer as an add-on that reads the JSON report of a local multimodal video analyzer, AI-Powered Video Analyzer. The add-on is not part of that package. The package behaviour described here is that of v1.1.0 (commit 313448a), checked on 2026-11-27.

To produce a report first, follow analyzing a video locally from install to first report.

What the analyzer sends to Ollama today

The built-in summary stage runs ollama run <model> and writes a fixed instruction and an evidence text to its input. The model receives text only, even if it can accept images. The evidence is the whole transcript, the keys of the audio-event field, counts of the ten most frequent detector labels and the first five captions. No timestamps, boxes or scores are included, although the instruction tells the model to reference timestamps when they are available. Since the audio-event stage returns no sound labels in this version, what arrives on that line is a status word such as model_not_found.

Three more behaviours matter in practice. A call that fails or exceeds 120 seconds leaves a placeholder sentence in the summary field. --summary-style is accepted and has no effect. And ollama run downloads a model that is not present. In one test run with Ollama 0.20.5, the stored summary also began with an unclosed <think> tag and contained terminal escape sequences with duplicated word fragments.

Detection-only report Report with a model written summary
Content boxes, scores, times the same, plus prose
Made by detector (and Whisper if installed) also a language model reading derived text
Times per sampled frame none in the built-in summary
New information none beyond the models' outputs none; it can only reword, omit or invent
Checking compare with the frames compare each sentence with records and frames

The design

From a report to a checked, cited summary

1. Read the report2. Build evidence3. Cut into windows4. Ask the model5. Check claims6. Assemble
Inputs and outputs of every stage
stageinputoutputwhat happens
1. Read the reportanalysis JSONdetections, captions, speechTimed speech can be added from a separate Whisper call.
2. Build evidencemodel outputsrecords with id and timeWeak boxes are dropped and repeated captions merged.
3. Cut into windowsrecordsrecords per time windowEach window must fit the context together with the reply.
4. Ask the modelone window of recordsJSON claims with citationsThe reply format is constrained by a JSON schema.
5. Check claimsclaims and recordsaccepted and rejectedChecks identifiers, citation counts and times written as digits with a seconds unit, not truth.
6. Assembleaccepted claimscited summaryCode orders the claims and states what was not analyzed.

Stage 1 of 6, Read the report. Input: analysis JSON. Output: detections, captions, speech.

Step through the stages. Only the middle stage uses a language model; the rest is ordinary code. A schematic of the stages as described by the author; nothing is executed.

Sample input

The test clip is 9 seconds long: three public domain or CC0 photographs (an astronaut's portrait, a cat, a cup of coffee on a saucer), 3 seconds each with a slow pan, and a synthetic voice saying "This is a synthetic narration. First a portrait, then a cat, and finally a cup of coffee." The block below rebuilds the relevant part of its real report, produced with D-FINE-S, BLIP captions and Whisper base. The one speech segment comes from calling Whisper directly, because the report stores the transcript without times.

python
# Excerpt of one real report: only boxes scoring 0.5 or more are kept.
BOXES = [
    [("person", .9534), ("bowl", .5727)],
    [("person", .9481), ("bowl", .5322), ("clock", .5277)],
    [("person", .9578), ("clock", .5642), ("bowl", .532)],
    [("cat", .9674)], [("cat", .9603)], [("cat", .9556)],
    [("diningtable", .8674), ("spoon", .739), ("cup", .7193), ("spoon", .5779)],
    [("diningtable", .8885), ("spoon", .8543), ("cup", .7261)],
    [("diningtable", .8928), ("cup", .8326), ("spoon", .7685)]]
FLAG = ("a woman in an orange space suit standing in front of an american flag "
        "with a space shuttle in the background")
CAT = "a close up of a cat ' s face with green eyes and white whised whiss"
CAPTIONS = [FLAG] * 3 + [CAT] * 3 + [
    "a cup of coffee sitting on top of a red saucer on a wooden table with a spoon",
    "a cup of coffee sitting on top of a red saucer next to a spoon on a wooden table",
    "a cup of coffee sitting on top of a red saucer with a spoon in front of it"]
report = {
    "duration_sec": 9.0,
    "transcript": " This is a synthetic narration, first departure, then a cat, and finally a cup of coffee.",
    "audio_events": {"model_not_found": []},
    "frame_observations": [
        {"frame_index": 30 * t, "timestamp_sec": float(t),
         "detections": [{"label": label, "score": score} for label, score in boxes]}
        for t, boxes in enumerate(BOXES)],
    "captions": [{"frame_index": 30 * t, "timestamp_sec": float(t), "caption": c}
                 for t, c in enumerate(CAPTIONS)]}
# Timed speech from calling openai-whisper directly; the report itself has no times.
speech = [{"start": 0.0, "end": 6.0, "text": report["transcript"]}]

How to get segment times is covered in offline video transcription with Whisper and FFmpeg.

For what captions can and cannot establish, see BLIP captioning of video frames.

Turn the report into evidence records

Each record has an identifier, a source, a start and end time and a short text. Detector records keep one entry per sampled frame with the labels scoring at least 0.5. Consecutive identical captions merge into one record covering their sample times. Status keys in audio_events are not evidence of sound, so they only add sound events to a list of things that are missing.

python
import math


def build_evidence(report, speech=(), min_score=0.5):
    records, missing = [], []
    for frame in report["frame_observations"]:
        labels = [d["label"] for d in sorted(frame["detections"], key=lambda d: -d["score"])
                  if d["score"] >= min_score]
        if labels:
            t = frame["timestamp_sec"]
            records.append({"src": "detector", "t0": t, "t1": t,
                            "text": ", ".join(dict.fromkeys(labels))})
    previous = None
    for cap in sorted(report["captions"], key=lambda c: c["frame_index"]):
        t = round(cap["timestamp_sec"], 3)
        if previous and previous["text"] == cap["caption"]:
            previous["t1"] = t                       # merge consecutive repeats
        else:
            previous = {"src": "caption", "t0": t, "t1": t, "text": cap["caption"]}
            records.append(previous)
    for seg in speech:                               # timed segments, if you have them
        records.append({"src": "speech", "t0": seg["start"], "t1": seg["end"],
                        "text": seg["text"].strip()})
    if not speech and report["transcript"].strip():  # the report's string has no times
        records.append({"src": "speech, untimed", "t0": 0.0, "t1": report["duration_sec"],
                        "text": report["transcript"].strip()})
    if not report["captions"]:
        missing.append("captions")
    if not speech and not report["transcript"].strip():
        missing.append("speech")
    status_keys = {"model_not_found", "unavailable", "silence", "error"}
    if not set(report["audio_events"]) - status_keys:
        missing.append("sound events")
    records.sort(key=lambda r: (r["t0"], r["src"]))
    for n, record in enumerate(records, 1):
        record["id"] = f"E{n:02d}"
    return records, missing


def windows(records, duration, size):
    for k in range(math.ceil(duration / size)):
        a, b = k * size, min((k + 1) * size, duration)
        yield a, b, [r for r in records if r["t0"] < b and (r["t1"] > a or r["t0"] >= a)]


def line(r):
    when = f"{r['t0']:.1f}" if r["t0"] == r["t1"] else f"{r['t0']:.1f}-{r['t1']:.1f}"
    return f"{r['id']} [{when} s] {r['src']}: {r['text']}"


records, missing = build_evidence(report, speech)
for r in records:
    print(line(r))
print("missing:", missing)
text
E01 [0.0-2.0 s] caption: a woman in an orange space suit standing in front of an american flag with a space shuttle in the background
E02 [0.0 s] detector: person, bowl
E03 [0.0-6.0 s] speech: This is a synthetic narration, first departure, then a cat, and finally a cup of coffee.
E04 [1.0 s] detector: person, bowl, clock
E05 [2.0 s] detector: person, clock, bowl
E06 [3.0-5.0 s] caption: a close up of a cat ' s face with green eyes and white whised whiss
E07 [3.0 s] detector: cat
E08 [4.0 s] detector: cat
E09 [5.0 s] detector: cat
E10 [6.0 s] caption: a cup of coffee sitting on top of a red saucer on a wooden table with a spoon
E11 [6.0 s] detector: diningtable, spoon, cup
E12 [7.0 s] caption: a cup of coffee sitting on top of a red saucer next to a spoon on a wooden table
E13 [7.0 s] detector: diningtable, spoon, cup
E14 [8.0 s] caption: a cup of coffee sitting on top of a red saucer with a spoon in front of it
E15 [8.0 s] detector: diningtable, cup, spoon
missing: ['sound events']

Reading the records already shows the limits of any summary built from them. The photographs contain no bowl and no clock. The speech says "first departure" where the narration says "First a portrait". Whisper returned one segment for the whole narration, so the record cannot say when the word "cat" was spoken.

Validate the report before building records from it; working with video analysis JSON shows how.

Budget the context window

The model's context holds the instruction, the evidence and the reply. Ollama's context length page gives defaults that depend on GPU memory (4k tokens below 24 GiB, 32k from 24 to 48 GiB, 256k above), while its FAQ states 4096. Do not rely on a default; set num_ctx yourself.

What happens when a prompt does not fit is worth testing, because by default nothing fails. A test prompt of about 13,800 characters began with a secret word, continued with 300 detector lines and ended by asking for the word. With Ollama 0.20.5 and the model used below:

Request Prompt tokens evaluated Result
num_ctx 16384 6236 answered with the secret word
num_ctx 2048 2048 HTTP success; the model could not see the word
num_ctx 1024 2048 ran with 2048 anyway; the word was gone
num_ctx 2048, "truncate": false none HTTP 400, the input length exceeds the context length

Send "truncate": false so that an oversized prompt is an error. This field was not listed in the chat API reference on 2026-11-27, so test it on your version, and also compare prompt_eval_count in the reply with your num_ctx.

For this clip the model counted 134 tokens for the instructions without any record and 476 with all 15 records, so the records cost 342 tokens for 9 seconds of video, about 38 per second. The package's own evidence prompt for the same clip was 355 tokens. The chart below is an illustration with round numbers close to those: 150 tokens of instructions, 40 tokens of records per second of video and 600 kept for the reply. A longer video need not produce records at a constant rate.

How evidence grows against a 4096 token context

Three stacked bars of instructions, records and reply reserve. One minute of video fits within 4096 tokens. Two minutes exceed the limit, and ten minutes need several times the context.

1. instructions2. records3. reply reserve

1 minute of video: 3150 tokens ×1.00 total within the num_ctx

2 minutes: 5550 tokens ×1.76 total over the num_ctx

10 minutes: 24750 tokens ×7.86 total over the num_ctx

Vertical mark: num_ctx, 4096 tokens.

Each × compares with 1 minute of video. Shown: total.

Values (tokens)
barinstructionsrecordsreply reservetotalnum_ctx
1 minute of video15024006003150within
2 minutes15048006005550over
10 minutes1502400060024750over

Showing the totals: 1 minute of video 3150 tokens; 2 minutes 5550 tokens; 10 minutes 24750 tokens. Ratios are to 1 minute of video.

Round, assumed rates near those of the 9 second test clip: 40 tokens of records per second of video and a 600 token reply reserve. Illustrative values chosen by the author: not measurements and not the output of any model. Bars start at zero; totals and ratios are computed from the values.

At that rate a 4096 token context holds under a minute and a half of video per window. Token counts depend on the model's tokenizer and on how much your records say, so measure with your own.

Request structured claims and check them

Ollama accepts a JSON schema in the format field, which constrains the shape of the reply. Ask for a list of claims, each with a text, a kind and the ids it rests on.

Kind Meaning The checker requires Example for this clip
observed restates what records say at least one cited record a caption mentions a cat from 3 s to 5 s
interpretation goes beyond the records at least one cited record the clip appears to be a slideshow
contradiction two records disagree at least two different records speech and caption describe different things
insufficient cannot tell nothing no information about sounds

The checker accepts a claim only if every cited id belongs to the window, the kind has enough citations and, when the claim cites records, any time written in digits with a seconds unit lies within the span those records cover. It cannot tell whether the sentence follows from them.

python
import re

KINDS = ["observed", "interpretation", "contradiction", "insufficient"]
SCHEMA = {
    "type": "object",
    "properties": {"claims": {"type": "array", "items": {
        "type": "object",
        "properties": {"text": {"type": "string"},
                       "kind": {"type": "string", "enum": KINDS},
                       "evidence": {"type": "array", "items": {"type": "string"}}},
        "required": ["text", "kind", "evidence"]}}},
    "required": ["claims"],
}


def make_prompt(a, b, selected):
    return "\n".join([
        "You describe one time window of a video from evidence records produced by other",
        "programs. You cannot see or hear the video. The records can be wrong.",
        f"Window: {a:.1f} to {b:.1f} s",
        "Records:", *map(line, selected),
        'Return JSON {"claims": [...]} with at most 4 claims. Each claim has:',
        '"text": one short sentence without technical terms;',
        '"kind": observed (restates records), interpretation (goes beyond them),',
        '  contradiction (two records disagree) or insufficient (cannot tell);',
        '"evidence": ids of the records the claim rests on, from this window only.',
    ])


def problems(claim, selected):
    by_id = {r["id"]: r for r in selected}
    found = []
    cited = [by_id[i] for i in claim["evidence"] if i in by_id]
    unknown = [i for i in claim["evidence"] if i not in by_id]
    if unknown:
        found.append(f"unknown id {unknown}")
    need = {"observed": 1, "interpretation": 1, "contradiction": 2, "insufficient": 0}
    if len({r["id"] for r in cited}) < need[claim["kind"]]:
        found.append(f"{claim['kind']} needs {need[claim['kind']]} citation(s)")
    for number in re.findall(r"(\d+(?:\.\d+)?)\s*(?:s\b|sec|seconds?\b)", claim["text"]):
        if cited and not min(r["t0"] for r in cited) <= float(number) <= max(r["t1"] for r in cited):
            found.append(f"time {number} s is outside the cited records")
    return found


# Hand-written claims, not model output, to show what the rules catch and miss.
first_window = next(windows(records, report["duration_sec"], 3.0))[2]
for claim in (
        {"text": "A dog runs in.", "kind": "observed", "evidence": ["E99"]},
        {"text": "A person appears at 8 s.", "kind": "observed", "evidence": ["E02"]},
        {"text": "The speech and the picture disagree.", "kind": "contradiction", "evidence": ["E03"]},
        {"text": "A dog sits next to the flag.", "kind": "observed", "evidence": ["E01"]}):
    print(problems(claim, first_window) or "passes", "<-", claim["text"])
text
["unknown id ['E99']", 'observed needs 1 citation(s)'] <- A dog runs in.
['time 8 s is outside the cited records'] <- A person appears at 8 s.
['contradiction needs 2 citation(s)'] <- The speech and the picture disagree.
passes <- A dog sits next to the flag.

The last line is the important one. The cited record says nothing about a dog, and the claim passes.

Call the model, window by window

python
import json
import urllib.request


def ask(model, prompt, num_ctx=4096, host="http://127.0.0.1:11434"):
    body = {"model": model, "stream": False, "format": SCHEMA, "truncate": False,
            "messages": [{"role": "user", "content": prompt}],
            "options": {"temperature": 0, "seed": 7, "num_ctx": num_ctx}}
    request = urllib.request.Request(host + "/api/chat", json.dumps(body).encode(),
                                     {"Content-Type": "application/json"})
    with urllib.request.urlopen(request, timeout=300) as response:
        return json.load(response)


def summarize(model, report, speech=(), size=3.0, num_ctx=4096):
    records, missing = build_evidence(report, speech)
    kept, rejected = [], []
    for a, b, selected in windows(records, report["duration_sec"], size):
        if not selected:
            kept.append((a, b, {"text": "No evidence in this window.",
                                "kind": "insufficient", "evidence": []}))
            continue
        reply = ask(model, make_prompt(a, b, selected), num_ctx)
        if reply.get("done_reason") != "stop":
            raise RuntimeError(f"window {a}-{b}: reply ended with {reply.get('done_reason')}")
        print(f"window {a:.0f}-{b:.0f} s: {reply['prompt_eval_count']} prompt tokens, "
              f"{reply['eval_count']} reply tokens")
        for claim in json.loads(reply["message"]["content"])["claims"]:
            why = problems(claim, selected)
            if why:
                rejected.append((a, b, claim, why))
            else:
                kept.append((a, b, claim))
    return missing, kept, rejected

A reply that did not stop normally raises an error instead of being parsed half finished. The summary is assembled by code from the accepted claims, so the combining step cannot introduce new statements. If you add a second model call that condenses the claims into prose, hold its output to the same ids and check it again.

With a model pulled and the server running:

python
missing, kept, rejected = summarize("openbmb/minicpm-v4.5:8b", report, speech)
for a, b, claim in kept:
    print(f"[{a:.0f}-{b:.0f} s] ({claim['kind']}; {','.join(claim['evidence'])}) {claim['text']}")
for a, b, claim, why in rejected:
    print(f"REJECTED [{a:.0f}-{b:.0f} s] {claim['text']} <- {'; '.join(why)}")
print("Not analyzed:", ", ".join(missing) or "nothing")

One run with openbmb/minicpm-v4.5:8b (8 billion parameters, 4-bit quantisation, Ollama 0.20.5), called right after the model was loaded, printed:

text
window 0-3 s: 255 prompt tokens, 152 reply tokens
window 3-6 s: 242 prompt tokens, 149 reply tokens
window 6-9 s: 282 prompt tokens, 156 reply tokens
[0-3 s] (observed; E01) A woman in an orange space suit is standing in front of a flag.
[0-3 s] (observed; E02) There are people and bowls detected at 0 seconds.
[0-3 s] (interpretation; E04) A clock was also detected with the person and bowl at around 1 second.
[3-6 s] (observed; E06) A cat is present in a close-up shot.
[3-6 s] (observed; E07,E08,E09) The video includes multiple detections of cats.
[3-6 s] (interpretation; E03) A synthetic narration mentions a cat, but it is unclear if this matches the visual content.
[3-6 s] (observed; E06) The video shows green eyes and white whiskers on one of the cats.
[6-9 s] (observed; E10,E12) A cup of coffee is sitting on a red saucer.
[6-9 s] (observed; E10,E11,E13) The scene includes a spoon and wooden table.
[6-9 s] (interpretation; E14) A cup of coffee is sitting on top of a red saucer with a spoon in front of it.
[6-9 s] (observed; E15) The scene includes dining table, cups and spoons.
REJECTED [0-3 s] The synthetic narration includes a cat, but it is unclear if this matches any visual content in the video. <- contradiction needs 2 citation(s)
Not analyzed: sound events

What the checks caught, and what they missed

One claim was rejected. Compare the accepted ones with the three photographs:

Passing the check is not the same as being supported

A cat in close-up(E06)People and bowlsat 0 s (E02)Eyes on one of thecats (E06)Contradictionciting only E03Accepted andsupportedAccepted; no bowlAccepted; only onecatRejected by rule
The same diagram as a table
boxarrows todetail
A cat in close-up (E06)Accepted and supported—
People and bowls at 0 s (E02)Accepted; no bowl—
Eyes on one of the cats (E06)Accepted; only one cat—
Contradiction citing only E03Rejected by rule—
Accepted and supported—The caption says it and the photograph shows it.
Accepted; no bowl—The detector record is wrong and the claim repeats it.
Accepted; only one cat—The cited caption describes a single face.
Rejected by rule—A contradiction needs two different records.

8 boxes and 4 arrows. No box is selected.

Four claims from the recorded run, with the checker's verdict and a comparison with the photographs. A schematic drawn from the author's description: nothing is executed or measured.

At least four of the eleven accepted claims are wrong against the pictures:

  • bowls and a clock: false detections, faithfully repeated;
  • "one of the cats": the model invented a plural that its own citation does not support;
  • "cups and spoons": box labels turned into several objects, where the photograph has one of each.

A fifth cites only the speech record and calls the match with the picture unclear, although the same window held a caption and detector records saying "cat". None of this can be seen from identifiers. To reduce it, remove bad evidence before the model sees it (a higher score threshold, a label that must appear in several frames), and have a person spot check frames for anything that matters.

Two other observations from these tests are worth carrying over.

Do not let the model report what is missing. An earlier version of the prompt included the line Not available: sound events. The model answered "There are people, bowls, clocks, but no sound events", turning "not analyzed" into "silent", in a clip that has speech throughout most of it. The claim cited detector records and passed. The program knows what is missing, so let the program print it.

A fixed seed was not enough for repeatable output. With temperature 0 and a fixed seed, the first set of calls after loading the model and later sets differed in the first window: the claim rejected above came back labelled interpretation and was accepted. Store the prompts and raw replies with the summary if you need to explain it later.

Contradictions and thin evidence

The structured kinds give the model a place to put disagreement, but do not expect it to find every conflict. Here the record with "departure" conflicts with nothing else the model could see, so a transcription error looks like any other fact. Rules that code can apply are more dependable: flag windows whose only source is untimed speech, require two sources before stating that something happened, and print "no evidence in this window" without asking the model.

Empty or weak windows are results. A summary that says nothing about a stretch of video, and says that it says nothing, is more useful than one that fills it.

Models, hardware and failure handling

The model above was used to test the mechanism, not selected by comparison, and one short clip says nothing about its quality. With a 4096 token context it occupied about 5.7 GB of GPU memory on a 16 GB RTX 5080. Larger models and contexts need more. For your own choice, check on your records that the model returns the schema, follows the citation rule and does not turn missing data into negative statements. With reasoning models, check how reasoning text is returned; the package's own path removes only complete <think> blocks.

Failure What you see What to do
Server not running connection error stop and say so; do not write a summary
Model not pulled HTTP 404, model ... not found pull it deliberately; the API call does not download it
Prompt too long HTTP 400 with truncate false shrink the window
Reply cut off done_reason is not stop raise the limit or ask for fewer claims
Invalid JSON json.loads raises mark the window as failed
Slow machine timeout after 300 s raise the timeout or use a smaller model

Local or hosted language model?

Local Ollama model Hosted model API
Where evidence goes stays on the host you call sent to the provider
Context limited by your memory set by the provider
Structured output schema in format provider specific
Cost hardware and time per use pricing
Reproducibility you control the model file the model may change

"Local" depends on your settings. If OLLAMA_HOST points to another machine, or you name a cloud model, the evidence, including the transcript, leaves your computer. Ollama's FAQ describes how to disable its cloud features (OLLAMA_NO_CLOUD=1). Its documentation also notes that Ollama's cloud did not support structured outputs when read on 2026-11-27.

Sound labels could become another evidence source if you run a tagger yourself; audio event detection with PANNs explains what its windows can support.

References