@mux/ai 0.1.2 → 0.1.4

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.
@@ -0,0 +1,2217 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/workflows/index.ts
31
+ var workflows_exports = {};
32
+ __export(workflows_exports, {
33
+ SUMMARY_KEYWORD_LIMIT: () => SUMMARY_KEYWORD_LIMIT,
34
+ burnedInCaptionsSchema: () => burnedInCaptionsSchema,
35
+ chapterSchema: () => chapterSchema,
36
+ chaptersSchema: () => chaptersSchema,
37
+ generateChapters: () => generateChapters,
38
+ generateVideoEmbeddings: () => generateVideoEmbeddings,
39
+ getModerationScores: () => getModerationScores,
40
+ getSummaryAndTags: () => getSummaryAndTags,
41
+ hasBurnedInCaptions: () => hasBurnedInCaptions,
42
+ summarySchema: () => summarySchema,
43
+ translateAudio: () => translateAudio,
44
+ translateCaptions: () => translateCaptions,
45
+ translationSchema: () => translationSchema
46
+ });
47
+ module.exports = __toCommonJS(workflows_exports);
48
+
49
+ // src/workflows/burned-in-captions.ts
50
+ var import_ai = require("ai");
51
+
52
+ // node_modules/dedent/dist/dedent.mjs
53
+ function ownKeys(object, enumerableOnly) {
54
+ var keys = Object.keys(object);
55
+ if (Object.getOwnPropertySymbols) {
56
+ var symbols = Object.getOwnPropertySymbols(object);
57
+ enumerableOnly && (symbols = symbols.filter(function(sym) {
58
+ return Object.getOwnPropertyDescriptor(object, sym).enumerable;
59
+ })), keys.push.apply(keys, symbols);
60
+ }
61
+ return keys;
62
+ }
63
+ function _objectSpread(target) {
64
+ for (var i = 1; i < arguments.length; i++) {
65
+ var source = null != arguments[i] ? arguments[i] : {};
66
+ i % 2 ? ownKeys(Object(source), true).forEach(function(key) {
67
+ _defineProperty(target, key, source[key]);
68
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function(key) {
69
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
70
+ });
71
+ }
72
+ return target;
73
+ }
74
+ function _defineProperty(obj, key, value) {
75
+ key = _toPropertyKey(key);
76
+ if (key in obj) {
77
+ Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
78
+ } else {
79
+ obj[key] = value;
80
+ }
81
+ return obj;
82
+ }
83
+ function _toPropertyKey(arg) {
84
+ var key = _toPrimitive(arg, "string");
85
+ return typeof key === "symbol" ? key : String(key);
86
+ }
87
+ function _toPrimitive(input, hint) {
88
+ if (typeof input !== "object" || input === null) return input;
89
+ var prim = input[Symbol.toPrimitive];
90
+ if (prim !== void 0) {
91
+ var res = prim.call(input, hint || "default");
92
+ if (typeof res !== "object") return res;
93
+ throw new TypeError("@@toPrimitive must return a primitive value.");
94
+ }
95
+ return (hint === "string" ? String : Number)(input);
96
+ }
97
+ var dedent = createDedent({});
98
+ var dedent_default = dedent;
99
+ function createDedent(options) {
100
+ dedent2.withOptions = (newOptions) => createDedent(_objectSpread(_objectSpread({}, options), newOptions));
101
+ return dedent2;
102
+ function dedent2(strings, ...values) {
103
+ const raw = typeof strings === "string" ? [strings] : strings.raw;
104
+ const {
105
+ alignValues = false,
106
+ escapeSpecialCharacters = Array.isArray(strings),
107
+ trimWhitespace = true
108
+ } = options;
109
+ let result = "";
110
+ for (let i = 0; i < raw.length; i++) {
111
+ let next = raw[i];
112
+ if (escapeSpecialCharacters) {
113
+ next = next.replace(/\\\n[ \t]*/g, "").replace(/\\`/g, "`").replace(/\\\$/g, "$").replace(/\\\{/g, "{");
114
+ }
115
+ result += next;
116
+ if (i < values.length) {
117
+ const value = alignValues ? alignValue(values[i], result) : values[i];
118
+ result += value;
119
+ }
120
+ }
121
+ const lines = result.split("\n");
122
+ let mindent = null;
123
+ for (const l of lines) {
124
+ const m = l.match(/^(\s+)\S+/);
125
+ if (m) {
126
+ const indent = m[1].length;
127
+ if (!mindent) {
128
+ mindent = indent;
129
+ } else {
130
+ mindent = Math.min(mindent, indent);
131
+ }
132
+ }
133
+ }
134
+ if (mindent !== null) {
135
+ const m = mindent;
136
+ result = lines.map((l) => l[0] === " " || l[0] === " " ? l.slice(m) : l).join("\n");
137
+ }
138
+ if (trimWhitespace) {
139
+ result = result.trim();
140
+ }
141
+ if (escapeSpecialCharacters) {
142
+ result = result.replace(/\\n/g, "\n");
143
+ }
144
+ return result;
145
+ }
146
+ }
147
+ function alignValue(value, precedingText) {
148
+ if (typeof value !== "string" || !value.includes("\n")) {
149
+ return value;
150
+ }
151
+ const currentLine = precedingText.slice(precedingText.lastIndexOf("\n") + 1);
152
+ const indentMatch = currentLine.match(/^(\s+)/);
153
+ if (indentMatch) {
154
+ const indent = indentMatch[1];
155
+ return value.replace(/\n/g, `
156
+ ${indent}`);
157
+ }
158
+ return value;
159
+ }
160
+
161
+ // src/workflows/burned-in-captions.ts
162
+ var import_zod2 = require("zod");
163
+
164
+ // src/lib/client-factory.ts
165
+ var import_mux_node = __toESM(require("@mux/mux-node"));
166
+
167
+ // src/env.ts
168
+ var import_node_path = __toESM(require("path"));
169
+ var import_dotenv = require("dotenv");
170
+ var import_dotenv_expand = require("dotenv-expand");
171
+ var import_zod = require("zod");
172
+ (0, import_dotenv_expand.expand)((0, import_dotenv.config)({
173
+ path: import_node_path.default.resolve(
174
+ process.cwd(),
175
+ process.env.NODE_ENV === "test" ? ".env.test" : ".env"
176
+ )
177
+ }));
178
+ function optionalString(description, message) {
179
+ return import_zod.z.preprocess(
180
+ (value) => typeof value === "string" && value.trim().length === 0 ? void 0 : value,
181
+ import_zod.z.string().trim().min(1, message).optional()
182
+ ).describe(description);
183
+ }
184
+ function requiredString(description, message) {
185
+ return import_zod.z.preprocess(
186
+ (value) => typeof value === "string" ? value.trim().length > 0 ? value.trim() : void 0 : value,
187
+ import_zod.z.string().trim().min(1, message)
188
+ ).describe(description);
189
+ }
190
+ var EnvSchema = import_zod.z.object({
191
+ NODE_ENV: import_zod.z.string().default("development").describe("Runtime environment."),
192
+ MUX_TOKEN_ID: requiredString("Mux access token ID.", "Required to access Mux APIs"),
193
+ MUX_TOKEN_SECRET: requiredString("Mux access token secret.", "Required to access Mux APIs"),
194
+ MUX_SIGNING_KEY: optionalString("Mux signing key ID for signed playback URLs.", "Used to sign playback URLs"),
195
+ MUX_PRIVATE_KEY: optionalString("Mux signing private key for signed playback URLs.", "Used to sign playback URLs"),
196
+ OPENAI_API_KEY: optionalString("OpenAI API key for OpenAI-backed workflows.", "OpenAI API key"),
197
+ ANTHROPIC_API_KEY: optionalString("Anthropic API key for Claude-backed workflows.", "Anthropic API key"),
198
+ GOOGLE_GENERATIVE_AI_API_KEY: optionalString("Google Generative AI API key for Gemini-backed workflows.", "Google Generative AI API key"),
199
+ ELEVENLABS_API_KEY: optionalString("ElevenLabs API key for audio translation.", "ElevenLabs API key"),
200
+ HIVE_API_KEY: optionalString("Hive Visual Moderation API key.", "Hive API key"),
201
+ S3_ENDPOINT: optionalString("S3-compatible endpoint for uploads.", "S3 endpoint"),
202
+ S3_REGION: optionalString("S3 region (defaults to 'auto' when omitted)."),
203
+ S3_BUCKET: optionalString("Bucket used for caption and audio uploads.", "S3 bucket"),
204
+ S3_ACCESS_KEY_ID: optionalString("Access key ID for S3-compatible uploads.", "S3 access key id"),
205
+ S3_SECRET_ACCESS_KEY: optionalString("Secret access key for S3-compatible uploads.", "S3 secret access key")
206
+ });
207
+ function parseEnv() {
208
+ const parsedEnv = EnvSchema.safeParse(process.env);
209
+ if (!parsedEnv.success) {
210
+ console.error("\u274C Invalid env:");
211
+ console.error(JSON.stringify(parsedEnv.error.flatten().fieldErrors, null, 2));
212
+ process.exit(1);
213
+ }
214
+ return parsedEnv.data;
215
+ }
216
+ var env = parseEnv();
217
+ var env_default = env;
218
+
219
+ // src/lib/providers.ts
220
+ var import_anthropic = require("@ai-sdk/anthropic");
221
+ var import_google = require("@ai-sdk/google");
222
+ var import_openai = require("@ai-sdk/openai");
223
+ var DEFAULT_LANGUAGE_MODELS = {
224
+ openai: "gpt-5-mini",
225
+ anthropic: "claude-haiku-4-5",
226
+ google: "gemini-2.5-flash"
227
+ };
228
+ var DEFAULT_EMBEDDING_MODELS = {
229
+ openai: "text-embedding-3-small",
230
+ google: "gemini-embedding-001"
231
+ };
232
+ function requireEnv(value, name) {
233
+ if (!value) {
234
+ throw new Error(`Missing ${name}. Set ${name} in your environment or pass it in options.`);
235
+ }
236
+ return value;
237
+ }
238
+ function resolveLanguageModel(options = {}) {
239
+ const provider = options.provider || "openai";
240
+ const modelId = options.model || DEFAULT_LANGUAGE_MODELS[provider];
241
+ switch (provider) {
242
+ case "openai": {
243
+ const apiKey = options.openaiApiKey ?? env_default.OPENAI_API_KEY;
244
+ requireEnv(apiKey, "OPENAI_API_KEY");
245
+ const openai = (0, import_openai.createOpenAI)({
246
+ apiKey
247
+ });
248
+ return {
249
+ provider,
250
+ modelId,
251
+ model: openai(modelId)
252
+ };
253
+ }
254
+ case "anthropic": {
255
+ const apiKey = options.anthropicApiKey ?? env_default.ANTHROPIC_API_KEY;
256
+ requireEnv(apiKey, "ANTHROPIC_API_KEY");
257
+ const anthropic = (0, import_anthropic.createAnthropic)({
258
+ apiKey
259
+ });
260
+ return {
261
+ provider,
262
+ modelId,
263
+ model: anthropic(modelId)
264
+ };
265
+ }
266
+ case "google": {
267
+ const apiKey = options.googleApiKey ?? env_default.GOOGLE_GENERATIVE_AI_API_KEY;
268
+ requireEnv(apiKey, "GOOGLE_GENERATIVE_AI_API_KEY");
269
+ const google = (0, import_google.createGoogleGenerativeAI)({
270
+ apiKey
271
+ });
272
+ return {
273
+ provider,
274
+ modelId,
275
+ model: google(modelId)
276
+ };
277
+ }
278
+ default: {
279
+ const exhaustiveCheck = provider;
280
+ throw new Error(`Unsupported provider: ${exhaustiveCheck}`);
281
+ }
282
+ }
283
+ }
284
+ function resolveEmbeddingModel(options = {}) {
285
+ const provider = options.provider || "openai";
286
+ const modelId = options.model || DEFAULT_EMBEDDING_MODELS[provider];
287
+ switch (provider) {
288
+ case "openai": {
289
+ const apiKey = options.openaiApiKey ?? env_default.OPENAI_API_KEY;
290
+ requireEnv(apiKey, "OPENAI_API_KEY");
291
+ const openai = (0, import_openai.createOpenAI)({
292
+ apiKey
293
+ });
294
+ return {
295
+ provider,
296
+ modelId,
297
+ model: openai.embedding(modelId)
298
+ };
299
+ }
300
+ case "google": {
301
+ const apiKey = options.googleApiKey ?? env_default.GOOGLE_GENERATIVE_AI_API_KEY;
302
+ requireEnv(apiKey, "GOOGLE_GENERATIVE_AI_API_KEY");
303
+ const google = (0, import_google.createGoogleGenerativeAI)({
304
+ apiKey
305
+ });
306
+ return {
307
+ provider,
308
+ modelId,
309
+ model: google.textEmbeddingModel(modelId)
310
+ };
311
+ }
312
+ default: {
313
+ const exhaustiveCheck = provider;
314
+ throw new Error(`Unsupported embedding provider: ${exhaustiveCheck}`);
315
+ }
316
+ }
317
+ }
318
+
319
+ // src/lib/client-factory.ts
320
+ function validateCredentials(options, requiredProvider) {
321
+ const muxTokenId = options.muxTokenId ?? env_default.MUX_TOKEN_ID;
322
+ const muxTokenSecret = options.muxTokenSecret ?? env_default.MUX_TOKEN_SECRET;
323
+ const openaiApiKey = options.openaiApiKey ?? env_default.OPENAI_API_KEY;
324
+ const anthropicApiKey = options.anthropicApiKey ?? env_default.ANTHROPIC_API_KEY;
325
+ const googleApiKey = options.googleApiKey ?? env_default.GOOGLE_GENERATIVE_AI_API_KEY;
326
+ if (!muxTokenId || !muxTokenSecret) {
327
+ throw new Error(
328
+ "Mux credentials are required. Provide muxTokenId and muxTokenSecret in options or set MUX_TOKEN_ID and MUX_TOKEN_SECRET environment variables."
329
+ );
330
+ }
331
+ if (requiredProvider === "openai" && !openaiApiKey) {
332
+ throw new Error(
333
+ "OpenAI API key is required. Provide openaiApiKey in options or set OPENAI_API_KEY environment variable."
334
+ );
335
+ }
336
+ if (requiredProvider === "anthropic" && !anthropicApiKey) {
337
+ throw new Error(
338
+ "Anthropic API key is required. Provide anthropicApiKey in options or set ANTHROPIC_API_KEY environment variable."
339
+ );
340
+ }
341
+ if (requiredProvider === "google" && !googleApiKey) {
342
+ throw new Error(
343
+ "Google Generative AI API key is required. Provide googleApiKey in options or set GOOGLE_GENERATIVE_AI_API_KEY environment variable."
344
+ );
345
+ }
346
+ return {
347
+ muxTokenId,
348
+ muxTokenSecret,
349
+ openaiApiKey,
350
+ anthropicApiKey,
351
+ googleApiKey
352
+ };
353
+ }
354
+ function createMuxClient(credentials) {
355
+ if (!credentials.muxTokenId || !credentials.muxTokenSecret) {
356
+ throw new Error("Mux credentials are required. Provide muxTokenId and muxTokenSecret in options or set MUX_TOKEN_ID and MUX_TOKEN_SECRET environment variables.");
357
+ }
358
+ return new import_mux_node.default({
359
+ tokenId: credentials.muxTokenId,
360
+ tokenSecret: credentials.muxTokenSecret
361
+ });
362
+ }
363
+ function createWorkflowClients(options, provider) {
364
+ const providerToUse = provider || options.provider || "openai";
365
+ const credentials = validateCredentials(options, providerToUse);
366
+ const languageModel = resolveLanguageModel({
367
+ ...options,
368
+ provider: providerToUse
369
+ });
370
+ return {
371
+ mux: createMuxClient(credentials),
372
+ languageModel,
373
+ credentials
374
+ };
375
+ }
376
+
377
+ // src/lib/image-download.ts
378
+ var import_node_buffer = require("buffer");
379
+ var import_p_retry = __toESM(require("p-retry"));
380
+ var DEFAULT_OPTIONS = {
381
+ timeout: 1e4,
382
+ retries: 3,
383
+ retryDelay: 1e3,
384
+ maxRetryDelay: 1e4,
385
+ exponentialBackoff: true
386
+ };
387
+ async function downloadImageAsBase64(url, options = {}) {
388
+ const opts = { ...DEFAULT_OPTIONS, ...options };
389
+ let attemptCount = 0;
390
+ return (0, import_p_retry.default)(
391
+ async () => {
392
+ attemptCount++;
393
+ const controller = new AbortController();
394
+ const timeoutId = setTimeout(() => controller.abort(), opts.timeout);
395
+ try {
396
+ const response = await fetch(url, {
397
+ signal: controller.signal,
398
+ headers: {
399
+ "User-Agent": "@mux/ai image downloader"
400
+ }
401
+ });
402
+ clearTimeout(timeoutId);
403
+ if (!response.ok) {
404
+ if (response.status >= 400 && response.status < 500 && response.status !== 429) {
405
+ throw new import_p_retry.AbortError(`HTTP ${response.status}: ${response.statusText}`);
406
+ }
407
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
408
+ }
409
+ const contentType = response.headers.get("content-type");
410
+ if (!contentType?.startsWith("image/")) {
411
+ throw new import_p_retry.AbortError(`Invalid content type: ${contentType}. Expected image/*`);
412
+ }
413
+ const arrayBuffer = await response.arrayBuffer();
414
+ const buffer = import_node_buffer.Buffer.from(arrayBuffer);
415
+ if (buffer.length === 0) {
416
+ throw new import_p_retry.AbortError("Downloaded image is empty");
417
+ }
418
+ const base64Data = `data:${contentType};base64,${buffer.toString("base64")}`;
419
+ return {
420
+ base64Data,
421
+ buffer,
422
+ url,
423
+ contentType,
424
+ sizeBytes: buffer.length,
425
+ attempts: attemptCount
426
+ };
427
+ } catch (error) {
428
+ clearTimeout(timeoutId);
429
+ if (error instanceof import_p_retry.AbortError) {
430
+ throw error;
431
+ }
432
+ if (error instanceof Error) {
433
+ if (error.name === "AbortError") {
434
+ throw new Error(`Request timeout after ${opts.timeout}ms`);
435
+ }
436
+ throw new Error(`Download failed: ${error.message}`);
437
+ }
438
+ throw new Error("Unknown download error");
439
+ }
440
+ },
441
+ {
442
+ retries: opts.retries,
443
+ minTimeout: opts.retryDelay,
444
+ maxTimeout: opts.maxRetryDelay,
445
+ factor: opts.exponentialBackoff ? 2 : 1,
446
+ randomize: true,
447
+ // Add jitter to prevent thundering herd
448
+ onFailedAttempt: (error) => {
449
+ console.warn(`Image download attempt ${error.attemptNumber} failed for ${url}`);
450
+ if (error.retriesLeft > 0) {
451
+ console.warn(`Retrying... (${error.retriesLeft} attempts left)`);
452
+ }
453
+ }
454
+ }
455
+ );
456
+ }
457
+ async function downloadImagesAsBase64(urls, options = {}, maxConcurrent = 5) {
458
+ const results = [];
459
+ for (let i = 0; i < urls.length; i += maxConcurrent) {
460
+ const batch = urls.slice(i, i + maxConcurrent);
461
+ const batchPromises = batch.map((url) => downloadImageAsBase64(url, options));
462
+ const batchResults = await Promise.all(batchPromises);
463
+ results.push(...batchResults);
464
+ }
465
+ return results;
466
+ }
467
+
468
+ // src/lib/mux-assets.ts
469
+ function getPlaybackId(asset) {
470
+ const playbackIds = asset.playback_ids || [];
471
+ const publicPlaybackId = playbackIds.find((pid) => pid.policy === "public");
472
+ if (publicPlaybackId?.id) {
473
+ return { id: publicPlaybackId.id, policy: "public" };
474
+ }
475
+ const signedPlaybackId = playbackIds.find((pid) => pid.policy === "signed");
476
+ if (signedPlaybackId?.id) {
477
+ return { id: signedPlaybackId.id, policy: "signed" };
478
+ }
479
+ throw new Error(
480
+ "No public or signed playback ID found for this asset. A public or signed playback ID is required. DRM playback IDs are not currently supported."
481
+ );
482
+ }
483
+ async function getPlaybackIdForAsset(mux, assetId) {
484
+ const asset = await mux.video.assets.retrieve(assetId);
485
+ const { id: playbackId, policy } = getPlaybackId(asset);
486
+ return { asset, playbackId, policy };
487
+ }
488
+
489
+ // src/lib/prompt-builder.ts
490
+ function renderSection(section) {
491
+ const { tag, content, attributes } = section;
492
+ const XML_NAME_PATTERN = /^[A-Z_][\w.:-]*$/i;
493
+ const assertValidXmlName = (name, context) => {
494
+ if (!XML_NAME_PATTERN.test(name)) {
495
+ throw new Error(`Invalid XML ${context} name: "${name}"`);
496
+ }
497
+ };
498
+ const escapeXmlText = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;/");
499
+ const escapeXmlAttribute = (value) => escapeXmlText(value).replace(/"/g, "&quot;");
500
+ if (!content.trim()) {
501
+ return "";
502
+ }
503
+ assertValidXmlName(tag, "tag");
504
+ const attrString = attributes ? ` ${Object.entries(attributes).map(([key, value]) => {
505
+ assertValidXmlName(key, "attribute");
506
+ return `${key}="${escapeXmlAttribute(value)}"`;
507
+ }).join(" ")}` : "";
508
+ const safeContent = escapeXmlText(content.trim());
509
+ return `<${tag}${attrString}>
510
+ ${safeContent}
511
+ </${tag}>`;
512
+ }
513
+ function resolveSection(defaultSection, override) {
514
+ if (override === void 0) {
515
+ return defaultSection;
516
+ }
517
+ if (typeof override === "string") {
518
+ return { ...defaultSection, content: override };
519
+ }
520
+ return override;
521
+ }
522
+ function createPromptBuilder(config2) {
523
+ const { template, sectionOrder } = config2;
524
+ const getSection = (section, override) => {
525
+ const resolved = resolveSection(template[section], override);
526
+ return renderSection(resolved);
527
+ };
528
+ const build = (overrides) => {
529
+ const sections = sectionOrder.map((sectionKey) => getSection(sectionKey, overrides?.[sectionKey])).filter(Boolean);
530
+ return sections.join("\n\n");
531
+ };
532
+ const buildWithContext = (overrides, additionalSections) => {
533
+ const basePrompt = build(overrides);
534
+ if (!additionalSections?.length) {
535
+ return basePrompt;
536
+ }
537
+ const additional = additionalSections.map(renderSection).filter(Boolean).join("\n\n");
538
+ return additional ? `${basePrompt}
539
+
540
+ ${additional}` : basePrompt;
541
+ };
542
+ return {
543
+ template,
544
+ build,
545
+ buildWithContext,
546
+ getSection
547
+ };
548
+ }
549
+ function createTranscriptSection(transcriptText, format = "plain text") {
550
+ return {
551
+ tag: "transcript",
552
+ content: transcriptText,
553
+ attributes: { format }
554
+ };
555
+ }
556
+ function createToneSection(instruction) {
557
+ return {
558
+ tag: "tone",
559
+ content: instruction
560
+ };
561
+ }
562
+
563
+ // src/lib/url-signing.ts
564
+ var import_mux_node2 = __toESM(require("@mux/mux-node"));
565
+ function resolveSigningContext(config2) {
566
+ const keyId = config2.muxSigningKey ?? env_default.MUX_SIGNING_KEY;
567
+ const keySecret = config2.muxPrivateKey ?? env_default.MUX_PRIVATE_KEY;
568
+ if (!keyId || !keySecret) {
569
+ return void 0;
570
+ }
571
+ return { keyId, keySecret };
572
+ }
573
+ function createSigningClient(context) {
574
+ return new import_mux_node2.default({
575
+ // These are not needed for signing, but the SDK requires them
576
+ // Using empty strings as we only need the jwt functionality
577
+ tokenId: env_default.MUX_TOKEN_ID || "",
578
+ tokenSecret: env_default.MUX_TOKEN_SECRET || "",
579
+ jwtSigningKey: context.keyId,
580
+ jwtPrivateKey: context.keySecret
581
+ });
582
+ }
583
+ async function signPlaybackId(playbackId, context, type = "video", params) {
584
+ const client = createSigningClient(context);
585
+ const stringParams = params ? Object.fromEntries(
586
+ Object.entries(params).map(([key, value]) => [key, String(value)])
587
+ ) : void 0;
588
+ return client.jwt.signPlaybackId(playbackId, {
589
+ type,
590
+ expiration: context.expiration || "1h",
591
+ params: stringParams
592
+ });
593
+ }
594
+ async function signUrl(url, playbackId, context, type = "video", params) {
595
+ const token = await signPlaybackId(playbackId, context, type, params);
596
+ const separator = url.includes("?") ? "&" : "?";
597
+ return `${url}${separator}token=${token}`;
598
+ }
599
+
600
+ // src/primitives/storyboards.ts
601
+ var DEFAULT_STORYBOARD_WIDTH = 640;
602
+ async function getStoryboardUrl(playbackId, width = DEFAULT_STORYBOARD_WIDTH, signingContext) {
603
+ const baseUrl = `https://image.mux.com/${playbackId}/storyboard.png`;
604
+ if (signingContext) {
605
+ return signUrl(baseUrl, playbackId, signingContext, "storyboard", { width });
606
+ }
607
+ return `${baseUrl}?width=${width}`;
608
+ }
609
+
610
+ // src/workflows/burned-in-captions.ts
611
+ var burnedInCaptionsSchema = import_zod2.z.object({
612
+ hasBurnedInCaptions: import_zod2.z.boolean(),
613
+ confidence: import_zod2.z.number().min(0).max(1),
614
+ detectedLanguage: import_zod2.z.string().nullable()
615
+ });
616
+ var SYSTEM_PROMPT = dedent_default`
617
+ <role>
618
+ You are an expert at analyzing video frames to detect burned-in captions (also called open captions or hardcoded subtitles).
619
+ These are text overlays that are permanently embedded in the video image, common on TikTok, Instagram Reels, and other social media platforms.
620
+ </role>
621
+
622
+ <critical_note>
623
+ Burned-in captions must appear consistently across MOST frames in the storyboard.
624
+ Text appearing in only 1-2 frames at the end is typically marketing copy, taglines, or end-cards - NOT burned-in captions.
625
+ </critical_note>
626
+
627
+ <confidence_scoring>
628
+ Use this rubric to determine your confidence score (0.0-1.0):
629
+
630
+ - Score 1.0: Definitive captions - text overlays visible in most frames, consistent positioning, content changes between frames indicating dialogue/narration, clear caption-style formatting
631
+ - Score 0.7-0.9: Strong evidence - captions visible across multiple frames with consistent placement, but minor ambiguity (e.g., some frames unclear, atypical styling)
632
+ - Score 0.4-0.6: Moderate evidence - text present in several frames but uncertain classification (e.g., could be captions or persistent on-screen graphics, ambiguous formatting)
633
+ - Score 0.1-0.3: Weak evidence - minimal text detected, appears in only a few frames, likely marketing copy or end-cards rather than captions
634
+ - Score 0.0: No captions - no text overlays detected, or text is clearly not captions (logos, watermarks, scene content, single end-card)
635
+ </confidence_scoring>
636
+
637
+ <context>
638
+ You receive storyboard images containing multiple sequential frames extracted from a video.
639
+ These frames are arranged in a grid and represent the visual progression of the content over time.
640
+ Read frames left-to-right, top-to-bottom to understand the temporal sequence.
641
+ </context>
642
+
643
+ <capabilities>
644
+ - Detect and analyze text overlays in video frames
645
+ - Distinguish between captions and other text elements (marketing, logos, UI)
646
+ - Identify language of detected caption text
647
+ - Assess confidence in caption detection
648
+ </capabilities>
649
+
650
+ <constraints>
651
+ - Only classify as burned-in captions when evidence is clear across multiple frames
652
+ - Base decisions on observable visual evidence
653
+ - Return structured data matching the requested schema
654
+ </constraints>`;
655
+ var burnedInCaptionsPromptBuilder = createPromptBuilder({
656
+ template: {
657
+ task: {
658
+ tag: "task",
659
+ content: dedent_default`
660
+ Analyze the provided video storyboard to detect burned-in captions (hardcoded subtitles).
661
+ Count frames with text vs no text, note position consistency and whether text changes across frames.
662
+ Decide if captions exist, with confidence (0.0-1.0) and detected language if any.`
663
+ },
664
+ analysisSteps: {
665
+ tag: "analysis_steps",
666
+ content: dedent_default`
667
+ 1. COUNT how many frames contain text overlays vs. how many don't
668
+ 2. Check if text appears in consistent positions across multiple frames
669
+ 3. Verify text changes content between frames (indicating dialogue/narration)
670
+ 4. Ensure text has caption-style formatting (contrasting colors, readable fonts)
671
+ 5. If captions are detected, identify the language of the text`
672
+ },
673
+ positiveIndicators: {
674
+ tag: "classify_as_captions",
675
+ content: dedent_default`
676
+ ONLY classify as burned-in captions if:
677
+ - Text appears in multiple frames (not just 1-2 end frames)
678
+ - Text positioning is consistent across those frames
679
+ - Content suggests dialogue, narration, or subtitles (not marketing)
680
+ - Formatting looks like captions (not graphics/logos)`
681
+ },
682
+ negativeIndicators: {
683
+ tag: "not_captions",
684
+ content: dedent_default`
685
+ DO NOT classify as burned-in captions:
686
+ - Marketing taglines appearing only in final 1-2 frames
687
+ - Single words or phrases that don't change between frames
688
+ - Graphics, logos, watermarks, or UI elements
689
+ - Text that's part of the original scene content
690
+ - End-cards with calls-to-action or brand messaging`
691
+ }
692
+ },
693
+ sectionOrder: ["task", "analysisSteps", "positiveIndicators", "negativeIndicators"]
694
+ });
695
+ function buildUserPrompt(promptOverrides) {
696
+ return burnedInCaptionsPromptBuilder.build(promptOverrides);
697
+ }
698
+ var DEFAULT_PROVIDER = "openai";
699
+ async function hasBurnedInCaptions(assetId, options = {}) {
700
+ const {
701
+ provider = DEFAULT_PROVIDER,
702
+ model,
703
+ imageSubmissionMode = "url",
704
+ imageDownloadOptions,
705
+ promptOverrides,
706
+ ...config2
707
+ } = options;
708
+ const userPrompt = buildUserPrompt(promptOverrides);
709
+ const clients = createWorkflowClients(
710
+ { ...config2, model },
711
+ provider
712
+ );
713
+ const { playbackId, policy } = await getPlaybackIdForAsset(clients.mux, assetId);
714
+ const signingContext = resolveSigningContext(options);
715
+ if (policy === "signed" && !signingContext) {
716
+ throw new Error(
717
+ "Signed playback ID requires signing credentials. Provide muxSigningKey and muxPrivateKey in options or set MUX_SIGNING_KEY and MUX_PRIVATE_KEY environment variables."
718
+ );
719
+ }
720
+ const imageUrl = await getStoryboardUrl(playbackId, 640, policy === "signed" ? signingContext : void 0);
721
+ const analyzeStoryboard = async (imageDataUrl) => {
722
+ const response = await (0, import_ai.generateObject)({
723
+ model: clients.languageModel.model,
724
+ schema: burnedInCaptionsSchema,
725
+ abortSignal: options.abortSignal,
726
+ experimental_telemetry: { isEnabled: true },
727
+ messages: [
728
+ {
729
+ role: "system",
730
+ content: SYSTEM_PROMPT
731
+ },
732
+ {
733
+ role: "user",
734
+ content: [
735
+ { type: "text", text: userPrompt },
736
+ { type: "image", image: imageDataUrl }
737
+ ]
738
+ }
739
+ ]
740
+ });
741
+ return {
742
+ result: response.object,
743
+ usage: {
744
+ inputTokens: response.usage.inputTokens,
745
+ outputTokens: response.usage.outputTokens,
746
+ totalTokens: response.usage.totalTokens,
747
+ reasoningTokens: response.usage.reasoningTokens,
748
+ cachedInputTokens: response.usage.cachedInputTokens
749
+ }
750
+ };
751
+ };
752
+ let analysisResponse;
753
+ if (imageSubmissionMode === "base64") {
754
+ const downloadResult = await downloadImageAsBase64(imageUrl, imageDownloadOptions);
755
+ analysisResponse = await analyzeStoryboard(downloadResult.base64Data);
756
+ } else {
757
+ analysisResponse = await analyzeStoryboard(imageUrl);
758
+ }
759
+ if (!analysisResponse.result) {
760
+ throw new Error("No analysis result received from AI provider");
761
+ }
762
+ return {
763
+ assetId,
764
+ hasBurnedInCaptions: analysisResponse.result.hasBurnedInCaptions ?? false,
765
+ confidence: analysisResponse.result.confidence ?? 0,
766
+ detectedLanguage: analysisResponse.result.detectedLanguage ?? null,
767
+ storyboardUrl: imageUrl,
768
+ usage: analysisResponse.usage
769
+ };
770
+ }
771
+
772
+ // src/workflows/chapters.ts
773
+ var import_ai2 = require("ai");
774
+ var import_zod3 = require("zod");
775
+
776
+ // src/lib/retry.ts
777
+ var DEFAULT_RETRY_OPTIONS = {
778
+ maxRetries: 3,
779
+ baseDelay: 2e3,
780
+ maxDelay: 1e4
781
+ };
782
+ function defaultShouldRetry(error, _attempt) {
783
+ return Boolean(error.message && error.message.includes("Timeout while downloading"));
784
+ }
785
+ function calculateDelay(attempt, baseDelay, maxDelay) {
786
+ const exponentialDelay = baseDelay * 2 ** (attempt - 1);
787
+ const delayWithJitter = exponentialDelay * (0.5 + Math.random() * 0.5);
788
+ return Math.min(delayWithJitter, maxDelay);
789
+ }
790
+ async function withRetry(fn, {
791
+ maxRetries = DEFAULT_RETRY_OPTIONS.maxRetries,
792
+ baseDelay = DEFAULT_RETRY_OPTIONS.baseDelay,
793
+ maxDelay = DEFAULT_RETRY_OPTIONS.maxDelay,
794
+ shouldRetry = defaultShouldRetry
795
+ } = {}) {
796
+ let lastError;
797
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
798
+ try {
799
+ return await fn();
800
+ } catch (error) {
801
+ lastError = error instanceof Error ? error : new Error(String(error));
802
+ const isLastAttempt = attempt === maxRetries;
803
+ if (isLastAttempt || !shouldRetry(lastError, attempt + 1)) {
804
+ throw lastError;
805
+ }
806
+ const delay2 = calculateDelay(attempt + 1, baseDelay, maxDelay);
807
+ console.warn(
808
+ `Attempt ${attempt + 1} failed: ${lastError.message}. Retrying in ${Math.round(delay2)}ms...`
809
+ );
810
+ await new Promise((resolve) => setTimeout(resolve, delay2));
811
+ }
812
+ }
813
+ throw lastError || new Error("Retry failed with unknown error");
814
+ }
815
+
816
+ // src/primitives/transcripts.ts
817
+ function getReadyTextTracks(asset) {
818
+ return (asset.tracks || []).filter(
819
+ (track) => track.type === "text" && track.status === "ready"
820
+ );
821
+ }
822
+ function findCaptionTrack(asset, languageCode) {
823
+ const tracks = getReadyTextTracks(asset);
824
+ if (!tracks.length)
825
+ return void 0;
826
+ if (!languageCode) {
827
+ return tracks[0];
828
+ }
829
+ return tracks.find(
830
+ (track) => track.text_type === "subtitles" && track.language_code === languageCode
831
+ );
832
+ }
833
+ function extractTextFromVTT(vttContent) {
834
+ if (!vttContent.trim()) {
835
+ return "";
836
+ }
837
+ const lines = vttContent.split("\n");
838
+ const textLines = [];
839
+ for (let i = 0; i < lines.length; i++) {
840
+ const line = lines[i].trim();
841
+ if (!line)
842
+ continue;
843
+ if (line === "WEBVTT")
844
+ continue;
845
+ if (line.startsWith("NOTE "))
846
+ continue;
847
+ if (line.includes("-->"))
848
+ continue;
849
+ if (/^[\w-]+$/.test(line) && !line.includes(" "))
850
+ continue;
851
+ if (line.startsWith("STYLE") || line.startsWith("REGION"))
852
+ continue;
853
+ const cleanLine = line.replace(/<[^>]*>/g, "").trim();
854
+ if (cleanLine) {
855
+ textLines.push(cleanLine);
856
+ }
857
+ }
858
+ return textLines.join(" ").replace(/\s+/g, " ").trim();
859
+ }
860
+ function vttTimestampToSeconds(timestamp) {
861
+ const parts = timestamp.split(":");
862
+ if (parts.length !== 3)
863
+ return 0;
864
+ const hours = Number.parseInt(parts[0], 10) || 0;
865
+ const minutes = Number.parseInt(parts[1], 10) || 0;
866
+ const seconds = Number.parseFloat(parts[2]) || 0;
867
+ return hours * 3600 + minutes * 60 + seconds;
868
+ }
869
+ function extractTimestampedTranscript(vttContent) {
870
+ if (!vttContent.trim()) {
871
+ return "";
872
+ }
873
+ const lines = vttContent.split("\n");
874
+ const segments = [];
875
+ for (let i = 0; i < lines.length; i++) {
876
+ const line = lines[i].trim();
877
+ if (line.includes("-->")) {
878
+ const startTime = line.split(" --> ")[0].trim();
879
+ const timeInSeconds = vttTimestampToSeconds(startTime);
880
+ let j = i + 1;
881
+ while (j < lines.length && !lines[j].trim()) {
882
+ j++;
883
+ }
884
+ if (j < lines.length) {
885
+ const text = lines[j].trim().replace(/<[^>]*>/g, "");
886
+ if (text) {
887
+ segments.push({ time: timeInSeconds, text });
888
+ }
889
+ }
890
+ }
891
+ }
892
+ return segments.map((segment) => `[${Math.floor(segment.time)}s] ${segment.text}`).join("\n");
893
+ }
894
+ function parseVTTCues(vttContent) {
895
+ if (!vttContent.trim())
896
+ return [];
897
+ const lines = vttContent.split("\n");
898
+ const cues = [];
899
+ for (let i = 0; i < lines.length; i++) {
900
+ const line = lines[i].trim();
901
+ if (line.includes("-->")) {
902
+ const [startStr, endStr] = line.split(" --> ").map((s) => s.trim());
903
+ const startTime = vttTimestampToSeconds(startStr);
904
+ const endTime = vttTimestampToSeconds(endStr.split(" ")[0]);
905
+ const textLines = [];
906
+ let j = i + 1;
907
+ while (j < lines.length && lines[j].trim() && !lines[j].includes("-->")) {
908
+ const cleanLine = lines[j].trim().replace(/<[^>]*>/g, "");
909
+ if (cleanLine)
910
+ textLines.push(cleanLine);
911
+ j++;
912
+ }
913
+ if (textLines.length > 0) {
914
+ cues.push({
915
+ startTime,
916
+ endTime,
917
+ text: textLines.join(" ")
918
+ });
919
+ }
920
+ }
921
+ }
922
+ return cues;
923
+ }
924
+ async function buildTranscriptUrl(playbackId, trackId, signingContext) {
925
+ const baseUrl = `https://stream.mux.com/${playbackId}/text/${trackId}.vtt`;
926
+ if (signingContext) {
927
+ return signUrl(baseUrl, playbackId, signingContext, "video");
928
+ }
929
+ return baseUrl;
930
+ }
931
+ async function fetchTranscriptForAsset(asset, playbackId, options = {}) {
932
+ const { languageCode, cleanTranscript = true, signingContext } = options;
933
+ const track = findCaptionTrack(asset, languageCode);
934
+ if (!track) {
935
+ return { transcriptText: "" };
936
+ }
937
+ if (!track.id) {
938
+ return { transcriptText: "", track };
939
+ }
940
+ const transcriptUrl = await buildTranscriptUrl(playbackId, track.id, signingContext);
941
+ try {
942
+ const response = await fetch(transcriptUrl);
943
+ if (!response.ok) {
944
+ return { transcriptText: "", transcriptUrl, track };
945
+ }
946
+ const rawVtt = await response.text();
947
+ const transcriptText = cleanTranscript ? extractTextFromVTT(rawVtt) : rawVtt;
948
+ return { transcriptText, transcriptUrl, track };
949
+ } catch (error) {
950
+ console.warn("Failed to fetch transcript:", error);
951
+ return { transcriptText: "", transcriptUrl, track };
952
+ }
953
+ }
954
+
955
+ // src/workflows/chapters.ts
956
+ var chapterSchema = import_zod3.z.object({
957
+ startTime: import_zod3.z.number(),
958
+ title: import_zod3.z.string()
959
+ });
960
+ var chaptersSchema = import_zod3.z.object({
961
+ chapters: import_zod3.z.array(chapterSchema)
962
+ });
963
+ var DEFAULT_PROVIDER2 = "openai";
964
+ var SYSTEM_PROMPT2 = `Your role is to segment the following captions into chunked chapters, summarising each chapter with a title.
965
+
966
+ Analyze the transcript and create logical chapter breaks based on topic changes, major transitions, or distinct sections of content. Each chapter should represent a meaningful segment of the video.
967
+
968
+ You must respond with valid JSON in exactly this format:
969
+ {
970
+ "chapters": [
971
+ {"startTime": 0, "title": "Introduction"},
972
+ {"startTime": 45.5, "title": "Main Topic Discussion"},
973
+ {"startTime": 120.0, "title": "Conclusion"}
974
+ ]
975
+ }
976
+
977
+ Important rules:
978
+ - startTime must be in seconds (not HH:MM:SS format)
979
+ - Always start with startTime: 0 for the first chapter
980
+ - Create 3-8 chapters depending on content length and natural breaks
981
+ - Chapter titles should be concise and descriptive
982
+ - Do not include any text before or after the JSON
983
+ - The JSON must be valid and parseable`;
984
+ async function generateChapters(assetId, languageCode, options = {}) {
985
+ const { provider = DEFAULT_PROVIDER2, model, abortSignal } = options;
986
+ const clients = createWorkflowClients({ ...options, model }, provider);
987
+ const { asset: assetData, playbackId, policy } = await getPlaybackIdForAsset(clients.mux, assetId);
988
+ const signingContext = resolveSigningContext(options);
989
+ if (policy === "signed" && !signingContext) {
990
+ throw new Error(
991
+ "Signed playback ID requires signing credentials. Provide muxSigningKey and muxPrivateKey in options or set MUX_SIGNING_KEY and MUX_PRIVATE_KEY environment variables."
992
+ );
993
+ }
994
+ const transcriptResult = await fetchTranscriptForAsset(assetData, playbackId, {
995
+ languageCode,
996
+ cleanTranscript: false,
997
+ // keep timestamps for chapter segmentation
998
+ signingContext: policy === "signed" ? signingContext : void 0
999
+ });
1000
+ if (!transcriptResult.track || !transcriptResult.transcriptText) {
1001
+ const availableLanguages = getReadyTextTracks(assetData).map((t) => t.language_code).filter(Boolean).join(", ");
1002
+ throw new Error(
1003
+ `No caption track found for language '${languageCode}'. Available languages: ${availableLanguages || "none"}`
1004
+ );
1005
+ }
1006
+ const timestampedTranscript = extractTimestampedTranscript(transcriptResult.transcriptText);
1007
+ if (!timestampedTranscript) {
1008
+ throw new Error("No usable content found in caption track");
1009
+ }
1010
+ let chaptersData = null;
1011
+ try {
1012
+ const response = await withRetry(
1013
+ () => (0, import_ai2.generateObject)({
1014
+ model: clients.languageModel.model,
1015
+ schema: chaptersSchema,
1016
+ abortSignal,
1017
+ messages: [
1018
+ {
1019
+ role: "system",
1020
+ content: SYSTEM_PROMPT2
1021
+ },
1022
+ {
1023
+ role: "user",
1024
+ content: timestampedTranscript
1025
+ }
1026
+ ]
1027
+ })
1028
+ );
1029
+ chaptersData = response.object;
1030
+ } catch (error) {
1031
+ throw new Error(
1032
+ `Failed to generate chapters with ${provider}: ${error instanceof Error ? error.message : "Unknown error"}`
1033
+ );
1034
+ }
1035
+ if (!chaptersData || !chaptersData.chapters) {
1036
+ throw new Error("No chapters generated from AI response");
1037
+ }
1038
+ const validChapters = chaptersData.chapters.filter((chapter) => typeof chapter.startTime === "number" && typeof chapter.title === "string").sort((a, b) => a.startTime - b.startTime);
1039
+ if (validChapters.length === 0) {
1040
+ throw new Error("No valid chapters found in AI response");
1041
+ }
1042
+ if (validChapters[0].startTime !== 0) {
1043
+ validChapters[0].startTime = 0;
1044
+ }
1045
+ return {
1046
+ assetId,
1047
+ languageCode,
1048
+ chapters: validChapters
1049
+ };
1050
+ }
1051
+
1052
+ // src/workflows/embeddings.ts
1053
+ var import_ai3 = require("ai");
1054
+
1055
+ // src/primitives/text-chunking.ts
1056
+ function estimateTokenCount(text) {
1057
+ const words = text.trim().split(/\s+/).length;
1058
+ return Math.ceil(words / 0.75);
1059
+ }
1060
+ function chunkByTokens(text, maxTokens, overlapTokens = 0) {
1061
+ if (!text.trim()) {
1062
+ return [];
1063
+ }
1064
+ const chunks = [];
1065
+ const words = text.trim().split(/\s+/);
1066
+ const wordsPerChunk = Math.floor(maxTokens * 0.75);
1067
+ const overlapWords = Math.floor(overlapTokens * 0.75);
1068
+ let chunkIndex = 0;
1069
+ let currentPosition = 0;
1070
+ while (currentPosition < words.length) {
1071
+ const chunkWords = words.slice(
1072
+ currentPosition,
1073
+ currentPosition + wordsPerChunk
1074
+ );
1075
+ const chunkText2 = chunkWords.join(" ");
1076
+ const tokenCount = estimateTokenCount(chunkText2);
1077
+ chunks.push({
1078
+ id: `chunk-${chunkIndex}`,
1079
+ text: chunkText2,
1080
+ tokenCount
1081
+ });
1082
+ currentPosition += wordsPerChunk - overlapWords;
1083
+ chunkIndex++;
1084
+ if (currentPosition <= (chunkIndex - 1) * (wordsPerChunk - overlapWords)) {
1085
+ break;
1086
+ }
1087
+ }
1088
+ return chunks;
1089
+ }
1090
+ function createChunkFromCues(cues, index) {
1091
+ const text = cues.map((c) => c.text).join(" ");
1092
+ return {
1093
+ id: `chunk-${index}`,
1094
+ text,
1095
+ tokenCount: estimateTokenCount(text),
1096
+ startTime: cues[0].startTime,
1097
+ endTime: cues[cues.length - 1].endTime
1098
+ };
1099
+ }
1100
+ function chunkVTTCues(cues, maxTokens, overlapCues = 2) {
1101
+ if (cues.length === 0)
1102
+ return [];
1103
+ const chunks = [];
1104
+ let currentCues = [];
1105
+ let currentTokens = 0;
1106
+ let chunkIndex = 0;
1107
+ for (let i = 0; i < cues.length; i++) {
1108
+ const cue = cues[i];
1109
+ const cueTokens = estimateTokenCount(cue.text);
1110
+ if (currentTokens + cueTokens > maxTokens && currentCues.length > 0) {
1111
+ chunks.push(createChunkFromCues(currentCues, chunkIndex));
1112
+ chunkIndex++;
1113
+ const overlapStart = Math.max(0, currentCues.length - overlapCues);
1114
+ currentCues = currentCues.slice(overlapStart);
1115
+ currentTokens = currentCues.reduce(
1116
+ (sum, c) => sum + estimateTokenCount(c.text),
1117
+ 0
1118
+ );
1119
+ }
1120
+ currentCues.push(cue);
1121
+ currentTokens += cueTokens;
1122
+ }
1123
+ if (currentCues.length > 0) {
1124
+ chunks.push(createChunkFromCues(currentCues, chunkIndex));
1125
+ }
1126
+ return chunks;
1127
+ }
1128
+ function chunkText(text, strategy) {
1129
+ switch (strategy.type) {
1130
+ case "token": {
1131
+ return chunkByTokens(text, strategy.maxTokens, strategy.overlap ?? 0);
1132
+ }
1133
+ default: {
1134
+ const exhaustiveCheck = strategy;
1135
+ throw new Error(`Unsupported chunking strategy: ${exhaustiveCheck}`);
1136
+ }
1137
+ }
1138
+ }
1139
+
1140
+ // src/workflows/embeddings.ts
1141
+ var DEFAULT_PROVIDER3 = "openai";
1142
+ var DEFAULT_CHUNKING_STRATEGY = {
1143
+ type: "token",
1144
+ maxTokens: 500,
1145
+ overlap: 100
1146
+ };
1147
+ var DEFAULT_BATCH_SIZE = 5;
1148
+ function averageEmbeddings(embeddings) {
1149
+ if (embeddings.length === 0) {
1150
+ return [];
1151
+ }
1152
+ const dimensions = embeddings[0].length;
1153
+ const averaged = Array.from({ length: dimensions }, () => 0);
1154
+ for (const embedding of embeddings) {
1155
+ for (let i = 0; i < dimensions; i++) {
1156
+ averaged[i] += embedding[i];
1157
+ }
1158
+ }
1159
+ for (let i = 0; i < dimensions; i++) {
1160
+ averaged[i] /= embeddings.length;
1161
+ }
1162
+ return averaged;
1163
+ }
1164
+ async function generateChunkEmbeddings(chunks, model, batchSize, abortSignal) {
1165
+ const results = [];
1166
+ for (let i = 0; i < chunks.length; i += batchSize) {
1167
+ const batch = chunks.slice(i, i + batchSize);
1168
+ const batchResults = await Promise.all(
1169
+ batch.map(async (chunk) => {
1170
+ const response = await withRetry(
1171
+ () => (0, import_ai3.embed)({
1172
+ model,
1173
+ value: chunk.text,
1174
+ abortSignal
1175
+ })
1176
+ );
1177
+ return {
1178
+ chunkId: chunk.id,
1179
+ embedding: response.embedding,
1180
+ metadata: {
1181
+ startTime: chunk.startTime,
1182
+ endTime: chunk.endTime,
1183
+ tokenCount: chunk.tokenCount
1184
+ }
1185
+ };
1186
+ })
1187
+ );
1188
+ results.push(...batchResults);
1189
+ }
1190
+ return results;
1191
+ }
1192
+ async function generateVideoEmbeddings(assetId, options = {}) {
1193
+ const {
1194
+ provider = DEFAULT_PROVIDER3,
1195
+ model,
1196
+ languageCode,
1197
+ chunkingStrategy = DEFAULT_CHUNKING_STRATEGY,
1198
+ batchSize = DEFAULT_BATCH_SIZE,
1199
+ abortSignal
1200
+ } = options;
1201
+ const credentials = validateCredentials(options, provider === "google" ? "google" : "openai");
1202
+ const muxClient = createMuxClient(credentials);
1203
+ const embeddingModel = resolveEmbeddingModel({ ...options, provider, model });
1204
+ const { asset: assetData, playbackId, policy } = await getPlaybackIdForAsset(
1205
+ muxClient,
1206
+ assetId
1207
+ );
1208
+ const signingContext = resolveSigningContext(options);
1209
+ if (policy === "signed" && !signingContext) {
1210
+ throw new Error(
1211
+ "Signed playback ID requires signing credentials. Provide muxSigningKey and muxPrivateKey in options or set MUX_SIGNING_KEY and MUX_PRIVATE_KEY environment variables."
1212
+ );
1213
+ }
1214
+ const useVttChunking = chunkingStrategy.type === "vtt";
1215
+ const transcriptResult = await fetchTranscriptForAsset(assetData, playbackId, {
1216
+ languageCode,
1217
+ cleanTranscript: !useVttChunking,
1218
+ signingContext: policy === "signed" ? signingContext : void 0
1219
+ });
1220
+ if (!transcriptResult.track || !transcriptResult.transcriptText) {
1221
+ const availableLanguages = getReadyTextTracks(assetData).map((t) => t.language_code).filter(Boolean).join(", ");
1222
+ throw new Error(
1223
+ `No caption track found${languageCode ? ` for language '${languageCode}'` : ""}. Available languages: ${availableLanguages || "none"}`
1224
+ );
1225
+ }
1226
+ const transcriptText = transcriptResult.transcriptText;
1227
+ if (!transcriptText.trim()) {
1228
+ throw new Error("Transcript is empty");
1229
+ }
1230
+ const chunks = useVttChunking ? chunkVTTCues(
1231
+ parseVTTCues(transcriptText),
1232
+ chunkingStrategy.maxTokens,
1233
+ chunkingStrategy.overlapCues
1234
+ ) : chunkText(transcriptText, chunkingStrategy);
1235
+ if (chunks.length === 0) {
1236
+ throw new Error("No chunks generated from transcript");
1237
+ }
1238
+ let chunkEmbeddings;
1239
+ try {
1240
+ chunkEmbeddings = await generateChunkEmbeddings(
1241
+ chunks,
1242
+ embeddingModel.model,
1243
+ batchSize,
1244
+ abortSignal
1245
+ );
1246
+ } catch (error) {
1247
+ throw new Error(
1248
+ `Failed to generate embeddings with ${provider}: ${error instanceof Error ? error.message : "Unknown error"}`
1249
+ );
1250
+ }
1251
+ if (chunkEmbeddings.length === 0) {
1252
+ throw new Error("No embeddings generated");
1253
+ }
1254
+ const averagedEmbedding = averageEmbeddings(chunkEmbeddings.map((ce) => ce.embedding));
1255
+ const totalTokens = chunks.reduce((sum, chunk) => sum + chunk.tokenCount, 0);
1256
+ return {
1257
+ assetId,
1258
+ chunks: chunkEmbeddings,
1259
+ averagedEmbedding,
1260
+ provider,
1261
+ model: embeddingModel.modelId,
1262
+ metadata: {
1263
+ totalChunks: chunks.length,
1264
+ totalTokens,
1265
+ chunkingStrategy: JSON.stringify(chunkingStrategy),
1266
+ embeddingDimensions: chunkEmbeddings[0].embedding.length,
1267
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString()
1268
+ }
1269
+ };
1270
+ }
1271
+
1272
+ // src/primitives/thumbnails.ts
1273
+ async function getThumbnailUrls(playbackId, duration, options = {}) {
1274
+ const { interval = 10, width = 640, signingContext } = options;
1275
+ const timestamps = [];
1276
+ if (duration <= 50) {
1277
+ const spacing = duration / 6;
1278
+ for (let i = 1; i <= 5; i++) {
1279
+ timestamps.push(Math.round(i * spacing));
1280
+ }
1281
+ } else {
1282
+ for (let time = 0; time < duration; time += interval) {
1283
+ timestamps.push(time);
1284
+ }
1285
+ }
1286
+ const baseUrl = `https://image.mux.com/${playbackId}/thumbnail.png`;
1287
+ const urlPromises = timestamps.map(async (time) => {
1288
+ if (signingContext) {
1289
+ return signUrl(baseUrl, playbackId, signingContext, "thumbnail", { time, width });
1290
+ }
1291
+ return `${baseUrl}?time=${time}&width=${width}`;
1292
+ });
1293
+ return Promise.all(urlPromises);
1294
+ }
1295
+
1296
+ // src/workflows/moderation.ts
1297
+ var DEFAULT_THRESHOLDS = {
1298
+ sexual: 0.7,
1299
+ violence: 0.8
1300
+ };
1301
+ var DEFAULT_PROVIDER4 = "openai";
1302
+ var HIVE_ENDPOINT = "https://api.thehive.ai/api/v2/task/sync";
1303
+ var HIVE_SEXUAL_CATEGORIES = [
1304
+ "general_nsfw",
1305
+ "general_suggestive",
1306
+ "yes_sexual_activity",
1307
+ "female_underwear",
1308
+ "male_underwear",
1309
+ "bra",
1310
+ "panties",
1311
+ "sex_toys",
1312
+ "nudity_female",
1313
+ "nudity_male",
1314
+ "cleavage",
1315
+ "swimwear"
1316
+ ];
1317
+ var HIVE_VIOLENCE_CATEGORIES = [
1318
+ "gun_in_hand",
1319
+ "gun_not_in_hand",
1320
+ "animated_gun",
1321
+ "knife_in_hand",
1322
+ "knife_not_in_hand",
1323
+ "culinary_knife_not_in_hand",
1324
+ "culinary_knife_in_hand",
1325
+ "very_bloody",
1326
+ "a_little_bloody",
1327
+ "other_blood",
1328
+ "hanging",
1329
+ "noose",
1330
+ "human_corpse",
1331
+ "animated_corpse",
1332
+ "emaciated_body",
1333
+ "self_harm",
1334
+ "animal_abuse",
1335
+ "fights",
1336
+ "garm_death_injury_or_military_conflict"
1337
+ ];
1338
+ async function processConcurrently(items, processor, maxConcurrent = 5) {
1339
+ const results = [];
1340
+ for (let i = 0; i < items.length; i += maxConcurrent) {
1341
+ const batch = items.slice(i, i + maxConcurrent);
1342
+ const batchPromises = batch.map(processor);
1343
+ const batchResults = await Promise.all(batchPromises);
1344
+ results.push(...batchResults);
1345
+ }
1346
+ return results;
1347
+ }
1348
+ async function requestOpenAIModeration(imageUrls, apiKey, model, maxConcurrent = 5, submissionMode = "url", downloadOptions) {
1349
+ const targetUrls = submissionMode === "base64" ? (await downloadImagesAsBase64(imageUrls, downloadOptions, maxConcurrent)).map(
1350
+ (img) => ({ url: img.url, image: img.base64Data })
1351
+ ) : imageUrls.map((url) => ({ url, image: url }));
1352
+ const moderate = async (entry) => {
1353
+ try {
1354
+ const res = await fetch("https://api.openai.com/v1/moderations", {
1355
+ method: "POST",
1356
+ headers: {
1357
+ "Content-Type": "application/json",
1358
+ "Authorization": `Bearer ${apiKey}`
1359
+ },
1360
+ body: JSON.stringify({
1361
+ model,
1362
+ input: [
1363
+ {
1364
+ type: "image_url",
1365
+ image_url: {
1366
+ url: entry.image
1367
+ }
1368
+ }
1369
+ ]
1370
+ })
1371
+ });
1372
+ const json = await res.json();
1373
+ if (!res.ok) {
1374
+ throw new Error(
1375
+ `OpenAI moderation error: ${res.status} ${res.statusText} - ${JSON.stringify(json)}`
1376
+ );
1377
+ }
1378
+ const categoryScores = json.results?.[0]?.category_scores || {};
1379
+ return {
1380
+ url: entry.url,
1381
+ sexual: categoryScores.sexual || 0,
1382
+ violence: categoryScores.violence || 0,
1383
+ error: false
1384
+ };
1385
+ } catch (error) {
1386
+ console.error("OpenAI moderation failed:", error);
1387
+ return {
1388
+ url: entry.url,
1389
+ sexual: 0,
1390
+ violence: 0,
1391
+ error: true
1392
+ };
1393
+ }
1394
+ };
1395
+ return processConcurrently(targetUrls, moderate, maxConcurrent);
1396
+ }
1397
+ function getHiveCategoryScores(classes, categoryNames) {
1398
+ const scoreMap = Object.fromEntries(
1399
+ classes.map((c) => [c.class, c.score])
1400
+ );
1401
+ const scores = categoryNames.map((category) => scoreMap[category] || 0);
1402
+ return Math.max(...scores, 0);
1403
+ }
1404
+ async function requestHiveModeration(imageUrls, apiKey, maxConcurrent = 5, submissionMode = "url", downloadOptions) {
1405
+ const targets = submissionMode === "base64" ? (await downloadImagesAsBase64(imageUrls, downloadOptions, maxConcurrent)).map((img) => ({
1406
+ url: img.url,
1407
+ source: {
1408
+ kind: "file",
1409
+ buffer: img.buffer,
1410
+ contentType: img.contentType
1411
+ }
1412
+ })) : imageUrls.map((url) => ({
1413
+ url,
1414
+ source: { kind: "url", value: url }
1415
+ }));
1416
+ const moderate = async (entry) => {
1417
+ try {
1418
+ const formData = new FormData();
1419
+ if (entry.source.kind === "url") {
1420
+ formData.append("url", entry.source.value);
1421
+ } else {
1422
+ const extension = entry.source.contentType.split("/")[1] || "jpg";
1423
+ const blob = new Blob([entry.source.buffer], {
1424
+ type: entry.source.contentType
1425
+ });
1426
+ formData.append("media", blob, `thumbnail.${extension}`);
1427
+ }
1428
+ const res = await fetch(HIVE_ENDPOINT, {
1429
+ method: "POST",
1430
+ headers: {
1431
+ Accept: "application/json",
1432
+ Authorization: `Token ${apiKey}`
1433
+ },
1434
+ body: formData
1435
+ });
1436
+ const json = await res.json().catch(() => void 0);
1437
+ if (!res.ok) {
1438
+ throw new Error(
1439
+ `Hive moderation error: ${res.status} ${res.statusText} - ${JSON.stringify(json)}`
1440
+ );
1441
+ }
1442
+ const classes = json?.status?.[0]?.response?.output?.[0]?.classes || [];
1443
+ return {
1444
+ url: entry.url,
1445
+ sexual: getHiveCategoryScores(classes, HIVE_SEXUAL_CATEGORIES),
1446
+ violence: getHiveCategoryScores(classes, HIVE_VIOLENCE_CATEGORIES),
1447
+ error: false
1448
+ };
1449
+ } catch (error) {
1450
+ console.error("Hive moderation failed:", error);
1451
+ return {
1452
+ url: entry.url,
1453
+ sexual: 0,
1454
+ violence: 0,
1455
+ error: true
1456
+ };
1457
+ }
1458
+ };
1459
+ return processConcurrently(targets, moderate, maxConcurrent);
1460
+ }
1461
+ async function getModerationScores(assetId, options = {}) {
1462
+ const {
1463
+ provider = DEFAULT_PROVIDER4,
1464
+ model = provider === "openai" ? "omni-moderation-latest" : void 0,
1465
+ thresholds = DEFAULT_THRESHOLDS,
1466
+ thumbnailInterval = 10,
1467
+ thumbnailWidth = 640,
1468
+ maxConcurrent = 5,
1469
+ imageSubmissionMode = "url",
1470
+ imageDownloadOptions
1471
+ } = options;
1472
+ const credentials = validateCredentials(options, provider === "openai" ? "openai" : void 0);
1473
+ const muxClient = createMuxClient(credentials);
1474
+ const { asset, playbackId, policy } = await getPlaybackIdForAsset(muxClient, assetId);
1475
+ const duration = asset.duration || 0;
1476
+ const signingContext = resolveSigningContext(options);
1477
+ if (policy === "signed" && !signingContext) {
1478
+ throw new Error(
1479
+ "Signed playback ID requires signing credentials. Provide muxSigningKey and muxPrivateKey in options or set MUX_SIGNING_KEY and MUX_PRIVATE_KEY environment variables."
1480
+ );
1481
+ }
1482
+ const thumbnailUrls = await getThumbnailUrls(playbackId, duration, {
1483
+ interval: thumbnailInterval,
1484
+ width: thumbnailWidth,
1485
+ signingContext: policy === "signed" ? signingContext : void 0
1486
+ });
1487
+ let thumbnailScores;
1488
+ if (provider === "openai") {
1489
+ const apiKey = credentials.openaiApiKey;
1490
+ if (!apiKey) {
1491
+ throw new Error("OpenAI API key is required for moderation. Set OPENAI_API_KEY or pass openaiApiKey.");
1492
+ }
1493
+ thumbnailScores = await requestOpenAIModeration(
1494
+ thumbnailUrls,
1495
+ apiKey,
1496
+ model || "omni-moderation-latest",
1497
+ maxConcurrent,
1498
+ imageSubmissionMode,
1499
+ imageDownloadOptions
1500
+ );
1501
+ } else if (provider === "hive") {
1502
+ const hiveApiKey = options.hiveApiKey || env_default.HIVE_API_KEY;
1503
+ if (!hiveApiKey) {
1504
+ throw new Error("Hive API key is required for moderation. Set HIVE_API_KEY or pass hiveApiKey.");
1505
+ }
1506
+ thumbnailScores = await requestHiveModeration(
1507
+ thumbnailUrls,
1508
+ hiveApiKey,
1509
+ maxConcurrent,
1510
+ imageSubmissionMode,
1511
+ imageDownloadOptions
1512
+ );
1513
+ } else {
1514
+ throw new Error(`Unsupported moderation provider: ${provider}`);
1515
+ }
1516
+ const maxSexual = Math.max(...thumbnailScores.map((s) => s.sexual));
1517
+ const maxViolence = Math.max(...thumbnailScores.map((s) => s.violence));
1518
+ const finalThresholds = { ...DEFAULT_THRESHOLDS, ...thresholds };
1519
+ return {
1520
+ assetId,
1521
+ thumbnailScores,
1522
+ maxScores: {
1523
+ sexual: maxSexual,
1524
+ violence: maxViolence
1525
+ },
1526
+ exceedsThreshold: maxSexual > finalThresholds.sexual || maxViolence > finalThresholds.violence,
1527
+ thresholds: finalThresholds
1528
+ };
1529
+ }
1530
+
1531
+ // src/workflows/summarization.ts
1532
+ var import_ai4 = require("ai");
1533
+ var import_zod4 = require("zod");
1534
+ var SUMMARY_KEYWORD_LIMIT = 10;
1535
+ var summarySchema = import_zod4.z.object({
1536
+ keywords: import_zod4.z.array(import_zod4.z.string()),
1537
+ title: import_zod4.z.string(),
1538
+ description: import_zod4.z.string()
1539
+ });
1540
+ var TONE_INSTRUCTIONS = {
1541
+ normal: "Provide a clear, straightforward analysis.",
1542
+ sassy: "Answer with a sassy, playful attitude and personality.",
1543
+ professional: "Provide a professional, executive-level analysis suitable for business reporting."
1544
+ };
1545
+ var summarizationPromptBuilder = createPromptBuilder({
1546
+ template: {
1547
+ task: {
1548
+ tag: "task",
1549
+ content: "Analyze the storyboard frames and generate metadata that captures the essence of the video content."
1550
+ },
1551
+ title: {
1552
+ tag: "title_requirements",
1553
+ content: dedent_default`
1554
+ A short, compelling headline that immediately communicates the subject or action.
1555
+ Aim for brevity - typically under 10 words. Think of how a news headline or video card title would read.
1556
+ Start with the primary subject, action, or topic - never begin with "A video of" or similar phrasing.
1557
+ Use active, specific language.`
1558
+ },
1559
+ description: {
1560
+ tag: "description_requirements",
1561
+ content: dedent_default`
1562
+ A concise summary (2-4 sentences) that describes what happens across the video.
1563
+ Cover the main subjects, actions, setting, and any notable progression visible across frames.
1564
+ Write in present tense. Be specific about observable details rather than making assumptions.
1565
+ If the transcript provides dialogue or narration, incorporate key points but prioritize visual content.`
1566
+ },
1567
+ keywords: {
1568
+ tag: "keywords_requirements",
1569
+ content: dedent_default`
1570
+ Specific, searchable terms (up to 10) that capture:
1571
+ - Primary subjects (people, animals, objects)
1572
+ - Actions and activities being performed
1573
+ - Setting and environment
1574
+ - Notable objects or tools
1575
+ - Style or genre (if applicable)
1576
+ Prefer concrete nouns and action verbs over abstract concepts.
1577
+ Use lowercase. Avoid redundant or overly generic terms like "video" or "content".`
1578
+ },
1579
+ qualityGuidelines: {
1580
+ tag: "quality_guidelines",
1581
+ content: dedent_default`
1582
+ - Examine all frames to understand the full context and progression
1583
+ - Be precise: "golden retriever" is better than "dog" when identifiable
1584
+ - Capture the narrative: what begins, develops, and concludes
1585
+ - Balance brevity with informativeness`
1586
+ }
1587
+ },
1588
+ sectionOrder: ["task", "title", "description", "keywords", "qualityGuidelines"]
1589
+ });
1590
+ var SYSTEM_PROMPT3 = dedent_default`
1591
+ <role>
1592
+ You are a video content analyst specializing in storyboard interpretation and multimodal analysis.
1593
+ </role>
1594
+
1595
+ <context>
1596
+ You receive storyboard images containing multiple sequential frames extracted from a video.
1597
+ These frames are arranged in a grid and represent the visual progression of the content over time.
1598
+ Read frames left-to-right, top-to-bottom to understand the temporal sequence.
1599
+ </context>
1600
+
1601
+ <transcript_guidance>
1602
+ When a transcript is provided alongside the storyboard:
1603
+ - Use it to understand spoken content, dialogue, narration, and audio context
1604
+ - Correlate transcript content with visual frames to build a complete picture
1605
+ - Extract key terminology, names, and specific language used by speakers
1606
+ - Let the transcript inform keyword selection, especially for topics not visually obvious
1607
+ - Prioritize visual content for the description, but enrich it with transcript insights
1608
+ - If transcript and visuals conflict, trust the visual evidence
1609
+ </transcript_guidance>
1610
+
1611
+ <capabilities>
1612
+ - Extract meaning from visual sequences
1613
+ - Identify subjects, actions, settings, and narrative arcs
1614
+ - Generate accurate, searchable metadata
1615
+ - Synthesize visual and transcript information when provided
1616
+ </capabilities>
1617
+
1618
+ <constraints>
1619
+ - Only describe what is clearly observable in the frames or explicitly stated in the transcript
1620
+ - Do not fabricate details or make unsupported assumptions
1621
+ - Return structured data matching the requested schema
1622
+ </constraints>`;
1623
+ function buildUserPrompt2({
1624
+ tone,
1625
+ transcriptText,
1626
+ isCleanTranscript = true,
1627
+ promptOverrides
1628
+ }) {
1629
+ const contextSections = [createToneSection(TONE_INSTRUCTIONS[tone])];
1630
+ if (transcriptText) {
1631
+ const format = isCleanTranscript ? "plain text" : "WebVTT";
1632
+ contextSections.push(createTranscriptSection(transcriptText, format));
1633
+ }
1634
+ return summarizationPromptBuilder.buildWithContext(promptOverrides, contextSections);
1635
+ }
1636
+ var DEFAULT_PROVIDER5 = "openai";
1637
+ var DEFAULT_TONE = "normal";
1638
+ function normalizeKeywords(keywords) {
1639
+ if (!Array.isArray(keywords) || keywords.length === 0) {
1640
+ return [];
1641
+ }
1642
+ const uniqueLowercase = /* @__PURE__ */ new Set();
1643
+ const normalized = [];
1644
+ for (const keyword of keywords) {
1645
+ const trimmed = keyword?.trim();
1646
+ if (!trimmed) {
1647
+ continue;
1648
+ }
1649
+ const lower = trimmed.toLowerCase();
1650
+ if (uniqueLowercase.has(lower)) {
1651
+ continue;
1652
+ }
1653
+ uniqueLowercase.add(lower);
1654
+ normalized.push(trimmed);
1655
+ if (normalized.length === SUMMARY_KEYWORD_LIMIT) {
1656
+ break;
1657
+ }
1658
+ }
1659
+ return normalized;
1660
+ }
1661
+ async function getSummaryAndTags(assetId, options) {
1662
+ const {
1663
+ provider = DEFAULT_PROVIDER5,
1664
+ model,
1665
+ tone = DEFAULT_TONE,
1666
+ includeTranscript = true,
1667
+ cleanTranscript = true,
1668
+ imageSubmissionMode = "url",
1669
+ imageDownloadOptions,
1670
+ abortSignal,
1671
+ promptOverrides
1672
+ } = options ?? {};
1673
+ const clients = createWorkflowClients(
1674
+ { ...options, model },
1675
+ provider
1676
+ );
1677
+ const { asset: assetData, playbackId, policy } = await getPlaybackIdForAsset(clients.mux, assetId);
1678
+ const signingContext = resolveSigningContext(options ?? {});
1679
+ if (policy === "signed" && !signingContext) {
1680
+ throw new Error(
1681
+ "Signed playback ID requires signing credentials. Provide muxSigningKey and muxPrivateKey in options or set MUX_SIGNING_KEY and MUX_PRIVATE_KEY environment variables."
1682
+ );
1683
+ }
1684
+ const transcriptText = includeTranscript ? (await fetchTranscriptForAsset(assetData, playbackId, {
1685
+ cleanTranscript,
1686
+ signingContext: policy === "signed" ? signingContext : void 0
1687
+ })).transcriptText : "";
1688
+ const userPrompt = buildUserPrompt2({
1689
+ tone,
1690
+ transcriptText,
1691
+ isCleanTranscript: cleanTranscript,
1692
+ promptOverrides
1693
+ });
1694
+ const imageUrl = await getStoryboardUrl(playbackId, 640, policy === "signed" ? signingContext : void 0);
1695
+ const analyzeStoryboard = async (imageDataUrl) => {
1696
+ const response = await (0, import_ai4.generateObject)({
1697
+ model: clients.languageModel.model,
1698
+ schema: summarySchema,
1699
+ abortSignal,
1700
+ messages: [
1701
+ {
1702
+ role: "system",
1703
+ content: SYSTEM_PROMPT3
1704
+ },
1705
+ {
1706
+ role: "user",
1707
+ content: [
1708
+ { type: "text", text: userPrompt },
1709
+ { type: "image", image: imageDataUrl }
1710
+ ]
1711
+ }
1712
+ ]
1713
+ });
1714
+ return response.object;
1715
+ };
1716
+ let aiAnalysis = null;
1717
+ try {
1718
+ if (imageSubmissionMode === "base64") {
1719
+ const downloadResult = await downloadImageAsBase64(imageUrl, imageDownloadOptions);
1720
+ aiAnalysis = await analyzeStoryboard(downloadResult.base64Data);
1721
+ } else {
1722
+ aiAnalysis = await withRetry(() => analyzeStoryboard(imageUrl));
1723
+ }
1724
+ } catch (error) {
1725
+ throw new Error(
1726
+ `Failed to analyze video content with ${provider}: ${error instanceof Error ? error.message : "Unknown error"}`
1727
+ );
1728
+ }
1729
+ if (!aiAnalysis) {
1730
+ throw new Error(`Failed to analyze video content for asset ${assetId}`);
1731
+ }
1732
+ if (!aiAnalysis.title) {
1733
+ throw new Error(`Failed to generate title for asset ${assetId}`);
1734
+ }
1735
+ if (!aiAnalysis.description) {
1736
+ throw new Error(`Failed to generate description for asset ${assetId}`);
1737
+ }
1738
+ return {
1739
+ assetId,
1740
+ title: aiAnalysis.title,
1741
+ description: aiAnalysis.description,
1742
+ tags: normalizeKeywords(aiAnalysis.keywords),
1743
+ storyboardUrl: imageUrl
1744
+ };
1745
+ }
1746
+
1747
+ // src/workflows/translate-audio.ts
1748
+ var import_client_s3 = require("@aws-sdk/client-s3");
1749
+ var import_lib_storage = require("@aws-sdk/lib-storage");
1750
+ var import_s3_request_presigner = require("@aws-sdk/s3-request-presigner");
1751
+ var import_mux_node3 = __toESM(require("@mux/mux-node"));
1752
+ var STATIC_RENDITION_POLL_INTERVAL_MS = 5e3;
1753
+ var STATIC_RENDITION_MAX_ATTEMPTS = 36;
1754
+ var delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1755
+ function getReadyAudioStaticRendition(asset) {
1756
+ const files = asset.static_renditions?.files;
1757
+ if (!files || files.length === 0) {
1758
+ return void 0;
1759
+ }
1760
+ return files.find(
1761
+ (rendition) => rendition.name === "audio.m4a" && rendition.status === "ready"
1762
+ );
1763
+ }
1764
+ var hasReadyAudioStaticRendition = (asset) => Boolean(getReadyAudioStaticRendition(asset));
1765
+ async function requestStaticRenditionCreation(muxClient, assetId) {
1766
+ console.log("\u{1F4FC} Requesting static rendition from Mux...");
1767
+ try {
1768
+ await muxClient.video.assets.createStaticRendition(assetId, {
1769
+ resolution: "audio-only"
1770
+ });
1771
+ console.log("\u{1F4FC} Static rendition request accepted by Mux.");
1772
+ } catch (error) {
1773
+ const statusCode = error?.status ?? error?.statusCode;
1774
+ const messages = error?.error?.messages;
1775
+ const alreadyDefined = messages?.some((message2) => message2.toLowerCase().includes("already defined")) ?? error?.message?.toLowerCase().includes("already defined");
1776
+ if (statusCode === 409 || alreadyDefined) {
1777
+ console.log("\u2139\uFE0F Static rendition already requested. Waiting for it to finish...");
1778
+ return;
1779
+ }
1780
+ const message = error instanceof Error ? error.message : "Unknown error";
1781
+ throw new Error(`Failed to request static rendition from Mux: ${message}`);
1782
+ }
1783
+ }
1784
+ async function waitForAudioStaticRendition({
1785
+ assetId,
1786
+ muxClient,
1787
+ initialAsset
1788
+ }) {
1789
+ let currentAsset = initialAsset;
1790
+ if (hasReadyAudioStaticRendition(currentAsset)) {
1791
+ return currentAsset;
1792
+ }
1793
+ const status = currentAsset.static_renditions?.status ?? "not_requested";
1794
+ if (status === "not_requested" || status === void 0) {
1795
+ await requestStaticRenditionCreation(muxClient, assetId);
1796
+ } else if (status === "errored") {
1797
+ console.log("\u26A0\uFE0F Previous static rendition request errored. Creating a new one...");
1798
+ await requestStaticRenditionCreation(muxClient, assetId);
1799
+ } else {
1800
+ console.log(`\u2139\uFE0F Static rendition already ${status}. Waiting for it to finish...`);
1801
+ }
1802
+ for (let attempt = 1; attempt <= STATIC_RENDITION_MAX_ATTEMPTS; attempt++) {
1803
+ await delay(STATIC_RENDITION_POLL_INTERVAL_MS);
1804
+ currentAsset = await muxClient.video.assets.retrieve(assetId);
1805
+ if (hasReadyAudioStaticRendition(currentAsset)) {
1806
+ console.log("\u2705 Audio static rendition is ready!");
1807
+ return currentAsset;
1808
+ }
1809
+ const currentStatus = currentAsset.static_renditions?.status || "unknown";
1810
+ console.log(
1811
+ `\u231B Waiting for static rendition (attempt ${attempt}/${STATIC_RENDITION_MAX_ATTEMPTS}) \u2192 ${currentStatus}`
1812
+ );
1813
+ if (currentStatus === "errored") {
1814
+ throw new Error(
1815
+ "Mux failed to create the static rendition for this asset. Please check the asset in the Mux dashboard."
1816
+ );
1817
+ }
1818
+ }
1819
+ throw new Error(
1820
+ "Timed out waiting for the static rendition to become ready. Please try again in a moment."
1821
+ );
1822
+ }
1823
+ async function translateAudio(assetId, toLanguageCode, options = {}) {
1824
+ const {
1825
+ provider = "elevenlabs",
1826
+ numSpeakers = 0,
1827
+ // 0 = auto-detect
1828
+ muxTokenId,
1829
+ muxTokenSecret,
1830
+ elevenLabsApiKey,
1831
+ uploadToMux = true
1832
+ } = options;
1833
+ if (provider !== "elevenlabs") {
1834
+ throw new Error("Only ElevenLabs provider is currently supported for audio translation");
1835
+ }
1836
+ const muxId = muxTokenId ?? env_default.MUX_TOKEN_ID;
1837
+ const muxSecret = muxTokenSecret ?? env_default.MUX_TOKEN_SECRET;
1838
+ const elevenLabsKey = elevenLabsApiKey ?? env_default.ELEVENLABS_API_KEY;
1839
+ const s3Endpoint = options.s3Endpoint ?? env_default.S3_ENDPOINT;
1840
+ const s3Region = options.s3Region ?? env_default.S3_REGION ?? "auto";
1841
+ const s3Bucket = options.s3Bucket ?? env_default.S3_BUCKET;
1842
+ const s3AccessKeyId = options.s3AccessKeyId ?? env_default.S3_ACCESS_KEY_ID;
1843
+ const s3SecretAccessKey = options.s3SecretAccessKey ?? env_default.S3_SECRET_ACCESS_KEY;
1844
+ if (!muxId || !muxSecret) {
1845
+ throw new Error("Mux credentials are required. Provide muxTokenId and muxTokenSecret in options or set MUX_TOKEN_ID and MUX_TOKEN_SECRET environment variables.");
1846
+ }
1847
+ if (!elevenLabsKey) {
1848
+ throw new Error("ElevenLabs API key is required. Provide elevenLabsApiKey in options or set ELEVENLABS_API_KEY environment variable.");
1849
+ }
1850
+ if (uploadToMux && (!s3Endpoint || !s3Bucket || !s3AccessKeyId || !s3SecretAccessKey)) {
1851
+ throw new Error("S3 configuration is required for uploading to Mux. Provide s3Endpoint, s3Bucket, s3AccessKeyId, and s3SecretAccessKey in options or set S3_ENDPOINT, S3_BUCKET, S3_ACCESS_KEY_ID, and S3_SECRET_ACCESS_KEY environment variables.");
1852
+ }
1853
+ const mux = new import_mux_node3.default({
1854
+ tokenId: muxId,
1855
+ tokenSecret: muxSecret
1856
+ });
1857
+ console.log(`\u{1F3AC} Fetching Mux asset: ${assetId}`);
1858
+ const { asset: initialAsset, playbackId, policy } = await getPlaybackIdForAsset(mux, assetId);
1859
+ const signingContext = resolveSigningContext(options);
1860
+ if (policy === "signed" && !signingContext) {
1861
+ throw new Error(
1862
+ "Signed playback ID requires signing credentials. Provide muxSigningKey and muxPrivateKey in options or set MUX_SIGNING_KEY and MUX_PRIVATE_KEY environment variables."
1863
+ );
1864
+ }
1865
+ console.log("\u{1F50D} Checking for audio-only static rendition...");
1866
+ let currentAsset = initialAsset;
1867
+ if (!hasReadyAudioStaticRendition(currentAsset)) {
1868
+ console.log("\u274C No ready audio static rendition found. Requesting one now...");
1869
+ currentAsset = await waitForAudioStaticRendition({
1870
+ assetId,
1871
+ muxClient: mux,
1872
+ initialAsset: currentAsset
1873
+ });
1874
+ }
1875
+ const audioRendition = getReadyAudioStaticRendition(currentAsset);
1876
+ if (!audioRendition) {
1877
+ throw new Error(
1878
+ "Unable to obtain an audio-only static rendition for this asset. Please verify static renditions are enabled in Mux."
1879
+ );
1880
+ }
1881
+ let audioUrl = `https://stream.mux.com/${playbackId}/audio.m4a`;
1882
+ if (policy === "signed" && signingContext) {
1883
+ audioUrl = await signUrl(audioUrl, playbackId, signingContext, "video");
1884
+ }
1885
+ console.log(`\u2705 Found audio rendition: ${audioUrl}`);
1886
+ console.log(`\u{1F399}\uFE0F Creating ElevenLabs dubbing job (auto-detect \u2192 ${toLanguageCode})`);
1887
+ let dubbingId;
1888
+ try {
1889
+ const audioResponse = await fetch(audioUrl);
1890
+ if (!audioResponse.ok) {
1891
+ throw new Error(`Failed to fetch audio file: ${audioResponse.statusText}`);
1892
+ }
1893
+ const audioBuffer = await audioResponse.arrayBuffer();
1894
+ const audioBlob = new Blob([audioBuffer], { type: "audio/mp4" });
1895
+ const audioFile = audioBlob;
1896
+ const formData = new FormData();
1897
+ formData.append("file", audioFile);
1898
+ formData.append("target_lang", toLanguageCode);
1899
+ formData.append("num_speakers", numSpeakers.toString());
1900
+ formData.append("name", `Mux Asset ${assetId} - auto to ${toLanguageCode}`);
1901
+ const dubbingResponse = await fetch("https://api.elevenlabs.io/v1/dubbing", {
1902
+ method: "POST",
1903
+ headers: {
1904
+ "xi-api-key": elevenLabsKey
1905
+ },
1906
+ body: formData
1907
+ });
1908
+ if (!dubbingResponse.ok) {
1909
+ throw new Error(`ElevenLabs API error: ${dubbingResponse.statusText}`);
1910
+ }
1911
+ const dubbingData = await dubbingResponse.json();
1912
+ dubbingId = dubbingData.dubbing_id;
1913
+ console.log(`\u2705 Dubbing job created: ${dubbingId}`);
1914
+ console.log(`\u23F1\uFE0F Expected duration: ${dubbingData.expected_duration_sec}s`);
1915
+ } catch (error) {
1916
+ throw new Error(`Failed to create ElevenLabs dubbing job: ${error instanceof Error ? error.message : "Unknown error"}`);
1917
+ }
1918
+ console.log("\u23F3 Waiting for dubbing to complete...");
1919
+ let dubbingStatus = "dubbing";
1920
+ let pollAttempts = 0;
1921
+ const maxPollAttempts = 180;
1922
+ while (dubbingStatus === "dubbing" && pollAttempts < maxPollAttempts) {
1923
+ await new Promise((resolve) => setTimeout(resolve, 1e4));
1924
+ pollAttempts++;
1925
+ try {
1926
+ const statusResponse = await fetch(`https://api.elevenlabs.io/v1/dubbing/${dubbingId}`, {
1927
+ headers: {
1928
+ "xi-api-key": elevenLabsKey
1929
+ }
1930
+ });
1931
+ if (!statusResponse.ok) {
1932
+ throw new Error(`Status check failed: ${statusResponse.statusText}`);
1933
+ }
1934
+ const statusData = await statusResponse.json();
1935
+ dubbingStatus = statusData.status;
1936
+ console.log(`\u{1F4CA} Status check ${pollAttempts}: ${dubbingStatus}`);
1937
+ if (dubbingStatus === "failed") {
1938
+ throw new Error("ElevenLabs dubbing job failed");
1939
+ }
1940
+ } catch (error) {
1941
+ throw new Error(`Failed to check dubbing status: ${error instanceof Error ? error.message : "Unknown error"}`);
1942
+ }
1943
+ }
1944
+ if (dubbingStatus !== "dubbed") {
1945
+ throw new Error(`Dubbing job timed out or failed. Final status: ${dubbingStatus}`);
1946
+ }
1947
+ console.log("\u2705 Dubbing completed successfully!");
1948
+ if (!uploadToMux) {
1949
+ return {
1950
+ assetId,
1951
+ targetLanguageCode: toLanguageCode,
1952
+ dubbingId
1953
+ };
1954
+ }
1955
+ console.log("\u{1F4E5} Downloading dubbed audio from ElevenLabs...");
1956
+ let dubbedAudioBuffer;
1957
+ try {
1958
+ const audioUrl2 = `https://api.elevenlabs.io/v1/dubbing/${dubbingId}/audio/${toLanguageCode}`;
1959
+ const audioResponse = await fetch(audioUrl2, {
1960
+ headers: {
1961
+ "xi-api-key": elevenLabsKey
1962
+ }
1963
+ });
1964
+ if (!audioResponse.ok) {
1965
+ throw new Error(`Failed to fetch dubbed audio: ${audioResponse.statusText}`);
1966
+ }
1967
+ dubbedAudioBuffer = await audioResponse.arrayBuffer();
1968
+ console.log(`\u2705 Downloaded dubbed audio (${dubbedAudioBuffer.byteLength} bytes)`);
1969
+ } catch (error) {
1970
+ throw new Error(`Failed to download dubbed audio: ${error instanceof Error ? error.message : "Unknown error"}`);
1971
+ }
1972
+ console.log("\u{1F4E4} Uploading dubbed audio to S3-compatible storage...");
1973
+ const s3Client = new import_client_s3.S3Client({
1974
+ region: s3Region,
1975
+ endpoint: s3Endpoint,
1976
+ credentials: {
1977
+ accessKeyId: s3AccessKeyId,
1978
+ secretAccessKey: s3SecretAccessKey
1979
+ },
1980
+ forcePathStyle: true
1981
+ });
1982
+ const audioKey = `audio-translations/${assetId}/auto-to-${toLanguageCode}-${Date.now()}.m4a`;
1983
+ let presignedUrl;
1984
+ try {
1985
+ const upload = new import_lib_storage.Upload({
1986
+ client: s3Client,
1987
+ params: {
1988
+ Bucket: s3Bucket,
1989
+ Key: audioKey,
1990
+ Body: new Uint8Array(dubbedAudioBuffer),
1991
+ ContentType: "audio/mp4"
1992
+ }
1993
+ });
1994
+ await upload.done();
1995
+ console.log(`\u2705 Audio uploaded successfully to: ${audioKey}`);
1996
+ const getObjectCommand = new import_client_s3.GetObjectCommand({
1997
+ Bucket: s3Bucket,
1998
+ Key: audioKey
1999
+ });
2000
+ presignedUrl = await (0, import_s3_request_presigner.getSignedUrl)(s3Client, getObjectCommand, {
2001
+ expiresIn: 3600
2002
+ // 1 hour
2003
+ });
2004
+ console.log(`\u{1F517} Generated presigned URL (expires in 1 hour)`);
2005
+ } catch (error) {
2006
+ throw new Error(`Failed to upload audio to S3: ${error instanceof Error ? error.message : "Unknown error"}`);
2007
+ }
2008
+ console.log("\u{1F3AC} Adding translated audio track to Mux asset...");
2009
+ let uploadedTrackId;
2010
+ try {
2011
+ const languageName = new Intl.DisplayNames(["en"], { type: "language" }).of(toLanguageCode) || toLanguageCode.toUpperCase();
2012
+ const trackName = `${languageName} (auto-dubbed)`;
2013
+ const trackResponse = await mux.video.assets.createTrack(assetId, {
2014
+ type: "audio",
2015
+ language_code: toLanguageCode,
2016
+ name: trackName,
2017
+ url: presignedUrl
2018
+ });
2019
+ uploadedTrackId = trackResponse.id;
2020
+ console.log(`\u2705 Audio track added to Mux asset with ID: ${uploadedTrackId}`);
2021
+ console.log(`\u{1F3B5} Track name: "${trackName}"`);
2022
+ } catch (error) {
2023
+ console.warn(`\u26A0\uFE0F Failed to add audio track to Mux asset: ${error instanceof Error ? error.message : "Unknown error"}`);
2024
+ console.log("\u{1F517} You can manually add the track using this presigned URL:");
2025
+ console.log(presignedUrl);
2026
+ }
2027
+ return {
2028
+ assetId,
2029
+ targetLanguageCode: toLanguageCode,
2030
+ dubbingId,
2031
+ uploadedTrackId,
2032
+ presignedUrl
2033
+ };
2034
+ }
2035
+
2036
+ // src/workflows/translate-captions.ts
2037
+ var import_client_s32 = require("@aws-sdk/client-s3");
2038
+ var import_lib_storage2 = require("@aws-sdk/lib-storage");
2039
+ var import_s3_request_presigner2 = require("@aws-sdk/s3-request-presigner");
2040
+ var import_ai5 = require("ai");
2041
+ var import_zod5 = require("zod");
2042
+ var translationSchema = import_zod5.z.object({
2043
+ translation: import_zod5.z.string()
2044
+ });
2045
+ var DEFAULT_PROVIDER6 = "openai";
2046
+ async function translateCaptions(assetId, fromLanguageCode, toLanguageCode, options) {
2047
+ const {
2048
+ provider = DEFAULT_PROVIDER6,
2049
+ model,
2050
+ s3Endpoint: providedS3Endpoint,
2051
+ s3Region: providedS3Region,
2052
+ s3Bucket: providedS3Bucket,
2053
+ s3AccessKeyId: providedS3AccessKeyId,
2054
+ s3SecretAccessKey: providedS3SecretAccessKey,
2055
+ uploadToMux: uploadToMuxOption,
2056
+ ...clientConfig
2057
+ } = options;
2058
+ const resolvedProvider = provider;
2059
+ const s3Endpoint = providedS3Endpoint ?? env_default.S3_ENDPOINT;
2060
+ const s3Region = providedS3Region ?? env_default.S3_REGION ?? "auto";
2061
+ const s3Bucket = providedS3Bucket ?? env_default.S3_BUCKET;
2062
+ const s3AccessKeyId = providedS3AccessKeyId ?? env_default.S3_ACCESS_KEY_ID;
2063
+ const s3SecretAccessKey = providedS3SecretAccessKey ?? env_default.S3_SECRET_ACCESS_KEY;
2064
+ const uploadToMux = uploadToMuxOption !== false;
2065
+ const clients = createWorkflowClients(
2066
+ { ...clientConfig, provider: resolvedProvider, model },
2067
+ resolvedProvider
2068
+ );
2069
+ if (uploadToMux && (!s3Endpoint || !s3Bucket || !s3AccessKeyId || !s3SecretAccessKey)) {
2070
+ throw new Error("S3 configuration is required for uploading to Mux. Provide s3Endpoint, s3Bucket, s3AccessKeyId, and s3SecretAccessKey in options or set S3_ENDPOINT, S3_BUCKET, S3_ACCESS_KEY_ID, and S3_SECRET_ACCESS_KEY environment variables.");
2071
+ }
2072
+ const { asset: assetData, playbackId, policy } = await getPlaybackIdForAsset(clients.mux, assetId);
2073
+ const signingContext = resolveSigningContext(options);
2074
+ if (policy === "signed" && !signingContext) {
2075
+ throw new Error(
2076
+ "Signed playback ID requires signing credentials. Provide muxSigningKey and muxPrivateKey in options or set MUX_SIGNING_KEY and MUX_PRIVATE_KEY environment variables."
2077
+ );
2078
+ }
2079
+ if (!assetData.tracks) {
2080
+ throw new Error("No tracks found for this asset");
2081
+ }
2082
+ const sourceTextTrack = assetData.tracks.find(
2083
+ (track) => track.type === "text" && track.status === "ready" && track.language_code === fromLanguageCode
2084
+ );
2085
+ if (!sourceTextTrack) {
2086
+ throw new Error(`No ready text track found with language code '${fromLanguageCode}' for this asset`);
2087
+ }
2088
+ let vttUrl = `https://stream.mux.com/${playbackId}/text/${sourceTextTrack.id}.vtt`;
2089
+ if (policy === "signed" && signingContext) {
2090
+ vttUrl = await signUrl(vttUrl, playbackId, signingContext, "video");
2091
+ }
2092
+ let vttContent;
2093
+ try {
2094
+ const vttResponse = await fetch(vttUrl);
2095
+ if (!vttResponse.ok) {
2096
+ throw new Error(`Failed to fetch VTT file: ${vttResponse.statusText}`);
2097
+ }
2098
+ vttContent = await vttResponse.text();
2099
+ } catch (error) {
2100
+ throw new Error(`Failed to fetch VTT content: ${error instanceof Error ? error.message : "Unknown error"}`);
2101
+ }
2102
+ console.log(`\u2705 Found VTT content for language '${fromLanguageCode}'`);
2103
+ let translatedVtt;
2104
+ try {
2105
+ const response = await (0, import_ai5.generateObject)({
2106
+ model: clients.languageModel.model,
2107
+ schema: translationSchema,
2108
+ abortSignal: options.abortSignal,
2109
+ messages: [
2110
+ {
2111
+ role: "user",
2112
+ content: `Translate the following VTT subtitle file from ${fromLanguageCode} to ${toLanguageCode}. Preserve all timestamps and VTT formatting exactly as they appear. Return JSON with a single key "translation" containing the translated VTT.
2113
+
2114
+ ${vttContent}`
2115
+ }
2116
+ ]
2117
+ });
2118
+ translatedVtt = response.object.translation;
2119
+ } catch (error) {
2120
+ throw new Error(`Failed to translate VTT with ${resolvedProvider}: ${error instanceof Error ? error.message : "Unknown error"}`);
2121
+ }
2122
+ console.log(`
2123
+ \u2705 Translation completed successfully!`);
2124
+ if (!uploadToMux) {
2125
+ console.log(`\u2705 VTT translated to ${toLanguageCode} successfully!`);
2126
+ return {
2127
+ assetId,
2128
+ sourceLanguageCode: fromLanguageCode,
2129
+ targetLanguageCode: toLanguageCode,
2130
+ originalVtt: vttContent,
2131
+ translatedVtt
2132
+ };
2133
+ }
2134
+ console.log("\u{1F4E4} Uploading translated VTT to S3-compatible storage...");
2135
+ const s3Client = new import_client_s32.S3Client({
2136
+ region: s3Region,
2137
+ endpoint: s3Endpoint,
2138
+ credentials: {
2139
+ accessKeyId: s3AccessKeyId,
2140
+ secretAccessKey: s3SecretAccessKey
2141
+ },
2142
+ forcePathStyle: true
2143
+ // Often needed for non-AWS S3 services
2144
+ });
2145
+ const vttKey = `translations/${assetId}/${fromLanguageCode}-to-${toLanguageCode}-${Date.now()}.vtt`;
2146
+ let presignedUrl;
2147
+ try {
2148
+ const upload = new import_lib_storage2.Upload({
2149
+ client: s3Client,
2150
+ params: {
2151
+ Bucket: s3Bucket,
2152
+ Key: vttKey,
2153
+ Body: translatedVtt,
2154
+ ContentType: "text/vtt"
2155
+ }
2156
+ });
2157
+ await upload.done();
2158
+ console.log(`\u2705 VTT uploaded successfully to: ${vttKey}`);
2159
+ const getObjectCommand = new import_client_s32.GetObjectCommand({
2160
+ Bucket: s3Bucket,
2161
+ Key: vttKey
2162
+ });
2163
+ presignedUrl = await (0, import_s3_request_presigner2.getSignedUrl)(s3Client, getObjectCommand, {
2164
+ expiresIn: 3600
2165
+ // 1 hour
2166
+ });
2167
+ console.log(`\u{1F517} Generated presigned URL (expires in 1 hour)`);
2168
+ } catch (error) {
2169
+ throw new Error(`Failed to upload VTT to S3: ${error instanceof Error ? error.message : "Unknown error"}`);
2170
+ }
2171
+ console.log("\u{1F4F9} Adding translated track to Mux asset...");
2172
+ let uploadedTrackId;
2173
+ try {
2174
+ const languageName = new Intl.DisplayNames(["en"], { type: "language" }).of(toLanguageCode) || toLanguageCode.toUpperCase();
2175
+ const trackName = `${languageName} (auto-translated)`;
2176
+ const trackResponse = await clients.mux.video.assets.createTrack(assetId, {
2177
+ type: "text",
2178
+ text_type: "subtitles",
2179
+ language_code: toLanguageCode,
2180
+ name: trackName,
2181
+ url: presignedUrl
2182
+ });
2183
+ uploadedTrackId = trackResponse.id;
2184
+ console.log(`\u2705 Track added to Mux asset with ID: ${uploadedTrackId}`);
2185
+ console.log(`\u{1F4CB} Track name: "${trackName}"`);
2186
+ } catch (error) {
2187
+ console.warn(`\u26A0\uFE0F Failed to add track to Mux asset: ${error instanceof Error ? error.message : "Unknown error"}`);
2188
+ console.log("\u{1F517} You can manually add the track using this presigned URL:");
2189
+ console.log(presignedUrl);
2190
+ }
2191
+ return {
2192
+ assetId,
2193
+ sourceLanguageCode: fromLanguageCode,
2194
+ targetLanguageCode: toLanguageCode,
2195
+ originalVtt: vttContent,
2196
+ translatedVtt,
2197
+ uploadedTrackId,
2198
+ presignedUrl
2199
+ };
2200
+ }
2201
+ // Annotate the CommonJS export names for ESM import in node:
2202
+ 0 && (module.exports = {
2203
+ SUMMARY_KEYWORD_LIMIT,
2204
+ burnedInCaptionsSchema,
2205
+ chapterSchema,
2206
+ chaptersSchema,
2207
+ generateChapters,
2208
+ generateVideoEmbeddings,
2209
+ getModerationScores,
2210
+ getSummaryAndTags,
2211
+ hasBurnedInCaptions,
2212
+ summarySchema,
2213
+ translateAudio,
2214
+ translateCaptions,
2215
+ translationSchema
2216
+ });
2217
+ //# sourceMappingURL=index.js.map