@larkup/tool-video-intelligence 0.3.13 → 0.3.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -41,6 +41,28 @@ runtime/app/
41
41
 
42
42
  `deploy/` is the operator/infrastructure side for Larkup's managed cloud offering: the AWS control plane (Lambda + API Gateway + DynamoDB + S3) and GPU provider dispatch/worker entrypoints (RunPod, Modal, and other vendors behind one interface). It is public for review and collaboration, but remains fully separate from `runtime/app` so a self-hosted Docker/local install never depends on it. It uses short-lived CI identity and contains no deployed credentials. See `deploy/README.md` for testing, validation, and deploy commands.
43
43
 
44
+ ## Bounded indexing
45
+
46
+ Completed clips use lossless temporary storage instead of retaining every raw
47
+ frame bucket in memory. Priority ranges influence selection inside the bounded
48
+ semantic clip budget. Sparse indexing does not guarantee brief-event recall;
49
+ result coverage reports that limitation explicitly.
50
+
51
+ ## Agent investigation skills
52
+
53
+ The shared chat tool composes its existing instructions from
54
+ [`src/investigation-skills.ts`](src/investigation-skills.ts). These are reusable
55
+ capability instructions, selected through typed scope and operation rather than
56
+ source genre or keyword lists. The executor still owns permissions, deadlines,
57
+ frame budgets and evidence validation; the skills add no model calls.
58
+
59
+ The skills cover semantic routing, evidence selection, chronological inventories,
60
+ full-source extraction, index reuse, pagination, source language, claim
61
+ verification, presence interpretation and grounded responses. A person's
62
+ appearance establishes neither their identity nor an action; source-wide scans
63
+ must distinguish indexed observations from complete coverage of reality. Brief
64
+ unsampled events remain a sampling limitation and are reported explicitly.
65
+
44
66
  ## Current roadmap
45
67
 
46
68
  Collaborators are currently focused on three connected improvements:
package/dist/agent.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { groundVideoIdentityEvidence } from './identity-grounding.js';
2
+ import { VIDEO_INVESTIGATION_GUIDE } from './investigation-skills.js';
1
3
  import { trackUsageEvent } from '@larkup/core/analytics-store';
2
4
  const MAX_INSPECTION_CHUNK_SECS = 60;
3
5
  const POINT_QUERY_RADIUS_SECS = MAX_INSPECTION_CHUNK_SECS / 2;
@@ -61,7 +63,7 @@ export const AGENT_TOOLS = [
61
63
  method: 'queryVideoEvidence',
62
64
  workflow: 'evidence-query',
63
65
  evidenceInput: 'media-asset',
64
- systemPromptFragment: 'Use this action for media questions. On every call, derive investigation from the user’s meaning in their own language: use focused for one local moment, temporal for a relationship or development across moments, and source when the answer must account for the recording as a whole. Set answer, compare, trace, enumerate, or synthesize according to the reasoning operation—not the video genre or a word list. If the user supplies a specific source time or range, put its resolved seconds in investigation.timeRange; otherwise omit it. Use recordSet observed only when the requested answer is the visible presence, recurrence, or timing ledger itself; never use it for clothing, colour, appearance attributes, identity, action, or another visual fact. For a source enumeration, set recordSet to source-authored for units authored in the recording, source-questions for only authored questions and their answers, observed for time-grounded observed facts, or all when both are needed. For exact spoken or sung wording across the recording, use source plus enumerate, speech evidence, and recordSet all. Choose source plus synthesize for the overall narrative. Focused questions use ranked evidence; source enumerations use a chronological database scan; source explanations use a durable navigation aggregate. Never turn a complete-source request into top-K retrieval. For an exhaustive result, follow continuation.nextCursor until hasMore=false; do not mistake one page for the complete answer. Answer in the returned sourceLanguage by default, including notes, speech, and lyrics; translate only when the user explicitly asks. Never default to English. Never say you do not know or that the source lacks an answer before this action has attempted its available fallback. State a value, identity, count, or exact visible fact only when established. observedSubjects, when present, is the reconciled frame-grounded visibility ledger: use its ranges for visible-presence and timing claims, never speech, titles, or a source name. Its durations are observed intervals, not inferred continuous screen time. Answer as a viewer who remembers the material: lead with the answer itself, and when natural say "I saw" or "I heard" rather than describing a system. Do not say "the video shows", "the analysis indicates", or "according to retrieved evidence". Never mention retrieval, search, indexing, frames, tools, or analysis unless the user asks how the answer was found.',
66
+ systemPromptFragment: VIDEO_INVESTIGATION_GUIDE,
65
67
  },
