@larkup/tool-video-intelligence 0.3.3 → 0.3.6

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
@@ -226,18 +226,37 @@ curl -X POST "$VIDEO_ENDPOINT/v1/admin/devices/$USER_ID/entitlement" \
226
226
  -d '{"sourceMinutesPerMonth":60,"maxConcurrentJobs":1,"requestsPerMinute":60,"plan":"support-grant"}'
227
227
  ```
228
228
 
229
- For the common “add credits” workflow, use the support script. It calls the
230
- authenticated control plane, which updates the DynamoDB device entitlement and
231
- reconciles the current billing-period allowance atomically; it does not write
232
- to a Neon database. The minutes value is the new total monthly allowance, not
233
- an increment.
229
+ Use the support script to inspect or change an installation by the generated
230
+ user ID shown in Installed Tools. It calls the authenticated control plane and
231
+ does not write to a Neon database. `set`, `add`, and `remove` change the monthly
232
+ allowance; `reset` clears consumed minutes for the current billing period.
233
+ Meter corrections are rejected while the user has an active job so reserved
234
+ minutes cannot be lost.
234
235
 
235
236
  ```bash
236
237
  export LARKUP_VIDEO_INTELLIGENCE_CLOUD_ENDPOINT='https://video.example.com'
237
238
  export LARKUP_VIDEO_ADMIN_TOKEN='...'