66
68
  {
67
69
  name: 'inspectVideoKnowledge',
@@ -92,7 +94,7 @@ export const AGENT_TOOLS = [
92
94
  ];
93
95
  export function attachVideoIntelligenceAgentClient(client, fetcher = globalThis.fetch) {
94
96
  const inspectVideoKnowledge = createInspector(fetcher);
95
- return Object.assign(client, {
97
+ const actions = {
96
98
  inspectVideoKnowledge,
97
99
  async queryVideoEvidence(input, context) {
98
100
  if (!isValidQueryInput(input))
@@ -457,6 +459,12 @@ export function attachVideoIntelligenceAgentClient(client, fetcher = globalThis.
457
459
  ...temporalContextResult(hits, plan),
458
460
  };
459
461
  },
462
+ };
463
+ return Object.assign(client, {
464
+ ...actions,
465
+ async queryVideoEvidence(input, context) {
466
+ return groundVideoIdentityEvidence(await actions.queryVideoEvidence(input, context));
467
+ },
460
468
  });
461
469
  }
462
470
  /**
@@ -222,6 +222,10 @@ export interface VideoEvidenceBundle {
222
222
  reason: string;
223
223
  }>;
224
224
  semanticClips?: number;
225
+ selectedSemanticClips?: number;
226
+ semanticClipBudget?: number;
227
+ samplingGuarantee?: 'sampled-evidence-only';
228
+ briefEventsMayBeMissed?: boolean;
225
229
  };
226
230
  agentPlan?: {
227
231
  mode: VideoIndexingMode;
@@ -259,6 +263,11 @@ export interface VideoEvidenceBundle {
259
263
  estimatedTotalSeconds: number;
260
264
  elapsedSeconds: number;
261
265
  estimateErrorSeconds: number;
266
+ frameStore?: {
267
+ storage: 'temporary-lossless-npy';
268
+ frames: number;
269
+ bytes: number;
270
+ };
262
271
  };
263
272
  transcriptionDiagnostics?: {
264
273
  provider?: string | null;
@@ -0,0 +1,2 @@
1
+ /** Project source records into answer evidence without changing the stored index. */
2
+ export declare function groundVideoIdentityEvidence<T>(value: T): T;
@@ -0,0 +1,154 @@
1
+ const record = (value) => value && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
2
+ const key = (value) => value.normalize('NFKC').toLocaleLowerCase().trim();
3
+ const label = (value) => (typeof value === 'string' ? value.trim() : '');
4
+ function mentions(text, name) {
5
+ const escaped = name.normalize('NFKC').replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
6
+ return new RegExp(`(?<![\\p{L}\\p{N}_])${escaped}(?![\\p{L}\\p{N}_])`, 'iu').test(text.normalize('NFKC'));
7
+ }
8
+ /** Project source records into answer evidence without changing the stored index. */
9
+ export function groundVideoIdentityEvidence(value) {
10
+ const input = record(value);
11
+ if (!input || !Array.isArray(input.evidence))
12
+ return value;
13
+ const subjects = Array.isArray(input.observedSubjects) ? input.observedSubjects : [];
14
+ const knownIdentities = subjects.flatMap((item) => {
15
+ const subject = record(item);
16
+ return subject && label(subject.identity) ? [label(subject.identity)] : [];
17
+ });
18
+ let withheld = 0;
19
+ const authored = ['source-authored', 'source-questions', 'speech'].includes(label(record(input.inventory)?.recordSet));
20
+ const sanitize = (text, timeRange, context = text) => {
21
+ if (!text.trim())
22
+ return text;
23
+ const local = context.split(/\r?\n/).flatMap((line) => {
24
+ if (!line.startsWith('Visible subject:'))
25
+ return [];
26
+ try {
27
+ const item = record(JSON.parse(line.slice('Visible subject:'.length)));
28
+ return item ? [item] : [];
29
+ }
30
+ catch {
31
+ return [];
32
+ }
33
+ });
34
+ const allowed = new Set(local
35
+ .filter((item) => item.identityBasis === 'source-named' || item.identityBasis === 'source-described')
36
+ .map((item) => key(label(item.identity))));
37
+ // An identity established elsewhere is useful only at its observed range.
38
+ for (const item of subjects) {
39
+ const subject = record(item);
40
+ if (!subject ||
41
+ !['source-named', 'source-described'].includes(label(subject.identityBasis)) ||
42
+ !timeRange ||
43
+ !Array.isArray(subject.appearances))
44
+ continue;
45
+ if (subject.appearances.some((entry) => {
46
+ const range = record(entry);
47
+ return (range &&
48
+ typeof range.startSecs === 'number' &&
49
+ typeof range.endSecs === 'number' &&
50
+ typeof timeRange.startSecs === 'number' &&
51
+ typeof timeRange.endSecs === 'number' &&
52
+ range.startSecs <= timeRange.endSecs &&
53
+ range.endSecs >= timeRange.startSecs);
54
+ }))
55
+ allowed.add(key(label(subject.identity)));
56
+ }
57
+ for (const item of local)
58
+ if (item.identityBasis === 'unresolved')
59
+ allowed.delete(key(label(item.identity)));
60
+ const candidates = [
61
+ ...knownIdentities,
62
+ ...local
63
+ .filter((item) => item.identityBasis === 'unresolved')
64
+ .map((item) => label(item.identity)),
65
+ ...Array.from(context.matchAll(/^Present:\s*(.+?)\s+—/gm), (match) => match[1].trim()),
66
+ ];
67
+ const blocked = [...new Set(candidates.filter((name) => name && !allowed.has(key(name))))];
68
+ const hasProtocol = /^(?:Visible subject:|Present:|On screen:|Happened(?: \(inferred\))?:|Direct component:|Claim bindings:)/mu.test(context);
69
+ const lines = text.split(/\r?\n/).filter((line) => {
70
+ const inferred = /^Happened \(inferred\):/u.test(line);
71
+ const unsafe = !line.startsWith('On screen:') && blocked.some((name) => mentions(line, name));
72
+ // Legacy prose can bind unlisted actors or repeat inferred events as facts.
73
+ const unqualifiedSummary = text === context && hasProtocol && line.trim() && !/^[\w -]+:/.test(line);
74
+ if (inferred || unsafe || unqualifiedSummary) {
75
+ withheld++;
76
+ return false;
77
+ }
78
+ return true;
79
+ });
80
+ return (lines.join('\n').trim() ||
81
+ 'Visual attribution withheld: the source does not establish the actor identity or action.');
82
+ };
83
+ const byId = new Map();
84
+ const evidence = input.evidence.map((entry) => {
85
+ const item = record(entry);
86
+ const payload = record(item?.payload);
87
+ if (!item ||
88
+ !payload ||
89
+ typeof payload.text !== 'string' ||
90
+ authored ||
91
+ item.modality === 'transcript' ||
92
+ /^(?:Source (?:question|item|structure))/u.test(payload.text))
93
+ return entry;
94
+ const text = sanitize(payload.text, record(item.timeRange));
95
+ if (typeof item.id === 'string')
96
+ byId.set(item.id, { text, context: payload.text, range: record(item.timeRange) });
97
+ return { ...item, payload: { ...payload, text } };
98
+ });
99
+ const rows = Array.isArray(input.rows)
100
+ ? input.rows.map((entry) => {
101
+ const row = record(entry);
102
+ if (!row || typeof row.id !== 'string' || !byId.has(row.id))
103
+ return entry;
104
+ const item = byId.get(row.id);
105
+ return {
106
+ ...row,
107
+ Content: item.text,
108
+ Answer: sanitize(label(row.Answer), item.range, item.context),
109
+ Respondent: sanitize(label(row.Respondent), item.range, item.context),
110
+ };
111
+ })
112
+ : undefined;
113
+ const extra = (entry) => {
114
+ if (Array.isArray(entry))
115
+ return entry.map(extra);
116
+ const item = record(entry);
117
+ if (!item)
118
+ return entry;
119
+ return Object.fromEntries(Object.entries(item).map(([name, child]) => [
120
+ name,
121
+ ['text', 'found', 'summary', 'overview'].includes(name) && typeof child === 'string'
122
+ ? sanitize(child, record(item.range) ?? record(item.timeRange))
123
+ : extra(child),
124
+ ]));
125
+ };
126
+ const directObservation = input.directObservation ? extra(input.directObservation) : undefined;
127
+ const temporalContext = input.temporalContext ? extra(input.temporalContext) : undefined;
128
+ const output = {
129
+ ...input,
130
+ evidence,
131
+ ...(rows ? { rows } : {}),
132
+ ...(Array.isArray(input.observedSubjects)
133
+ ? {
134
+ observedSubjects: subjects.filter((item) => record(item)?.identityBasis !== 'unresolved'),
135
+ }
136
+ : {}),
137
+ ...(directObservation ? { directObservation } : {}),
138
+ ...(temporalContext ? { temporalContext } : {}),
139
+ };
140
+ if (withheld > 0)
141
+ Object.assign(output, {
142
+ identityGrounding: {
143
+ withheldUnits: withheld,
144
+ instruction: 'Some visual attributions were withheld. A spoken name or unresolved identity does not establish a named visible actor or their action. Report the remaining observations, keep uncertain identities/actions unconfirmed, and never reconstruct withheld claims. Sampled observations do not prove every person or every event was captured.',
145
+ },
146
+ claimVerification: {
147
+ ...record(input.claimVerification),
148
+ status: 'needs-corroboration',
149
+ directlyEstablished: false,
150
+ rule: 'Answer only from the remaining grounded evidence. A source-complete scan is not proof of a complete person/action inventory. Identity, appearance, and action each need their own source evidence.',
151
+ },
152
+ });
153
+ return output;
154
+ }
package/dist/index.d.ts CHANGED
@@ -9,7 +9,7 @@ export * from './ui.js';
9
9
  export declare const TOOL_META: {
10
10
  readonly id: "video-intelligence";
11
11
  readonly name: "Video Intelligence";
12
- readonly version: "0.3.13";
12
+ readonly version: "0.3.15";
13
13
  };
14
14
  export declare const TOOL_EXTENSION: {
15
15
  id: "video-intelligence";
package/dist/index.js CHANGED
@@ -11,7 +11,7 @@ export * from './ui.js';
11
11
  export const TOOL_META = {
12
12
  id: 'video-intelligence',
13
13
  name: 'Video Intelligence',
14
- version: '0.3.13',
14
+ version: '0.3.15',
15
15
  };
16
16
  /** Managed infrastructure stays an implementation detail of Larkup Cloud. */
17
17
  const MANAGED_CLOUD_ENDPOINT = process.env.LARKUP_VIDEO_INTELLIGENCE_CLOUD_ENDPOINT ??
@@ -0,0 +1,33 @@
1
+ /** Reusable investigation skills selected by semantic scope and operation. */
2
+ export declare const VIDEO_INVESTIGATION_SKILLS: readonly [{
3
+ readonly id: "route";
4
+ readonly instruction: "Use this action for media questions. On every call, derive investigation from the user’s meaning in their own language: use focused for one local moment, temporal for a relationship or development across moments, and source when the answer must account for the recording as a whole. Set answer, compare, trace, enumerate, or synthesize according to the reasoning operation—not the video genre or a word list. If the user supplies a specific source time or range, put its resolved seconds in investigation.timeRange; otherwise omit it.";
5
+ }, {
6
+ readonly id: "select-evidence";
7
+ readonly instruction: "Use recordSet observed only when the requested answer is the visible presence, recurrence, or timing ledger itself; never use it for clothing, colour, appearance attributes, identity, action, or another visual fact.";
8
+ }, {
9
+ readonly id: "enumerate";
10
+ readonly instruction: "For a source enumeration, set recordSet to source-authored for units authored in the recording, source-questions for only authored questions and their answers, observed for time-grounded observed facts, or all when both are needed.";
11
+ }, {
12
+ readonly id: "extract-source";
13
+ readonly instruction: "For exact spoken or sung wording across the recording, use source plus enumerate, speech evidence, and recordSet all. Choose source plus synthesize for the overall narrative.";
14
+ }, {
15
+ readonly id: "reuse-index";
16
+ readonly instruction: "Focused questions use ranked evidence; source enumerations use a chronological database scan; source explanations use a durable navigation aggregate. Never turn a complete-source request into top-K retrieval.";
17
+ }, {
18
+ readonly id: "complete-pages";
19
+ readonly instruction: "For an exhaustive result, follow continuation.nextCursor until hasMore=false; do not mistake one page for the complete answer.";
20
+ }, {
21
+ readonly id: "preserve-language";
22
+ readonly instruction: "Answer in the returned sourceLanguage by default, including notes, speech, and lyrics; translate only when the user explicitly asks. Never default to English.";
23
+ }, {
24
+ readonly id: "verify-claims";
25
+ readonly instruction: "Never say you do not know or that the source lacks an answer before this action has attempted its available fallback. State a value, identity, count, or exact visible fact only when established.";
26
+ }, {
27
+ readonly id: "interpret-presence";
28
+ readonly instruction: "observedSubjects, when present, is the reconciled frame-grounded visibility ledger: use its ranges for visible-presence and timing claims, never speech, titles, or a source name. Its durations are observed intervals, not inferred continuous screen time.";
29
+ }, {
30
+ readonly id: "respond";
31
+ readonly instruction: "Answer as a viewer who remembers the material: lead with the answer itself, and when natural say \"I saw\" or \"I heard\" rather than describing a system. Do not say \"the video shows\", \"the analysis indicates\", or \"according to retrieved evidence\". Never mention retrieval, search, indexing, frames, tools, or analysis unless the user asks how the answer was found.";
32
+ }];
33
+ export declare const VIDEO_INVESTIGATION_GUIDE: string;
@@ -0,0 +1,44 @@
1
+ /** Reusable investigation skills selected by semantic scope and operation. */
2
+ export const VIDEO_INVESTIGATION_SKILLS = [
3
+ {
4
+ id: 'route',
5
+ instruction: 'Use this action for media questions. On every call, derive investigation from the user’s meaning in their own language: use focused for one local moment, temporal for a relationship or development across moments, and source when the answer must account for the recording as a whole. Set answer, compare, trace, enumerate, or synthesize according to the reasoning operation—not the video genre or a word list. If the user supplies a specific source time or range, put its resolved seconds in investigation.timeRange; otherwise omit it.',
6
+ },
7
+ {
8
+ id: 'select-evidence',
9
+ instruction: 'Use recordSet observed only when the requested answer is the visible presence, recurrence, or timing ledger itself; never use it for clothing, colour, appearance attributes, identity, action, or another visual fact.',
10
+ },
11
+ {
12
+ id: 'enumerate',
13
+ instruction: 'For a source enumeration, set recordSet to source-authored for units authored in the recording, source-questions for only authored questions and their answers, observed for time-grounded observed facts, or all when both are needed.',
14
+ },
15
+ {
16
+ id: 'extract-source',
17
+ instruction: 'For exact spoken or sung wording across the recording, use source plus enumerate, speech evidence, and recordSet all. Choose source plus synthesize for the overall narrative.',
18
+ },
19
+ {
20
+ id: 'reuse-index',
21
+ instruction: 'Focused questions use ranked evidence; source enumerations use a chronological database scan; source explanations use a durable navigation aggregate. Never turn a complete-source request into top-K retrieval.',
22
+ },
23
+ {
24
+ id: 'complete-pages',
25
+ instruction: 'For an exhaustive result, follow continuation.nextCursor until hasMore=false; do not mistake one page for the complete answer.',
26
+ },
27
+ {
28
+ id: 'preserve-language',
29
+ instruction: 'Answer in the returned sourceLanguage by default, including notes, speech, and lyrics; translate only when the user explicitly asks. Never default to English.',
30
+ },
31
+ {
32
+ id: 'verify-claims',
33
+ instruction: 'Never say you do not know or that the source lacks an answer before this action has attempted its available fallback. State a value, identity, count, or exact visible fact only when established.',
34
+ },
35
+ {
36
+ id: 'interpret-presence',
37
+ instruction: 'observedSubjects, when present, is the reconciled frame-grounded visibility ledger: use its ranges for visible-presence and timing claims, never speech, titles, or a source name. Its durations are observed intervals, not inferred continuous screen time.',
38
+ },
39
+ {
40
+ id: 'respond',
41
+ instruction: 'Answer as a viewer who remembers the material: lead with the answer itself, and when natural say "I saw" or "I heard" rather than describing a system. Do not say "the video shows", "the analysis indicates", or "according to retrieved evidence". Never mention retrieval, search, indexing, frames, tools, or analysis unless the user asks how the answer was found.',
42
+ },
43
+ ];
44
+ export const VIDEO_INVESTIGATION_GUIDE = VIDEO_INVESTIGATION_SKILLS.map((skill) => skill.instruction).join(' ');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@larkup/tool-video-intelligence",
3
- "version": "0.3.13",
3
+ "version": "0.3.15",
4
4
  "type": "module",
5
5
  "description": "Installable local and cloud video intelligence with evidence-first indexing.",
6
6
  "main": "./dist/index.js",
@@ -12,6 +12,8 @@ and Hugging Face Inference Endpoint deployments.
12
12
 
13
13
  from __future__ import annotations
14
14
 
15
+ from collections.abc import Sequence
16
+
15
17
  import base64
16
18
  import os
17
19
  import threading
@@ -30,7 +32,7 @@ class VideoClipInput:
30
32
  clip_id: str
31
33
  start_ms: int
32
34
  end_ms: int
33
- frames: list[tuple[int, np.ndarray]]
35
+ frames: Sequence[tuple[int, np.ndarray]]
34
36
 
35
37
 
36
38
  @dataclass(frozen=True)
@@ -0,0 +1,77 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Iterator, Sequence
4
+ from pathlib import Path
5
+ from tempfile import TemporaryDirectory
6
+ from typing import overload
7
+
8
+ import numpy as np
9
+
10
+
11
+ Frame = tuple[int, np.ndarray]
12
+
13
+
14
+ class StoredFrames(Sequence[Frame]):
15
+ """Read immutable, lossless frames on demand; concurrent readers share no cursor."""
16
+
17
+ def __init__(self, entries: list[tuple[int, Path]]) -> None:
18
+ self._entries = tuple(entries)
19
+
20
+ def __len__(self) -> int:
21
+ return len(self._entries)
22
+
23
+ @overload
24
+ def __getitem__(self, index: int) -> Frame: ...
25
+
26
+ @overload
27
+ def __getitem__(self, index: slice) -> list[Frame]: ...
28
+
29
+ def __getitem__(self, index: int | slice) -> Frame | list[Frame]:
30
+ if isinstance(index, slice):
31
+ return [self[i] for i in range(*index.indices(len(self)))]
32
+ time_ms, path = self._entries[index]
33
+ try:
34
+ with path.open("rb") as stream:
35
+ frame = np.load(stream, allow_pickle=False)
36
+ frame.setflags(write=False)
37
+ except (OSError, ValueError) as error:
38
+ raise RuntimeError("A temporary video frame could not be read") from error
39
+ return time_ms, frame
40
+
41
+ def __iter__(self) -> Iterator[Frame]:
42
+ for index in range(len(self)):
43
+ yield self[index]
44
+
45
+
46
+ class FrameStore:
47
+ """Spool completed clips outside RAM for one job; remove them on every exit."""
48
+
49
+ def __init__(self) -> None:
50
+ self._directory = TemporaryDirectory(prefix="larkup-video-frames-")
51
+ self.path = Path(self._directory.name)
52
+ self._count = 0
53
+ self._bytes = 0
54
+
55
+ def save(self, frames: Sequence[Frame]) -> StoredFrames:
56
+ entries: list[tuple[int, Path]] = []
57
+ for time_ms, frame in frames:
58
+ path = self.path / f"{self._count}.npy"
59
+ # Avoid compression work and preserve pixels. Consumers load one
60
+ # frame at a time; no open mappings prevent cleanup on Windows.
61
+ try:
62
+ np.save(path, frame, allow_pickle=False)
63
+ except OSError as error:
64
+ raise RuntimeError("A temporary video frame could not be written") from error
65
+ self._count += 1
66
+ self._bytes += path.stat().st_size
67
+ entries.append((time_ms, path))
68
+ return StoredFrames(entries)
69
+
70
+ def diagnostics(self) -> dict[str, int | str]:
71
+ return {"storage": "temporary-lossless-npy", "frames": self._count, "bytes": self._bytes}
72
+
73
+ def __enter__(self) -> FrameStore:
74
+ return self
75
+
76
+ def __exit__(self, *_exception: object) -> None:
77
+ self._directory.cleanup()
@@ -18,6 +18,7 @@ import subprocess
18
18
  import threading
19
19
  import time
20
20
  from collections import Counter, defaultdict
21
+ from collections.abc import Sequence
21
22
  from dataclasses import dataclass, replace
22
23
  from pathlib import Path
23
24
  from typing import Any, Callable, Iterator
@@ -40,6 +41,7 @@ from app.services.brain import (
40
41
  )
41
42
  from app.services.embedding import VideoClipInput, get_video_embedding_provider
42
43
  from app.services.motion import MotionSampler
44
+ from app.services.frame_store import FrameStore
43
45
  from app.services.scene import ClipBounds, SceneDetector
44
46
  from app.services.transcription import TranscriptionService
45
47
  from app.services.vision import SemanticVisionService
@@ -1044,7 +1046,6 @@ def _select_semantic_clip_ids(
1044
1046
  if (item.get("objects") or item.get("ocr"))
1045
1047
  ]
1046
1048
  scored: list[tuple[float, int, ClipBounds]] = []
1047
- priority_ids: set[str] = set()
1048
1049
  for index, clip in enumerate(clip_plan):
1049
1050
  motion = clip_frame_scores.get(clip.clip_id) or []
1050
1051
  motion_score = (max(motion, default=0.0) * 1.5) + (
@@ -1063,8 +1064,6 @@ def _select_semantic_clip_ids(
1063
1064
  clip.start_secs < item.end_secs and clip.end_secs > item.start_secs
1064
1065
  for item in priority_ranges
1065
1066
  )
1066
- if prioritized:
1067
- priority_ids.add(clip.clip_id)
1068
1067
  # Motion, visible evidence, and local speech density are all generic
1069
1068
  # signals. A tiny chronological tie-break keeps selection deterministic.
1070
1069
  score = (
@@ -1075,7 +1074,7 @@ def _select_semantic_clip_ids(
1075
1074
  )
1076
1075
  scored.append((score, index, clip))
1077
1076
 
1078
- selected: set[str] = set(priority_ids)
1077
+ selected: set[str] = set()
1079
1078
  # Divide the source into equal chronological buckets and keep the most
1080
1079
  # informative clip in each. This guarantees whole-video coverage while
1081
1080
  # behaving like a person who skims and pauses on change-rich moments.
@@ -1264,7 +1263,7 @@ def _planner_transcript_signal(
1264
1263
 
1265
1264
  def _compute_video_embeddings(
1266
1265
  clip_plan: list[ClipBounds],
1267
- clip_frames: dict[str, list[tuple[int, np.ndarray]]],
1266
+ clip_frames: dict[str, Sequence[tuple[int, np.ndarray]]],
1268
1267
  progress: Callable[[str, int, str], None],
1269
1268
  on_clip_progress: Callable[[int, int], None] | None = None,
1270
1269
  ) -> tuple[list[dict[str, Any]], dict[str, Any]]:
@@ -1450,7 +1449,7 @@ def run_pipeline(
1450
1449
  source_duration_secs: float | None = None,
1451
1450
  ) -> tuple[dict[str, Any], float]:
1452
1451
  pipeline_started = time.monotonic()
1453
- with SmoothProgress(progress) as smooth:
1452
+ with SmoothProgress(progress) as smooth, FrameStore() as frame_store:
1454
1453
  return _run_pipeline(
1455
1454
  path,
1456
1455
  brief,
@@ -1462,6 +1461,7 @@ def run_pipeline(
1462
1461
  semantic_vision_enabled,
1463
1462
  timestamp_offset_secs,
1464
1463
  source_duration_secs,
1464
+ frame_store,
1465
1465
  )
1466
1466
 
1467
1467
 
@@ -1476,6 +1476,7 @@ def _run_pipeline(
1476
1476
  semantic_vision_enabled: bool,
1477
1477
  timestamp_offset_secs: float,
1478
1478
  source_duration_secs: float | None,
1479
+ frame_store: FrameStore,
1479
1480
  ) -> tuple[dict[str, Any], float]:
1480
1481
  smooth.phase(
1481
1482
  "probe", PHASES["plan"][0], "Reading video metadata", PHASES["plan"][1], 20
@@ -1740,11 +1741,20 @@ def _run_pipeline(
1740
1741
  )
1741
1742
  smooth.configure_eta(plan.estimated_seconds)
1742
1743
  clip_starts_ms = [round(clip.start_secs * 1_000) for clip in clip_plan]
1743
- clip_frames: dict[str, list[tuple[int, np.ndarray]]] = {
1744
+ clip_frames: dict[str, Sequence[tuple[int, np.ndarray]]] = {
1744
1745
  clip.clip_id: [] for clip in clip_plan
1745
1746
  }
1746
1747
  clip_frame_scores: dict[str, list[float]] = {clip.clip_id: [] for clip in clip_plan}
1747
- clip_previous_gray: dict[str, np.ndarray] = {}
1748
+ active_clip_id: str | None = None
1749
+ active_frames: list[tuple[int, np.ndarray]] = []
1750
+ previous_gray: np.ndarray | None = None
1751
+
1752
+ def flush_clip() -> None:
1753
+ nonlocal previous_gray
1754
+ if active_clip_id is not None and active_frames:
1755
+ clip_frames[active_clip_id] = frame_store.save(active_frames)
1756
+ active_frames.clear()
1757
+ previous_gray = None
1748
1758
  # The mode and bounded question decide the remote-frame budget. Motion
1749
1759
  # retention below then makes that budget content-aware without assuming a
1750
1760
  # genre from user-supplied descriptive metadata.
@@ -1781,14 +1791,17 @@ def _run_pipeline(
1781
1791
  len(clip_plan) - 1,
1782
1792
  )
1783
1793
  clip_id = clip_plan[clip_index].clip_id
1784
- clip_previous_gray[clip_id] = _retain_clip_frame(
1794
+ if clip_id != active_clip_id:
1795
+ flush_clip()
1796
+ active_clip_id = clip_id
1797
+ previous_gray = _retain_clip_frame(
1785
1798
  motion_sampler,
1786
- clip_frames[clip_id],
1799
+ active_frames,
1787
1800
  clip_frame_scores[clip_id],
1788
1801
  time_ms,
1789
1802
  frame,
1790
1803
  frames_per_clip,
1791
- clip_previous_gray.get(clip_id),
1804
+ previous_gray,
1792
1805
  )
1793
1806
  for detection in detections:
1794
1807
  label_counts[detection["label"]] += 1
@@ -1803,6 +1816,9 @@ def _run_pipeline(
1803
1816
  {"timeMs": time_ms, "objects": detections, "ocr": ocr_lines}
1804
1817
  )
1805
1818
 
1819
+ flush_clip()
1820
+ previous_gray = None
1821
+
1806
1822
  clips_for_description = {
1807
1823
  clip.clip_id: (
1808
1824
  round(clip.start_secs * 1_000),
@@ -2096,6 +2112,7 @@ def _run_pipeline(
2096
2112
  "processingDiagnostics": {
2097
2113
  "estimatedTotalSeconds": plan.estimated_seconds,
2098
2114
  "elapsedSeconds": elapsed_seconds,
2115
+ "frameStore": frame_store.diagnostics(),
2099
2116
  "estimateErrorSeconds": round(elapsed_seconds - plan.estimated_seconds, 3),
2100
2117
  },
2101
2118
  "transcriptionDiagnostics": {
@@ -2146,6 +2163,10 @@ def _run_pipeline(
2146
2163
  for item in plan.priority_ranges
2147
2164
  ],
2148
2165
  "semanticClips": len(clip_plan),
2166
+ "selectedSemanticClips": caption_total,
2167
+ "semanticClipBudget": _semantic_clip_budget(plan.mode, probe.duration_seconds, len(clip_plan)),
2168
+ "samplingGuarantee": "sampled-evidence-only",
2169
+ "briefEventsMayBeMissed": True,
2149
2170
  },
2150
2171
  "answeringGuide": {
2151
2172
  "goal": brief.get("goal"),
@@ -9,6 +9,8 @@ pipeline calls; `GatewayVisionClient` is its HTTP implementation detail.
9
9
 
10
10
  from __future__ import annotations
11
11
 
12
+ from collections.abc import Sequence
13
+
12
14
  import base64
13
15
  import json
14
16
  import os
@@ -203,7 +205,7 @@ class ClipCaptionRequest:
203
205
  clip_id: str
204
206
  start_ms: int
205
207
  end_ms: int
206
- frames: list[tuple[int, np.ndarray]]
208
+ frames: Sequence[tuple[int, np.ndarray]]
207
209
 
208
210
 
209
211
  @dataclass(frozen=True)
@@ -266,7 +268,7 @@ def _frame_to_inline_data(frame: np.ndarray) -> dict[str, str]:
266
268
 
267
269
 
268
270
  def _precision_frames(
269
- frames: list[tuple[int, np.ndarray]],
271
+ frames: Sequence[tuple[int, np.ndarray]],
270
272
  max_source_frames: int = 4,
271
273
  ) -> list[tuple[int, np.ndarray]]:
272
274
  """Keep a bounded chronology spanning the whole clip.
@@ -1448,7 +1450,7 @@ class SemanticVisionService:
1448
1450
 
1449
1451
  def describe_clips(
1450
1452
  self,
1451
- clips: dict[str, tuple[int, int, list[tuple[int, Any]]]],
1453
+ clips: dict[str, tuple[int, int, Sequence[tuple[int, Any]]]],
1452
1454
  brief: dict[str, Any],
1453
1455
  transcript: list[dict[str, Any]] | None = None,
1454
1456
  on_progress: Callable[[int, int], None] | None = None,
@@ -7,7 +7,7 @@
7
7
  "description": "Help your AI understand your videos, so you can ask questions and get answers from the right moments.",
8
8
  "longDescription": "Turn videos into knowledge your AI can understand. It listens to what is said, reads what appears on screen, and helps you find the moments that matter.",
9
9
  "category": "media",
10
- "version": "0.3.13",
10
+ "version": "0.3.15",
11
11
  "pricing": "free",
12
12
  "emoji": "🎥",
13
13
  "icon": "Film",