238
- bash scripts/grant-cloud-credits.sh <user-id> 120 support-grant
239
+
240
+ # Read the current allowance and consumption.
241
+ bash scripts/manage-cloud-usage.sh status <user-id>
242
+
243
+ # Clear current-period consumption, preserving the monthly allowance.
244
+ bash scripts/manage-cloud-usage.sh reset <user-id>
245
+
246
+ # Set, add, or remove monthly source-minute allowance.
247
+ bash scripts/manage-cloud-usage.sh set <user-id> 120 support-grant
248
+ bash scripts/manage-cloud-usage.sh add <user-id> 60 support-grant
249
+ bash scripts/manage-cloud-usage.sh remove <user-id> 30 support-grant
250
+
251
+ # Correct the consumed-minute meter when support needs an exact adjustment.
252
+ bash scripts/manage-cloud-usage.sh usage-set <user-id> 15
253
+ bash scripts/manage-cloud-usage.sh usage-add <user-id> 5
254
+ bash scripts/manage-cloud-usage.sh usage-remove <user-id> 2.5
239
255
  ```
240
256
 
257
+ `grant-cloud-credits.sh <user-id> <minutes> [plan]` remains as a compatibility
258
+ alias for `manage-cloud-usage.sh set`.
259
+
241
260
  `$USER_ID` is the generated ID shown in Installed Tools and included in the Resend support request. Each local Larkup installation receives a separate key, while DynamoDB stores only hashes of keys and installation identifiers plus aggregate usage.
242
261
 
243
262
  Access codes remain available for support-issued or upgraded plans:
package/dist/agent.js CHANGED
@@ -61,7 +61,7 @@ export const AGENT_TOOLS = [
61
61
  method: 'queryVideoEvidence',
62
62
  workflow: 'evidence-query',
63
63
  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. 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. 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. 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.',
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. 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.',
65
65
  },
66
66
  {
67
67
  name: 'inspectVideoKnowledge',
@@ -104,6 +104,7 @@ export function attachVideoIntelligenceAgentClient(client, fetcher = globalThis.
104
104
  const asset = await mediaEvidence.getAsset(input.mediaAssetId);
105
105
  if (!asset || asset.processingStatus !== 'completed')
106
106
  return { success: false, error: 'A completed video asset is required.' };
107
+ const sourceLanguage = asset.sourceLanguage?.trim();
107
108
  const focusedQuery = focusQuestion(input.query, asset.fileName);
108
109
  const directive = validInvestigation(input.investigation)
109
110
  ? input.investigation
@@ -143,6 +144,9 @@ export function attachVideoIntelligenceAgentClient(client, fetcher = globalThis.
143
144
  kind: sourceInventory ? 'source-inventory' : 'all-evidence',
144
145
  cursor: input.cursor,
145
146
  limit: input.limit,
147
+ ...(!sourceInventory && (plan.modalities?.length ?? 0) > 0
148
+ ? { modalities: plan.modalities }
149
+ : {}),
146
150
  });
147
151
  if (scanned) {
148
152
  // A source inventory can contain headings, slides, and literal list
@@ -178,14 +182,18 @@ export function attachVideoIntelligenceAgentClient(client, fetcher = globalThis.
178
182
  timestamp: new Date().toISOString(),
179
183
  });
180
184
  const observedSubjects = observedSubjectsForAnswer(aggregate, directive);
185
+ const recordSet = !sourceInventory && plan.modalities?.length === 1 && plan.modalities[0] === 'transcript'
186
+ ? 'speech'
187
+ : (focusedInput.investigation.recordSet ?? 'all');
181
188
  return {
182
189
  success: true,
183
190
  mediaAssetId: input.mediaAssetId,
184
191
  fileName: asset.fileName,
192
+ ...(sourceLanguage ? { sourceLanguage } : {}),
185
193
  evidence,
186
194
  ...(observedSubjects.length > 0 ? { observedSubjects } : {}),
187
195
  inventory: {
188
- recordSet: focusedInput.investigation.recordSet ?? 'all',
196
+ recordSet,
189
197
  coverage: {
190
198
  complete,
191
199
  ...(scanned.coverage.reason ? { reason: scanned.coverage.reason } : {}),
@@ -300,6 +308,7 @@ export function attachVideoIntelligenceAgentClient(client, fetcher = globalThis.
300
308
  success: true,
301
309
  mediaAssetId: input.mediaAssetId,
302
310
  fileName: asset.fileName,
311
+ ...(sourceLanguage ? { sourceLanguage } : {}),
303
312
  evidence: indexedEvidence,
304
313
  supportingClip,
305
314
  ui: citationSurface(asset, context, established.map((reading) => ({
@@ -412,6 +421,7 @@ export function attachVideoIntelligenceAgentClient(client, fetcher = globalThis.
412
421
  success: true,
413
422
  mediaAssetId: input.mediaAssetId,
414
423
  fileName: asset.fileName,
424
+ ...(sourceLanguage ? { sourceLanguage } : {}),
415
425
  evidence,
416
426
  ...(supportingClip ? { supportingClip } : {}),
417
427
  ...(assessment.sufficient && supportingClip
@@ -513,6 +523,7 @@ function investigationDirectiveForOutput(directive) {
513
523
  return {
514
524
  scope: directive.scope,
515
525
  goal: directive.goal,
526
+ ...(directive.evidence?.length ? { evidence: directive.evidence } : {}),
516
527
  ...(directive.recordSet ? { recordSet: directive.recordSet } : {}),
517
528
  ...(directive.timeRange ? { timeRange: directive.timeRange } : {}),
518
529
  };
package/dist/client.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { SubmitVideoJobRequest, VideoIntelligenceClientContract, VideoJob, VideoRuntimeMode, VideoServiceEntitlement, VideoServiceUsage } from './contracts.js';
1
+ import type { SubmitVideoJobRequest, VideoIntelligenceClientContract, VideoJob, VideoMaterializationJob, VideoRuntimeMode, VideoServiceEntitlement, VideoServiceUsage } from './contracts.js';
2
2
  export interface VideoIntelligenceClientOptions {
3
3
  mode: VideoRuntimeMode;
4
4
  endpoint?: string;
@@ -38,6 +38,16 @@ export declare class VideoIntelligenceClient implements VideoIntelligenceClientC
38
38
  alreadyStopped?: boolean;
39
39
  }>;
40
40
  getUsage(): Promise<VideoServiceUsage>;
41
+ submitMaterialization(request: {
42
+ sourceUrl: string;
43
+ fileName?: string;
44
+ durationSecs?: number;
45
+ }): Promise<VideoMaterializationJob>;
46
+ getMaterialization(jobId: string): Promise<VideoMaterializationJob>;
47
+ acknowledgeMaterialization(jobId: string): Promise<{
48
+ status: string;
49
+ }>;
50
+ cancelMaterialization(jobId: string): Promise<VideoMaterializationJob>;
41
51
  redeemAccessCode(code: string): Promise<{
42
52
  apiKey: string;
43
53
  entitlement: VideoServiceEntitlement;
package/dist/client.js CHANGED
@@ -94,6 +94,26 @@ export class VideoIntelligenceClient {
94
94
  getUsage() {
95
95
  return this.request('/v1/usage');
96
96
  }
97
+ submitMaterialization(request) {
98
+ return this.request('/v1/materializations', {
99
+ method: 'POST',
100
+ body: JSON.stringify(request),
101
+ });
102
+ }
103
+ getMaterialization(jobId) {
104
+ return this.request(`/v1/materializations/${encodeURIComponent(jobId)}`);
105
+ }
106
+ acknowledgeMaterialization(jobId) {
107
+ return this.request(`/v1/materializations/${encodeURIComponent(jobId)}/ack`, {
108
+ method: 'POST',
109
+ body: JSON.stringify({}),
110
+ });
111
+ }
112
+ cancelMaterialization(jobId) {
113
+ return this.request(`/v1/materializations/${encodeURIComponent(jobId)}`, {
114
+ method: 'DELETE',
115
+ });
116
+ }
97
117
  redeemAccessCode(code) {
98
118
  return this.request('/v1/access-codes/redeem', {
99
119
  method: 'POST',
@@ -104,6 +104,22 @@ export interface VideoJob {
104
104
  resultUrl?: string | null;
105
105
  error: string | null;
106
106
  }
107
+ export interface VideoMaterializationSource {
108
+ url: string;
109
+ fileName: string;
110
+ mimeType: string;
111
+ sizeBytes: number;
112
+ durationSecs: number;
113
+ }
114
+ export interface VideoMaterializationJob {
115
+ id: string;
116
+ status: VideoJobStatus;
117
+ createdAt: string;
118
+ updatedAt: string;
119
+ progress: VideoJobProgress;
120
+ source: VideoMaterializationSource | null;
121
+ error: string | null;
122
+ }
107
123
  export interface TranscriptEvidence {
108
124
  startMs: number;
109
125
  endMs: number;
@@ -379,6 +395,16 @@ export interface VideoIntelligenceClientContract {
379
395
  status: string;
380
396
  }>;
381
397
  cancelJob(jobId: string): Promise<VideoJob>;
398
+ submitMaterialization(request: {
399
+ sourceUrl: string;
400
+ fileName?: string;
401
+ durationSecs?: number;
402
+ }): Promise<VideoMaterializationJob>;
403
+ getMaterialization(jobId: string): Promise<VideoMaterializationJob>;
404
+ acknowledgeMaterialization(jobId: string): Promise<{
405
+ status: string;
406
+ }>;
407
+ cancelMaterialization(jobId: string): Promise<VideoMaterializationJob>;
382
408
  /** Removes a local runtime's durable source/result cache for a deleted asset. */
383
409
  purgeJobData(jobId: string): Promise<void>;
384
410
  getUsage(): Promise<VideoServiceUsage>;
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.3";
12
+ readonly version: "0.3.6";
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.3',
14
+ version: '0.3.6',
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 ??
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@larkup/tool-video-intelligence",
3
- "version": "0.3.3",
3
+ "version": "0.3.6",
4
4
  "type": "module",
5
5
  "description": "Installable local and cloud video intelligence with evidence-first indexing.",
6
6
  "main": "./dist/index.js",
@@ -25,7 +25,8 @@
25
25
  "types": "./dist/runtime.d.ts",
26
26
  "import": "./dist/runtime.js",
27
27
  "default": "./dist/runtime.js"
28
- }
28
+ },
29
+ "./manifest": "./tool.manifest.json"
29
30
  },
30
31
  "bin": {
31
32
  "larkup-video-intelligence": "./scripts/runtime.mjs"
@@ -55,13 +56,13 @@
55
56
  }
56
57
  },
57
58
  "dependencies": {
58
- "@larkup/core": "0.7.4"
59
+ "@larkup/core": "0.8.0"
59
60
  },
60
61
  "devDependencies": {
61
62
  "@types/node": "^26",
62
63
  "typescript": "^7.0.2",
63
64
  "vitest": "^5.0.0",
64
- "@larkup/marketplace": "0.3.5"
65
+ "@larkup/marketplace": "0.3.9"
65
66
  },
66
67
  "publishConfig": {
67
68
  "access": "public"
@@ -50,7 +50,7 @@ ARG YOLOX_MODEL_URL=https://github.com/Megvii-BaseDetection/YOLOX/releases/downl
50
50
 
51
51
  RUN apt-get update \
52
52
  && apt-get dist-upgrade -y \
53
- && apt-get install -y --no-install-recommends ca-certificates curl ffmpeg libgomp1 python3 python3-pip \
53
+ && apt-get install -y --no-install-recommends ca-certificates curl ffmpeg fonts-liberation libasound2 libatk-bridge2.0-0 libgbm1 libgomp1 libgtk-3-0 libnss3 python3 python3-pip unzip xz-utils xvfb \
54
54
  && rm -rf /var/lib/apt/lists/*
55
55
 
56
56
  WORKDIR /service
@@ -58,7 +58,7 @@ WORKDIR /service
58
58
  FROM system AS runtime
59
59
  COPY runtime/requirements.txt ./requirements.txt
60
60
  RUN python3 -m pip install --no-cache-dir --upgrade pip \
61
- && python3 -m pip install --no-cache-dir paddlepaddle==3.0.0 -i https://www.paddlepaddle.org.cn/packages/stable/cpu/ \
61
+ && python3 -m pip install --no-cache-dir paddlepaddle==3.0.0 \
62
62
  && python3 -m pip install --no-cache-dir -r requirements.txt
63
63
 
64
64
  RUN mkdir -p /models /data \
@@ -87,6 +87,22 @@ CMD ["python3", "-m", "uvicorn", "app.main:app", "--host", "0.0.0.0", "--port",
87
87
 
88
88
  FROM runtime AS runpod
89
89
 
90
+ ARG NODE_VERSION=22.23.0
91
+ ARG CHROME_VERSION=155.0.8059.79
92
+
93
+ RUN curl --fail --location --retry 4 "https://nodejs.org/dist/v${NODE_VERSION}/node-v${NODE_VERSION}-linux-x64.tar.xz" --output /tmp/node.tar.xz \
94
+ && mkdir -p /opt/node \
95
+ && tar -xJf /tmp/node.tar.xz --strip-components=1 -C /opt/node \
96
+ && curl --fail --location --retry 4 "https://storage.googleapis.com/chrome-for-testing-public/${CHROME_VERSION}/linux64/chrome-linux64.zip" --output /tmp/chrome.zip \
97
+ && unzip -q /tmp/chrome.zip -d /opt \
98
+ && mv /opt/chrome-linux64 /opt/chrome \
99
+ && rm -f /tmp/node.tar.xz /tmp/chrome.zip \
100
+ && python3 -m pip install --no-cache-dir 'yt-dlp[default]==2026.8.19' 'yt-dlp-getpot-wpc==1.1.2' \
101
+ && mv /usr/local/bin/yt-dlp /usr/local/bin/yt-dlp-python
102
+
103
+ COPY --chmod=0755 deploy/gpu_providers/yt-dlp-wrapper.sh /usr/local/bin/yt-dlp
104
+ COPY --chmod=0755 deploy/gpu_providers/chrome-wrapper.sh /usr/local/bin/larkup-chrome
105
+
90
106
  # The RunPod entrypoint is deliberately kept out of runtime/app (and out of
91
107
  # the published npm package) -- see deploy/gpu_providers/README.md. It still
92
108
  # has to land inside the `app` package here because its imports and the
@@ -105,9 +105,14 @@ def temporary_model_environment(payload: dict[str, Any]) -> Iterator[None]:
105
105
 
106
106
  audio = parsed["audio"]
107
107
  os.environ["LARKUP_VIDEO_TRANSCRIPTION_PROVIDER"] = audio["provider"]
108
- # A managed worker must not silently spend Larkup GPU time on Whisper
109
- # after the user's paid provider rejects a request.
110
- os.environ["LARKUP_VIDEO_TRANSCRIPTION_FALLBACK"] = ""
108
+ # Keep transcription complete when a hosted recognizer cannot hear
109
+ # a source (notably singing, noisy recordings, or an unsupported
110
+ # language). This is the same canonical Modal worker, not a second
111
+ # control plane or provider pipeline; it runs only after the
112
+ # selected provider has failed or returned no usable speech.
113
+ os.environ["LARKUP_VIDEO_TRANSCRIPTION_FALLBACK"] = (
114
+ "whisper" if audio["provider"] != "whisper" else ""
115
+ )
111
116
  key_name, model_names = {
112
117
  "deepgram": (
113
118
  "DEEPGRAM_API_KEY",
@@ -2073,14 +2073,16 @@ def _synthesis_prompt(
2073
2073
  "- keyEvents are moments something happened. Include one when the evidence shows it, and say what "
2074
2074
  "the evidence shows rather than what it implies. An event that would move a tracked value belongs "
2075
2075
  "here only when the ledger actually moves to that value and stays there.\n"
2076
+ "- Write every generated natural-language summary value -- overview, participant roles, states, "
2077
+ "events, narrative notes, context facts, and uncertainties -- in the dominant spoken language "
2078
+ "identified by sourceLanguage (or the dominant language of transcriptEvidence when it is auto). "
2079
+ "Preserve names and exact on-screen text as supplied rather than translating them.\n"
2076
2080
  "- narrative is the human notebook: a compact, continuous chronological account that combines "
2077
2081
  "the synchronized speech, named participants, visual layout, appearance, on-screen labels, states, "
2078
2082
  "and events. Each entry must make sense after the preceding entry, so preserve who is on which side "
2079
2083
  "or in which group and carry that identity forward only while the evidence supports it. Replace vague "
2080
2084
  "descriptions such as 'two people discuss something' with the supported names, relationships, and "
2081
- "purpose available anywhere in the supplied evidence. Do not invent a bridge across an edit. Write "
2082
- "narrative text in the dominant spoken language identified by sourceLanguage (or the dominant language "
2083
- "of transcriptEvidence when it is auto), while preserving names and exact on-screen text as supplied. "
2085
+ "purpose available anywhere in the supplied evidence. Do not invent a bridge across an edit. "
2084
2086
  "Do not repeatedly say 'the video shows' or describe the act of analysis.\n"
2085
2087
  "- recurringOnScreenText lists short text that stayed legible across several frames. It marks "
2086
2088
  "where a display existed and when it changed. It never states what that text means: use it to "
@@ -2548,10 +2550,10 @@ def _fallback_knowledge_summary(
2548
2550
  elif len(key_events) == 1:
2549
2551
  overview = key_events[0]["event"]
2550
2552
  else:
2551
- overview = (
2552
- f"The sequence opens with {key_events[0]['event']} "
2553
- f"By the final indexed moment, {key_events[-1]['event']}"
2554
- )[:2_000]
2553
+ # Keep deterministic fallback text in the same language as the
2554
+ # semantic observations. English connective prose here was enough to
2555
+ # make an otherwise-Arabic index appear translated.
2556
+ overview = f"{key_events[0]['event']} … {key_events[-1]['event']}"[:2_000]
2555
2557
  return {
2556
2558
  "overview": overview,
2557
2559
  "participants": list(participants_by_name.values())[:50],
@@ -1406,6 +1406,16 @@ def _link_chronological_notes(
1406
1406
  )
1407
1407
 
1408
1408
 
1409
+ def _supplied_transcript_language(
1410
+ brief: dict[str, Any], transcript: list[dict[str, Any]]
1411
+ ) -> str | None:
1412
+ """Carry source/caption language through jobs that intentionally skip local STT."""
1413
+ if not transcript:
1414
+ return None
1415
+ language = str(brief.get("detectedLanguage") or brief.get("language") or "").strip()
1416
+ return language if language and language.casefold() != "auto" else None
1417
+
1418
+
1409
1419
  def _apply_video_embedding_policy(
1410
1420
  plan: ExtractionPlan,
1411
1421
  brief: dict[str, Any],
@@ -1506,7 +1516,7 @@ def _run_pipeline(
1506
1516
  for segment in (brief.get("transcriptContext") or [])
1507
1517
  if isinstance(segment, dict)
1508
1518
  ]
1509
- detected_language: str | None = None
1519
+ detected_language: str | None = _supplied_transcript_language(brief, transcript)
1510
1520
  transcription_error: BaseException | None = None
1511
1521
  transcription_units = {"completed": 0, "total": 1}
1512
1522
  transcription_units_lock = threading.Lock()
@@ -1495,6 +1495,19 @@ class SemanticVisionService:
1495
1495
  )
1496
1496
  if part
1497
1497
  )
1498
+ source_language = str(
1499
+ brief.get("detectedLanguage") or brief.get("language") or ""
1500
+ ).strip()
1501
+ if source_language and source_language.casefold() != "auto":
1502
+ goal = "\n".join(
1503
+ part
1504
+ for part in (
1505
+ goal,
1506
+ "Write every generated note and event in the source language "
1507
+ f"({source_language}); translate only when explicitly requested.",
1508
+ )
1509
+ if part
1510
+ )
1498
1511
  requests_ = [
1499
1512
  ClipCaptionRequest(clip_id=clip_id, start_ms=start_ms, end_ms=end_ms, frames=frames)
1500
1513
  for clip_id, (start_ms, end_ms, frames) in clips.items()