@mux/ai 0.66.0 → 0.67.0-canary.110
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/dist/{index-D_kEPGJj.d.ts → index-CV-IZBbE.d.ts} +1 -1
- package/dist/{index-Be9HQB67.d.ts → index-D1v-3Mgj.d.ts} +2 -2
- package/dist/index.d.ts +8 -5
- package/dist/index.js +530 -237
- package/dist/index.js.map +1 -1
- package/dist/primitives/index.d.ts +2 -2
- package/dist/primitives/index.js +3 -0
- package/dist/primitives/index.js.map +1 -1
- package/dist/{transcripts-DYpx6Mac.d.ts → transcripts-BkjWyvVz.d.ts} +7 -0
- package/dist/workflows/index.d.ts +2 -2
- package/dist/workflows/index.js +534 -241
- package/dist/workflows/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -5,7 +5,7 @@ var __export = (target, all) => {
|
|
|
5
5
|
};
|
|
6
6
|
|
|
7
7
|
// package.json
|
|
8
|
-
var version = "0.
|
|
8
|
+
var version = "0.67.0-canary.110";
|
|
9
9
|
|
|
10
10
|
// node_modules/@workflow/serde/dist/index.js
|
|
11
11
|
var WORKFLOW_SERIALIZE = /* @__PURE__ */ Symbol.for("workflow-serialize");
|
|
@@ -656,6 +656,8 @@ var MUX_AI_ERROR_CODES = {
|
|
|
656
656
|
PROVIDER_UNAVAILABLE: "provider_unavailable",
|
|
657
657
|
/** The provider can't process the asset's audio. The site names the dependency. Facts: `call`, `status`, `providerCode`, `reason` (`corrupt`, `unsupported_format`, `too_long`, `too_short`). */
|
|
658
658
|
AUDIO_UNPROCESSABLE: "audio_unprocessable",
|
|
659
|
+
/** The provider says it can't process an image taken from the asset (invalid or unreadable). The site names the dependency. Facts: `call`, `providerCode`. */
|
|
660
|
+
IMAGE_UNPROCESSABLE: "image_unprocessable",
|
|
659
661
|
/** Mux rejected the caller's access token (401), or the token lacks permission for this call (403), e.g. Mux Data access. Facts: `call`, `status`, `inputs` (`credentials`). */
|
|
660
662
|
ACCOUNT_CREDENTIALS_REJECTED: "account_credentials_rejected",
|
|
661
663
|
/** Mux answered 404 for something belonging to the asset (a track, a rendition, an image, its engagement data): gone, or not ready yet. A missing asset itself is `asset_not_found`. Facts: `call`, `status`. */
|
|
@@ -752,6 +754,7 @@ var MUX_AI_ERROR_CATALOG = {
|
|
|
752
754
|
[MUX_AI_ERROR_CODES.PROVIDER_RATE_LIMITED]: { type: MUX_AI_ERROR_TYPES.CAPACITY_ERROR, source: MUX_AI_ERROR_SOURCES.UPSTREAM, siteDependency: true, transient: true, retryable: true },
|
|
753
755
|
[MUX_AI_ERROR_CODES.PROVIDER_UNAVAILABLE]: { type: MUX_AI_ERROR_TYPES.CAPACITY_ERROR, source: MUX_AI_ERROR_SOURCES.UPSTREAM, siteDependency: true, transient: true, retryable: true },
|
|
754
756
|
[MUX_AI_ERROR_CODES.AUDIO_UNPROCESSABLE]: { type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR, source: MUX_AI_ERROR_SOURCES.ASSET, siteDependency: true },
|
|
757
|
+
[MUX_AI_ERROR_CODES.IMAGE_UNPROCESSABLE]: { type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR, source: MUX_AI_ERROR_SOURCES.ASSET, siteDependency: true },
|
|
755
758
|
// Mux's own responses, where the call says whose they are (see mux-video-errors.ts).
|
|
756
759
|
// The access token is the caller's: only its permissions decide what Mux allows.
|
|
757
760
|
[MUX_AI_ERROR_CODES.ACCOUNT_CREDENTIALS_REJECTED]: { type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR, source: MUX_AI_ERROR_SOURCES.ACCOUNT, siteDependency: true },
|
|
@@ -2712,6 +2715,9 @@ var MUX_AI_ERROR_PUBLIC_MAPPINGS = {
|
|
|
2712
2715
|
facts: ["providerError"],
|
|
2713
2716
|
message: (facts, { retryable }) => `Audio dubbing failed${facts.providerError ? `: ${text(facts.providerError)}` : "."}${retryable ? TRY_AGAIN : ""}`
|
|
2714
2717
|
},
|
|
2718
|
+
[MUX_AI_ERROR_CODES.IMAGE_UNPROCESSABLE]: {
|
|
2719
|
+
message: "The asset's images couldn't be processed."
|
|
2720
|
+
},
|
|
2715
2721
|
[MUX_AI_ERROR_CODES.AUDIO_UNPROCESSABLE]: {
|
|
2716
2722
|
facts: ["reason"],
|
|
2717
2723
|
message: (facts) => {
|
|
@@ -4938,7 +4944,7 @@ import { generateText, jsonSchema, NoObjectGeneratedError as NoObjectGeneratedEr
|
|
|
4938
4944
|
|
|
4939
4945
|
// src/lib/content-policy-error.ts
|
|
4940
4946
|
import { APICallError as APICallError2, NoObjectGeneratedError, NoOutputGeneratedError as NoOutputGeneratedError2, RetryError, TypeValidationError } from "ai";
|
|
4941
|
-
import { z as
|
|
4947
|
+
import { z as z5 } from "zod";
|
|
4942
4948
|
|
|
4943
4949
|
// src/lib/google-errors.ts
|
|
4944
4950
|
import { z as z3 } from "zod";
|
|
@@ -4982,6 +4988,77 @@ function googleCallError(apiError, message, init) {
|
|
|
4982
4988
|
});
|
|
4983
4989
|
}
|
|
4984
4990
|
|
|
4991
|
+
// src/lib/openai-errors.ts
|
|
4992
|
+
import { z as z4 } from "zod";
|
|
4993
|
+
var OpenAITokenSchema = z4.string().regex(/^[\w.-]{1,64}$/);
|
|
4994
|
+
var OpenAIErrorBodySchema = z4.object({
|
|
4995
|
+
error: z4.object({
|
|
4996
|
+
code: OpenAITokenSchema.nullish(),
|
|
4997
|
+
type: OpenAITokenSchema.nullish()
|
|
4998
|
+
})
|
|
4999
|
+
});
|
|
5000
|
+
function parseOpenAIErrorBody(responseBody) {
|
|
5001
|
+
if (!responseBody) {
|
|
5002
|
+
return {};
|
|
5003
|
+
}
|
|
5004
|
+
let body;
|
|
5005
|
+
try {
|
|
5006
|
+
body = JSON.parse(responseBody);
|
|
5007
|
+
} catch {
|
|
5008
|
+
return {};
|
|
5009
|
+
}
|
|
5010
|
+
const parsed = OpenAIErrorBodySchema.safeParse(body);
|
|
5011
|
+
if (!parsed.success) {
|
|
5012
|
+
return {};
|
|
5013
|
+
}
|
|
5014
|
+
const { code, type } = parsed.data.error;
|
|
5015
|
+
return { ...code && { code }, ...type && { type } };
|
|
5016
|
+
}
|
|
5017
|
+
var OPENAI_QUOTA_CODES = /* @__PURE__ */ new Set(["credit_balance_exhausted", "organization_spend_limit_exceeded", "project_spend_limit_exceeded", "organization_usage_limit_exceeded", "insufficient_quota"]);
|
|
5018
|
+
var OPENAI_RATE_LIMIT_CODES = /* @__PURE__ */ new Set(["slow_down", "rate_limit_exceeded"]);
|
|
5019
|
+
var OPENAI_UNAVAILABLE_CODES = /* @__PURE__ */ new Set(["server_is_overloaded", "service_unavailable_error"]);
|
|
5020
|
+
function openAIErrorRule(status, { code, type }) {
|
|
5021
|
+
if (code && OPENAI_QUOTA_CODES.has(code) || !code && type === "insufficient_quota") {
|
|
5022
|
+
return MUX_AI_ERROR_CODES.PROVIDER_QUOTA_EXHAUSTED;
|
|
5023
|
+
}
|
|
5024
|
+
if (code && OPENAI_RATE_LIMIT_CODES.has(code)) {
|
|
5025
|
+
return MUX_AI_ERROR_CODES.PROVIDER_RATE_LIMITED;
|
|
5026
|
+
}
|
|
5027
|
+
if (code && OPENAI_UNAVAILABLE_CODES.has(code)) {
|
|
5028
|
+
return MUX_AI_ERROR_CODES.PROVIDER_UNAVAILABLE;
|
|
5029
|
+
}
|
|
5030
|
+
return status === 401 ? MUX_AI_ERROR_CODES.PROVIDER_CREDENTIALS_REJECTED : void 0;
|
|
5031
|
+
}
|
|
5032
|
+
function openAICallError(apiError, message, init) {
|
|
5033
|
+
const body = parseOpenAIErrorBody(apiError.responseBody);
|
|
5034
|
+
const providerCode = body.code ?? body.type;
|
|
5035
|
+
const code = openAIErrorRule(apiError.statusCode, body);
|
|
5036
|
+
return dependencyError(message, {
|
|
5037
|
+
dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
|
|
5038
|
+
call: init.call,
|
|
5039
|
+
status: apiError.statusCode,
|
|
5040
|
+
requestId: requestIdOf(apiError.responseHeaders),
|
|
5041
|
+
facts: { ...init.facts, ...providerCode && { providerCode } },
|
|
5042
|
+
...code && { code },
|
|
5043
|
+
cause: init.cause ?? apiError
|
|
5044
|
+
});
|
|
5045
|
+
}
|
|
5046
|
+
function openAIFetchError(message, init) {
|
|
5047
|
+
const body = parseOpenAIErrorBody(init.body);
|
|
5048
|
+
const providerCode = body.code ?? body.type;
|
|
5049
|
+
const code = init.status === void 0 ? void 0 : openAIErrorRule(init.status, body);
|
|
5050
|
+
return dependencyError(message, {
|
|
5051
|
+
dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
|
|
5052
|
+
call: init.call,
|
|
5053
|
+
status: init.status,
|
|
5054
|
+
requestId: init.requestId,
|
|
5055
|
+
timedOut: init.timedOut,
|
|
5056
|
+
facts: { ...init.facts, ...providerCode && { providerCode } },
|
|
5057
|
+
...code && { code },
|
|
5058
|
+
cause: init.cause
|
|
5059
|
+
});
|
|
5060
|
+
}
|
|
5061
|
+
|
|
4985
5062
|
// src/lib/retry.ts
|
|
4986
5063
|
import { APICallError, DownloadError, NoOutputGeneratedError } from "ai";
|
|
4987
5064
|
var DEFAULT_RETRY_OPTIONS = {
|
|
@@ -5046,50 +5123,50 @@ async function withRetry(fn, {
|
|
|
5046
5123
|
}
|
|
5047
5124
|
|
|
5048
5125
|
// src/lib/content-policy-error.ts
|
|
5049
|
-
var PolicyTokenSchema =
|
|
5050
|
-
var SafetyRatingSchema =
|
|
5126
|
+
var PolicyTokenSchema = z5.string().trim().min(1).max(64).regex(/^[A-Z0-9_]+$/);
|
|
5127
|
+
var SafetyRatingSchema = z5.object({
|
|
5051
5128
|
category: PolicyTokenSchema.nullish(),
|
|
5052
|
-
blocked:
|
|
5129
|
+
blocked: z5.boolean().nullish()
|
|
5053
5130
|
});
|
|
5054
|
-
var ContentPolicyResponseSchema =
|
|
5055
|
-
promptFeedback:
|
|
5131
|
+
var ContentPolicyResponseSchema = z5.object({
|
|
5132
|
+
promptFeedback: z5.object({
|
|
5056
5133
|
blockReason: PolicyTokenSchema.nullish(),
|
|
5057
|
-
safetyRatings:
|
|
5134
|
+
safetyRatings: z5.array(SafetyRatingSchema).max(32).nullish()
|
|
5058
5135
|
}).nullish(),
|
|
5059
|
-
candidates:
|
|
5136
|
+
candidates: z5.array(z5.object({
|
|
5060
5137
|
finishReason: PolicyTokenSchema.nullish(),
|
|
5061
|
-
safetyRatings:
|
|
5138
|
+
safetyRatings: z5.array(SafetyRatingSchema).max(32).nullish()
|
|
5062
5139
|
})).max(8).nullish()
|
|
5063
5140
|
});
|
|
5064
|
-
var ContentPolicyUsageResponseSchema =
|
|
5065
|
-
usageMetadata:
|
|
5066
|
-
promptTokenCount:
|
|
5067
|
-
candidatesTokenCount:
|
|
5068
|
-
totalTokenCount:
|
|
5069
|
-
cachedContentTokenCount:
|
|
5070
|
-
thoughtsTokenCount:
|
|
5141
|
+
var ContentPolicyUsageResponseSchema = z5.object({
|
|
5142
|
+
usageMetadata: z5.object({
|
|
5143
|
+
promptTokenCount: z5.number().finite().nonnegative().nullish(),
|
|
5144
|
+
candidatesTokenCount: z5.number().finite().nonnegative().nullish(),
|
|
5145
|
+
totalTokenCount: z5.number().finite().nonnegative().nullish(),
|
|
5146
|
+
cachedContentTokenCount: z5.number().finite().nonnegative().nullish(),
|
|
5147
|
+
thoughtsTokenCount: z5.number().finite().nonnegative().nullish()
|
|
5071
5148
|
}).nullish()
|
|
5072
5149
|
});
|
|
5073
|
-
var OpenAIRefusalResponseSchema =
|
|
5074
|
-
output:
|
|
5075
|
-
type:
|
|
5076
|
-
content:
|
|
5150
|
+
var OpenAIRefusalResponseSchema = z5.object({
|
|
5151
|
+
output: z5.array(z5.object({
|
|
5152
|
+
type: z5.string(),
|
|
5153
|
+
content: z5.array(z5.object({ type: z5.string() })).max(32).nullish()
|
|
5077
5154
|
})).max(8)
|
|
5078
5155
|
});
|
|
5079
|
-
var OpenAIUsageResponseSchema =
|
|
5080
|
-
usage:
|
|
5081
|
-
input_tokens:
|
|
5082
|
-
output_tokens:
|
|
5083
|
-
total_tokens:
|
|
5084
|
-
input_tokens_details:
|
|
5085
|
-
cached_tokens:
|
|
5086
|
-
cache_write_tokens:
|
|
5156
|
+
var OpenAIUsageResponseSchema = z5.object({
|
|
5157
|
+
usage: z5.object({
|
|
5158
|
+
input_tokens: z5.number().finite().nonnegative(),
|
|
5159
|
+
output_tokens: z5.number().finite().nonnegative(),
|
|
5160
|
+
total_tokens: z5.number().finite().nonnegative().optional(),
|
|
5161
|
+
input_tokens_details: z5.object({
|
|
5162
|
+
cached_tokens: z5.number().finite().nonnegative().nullish(),
|
|
5163
|
+
cache_write_tokens: z5.number().finite().nonnegative().nullish()
|
|
5087
5164
|
}).nullish(),
|
|
5088
|
-
output_tokens_details:
|
|
5165
|
+
output_tokens_details: z5.object({ reasoning_tokens: z5.number().finite().nonnegative().nullish() }).nullish()
|
|
5089
5166
|
})
|
|
5090
5167
|
});
|
|
5091
|
-
var OpenAIPolicyErrorSchema =
|
|
5092
|
-
error:
|
|
5168
|
+
var OpenAIPolicyErrorSchema = z5.object({
|
|
5169
|
+
error: z5.object({ code: z5.enum(["content_policy_violation", "content_filter"]) })
|
|
5093
5170
|
});
|
|
5094
5171
|
var OPENAI_PROMPT_FLAG = /invalid prompt:.*flagged as potentially violating/i;
|
|
5095
5172
|
var OPENAI_PROMPT_FLAGGED = "PROMPT_FLAGGED";
|
|
@@ -5266,6 +5343,8 @@ function classifyModelCallError(error, context) {
|
|
|
5266
5343
|
switch (context.provider) {
|
|
5267
5344
|
case "google":
|
|
5268
5345
|
return withUsage(googleCallError(apiError, message, { call: context.call, facts: modelCallFacts(context), cause: error }), getErrorTokenUsage(error));
|
|
5346
|
+
case "openai":
|
|
5347
|
+
return withUsage(openAICallError(apiError, message, { call: context.call, facts: modelCallFacts(context), cause: error }), getErrorTokenUsage(error));
|
|
5269
5348
|
default:
|
|
5270
5349
|
return void 0;
|
|
5271
5350
|
}
|
|
@@ -5756,7 +5835,7 @@ function repairText(options) {
|
|
|
5756
5835
|
// src/workflows/ask-questions.ts
|
|
5757
5836
|
import { generateText as generateText2, Output as Output2 } from "ai";
|
|
5758
5837
|
import dedent2 from "dedent";
|
|
5759
|
-
import { z as
|
|
5838
|
+
import { z as z6 } from "zod";
|
|
5760
5839
|
|
|
5761
5840
|
// src/lib/image-download.ts
|
|
5762
5841
|
import pRetry, { AbortError } from "p-retry";
|
|
@@ -5889,12 +5968,12 @@ function imageDownloadError(failure, call, cause) {
|
|
|
5889
5968
|
{ call, cause, timedOut: failure?.timedOut }
|
|
5890
5969
|
);
|
|
5891
5970
|
}
|
|
5892
|
-
async function downloadImagesAsBase64(urls, options = {}, maxConcurrent = 5) {
|
|
5971
|
+
async function downloadImagesAsBase64(urls, options = {}, maxConcurrent = 5, errorOptions = {}) {
|
|
5893
5972
|
"use step";
|
|
5894
5973
|
const results = [];
|
|
5895
5974
|
for (let i = 0; i < urls.length; i += maxConcurrent) {
|
|
5896
5975
|
const batch = urls.slice(i, i + maxConcurrent);
|
|
5897
|
-
const batchPromises = batch.map((url) => downloadImageAsBase64(url, options));
|
|
5976
|
+
const batchPromises = batch.map((url) => downloadImageAsBase64(url, options, errorOptions));
|
|
5898
5977
|
const batchResults = await Promise.all(batchPromises);
|
|
5899
5978
|
results.push(...batchResults);
|
|
5900
5979
|
}
|
|
@@ -5986,17 +6065,17 @@ var ASK_QUESTIONS_MAX_QUESTION_LENGTH = 600;
|
|
|
5986
6065
|
var ASK_QUESTIONS_MAX_QUESTIONS_PER_CALL = 50;
|
|
5987
6066
|
var ASK_QUESTIONS_DEFAULT_MAX_ANSWER_OPTION_LENGTH = 150;
|
|
5988
6067
|
var ASK_QUESTIONS_DEFAULT_MAX_FREE_FORM_ANSWER_LENGTH = 500;
|
|
5989
|
-
var questionAnswerSchema =
|
|
5990
|
-
question:
|
|
5991
|
-
answer:
|
|
5992
|
-
confidence:
|
|
5993
|
-
reasoning:
|
|
5994
|
-
skipped:
|
|
6068
|
+
var questionAnswerSchema = z6.object({
|
|
6069
|
+
question: z6.string().describe("The full text of the original question"),
|
|
6070
|
+
answer: z6.string().nullable(),
|
|
6071
|
+
confidence: z6.number(),
|
|
6072
|
+
reasoning: z6.string().max(1e3),
|
|
6073
|
+
skipped: z6.boolean()
|
|
5995
6074
|
});
|
|
5996
6075
|
var SKIP_SENTINEL = "__SKIPPED__";
|
|
5997
6076
|
function createAskQuestionsSchema(answerSchema) {
|
|
5998
|
-
return
|
|
5999
|
-
answers:
|
|
6077
|
+
return z6.object({
|
|
6078
|
+
answers: z6.array(
|
|
6000
6079
|
questionAnswerSchema.extend({
|
|
6001
6080
|
answer: answerSchema
|
|
6002
6081
|
})
|
|
@@ -6371,12 +6450,12 @@ function buildResponseSchemaForQuestions(normalizedQuestions, maxFreeFormAnswerL
|
|
|
6371
6450
|
SKIP_SENTINEL.length,
|
|
6372
6451
|
longestConstrained
|
|
6373
6452
|
);
|
|
6374
|
-
return createAskQuestionsSchema(
|
|
6453
|
+
return createAskQuestionsSchema(z6.string().min(1).max(schemaMax));
|
|
6375
6454
|
}
|
|
6376
6455
|
const allowed = Array.from(
|
|
6377
6456
|
new Set(normalizedQuestions.flatMap(allowedAnswersForQuestion))
|
|
6378
6457
|
);
|
|
6379
|
-
return createAskQuestionsSchema(
|
|
6458
|
+
return createAskQuestionsSchema(z6.enum([...allowed, SKIP_SENTINEL]));
|
|
6380
6459
|
}
|
|
6381
6460
|
async function analyzeQuestions({
|
|
6382
6461
|
provider,
|
|
@@ -6678,11 +6757,11 @@ async function askQuestionsInternal(assetId, questions, options, collectedUsage)
|
|
|
6678
6757
|
// src/workflows/burned-in-captions.ts
|
|
6679
6758
|
import { generateText as generateText3, Output as Output3 } from "ai";
|
|
6680
6759
|
import dedent3 from "dedent";
|
|
6681
|
-
import { z as
|
|
6682
|
-
var burnedInCaptionsSchema =
|
|
6683
|
-
hasBurnedInCaptions:
|
|
6684
|
-
confidence:
|
|
6685
|
-
detectedLanguage:
|
|
6760
|
+
import { z as z7 } from "zod";
|
|
6761
|
+
var burnedInCaptionsSchema = z7.object({
|
|
6762
|
+
hasBurnedInCaptions: z7.boolean(),
|
|
6763
|
+
confidence: z7.number(),
|
|
6764
|
+
detectedLanguage: z7.string().max(100).nullable()
|
|
6686
6765
|
});
|
|
6687
6766
|
var SYSTEM_PROMPT2 = promptDedent`
|
|
6688
6767
|
<role>
|
|
@@ -6779,7 +6858,7 @@ function buildUserPrompt2(promptOverrides) {
|
|
|
6779
6858
|
var DEFAULT_PROVIDER = "openai";
|
|
6780
6859
|
async function fetchImageAsBase642(imageUrl, imageDownloadOptions) {
|
|
6781
6860
|
"use step";
|
|
6782
|
-
const downloadResult = await downloadImageAsBase64(imageUrl, imageDownloadOptions);
|
|
6861
|
+
const downloadResult = await downloadImageAsBase64(imageUrl, imageDownloadOptions, { classifiedErrors: true, call: "fetch_storyboard" });
|
|
6783
6862
|
return downloadResult.base64Data;
|
|
6784
6863
|
}
|
|
6785
6864
|
async function analyzeStoryboard({
|
|
@@ -6792,6 +6871,7 @@ async function analyzeStoryboard({
|
|
|
6792
6871
|
}) {
|
|
6793
6872
|
"use step";
|
|
6794
6873
|
const model = await createLanguageModelFromConfig(provider, modelId, credentials);
|
|
6874
|
+
const context = { call: "detect_burned_in_captions", provider, model: modelId };
|
|
6795
6875
|
const response = await withContentPolicyAwareRetry(() => generateText3({
|
|
6796
6876
|
model,
|
|
6797
6877
|
maxRetries: 0,
|
|
@@ -6807,8 +6887,10 @@ async function analyzeStoryboard({
|
|
|
6807
6887
|
]
|
|
6808
6888
|
}
|
|
6809
6889
|
]
|
|
6810
|
-
}))
|
|
6811
|
-
|
|
6890
|
+
}), void 0, context).catch((error) => {
|
|
6891
|
+
throw modelStepError(error, "Burned-in captions model call failed", { ...context });
|
|
6892
|
+
});
|
|
6893
|
+
const output = getGeneratedOutputWithContentPolicyHandling(response, context);
|
|
6812
6894
|
const unexpectedKeys = detectUnexpectedKeysFromRawText(
|
|
6813
6895
|
response.text,
|
|
6814
6896
|
burnedInCaptionsSchema.keyof().options
|
|
@@ -6855,12 +6937,13 @@ async function hasBurnedInCaptionsInternal(assetId, options, collectedUsage) {
|
|
|
6855
6937
|
model,
|
|
6856
6938
|
provider
|
|
6857
6939
|
});
|
|
6858
|
-
const { asset: assetData, playbackId, policy } = await getPlaybackIdForAsset(assetId, credentials, options.assetSnapshot);
|
|
6940
|
+
const { asset: assetData, playbackId, policy } = await getPlaybackIdForAsset(assetId, credentials, options.assetSnapshot, { classifiedErrors: true });
|
|
6859
6941
|
const assetDurationSeconds = getAssetDurationSecondsFromAsset(assetData);
|
|
6860
6942
|
const storyboardScope = resolveRenderableVideoScope(
|
|
6861
6943
|
scope,
|
|
6862
6944
|
assetDurationSeconds,
|
|
6863
|
-
getVideoTrackDurationSecondsFromAsset(assetData)
|
|
6945
|
+
getVideoTrackDurationSecondsFromAsset(assetData),
|
|
6946
|
+
{ classifiedErrors: true, assetId }
|
|
6864
6947
|
);
|
|
6865
6948
|
const imageUrl = await getStoryboardUrl(
|
|
6866
6949
|
playbackId,
|
|
@@ -6869,31 +6952,17 @@ async function hasBurnedInCaptionsInternal(assetId, options, collectedUsage) {
|
|
|
6869
6952
|
credentials,
|
|
6870
6953
|
storyboardScope
|
|
6871
6954
|
);
|
|
6872
|
-
|
|
6873
|
-
|
|
6874
|
-
|
|
6875
|
-
|
|
6876
|
-
|
|
6877
|
-
|
|
6878
|
-
|
|
6879
|
-
|
|
6880
|
-
|
|
6881
|
-
|
|
6882
|
-
});
|
|
6883
|
-
} else {
|
|
6884
|
-
analysisResponse = await analyzeStoryboard({
|
|
6885
|
-
imageDataUrl: imageUrl,
|
|
6886
|
-
provider: modelConfig.provider,
|
|
6887
|
-
modelId: modelConfig.modelId,
|
|
6888
|
-
userPrompt,
|
|
6889
|
-
systemPrompt: SYSTEM_PROMPT2,
|
|
6890
|
-
credentials
|
|
6891
|
-
});
|
|
6892
|
-
}
|
|
6955
|
+
const imageDataUrl = imageSubmissionMode === "base64" ? await fetchImageAsBase642(imageUrl, imageDownloadOptions) : imageUrl;
|
|
6956
|
+
const modelFacts = { call: "detect_burned_in_captions", provider: modelConfig.provider, model: modelConfig.modelId, assetId };
|
|
6957
|
+
const analysisResponse = await analyzeStoryboard({
|
|
6958
|
+
imageDataUrl,
|
|
6959
|
+
provider: modelConfig.provider,
|
|
6960
|
+
modelId: modelConfig.modelId,
|
|
6961
|
+
userPrompt,
|
|
6962
|
+
systemPrompt: SYSTEM_PROMPT2,
|
|
6963
|
+
credentials
|
|
6964
|
+
}).catch((error) => wrapError(error, `Failed to analyze storyboard with ${modelConfig.provider}`, modelFacts));
|
|
6893
6965
|
collectedUsage.push(analysisResponse.usage);
|
|
6894
|
-
if (!analysisResponse.result) {
|
|
6895
|
-
throw new Error("No analysis result received from AI provider");
|
|
6896
|
-
}
|
|
6897
6966
|
const safety = createSafetyReporter();
|
|
6898
6967
|
if (analysisResponse.unexpectedKeys.length > 0) {
|
|
6899
6968
|
console.warn(
|
|
@@ -6922,7 +6991,7 @@ async function hasBurnedInCaptionsInternal(assetId, options, collectedUsage) {
|
|
|
6922
6991
|
// src/workflows/chapters.ts
|
|
6923
6992
|
import { generateText as generateText4, Output as Output4 } from "ai";
|
|
6924
6993
|
import dedent5 from "dedent";
|
|
6925
|
-
import { z as
|
|
6994
|
+
import { z as z8 } from "zod";
|
|
6926
6995
|
|
|
6927
6996
|
// src/prompts/chapters.ts
|
|
6928
6997
|
import dedent4 from "dedent";
|
|
@@ -6947,12 +7016,12 @@ function createChapterGuidance({
|
|
|
6947
7016
|
}
|
|
6948
7017
|
|
|
6949
7018
|
// src/workflows/chapters.ts
|
|
6950
|
-
var chapterSchema =
|
|
6951
|
-
startTime:
|
|
6952
|
-
title:
|
|
7019
|
+
var chapterSchema = z8.object({
|
|
7020
|
+
startTime: z8.number(),
|
|
7021
|
+
title: z8.string().max(300)
|
|
6953
7022
|
});
|
|
6954
|
-
var chaptersSchema =
|
|
6955
|
-
chapters:
|
|
7023
|
+
var chaptersSchema = z8.object({
|
|
7024
|
+
chapters: z8.array(chapterSchema)
|
|
6956
7025
|
});
|
|
6957
7026
|
async function generateChaptersWithAI({
|
|
6958
7027
|
provider,
|
|
@@ -7327,9 +7396,9 @@ async function generateChaptersInternal(assetId, options, collectedUsage) {
|
|
|
7327
7396
|
|
|
7328
7397
|
// src/workflows/edit-captions.ts
|
|
7329
7398
|
import { generateText as generateText5, Output as Output5 } from "ai";
|
|
7330
|
-
import { z as
|
|
7331
|
-
var profanityDetectionSchema =
|
|
7332
|
-
profanity:
|
|
7399
|
+
import { z as z9 } from "zod";
|
|
7400
|
+
var profanityDetectionSchema = z9.object({
|
|
7401
|
+
profanity: z9.array(z9.string().max(100)).describe(
|
|
7333
7402
|
"Unique profane words or short phrases exactly as they appear in the transcript text. Include each distinct form only once (e.g., if 'fuck' and 'fucking' both appear, list both)."
|
|
7334
7403
|
)
|
|
7335
7404
|
});
|
|
@@ -8162,21 +8231,21 @@ async function generateVideoEmbeddings(assetId, options = {}) {
|
|
|
8162
8231
|
// src/workflows/engagement-insights.ts
|
|
8163
8232
|
import { generateText as generateText6, Output as Output6 } from "ai";
|
|
8164
8233
|
import dedent6 from "dedent";
|
|
8165
|
-
import { z as
|
|
8166
|
-
var aiMomentInsightSchema =
|
|
8167
|
-
hotspotIndex:
|
|
8168
|
-
startMs:
|
|
8169
|
-
endMs:
|
|
8170
|
-
timestamp:
|
|
8171
|
-
engagementScore:
|
|
8172
|
-
insight:
|
|
8234
|
+
import { z as z10 } from "zod";
|
|
8235
|
+
var aiMomentInsightSchema = z10.object({
|
|
8236
|
+
hotspotIndex: z10.number(),
|
|
8237
|
+
startMs: z10.number(),
|
|
8238
|
+
endMs: z10.number(),
|
|
8239
|
+
timestamp: z10.string(),
|
|
8240
|
+
engagementScore: z10.number(),
|
|
8241
|
+
insight: z10.string().max(1e3)
|
|
8173
8242
|
});
|
|
8174
|
-
var aiOverallInsightSchema =
|
|
8175
|
-
summary:
|
|
8176
|
-
trends:
|
|
8243
|
+
var aiOverallInsightSchema = z10.object({
|
|
8244
|
+
summary: z10.string().max(2e3),
|
|
8245
|
+
trends: z10.array(z10.string().max(500))
|
|
8177
8246
|
});
|
|
8178
|
-
var engagementInsightsSchema =
|
|
8179
|
-
momentInsights:
|
|
8247
|
+
var engagementInsightsSchema = z10.object({
|
|
8248
|
+
momentInsights: z10.array(aiMomentInsightSchema),
|
|
8180
8249
|
overallInsight: aiOverallInsightSchema
|
|
8181
8250
|
});
|
|
8182
8251
|
var SYSTEM_PROMPT4 = promptDedent`
|
|
@@ -8740,7 +8809,7 @@ async function generateEngagementInsightsInternal(assetId, options, collectedUsa
|
|
|
8740
8809
|
|
|
8741
8810
|
// src/workflows/generate-text.ts
|
|
8742
8811
|
import { APICallError as APICallError4, generateText as generateTextWithModel, Output as Output7 } from "ai";
|
|
8743
|
-
import { z as
|
|
8812
|
+
import { z as z11 } from "zod";
|
|
8744
8813
|
var GENERATE_TEXT_MAX_VARIANTS = 5;
|
|
8745
8814
|
var GENERATE_TEXT_MAX_ARTIFACTS = 5;
|
|
8746
8815
|
var GENERATE_TEXT_MAX_INSTRUCTIONS_CHARS = 500;
|
|
@@ -8915,14 +8984,14 @@ async function getCompletedShots(assetId, credentials) {
|
|
|
8915
8984
|
}
|
|
8916
8985
|
return void 0;
|
|
8917
8986
|
}
|
|
8918
|
-
var briefSchema =
|
|
8919
|
-
centralIdea:
|
|
8920
|
-
readerValue:
|
|
8921
|
-
keyPoints:
|
|
8922
|
-
sourceSpecifics:
|
|
8923
|
-
visualContext:
|
|
8924
|
-
voiceSignals:
|
|
8925
|
-
claimsToQualify:
|
|
8987
|
+
var briefSchema = z11.object({
|
|
8988
|
+
centralIdea: z11.string().max(500),
|
|
8989
|
+
readerValue: z11.string().max(500),
|
|
8990
|
+
keyPoints: z11.array(z11.string().max(500)),
|
|
8991
|
+
sourceSpecifics: z11.array(z11.string().max(500)),
|
|
8992
|
+
visualContext: z11.array(z11.string().max(500)),
|
|
8993
|
+
voiceSignals: z11.array(z11.string().max(300)),
|
|
8994
|
+
claimsToQualify: z11.array(z11.string().max(500))
|
|
8926
8995
|
});
|
|
8927
8996
|
var BRIEF_LIST_LIMITS = {
|
|
8928
8997
|
keyPoints: 8,
|
|
@@ -9183,7 +9252,7 @@ async function extractBriefWithModel(args) {
|
|
|
9183
9252
|
};
|
|
9184
9253
|
});
|
|
9185
9254
|
}
|
|
9186
|
-
var artifactSchema =
|
|
9255
|
+
var artifactSchema = z11.object({ content: z11.string() });
|
|
9187
9256
|
async function generateArtifactWithModel(args) {
|
|
9188
9257
|
"use step";
|
|
9189
9258
|
const diagnostics = { phase: "draft", provider: args.provider, modelId: args.modelId };
|
|
@@ -9444,7 +9513,71 @@ async function generateTextInternal(assetId, rawOptions, collectedUsage) {
|
|
|
9444
9513
|
}
|
|
9445
9514
|
|
|
9446
9515
|
// src/workflows/moderation.ts
|
|
9447
|
-
import { z as
|
|
9516
|
+
import { z as z12 } from "zod";
|
|
9517
|
+
|
|
9518
|
+
// src/lib/google-vision-errors.ts
|
|
9519
|
+
var GOOGLE_RPC_INVALID_ARGUMENT = "3";
|
|
9520
|
+
var GOOGLE_RPC_RESOURCE_EXHAUSTED = "8";
|
|
9521
|
+
var GOOGLE_RPC_UNAVAILABLE = "14";
|
|
9522
|
+
function googleVisionImageErrorRule(rpcCode, { inline }) {
|
|
9523
|
+
switch (rpcCode) {
|
|
9524
|
+
// Per image, not per request. With the image sent inline, it's that image that can't be
|
|
9525
|
+
// used. With a URL, Vision fetches the image itself and reports a failed fetch with the
|
|
9526
|
+
// same code ("The URL does not appear to be accessible by us"), which says nothing about
|
|
9527
|
+
// the image, so it stays `dependency_response_failed`.
|
|
9528
|
+
case GOOGLE_RPC_INVALID_ARGUMENT:
|
|
9529
|
+
return inline ? { code: MUX_AI_ERROR_CODES.IMAGE_UNPROCESSABLE } : void 0;
|
|
9530
|
+
case GOOGLE_RPC_UNAVAILABLE:
|
|
9531
|
+
return { code: MUX_AI_ERROR_CODES.PROVIDER_UNAVAILABLE };
|
|
9532
|
+
// A rate limit or a spent quota, which Google can't tell apart here: "generally don't retry".
|
|
9533
|
+
case GOOGLE_RPC_RESOURCE_EXHAUSTED:
|
|
9534
|
+
return { retryable: false };
|
|
9535
|
+
default:
|
|
9536
|
+
return void 0;
|
|
9537
|
+
}
|
|
9538
|
+
}
|
|
9539
|
+
function googleVisionCallError(message, init) {
|
|
9540
|
+
const answered = init.answered === true;
|
|
9541
|
+
const rule = answered ? googleVisionImageErrorRule(init.rpcCode, { inline: init.inline === true }) : void 0;
|
|
9542
|
+
return dependencyError(message, {
|
|
9543
|
+
dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
|
|
9544
|
+
call: init.call,
|
|
9545
|
+
status: init.status,
|
|
9546
|
+
requestId: init.requestId,
|
|
9547
|
+
timedOut: init.timedOut,
|
|
9548
|
+
facts: { provider: "google-vision-api", ...init.facts, ...init.rpcCode && { providerCode: init.rpcCode } },
|
|
9549
|
+
...answered && { code: rule?.code ?? MUX_AI_ERROR_CODES.DEPENDENCY_RESPONSE_FAILED },
|
|
9550
|
+
...rule?.retryable !== void 0 && { retryable: rule.retryable },
|
|
9551
|
+
cause: init.cause
|
|
9552
|
+
});
|
|
9553
|
+
}
|
|
9554
|
+
|
|
9555
|
+
// src/lib/hive-errors.ts
|
|
9556
|
+
function hiveErrorRule(status) {
|
|
9557
|
+
switch (status) {
|
|
9558
|
+
case 405:
|
|
9559
|
+
return MUX_AI_ERROR_CODES.PROVIDER_QUOTA_EXHAUSTED;
|
|
9560
|
+
case 403:
|
|
9561
|
+
return MUX_AI_ERROR_CODES.PROVIDER_CREDENTIALS_REJECTED;
|
|
9562
|
+
case 429:
|
|
9563
|
+
return MUX_AI_ERROR_CODES.PROVIDER_RATE_LIMITED;
|
|
9564
|
+
default:
|
|
9565
|
+
return void 0;
|
|
9566
|
+
}
|
|
9567
|
+
}
|
|
9568
|
+
function hiveCallError(message, init) {
|
|
9569
|
+
const code = init.answered ? MUX_AI_ERROR_CODES.DEPENDENCY_RESPONSE_FAILED : hiveErrorRule(init.status);
|
|
9570
|
+
return dependencyError(message, {
|
|
9571
|
+
dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
|
|
9572
|
+
call: init.call,
|
|
9573
|
+
status: init.status,
|
|
9574
|
+
requestId: init.requestId,
|
|
9575
|
+
timedOut: init.timedOut,
|
|
9576
|
+
facts: { provider: "hive", ...init.facts, ...init.returnCode && { providerCode: init.returnCode } },
|
|
9577
|
+
...code && { code },
|
|
9578
|
+
cause: init.cause
|
|
9579
|
+
});
|
|
9580
|
+
}
|
|
9448
9581
|
|
|
9449
9582
|
// src/lib/sampling-plan.ts
|
|
9450
9583
|
var DEFAULT_FPS = 30;
|
|
@@ -9512,7 +9645,6 @@ var DEFAULT_THRESHOLDS = {
|
|
|
9512
9645
|
violence: 0.8
|
|
9513
9646
|
};
|
|
9514
9647
|
var DEFAULT_PROVIDER2 = "openai";
|
|
9515
|
-
var OPENAI_MODERATION_RETRIABLE_STATUS_CODES = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
|
|
9516
9648
|
var OPENAI_MODERATION_MAX_RETRIES = 2;
|
|
9517
9649
|
var OPENAI_MODERATION_BASE_DELAY_MS = 750;
|
|
9518
9650
|
var OPENAI_MODERATION_MAX_DELAY_MS = 3e3;
|
|
@@ -9557,19 +9689,23 @@ var HIVE_VIOLENCE_CATEGORIES = [
|
|
|
9557
9689
|
"yes_self_harm",
|
|
9558
9690
|
"garm_death_injury_or_military_conflict"
|
|
9559
9691
|
];
|
|
9560
|
-
|
|
9561
|
-
|
|
9562
|
-
|
|
9563
|
-
|
|
9564
|
-
|
|
9565
|
-
|
|
9566
|
-
|
|
9567
|
-
|
|
9568
|
-
|
|
9569
|
-
|
|
9570
|
-
|
|
9571
|
-
|
|
9572
|
-
|
|
9692
|
+
function unusableResponseError(message, call, provider) {
|
|
9693
|
+
return new MuxAiError(message, {
|
|
9694
|
+
code: MUX_AI_ERROR_CODES.MODEL_OUTPUT_INVALID,
|
|
9695
|
+
type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
|
|
9696
|
+
source: MUX_AI_ERROR_SOURCES.UPSTREAM,
|
|
9697
|
+
dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
|
|
9698
|
+
facts: { call, provider }
|
|
9699
|
+
});
|
|
9700
|
+
}
|
|
9701
|
+
var RETRIED_WITHIN_CALL = /* @__PURE__ */ new WeakSet();
|
|
9702
|
+
function sampleFailureOf(error) {
|
|
9703
|
+
return MuxAiError.is(error) ? error : void 0;
|
|
9704
|
+
}
|
|
9705
|
+
var ProviderCodeSchema = z12.string().regex(/^[\w.-]{1,64}$/);
|
|
9706
|
+
function providerCodeOf(value) {
|
|
9707
|
+
const parsed = ProviderCodeSchema.safeParse(typeof value === "number" ? String(value) : value);
|
|
9708
|
+
return parsed.success ? parsed.data : void 0;
|
|
9573
9709
|
}
|
|
9574
9710
|
function compactBodySnippet(body, maxLength = 180) {
|
|
9575
9711
|
const compact = body.replace(/\s+/g, " ").trim();
|
|
@@ -9578,34 +9714,45 @@ function compactBodySnippet(body, maxLength = 180) {
|
|
|
9578
9714
|
}
|
|
9579
9715
|
return compact.length > maxLength ? `${compact.slice(0, maxLength)}...` : compact;
|
|
9580
9716
|
}
|
|
9581
|
-
function
|
|
9717
|
+
function unreadableOpenAIResponseError(message, res, call, { retryWithinCall }) {
|
|
9718
|
+
if (!res.ok) {
|
|
9719
|
+
return openAIFetchError(message, { call, status: res.status, requestId: requestIdOf(res.headers), facts: { provider: "openai" } });
|
|
9720
|
+
}
|
|
9721
|
+
const error = unusableResponseError(message, call, "openai");
|
|
9722
|
+
if (retryWithinCall) {
|
|
9723
|
+
RETRIED_WITHIN_CALL.add(error);
|
|
9724
|
+
}
|
|
9725
|
+
return error;
|
|
9726
|
+
}
|
|
9727
|
+
function parseOpenAIModerationResponse(bodyText, res, call) {
|
|
9728
|
+
const { status, statusText } = res;
|
|
9582
9729
|
if (!bodyText.trim()) {
|
|
9583
|
-
throw
|
|
9584
|
-
`OpenAI moderation returned an empty response (${status} ${statusText}).`,
|
|
9585
|
-
{ status, retriable: isRetriableOpenAIModerationStatus(status) }
|
|
9586
|
-
);
|
|
9730
|
+
throw unreadableOpenAIResponseError(`OpenAI moderation returned an empty response (${status} ${statusText}).`, res, call, { retryWithinCall: false });
|
|
9587
9731
|
}
|
|
9588
9732
|
try {
|
|
9589
9733
|
return JSON.parse(bodyText);
|
|
9590
9734
|
} catch {
|
|
9591
|
-
throw
|
|
9735
|
+
throw unreadableOpenAIResponseError(
|
|
9592
9736
|
`OpenAI moderation returned non-JSON response (${status} ${statusText}): ${compactBodySnippet(bodyText)}`,
|
|
9593
|
-
|
|
9737
|
+
res,
|
|
9738
|
+
call,
|
|
9739
|
+
{ retryWithinCall: true }
|
|
9594
9740
|
);
|
|
9595
9741
|
}
|
|
9596
9742
|
}
|
|
9597
|
-
var OpenAIModerationResponseSchema =
|
|
9598
|
-
results:
|
|
9599
|
-
category_scores:
|
|
9600
|
-
sexual:
|
|
9601
|
-
violence:
|
|
9743
|
+
var OpenAIModerationResponseSchema = z12.object({
|
|
9744
|
+
results: z12.array(z12.object({
|
|
9745
|
+
category_scores: z12.object({
|
|
9746
|
+
sexual: z12.number().finite().nullish(),
|
|
9747
|
+
violence: z12.number().finite().nullish()
|
|
9602
9748
|
})
|
|
9603
9749
|
}))
|
|
9604
9750
|
});
|
|
9605
9751
|
async function callOpenAIModerationApi({
|
|
9606
9752
|
model,
|
|
9607
9753
|
input,
|
|
9608
|
-
credentials
|
|
9754
|
+
credentials,
|
|
9755
|
+
call
|
|
9609
9756
|
}) {
|
|
9610
9757
|
"use step";
|
|
9611
9758
|
const apiKey = await getApiKeyFromEnv("openai", credentials);
|
|
@@ -9625,35 +9772,34 @@ async function callOpenAIModerationApi({
|
|
|
9625
9772
|
})
|
|
9626
9773
|
});
|
|
9627
9774
|
} catch (error) {
|
|
9628
|
-
throw
|
|
9775
|
+
throw openAIFetchError(
|
|
9629
9776
|
`OpenAI moderation request failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
9630
|
-
{
|
|
9777
|
+
{ call, facts: { provider: "openai" }, cause: error }
|
|
9631
9778
|
);
|
|
9632
9779
|
}
|
|
9633
|
-
|
|
9634
|
-
|
|
9780
|
+
let bodyText;
|
|
9781
|
+
try {
|
|
9782
|
+
bodyText = await res.text();
|
|
9783
|
+
} catch (error) {
|
|
9784
|
+
throw openAIFetchError(
|
|
9785
|
+
`OpenAI moderation response could not be read: ${error instanceof Error ? error.message : String(error)}`,
|
|
9786
|
+
{ call, requestId: requestIdOf(res.headers), facts: { provider: "openai" }, cause: error }
|
|
9787
|
+
);
|
|
9788
|
+
}
|
|
9789
|
+
const json = parseOpenAIModerationResponse(bodyText, res, call);
|
|
9635
9790
|
if (!res.ok) {
|
|
9636
|
-
throw
|
|
9791
|
+
throw openAIFetchError(
|
|
9637
9792
|
`OpenAI moderation error: ${res.status} ${res.statusText} - ${JSON.stringify(json)}`,
|
|
9638
|
-
{
|
|
9639
|
-
status: res.status,
|
|
9640
|
-
retriable: isRetriableOpenAIModerationStatus(res.status)
|
|
9641
|
-
}
|
|
9793
|
+
{ call, status: res.status, requestId: requestIdOf(res.headers), body: bodyText, facts: { provider: "openai" } }
|
|
9642
9794
|
);
|
|
9643
9795
|
}
|
|
9644
9796
|
const parsed = OpenAIModerationResponseSchema.safeParse(json);
|
|
9645
9797
|
if (!parsed.success) {
|
|
9646
|
-
throw
|
|
9647
|
-
`OpenAI moderation returned an unexpected response shape: ${compactBodySnippet(bodyText)}`,
|
|
9648
|
-
{ status: res.status, retriable: false }
|
|
9649
|
-
);
|
|
9798
|
+
throw unusableResponseError(`OpenAI moderation returned an unexpected response shape: ${compactBodySnippet(bodyText)}`, call, "openai");
|
|
9650
9799
|
}
|
|
9651
9800
|
const expectedResultCount = Array.isArray(input) ? input.length : 1;
|
|
9652
9801
|
if (parsed.data.results.length !== expectedResultCount) {
|
|
9653
|
-
throw
|
|
9654
|
-
`OpenAI moderation returned ${parsed.data.results.length} result(s) for ${expectedResultCount} input(s).`,
|
|
9655
|
-
{ status: res.status, retriable: false }
|
|
9656
|
-
);
|
|
9802
|
+
throw unusableResponseError(`OpenAI moderation returned ${parsed.data.results.length} result(s) for ${expectedResultCount} input(s).`, call, "openai");
|
|
9657
9803
|
}
|
|
9658
9804
|
return parsed.data;
|
|
9659
9805
|
},
|
|
@@ -9661,10 +9807,27 @@ async function callOpenAIModerationApi({
|
|
|
9661
9807
|
maxRetries: OPENAI_MODERATION_MAX_RETRIES,
|
|
9662
9808
|
baseDelay: OPENAI_MODERATION_BASE_DELAY_MS,
|
|
9663
9809
|
maxDelay: OPENAI_MODERATION_MAX_DELAY_MS,
|
|
9664
|
-
|
|
9810
|
+
// The classification decides: no response, 408/429/5xx and an accepted call's
|
|
9811
|
+
// unreadable body are transient; a spent quota and other rejections aren't.
|
|
9812
|
+
shouldRetry: (error) => MuxAiError.is(error) ? error.transient || RETRIED_WITHIN_CALL.has(error) : true
|
|
9665
9813
|
}
|
|
9666
9814
|
);
|
|
9667
9815
|
}
|
|
9816
|
+
function withoutFailure({ failure: _failure, ...score }) {
|
|
9817
|
+
return score;
|
|
9818
|
+
}
|
|
9819
|
+
function thumbnailErrorSample(entry, error) {
|
|
9820
|
+
const failure = sampleFailureOf(error);
|
|
9821
|
+
return {
|
|
9822
|
+
url: entry.url,
|
|
9823
|
+
time: entry.time,
|
|
9824
|
+
sexual: 0,
|
|
9825
|
+
violence: 0,
|
|
9826
|
+
error: true,
|
|
9827
|
+
errorMessage: error instanceof Error ? error.message : String(error),
|
|
9828
|
+
...failure && { failure }
|
|
9829
|
+
};
|
|
9830
|
+
}
|
|
9668
9831
|
async function processConcurrently(items, processor, maxConcurrent = 5) {
|
|
9669
9832
|
"use step";
|
|
9670
9833
|
const results = [];
|
|
@@ -9680,6 +9843,7 @@ async function moderateImageWithOpenAI(entry) {
|
|
|
9680
9843
|
"use step";
|
|
9681
9844
|
try {
|
|
9682
9845
|
const { results } = await callOpenAIModerationApi({
|
|
9846
|
+
call: "moderate_thumbnails",
|
|
9683
9847
|
model: entry.model,
|
|
9684
9848
|
input: [
|
|
9685
9849
|
{
|
|
@@ -9701,21 +9865,15 @@ async function moderateImageWithOpenAI(entry) {
|
|
|
9701
9865
|
};
|
|
9702
9866
|
} catch (error) {
|
|
9703
9867
|
console.error("OpenAI moderation failed:", error);
|
|
9704
|
-
return
|
|
9705
|
-
url: entry.url,
|
|
9706
|
-
time: entry.time,
|
|
9707
|
-
sexual: 0,
|
|
9708
|
-
violence: 0,
|
|
9709
|
-
error: true,
|
|
9710
|
-
errorMessage: error instanceof Error ? error.message : String(error)
|
|
9711
|
-
};
|
|
9868
|
+
return thumbnailErrorSample(entry, error);
|
|
9712
9869
|
}
|
|
9713
9870
|
}
|
|
9871
|
+
var THUMBNAIL_DOWNLOAD_ERRORS = { classifiedErrors: true, call: "fetch_thumbnail" };
|
|
9714
9872
|
async function requestOpenAIModeration(images, model, maxConcurrent = 5, submissionMode = "url", downloadOptions, credentials) {
|
|
9715
9873
|
"use step";
|
|
9716
9874
|
const imageUrls = images.map((img) => img.url);
|
|
9717
9875
|
const timeByUrl = new Map(images.map((img) => [img.url, img.time]));
|
|
9718
|
-
const targetUrls = submissionMode === "base64" ? (await downloadImagesAsBase64(imageUrls, downloadOptions, maxConcurrent)).map(
|
|
9876
|
+
const targetUrls = submissionMode === "base64" ? (await downloadImagesAsBase64(imageUrls, downloadOptions, maxConcurrent, THUMBNAIL_DOWNLOAD_ERRORS)).map(
|
|
9719
9877
|
(img) => ({ url: img.url, time: timeByUrl.get(img.url), image: img.base64Data, model, credentials })
|
|
9720
9878
|
) : images.map((img) => ({ url: img.url, time: img.time, image: img.url, model, credentials }));
|
|
9721
9879
|
return processConcurrently(targetUrls, moderateImageWithOpenAI, maxConcurrent);
|
|
@@ -9841,13 +9999,15 @@ function packWindowsIntoBatches(windows) {
|
|
|
9841
9999
|
return batches;
|
|
9842
10000
|
}
|
|
9843
10001
|
function transcriptErrorScore(window, error) {
|
|
10002
|
+
const failure = sampleFailureOf(error);
|
|
9844
10003
|
return {
|
|
9845
10004
|
startTime: window.startTime,
|
|
9846
10005
|
endTime: window.endTime,
|
|
9847
10006
|
sexual: 0,
|
|
9848
10007
|
violence: 0,
|
|
9849
10008
|
error: true,
|
|
9850
|
-
errorMessage: error instanceof Error ? error.message : String(error)
|
|
10009
|
+
errorMessage: error instanceof Error ? error.message : String(error),
|
|
10010
|
+
...failure && { failure }
|
|
9851
10011
|
};
|
|
9852
10012
|
}
|
|
9853
10013
|
async function moderateTranscriptBatchWithOpenAI(batch) {
|
|
@@ -9858,6 +10018,7 @@ async function moderateTranscriptBatchWithOpenAI(batch) {
|
|
|
9858
10018
|
}
|
|
9859
10019
|
try {
|
|
9860
10020
|
const { results } = await callOpenAIModerationApi({
|
|
10021
|
+
call: "moderate_transcript",
|
|
9861
10022
|
model,
|
|
9862
10023
|
input: windows.map((window) => window.text),
|
|
9863
10024
|
credentials
|
|
@@ -9873,7 +10034,7 @@ async function moderateTranscriptBatchWithOpenAI(batch) {
|
|
|
9873
10034
|
};
|
|
9874
10035
|
});
|
|
9875
10036
|
} catch (error) {
|
|
9876
|
-
const status = error
|
|
10037
|
+
const status = MuxAiError.is(error) ? error.facts.status : void 0;
|
|
9877
10038
|
if (status === 400 && windows.length > 1) {
|
|
9878
10039
|
const mid = Math.ceil(windows.length / 2);
|
|
9879
10040
|
const [left, right] = await Promise.all([
|
|
@@ -9917,8 +10078,8 @@ function getHiveCategoryScores(classes, categoryNames) {
|
|
|
9917
10078
|
}
|
|
9918
10079
|
async function moderateImageWithHive(entry) {
|
|
9919
10080
|
"use step";
|
|
9920
|
-
const apiKey = await getApiKeyFromEnv("hive", entry.credentials);
|
|
9921
10081
|
try {
|
|
10082
|
+
const apiKey = await getApiKeyFromEnv("hive", entry.credentials);
|
|
9922
10083
|
const formData = new FormData();
|
|
9923
10084
|
if (entry.source.kind === "url") {
|
|
9924
10085
|
formData.append("url", entry.source.value);
|
|
@@ -9944,28 +10105,28 @@ async function moderateImageWithHive(entry) {
|
|
|
9944
10105
|
});
|
|
9945
10106
|
} catch (err) {
|
|
9946
10107
|
if (err?.name === "AbortError") {
|
|
9947
|
-
throw
|
|
10108
|
+
throw hiveCallError("Hive request timed out after 15s", { call: "moderate_thumbnails", timedOut: true, cause: err });
|
|
9948
10109
|
}
|
|
9949
|
-
throw err;
|
|
10110
|
+
throw hiveCallError(err instanceof Error ? err.message : String(err), { call: "moderate_thumbnails", cause: err });
|
|
9950
10111
|
} finally {
|
|
9951
10112
|
clearTimeout(timeout);
|
|
9952
10113
|
}
|
|
9953
10114
|
const json = await res.json().catch(() => void 0);
|
|
9954
10115
|
if (!res.ok) {
|
|
9955
|
-
throw
|
|
9956
|
-
`Hive moderation error: ${res.status} ${res.statusText} - ${JSON.stringify(json)}
|
|
10116
|
+
throw hiveCallError(
|
|
10117
|
+
`Hive moderation error: ${res.status} ${res.statusText} - ${JSON.stringify(json)}`,
|
|
10118
|
+
{ call: "moderate_thumbnails", status: res.status, requestId: requestIdOf(res.headers) }
|
|
9957
10119
|
);
|
|
9958
10120
|
}
|
|
9959
10121
|
if (json?.return_code != null && json.return_code !== 0) {
|
|
9960
|
-
throw
|
|
9961
|
-
`Hive API error (return_code ${json.return_code}): ${json.message || "Unknown error"}
|
|
10122
|
+
throw hiveCallError(
|
|
10123
|
+
`Hive API error (return_code ${json.return_code}): ${json.message || "Unknown error"}`,
|
|
10124
|
+
{ call: "moderate_thumbnails", answered: true, returnCode: providerCodeOf(json.return_code) }
|
|
9962
10125
|
);
|
|
9963
10126
|
}
|
|
9964
10127
|
const classes = json?.status?.[0]?.response?.output?.[0]?.classes;
|
|
9965
10128
|
if (!Array.isArray(classes)) {
|
|
9966
|
-
throw
|
|
9967
|
-
`Unexpected Hive response structure: ${JSON.stringify(json)}`
|
|
9968
|
-
);
|
|
10129
|
+
throw unusableResponseError(`Unexpected Hive response structure: ${JSON.stringify(json)}`, "moderate_thumbnails", "hive");
|
|
9969
10130
|
}
|
|
9970
10131
|
const sexual = getHiveCategoryScores(classes, HIVE_SEXUAL_CATEGORIES);
|
|
9971
10132
|
const violence = getHiveCategoryScores(classes, HIVE_VIOLENCE_CATEGORIES);
|
|
@@ -9977,21 +10138,14 @@ async function moderateImageWithHive(entry) {
|
|
|
9977
10138
|
error: false
|
|
9978
10139
|
};
|
|
9979
10140
|
} catch (error) {
|
|
9980
|
-
return
|
|
9981
|
-
url: entry.url,
|
|
9982
|
-
time: entry.time,
|
|
9983
|
-
sexual: 0,
|
|
9984
|
-
violence: 0,
|
|
9985
|
-
error: true,
|
|
9986
|
-
errorMessage: error instanceof Error ? error.message : String(error)
|
|
9987
|
-
};
|
|
10141
|
+
return thumbnailErrorSample(entry, error);
|
|
9988
10142
|
}
|
|
9989
10143
|
}
|
|
9990
10144
|
async function requestHiveModeration(images, maxConcurrent = 5, submissionMode = "url", downloadOptions, credentials) {
|
|
9991
10145
|
"use step";
|
|
9992
10146
|
const imageUrls = images.map((img) => img.url);
|
|
9993
10147
|
const timeByUrl = new Map(images.map((img) => [img.url, img.time]));
|
|
9994
|
-
const targets = submissionMode === "base64" ? (await downloadImagesAsBase64(imageUrls, downloadOptions, maxConcurrent)).map((img) => ({
|
|
10148
|
+
const targets = submissionMode === "base64" ? (await downloadImagesAsBase64(imageUrls, downloadOptions, maxConcurrent, THUMBNAIL_DOWNLOAD_ERRORS)).map((img) => ({
|
|
9995
10149
|
url: img.url,
|
|
9996
10150
|
time: timeByUrl.get(img.url),
|
|
9997
10151
|
source: {
|
|
@@ -10036,27 +10190,29 @@ async function moderateImageWithGoogleVision(entry) {
|
|
|
10036
10190
|
});
|
|
10037
10191
|
} catch (err) {
|
|
10038
10192
|
if (err?.name === "AbortError") {
|
|
10039
|
-
throw
|
|
10193
|
+
throw googleVisionCallError("Google Vision request timed out after 15s", { call: "moderate_thumbnails", timedOut: true, cause: err });
|
|
10040
10194
|
}
|
|
10041
|
-
throw err;
|
|
10195
|
+
throw googleVisionCallError(err instanceof Error ? err.message : String(err), { call: "moderate_thumbnails", cause: err });
|
|
10042
10196
|
} finally {
|
|
10043
10197
|
clearTimeout(timeout);
|
|
10044
10198
|
}
|
|
10045
10199
|
const json = await res.json().catch(() => void 0);
|
|
10046
10200
|
if (!res.ok) {
|
|
10047
|
-
throw
|
|
10048
|
-
`Google Vision moderation error: ${res.status} ${res.statusText} - ${JSON.stringify(json)}
|
|
10201
|
+
throw googleVisionCallError(
|
|
10202
|
+
`Google Vision moderation error: ${res.status} ${res.statusText} - ${JSON.stringify(json)}`,
|
|
10203
|
+
{ call: "moderate_thumbnails", status: res.status, requestId: requestIdOf(res.headers) }
|
|
10049
10204
|
);
|
|
10050
10205
|
}
|
|
10051
10206
|
const perImage = json?.responses?.[0];
|
|
10052
10207
|
if (perImage?.error) {
|
|
10053
|
-
throw
|
|
10054
|
-
`Google Vision per-image error: ${perImage.error.code} ${perImage.error.message || "Unknown error"}
|
|
10208
|
+
throw googleVisionCallError(
|
|
10209
|
+
`Google Vision per-image error: ${perImage.error.code} ${perImage.error.message || "Unknown error"}`,
|
|
10210
|
+
{ call: "moderate_thumbnails", answered: true, rpcCode: providerCodeOf(perImage.error.code), inline: entry.isBase64 }
|
|
10055
10211
|
);
|
|
10056
10212
|
}
|
|
10057
10213
|
const annotation = perImage?.safeSearchAnnotation;
|
|
10058
10214
|
if (!annotation) {
|
|
10059
|
-
throw
|
|
10215
|
+
throw unusableResponseError(`Google Vision response missing safeSearchAnnotation: ${JSON.stringify(json)}`, "moderate_thumbnails", "google-vision-api");
|
|
10060
10216
|
}
|
|
10061
10217
|
const adultLikelihood = typeof annotation.adult === "string" ? annotation.adult : "UNKNOWN";
|
|
10062
10218
|
const violenceLikelihood = typeof annotation.violence === "string" ? annotation.violence : "UNKNOWN";
|
|
@@ -10070,21 +10226,14 @@ async function moderateImageWithGoogleVision(entry) {
|
|
|
10070
10226
|
error: false
|
|
10071
10227
|
};
|
|
10072
10228
|
} catch (error) {
|
|
10073
|
-
return
|
|
10074
|
-
url: entry.url,
|
|
10075
|
-
time: entry.time,
|
|
10076
|
-
sexual: 0,
|
|
10077
|
-
violence: 0,
|
|
10078
|
-
error: true,
|
|
10079
|
-
errorMessage: error instanceof Error ? error.message : String(error)
|
|
10080
|
-
};
|
|
10229
|
+
return thumbnailErrorSample(entry, error);
|
|
10081
10230
|
}
|
|
10082
10231
|
}
|
|
10083
10232
|
async function requestGoogleVisionModeration(images, maxConcurrent = 5, submissionMode = "url", downloadOptions, credentials) {
|
|
10084
10233
|
"use step";
|
|
10085
10234
|
const imageUrls = images.map((img) => img.url);
|
|
10086
10235
|
const timeByUrl = new Map(images.map((img) => [img.url, img.time]));
|
|
10087
|
-
const targets = submissionMode === "base64" ? (await downloadImagesAsBase64(imageUrls, downloadOptions, maxConcurrent)).map((img) => ({
|
|
10236
|
+
const targets = submissionMode === "base64" ? (await downloadImagesAsBase64(imageUrls, downloadOptions, maxConcurrent, THUMBNAIL_DOWNLOAD_ERRORS)).map((img) => ({
|
|
10088
10237
|
url: img.url,
|
|
10089
10238
|
time: timeByUrl.get(img.url),
|
|
10090
10239
|
// Vision REST wants raw base64; downloadImagesAsBase64 returns a data URI.
|
|
@@ -10139,12 +10288,99 @@ async function requestThumbnailModeration(provider, thumbnailUrls, options) {
|
|
|
10139
10288
|
return requestHiveModeration(thumbnailUrls, maxConcurrent, imageSubmissionMode, imageDownloadOptions, credentials);
|
|
10140
10289
|
case "google-vision-api":
|
|
10141
10290
|
return requestGoogleVisionModeration(thumbnailUrls, maxConcurrent, imageSubmissionMode, imageDownloadOptions, credentials);
|
|
10142
|
-
default:
|
|
10143
|
-
|
|
10144
|
-
|
|
10291
|
+
default:
|
|
10292
|
+
return assertNever(provider, "moderation provider");
|
|
10293
|
+
}
|
|
10294
|
+
}
|
|
10295
|
+
var MODERATION_PROVIDERS = ["openai", "hive", "google-vision-api"];
|
|
10296
|
+
function nothingToModerateError(message, context) {
|
|
10297
|
+
const { assetId, thumbnailModeration, transcriptModeration } = context;
|
|
10298
|
+
const skips = {
|
|
10299
|
+
assetId,
|
|
10300
|
+
...thumbnailModeration.skipReason && { thumbnailSkipReason: thumbnailModeration.skipReason },
|
|
10301
|
+
...transcriptModeration.skipReason && { transcriptSkipReason: transcriptModeration.skipReason }
|
|
10302
|
+
};
|
|
10303
|
+
if (thumbnailModeration.skipReason === "no_video_in_scope" && context.resolvedScope) {
|
|
10304
|
+
return invalidScopeError(message, {
|
|
10305
|
+
reason: "no_video",
|
|
10306
|
+
startTime: context.resolvedScope.startTime,
|
|
10307
|
+
endTime: context.resolvedScope.endTime,
|
|
10308
|
+
videoEndTime: context.videoEndTime,
|
|
10309
|
+
...skips
|
|
10310
|
+
}, ["scope"]);
|
|
10311
|
+
}
|
|
10312
|
+
switch (transcriptModeration.skipReason) {
|
|
10313
|
+
case "unsupported_provider":
|
|
10314
|
+
return new MuxAiError(message, {
|
|
10315
|
+
code: MUX_AI_ERROR_CODES.INVALID_PARAMETER,
|
|
10316
|
+
type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
|
|
10317
|
+
source: MUX_AI_ERROR_SOURCES.REQUEST,
|
|
10318
|
+
facts: { parameter: "provider", reason: "not_allowed", allowed: ["openai"], value: context.provider, ...skips, inputs: ["provider"] }
|
|
10319
|
+
});
|
|
10320
|
+
case "disabled":
|
|
10321
|
+
return new MuxAiError(message, {
|
|
10322
|
+
code: MUX_AI_ERROR_CODES.INVALID_PARAMETER,
|
|
10323
|
+
type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
|
|
10324
|
+
source: MUX_AI_ERROR_SOURCES.REQUEST,
|
|
10325
|
+
facts: { parameter: "includeTranscript", reason: "audio_only", allowed: [true], value: false, ...skips, inputs: ["includeTranscript"] }
|
|
10326
|
+
});
|
|
10327
|
+
case "no_ready_text_track": {
|
|
10328
|
+
const availableLanguages = getReadyTextTracks(context.asset).map((track) => track.language_code).filter((code) => !!code);
|
|
10329
|
+
return new MuxAiError(message, {
|
|
10330
|
+
code: MUX_AI_ERROR_CODES.CAPTION_TRACK_NOT_FOUND,
|
|
10331
|
+
type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
|
|
10332
|
+
source: MUX_AI_ERROR_SOURCES.ASSET,
|
|
10333
|
+
facts: { ...context.languageCode && { languageCode: context.languageCode }, availableLanguages, ...skips }
|
|
10334
|
+
});
|
|
10145
10335
|
}
|
|
10336
|
+
case "no_cues":
|
|
10337
|
+
if (context.transcriptEmptyCause === "no_scoped_cues") {
|
|
10338
|
+
return invalidScopeError(message, {
|
|
10339
|
+
reason: "no_transcript",
|
|
10340
|
+
...context.captionTrackId && { trackId: context.captionTrackId },
|
|
10341
|
+
...context.scope?.startTime !== void 0 && { startTime: context.scope.startTime },
|
|
10342
|
+
...context.scope?.endTime !== void 0 && { endTime: context.scope.endTime },
|
|
10343
|
+
...skips
|
|
10344
|
+
}, ["scope"]);
|
|
10345
|
+
}
|
|
10346
|
+
return new MuxAiError(message, {
|
|
10347
|
+
code: MUX_AI_ERROR_CODES.TRANSCRIPT_EMPTY,
|
|
10348
|
+
type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
|
|
10349
|
+
source: MUX_AI_ERROR_SOURCES.ASSET,
|
|
10350
|
+
facts: { ...context.captionTrackId && { trackId: context.captionTrackId }, ...context.transcriptEmptyCause && { reason: context.transcriptEmptyCause }, ...skips }
|
|
10351
|
+
});
|
|
10352
|
+
case void 0:
|
|
10353
|
+
return internalError(message, skips);
|
|
10354
|
+
default:
|
|
10355
|
+
return assertNever(transcriptModeration.skipReason, "transcript skip reason");
|
|
10146
10356
|
}
|
|
10147
10357
|
}
|
|
10358
|
+
var SAMPLE_SPECIFIC_CODES = /* @__PURE__ */ new Set([
|
|
10359
|
+
MUX_AI_ERROR_CODES.IMAGE_UNPROCESSABLE,
|
|
10360
|
+
MUX_AI_ERROR_CODES.MODEL_OUTPUT_INVALID,
|
|
10361
|
+
MUX_AI_ERROR_CODES.DEPENDENCY_RESPONSE_FAILED
|
|
10362
|
+
]);
|
|
10363
|
+
function isSampleSpecific(error) {
|
|
10364
|
+
return error.source === MUX_AI_ERROR_SOURCES.ASSET || error.code !== void 0 && SAMPLE_SPECIFIC_CODES.has(error.code);
|
|
10365
|
+
}
|
|
10366
|
+
function allSamplesFailedError(message, failures, facts) {
|
|
10367
|
+
const errors = failures.map(({ call, failure }) => failure ?? internalError(message, { ...facts, call }));
|
|
10368
|
+
const callWide = errors.filter((error) => !isSampleSpecific(error));
|
|
10369
|
+
const representative = callWide.find((error) => !error.transient) ?? callWide[0] ?? errors.find((error) => !error.transient) ?? errors[0];
|
|
10370
|
+
if (!representative) {
|
|
10371
|
+
return internalError(message, facts);
|
|
10372
|
+
}
|
|
10373
|
+
return new MuxAiError(message, {
|
|
10374
|
+
...representative.code && { code: representative.code },
|
|
10375
|
+
type: representative.type,
|
|
10376
|
+
source: representative.source,
|
|
10377
|
+
...representative.dependency && { dependency: representative.dependency },
|
|
10378
|
+
facts: { ...facts, ...representative.facts },
|
|
10379
|
+
transient: representative.transient,
|
|
10380
|
+
retryable: representative.retryable,
|
|
10381
|
+
cause: representative
|
|
10382
|
+
});
|
|
10383
|
+
}
|
|
10148
10384
|
async function getModerationScores(assetId, options = {}) {
|
|
10149
10385
|
"use workflow";
|
|
10150
10386
|
const {
|
|
@@ -10163,7 +10399,23 @@ async function getModerationScores(assetId, options = {}) {
|
|
|
10163
10399
|
scope
|
|
10164
10400
|
} = options;
|
|
10165
10401
|
const credentials = providedCredentials;
|
|
10166
|
-
|
|
10402
|
+
if (!MODERATION_PROVIDERS.includes(provider)) {
|
|
10403
|
+
throw new MuxAiError(`Unsupported moderation provider: ${String(provider)}`, {
|
|
10404
|
+
code: MUX_AI_ERROR_CODES.INVALID_PARAMETER,
|
|
10405
|
+
type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
|
|
10406
|
+
source: MUX_AI_ERROR_SOURCES.REQUEST,
|
|
10407
|
+
facts: { parameter: "provider", reason: "not_allowed", allowed: [...MODERATION_PROVIDERS], value: String(provider).slice(0, 100), inputs: ["provider"] }
|
|
10408
|
+
});
|
|
10409
|
+
}
|
|
10410
|
+
if (maxSamples !== void 0 && !(maxSamples > 0)) {
|
|
10411
|
+
throw new MuxAiError(`maxSamples must be a positive number (received ${String(maxSamples)}).`, {
|
|
10412
|
+
code: MUX_AI_ERROR_CODES.INVALID_PARAMETER,
|
|
10413
|
+
type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
|
|
10414
|
+
source: MUX_AI_ERROR_SOURCES.REQUEST,
|
|
10415
|
+
facts: { parameter: "maxSamples", reason: "not_positive", ...typeof maxSamples === "number" && Number.isFinite(maxSamples) && { value: maxSamples }, inputs: ["maxSamples"] }
|
|
10416
|
+
});
|
|
10417
|
+
}
|
|
10418
|
+
const { asset, playbackId, policy } = await getPlaybackIdForAsset(assetId, credentials, options.assetSnapshot, { classifiedErrors: true });
|
|
10167
10419
|
const videoTrackDurationSeconds = getVideoTrackDurationSecondsFromAsset(asset);
|
|
10168
10420
|
const videoTrackFps = getVideoTrackMaxFrameRateFromAsset(asset);
|
|
10169
10421
|
const assetDurationSeconds = getAssetDurationSecondsFromAsset(asset);
|
|
@@ -10172,7 +10424,7 @@ async function getModerationScores(assetId, options = {}) {
|
|
|
10172
10424
|
);
|
|
10173
10425
|
const duration = candidateDurations.length > 0 ? Math.min(...candidateDurations) : 0;
|
|
10174
10426
|
const effectiveScope = hasWorkflowScopeBoundaries(scope) ? scope : void 0;
|
|
10175
|
-
const resolvedScope = effectiveScope ? resolveWorkflowScope(effectiveScope, assetDurationSeconds) : void 0;
|
|
10427
|
+
const resolvedScope = effectiveScope ? resolveWorkflowScope(effectiveScope, assetDurationSeconds, { classifiedErrors: true, assetId }) : void 0;
|
|
10176
10428
|
const isAudioOnly = isAudioOnlyAsset(asset);
|
|
10177
10429
|
const renderableScope = resolvedScope ? {
|
|
10178
10430
|
startTime: Math.min(resolvedScope.startTime, duration),
|
|
@@ -10180,19 +10432,20 @@ async function getModerationScores(assetId, options = {}) {
|
|
|
10180
10432
|
} : void 0;
|
|
10181
10433
|
const signingContext = await resolveMuxSigningContext(credentials);
|
|
10182
10434
|
if (policy === "signed" && !signingContext) {
|
|
10183
|
-
throw
|
|
10184
|
-
"Signed playback ID requires signing credentials. Set MUX_SIGNING_KEY and MUX_PRIVATE_KEY environment variables."
|
|
10185
|
-
);
|
|
10435
|
+
throw signingCredentialsMissingError();
|
|
10186
10436
|
}
|
|
10187
10437
|
let thumbnailModeration = { status: "completed" };
|
|
10188
10438
|
let thumbnailUrls = [];
|
|
10189
10439
|
let shouldRunThumbnails = false;
|
|
10440
|
+
let thumbnailsUnsampled = false;
|
|
10190
10441
|
if (isAudioOnly) {
|
|
10191
10442
|
thumbnailModeration = {
|
|
10192
10443
|
status: "skipped",
|
|
10193
10444
|
skipReason: "no_video_track",
|
|
10194
10445
|
skipMessage: "Asset has no video track, so there are no thumbnails to moderate."
|
|
10195
10446
|
};
|
|
10447
|
+
} else if (duration <= 0) {
|
|
10448
|
+
thumbnailsUnsampled = true;
|
|
10196
10449
|
} else if (renderableScope && renderableScope.startTime >= renderableScope.endTime) {
|
|
10197
10450
|
thumbnailModeration = {
|
|
10198
10451
|
status: "skipped",
|
|
@@ -10207,7 +10460,7 @@ async function getModerationScores(assetId, options = {}) {
|
|
|
10207
10460
|
filterTimestampsWithinExclusiveScope(
|
|
10208
10461
|
planSamplingTimestamps({
|
|
10209
10462
|
duration_sec: duration,
|
|
10210
|
-
max_candidates: maxSamples,
|
|
10463
|
+
max_candidates: Math.max(1, Math.floor(maxSamples)),
|
|
10211
10464
|
trim_start_sec: renderableScope?.startTime ?? (duration > 2 ? Math.min(5, Math.max(1, duration / 6)) : 0),
|
|
10212
10465
|
trim_end_sec: renderableScope ? duration - renderableScope.endTime : duration > 2 ? Math.min(5, Math.max(1, duration / 6)) : 0,
|
|
10213
10466
|
fps: videoTrackFps,
|
|
@@ -10227,9 +10480,18 @@ async function getModerationScores(assetId, options = {}) {
|
|
|
10227
10480
|
credentials,
|
|
10228
10481
|
scope: renderableScope
|
|
10229
10482
|
});
|
|
10230
|
-
|
|
10483
|
+
if (thumbnailUrls.length > 0) {
|
|
10484
|
+
shouldRunThumbnails = true;
|
|
10485
|
+
} else {
|
|
10486
|
+
thumbnailModeration = {
|
|
10487
|
+
status: "skipped",
|
|
10488
|
+
skipReason: "no_video_in_scope",
|
|
10489
|
+
skipMessage: "The requested scope does not include any renderable video, so there are no thumbnails to moderate."
|
|
10490
|
+
};
|
|
10491
|
+
}
|
|
10231
10492
|
}
|
|
10232
10493
|
let transcriptModeration = { status: "completed" };
|
|
10494
|
+
let transcriptEmptyCause;
|
|
10233
10495
|
let transcriptCues = [];
|
|
10234
10496
|
let shouldRunTranscript = false;
|
|
10235
10497
|
const transcriptEnabled = includeTranscript || isAudioOnly;
|
|
@@ -10254,14 +10516,22 @@ async function getModerationScores(assetId, options = {}) {
|
|
|
10254
10516
|
};
|
|
10255
10517
|
} else {
|
|
10256
10518
|
if (!captionTrack.id) {
|
|
10257
|
-
throw new
|
|
10519
|
+
throw new MuxAiError("Transcript track is missing an id.", {
|
|
10520
|
+
code: MUX_AI_ERROR_CODES.CAPTION_TRACK_ID_MISSING,
|
|
10521
|
+
type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
|
|
10522
|
+
source: MUX_AI_ERROR_SOURCES.UPSTREAM,
|
|
10523
|
+
dependency: MUX_AI_ERROR_DEPENDENCIES.MUX_VIDEO,
|
|
10524
|
+
facts: { assetId, ...captionTrack.language_code && { languageCode: captionTrack.language_code } }
|
|
10525
|
+
});
|
|
10258
10526
|
}
|
|
10259
10527
|
const transcriptUrl = await buildTranscriptUrl(playbackId, captionTrack.id, policy === "signed", credentials);
|
|
10260
10528
|
const { transcriptText, emptyReason } = await fetchTranscriptDataForUrl(transcriptUrl, {
|
|
10261
10529
|
cleanTranscript: false,
|
|
10262
|
-
scope: effectiveScope
|
|
10530
|
+
scope: effectiveScope,
|
|
10531
|
+
classifiedErrors: true
|
|
10263
10532
|
});
|
|
10264
10533
|
if (emptyReason) {
|
|
10534
|
+
transcriptEmptyCause = emptyReason;
|
|
10265
10535
|
transcriptModeration = {
|
|
10266
10536
|
status: "skipped",
|
|
10267
10537
|
skipReason: "no_cues",
|
|
@@ -10271,6 +10541,7 @@ async function getModerationScores(assetId, options = {}) {
|
|
|
10271
10541
|
transcriptCues = parseVTTCues(transcriptText, { capCueText: false });
|
|
10272
10542
|
const windows = transcriptCues.length === 0 ? [] : buildTranscriptWindows(transcriptCues, duration);
|
|
10273
10543
|
if (windows.length === 0) {
|
|
10544
|
+
transcriptEmptyCause = "no_parseable_cues";
|
|
10274
10545
|
transcriptModeration = {
|
|
10275
10546
|
status: "skipped",
|
|
10276
10547
|
skipReason: "no_cues",
|
|
@@ -10281,10 +10552,30 @@ async function getModerationScores(assetId, options = {}) {
|
|
|
10281
10552
|
}
|
|
10282
10553
|
}
|
|
10283
10554
|
}
|
|
10555
|
+
if (thumbnailsUnsampled && !shouldRunTranscript) {
|
|
10556
|
+
throw new MuxAiError(`Nothing to moderate: asset ${assetId} has no valid duration to sample thumbnails from, and the transcript was skipped: ${transcriptModeration.skipMessage}`, {
|
|
10557
|
+
code: MUX_AI_ERROR_CODES.ASSET_DURATION_UNAVAILABLE,
|
|
10558
|
+
type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
|
|
10559
|
+
source: MUX_AI_ERROR_SOURCES.ASSET,
|
|
10560
|
+
facts: { assetId, ...transcriptModeration.skipReason && { transcriptSkipReason: transcriptModeration.skipReason } }
|
|
10561
|
+
});
|
|
10562
|
+
}
|
|
10284
10563
|
if (!shouldRunThumbnails && !shouldRunTranscript) {
|
|
10285
|
-
throw
|
|
10564
|
+
throw nothingToModerateError(
|
|
10286
10565
|
`Nothing to moderate. Thumbnails skipped: ${thumbnailModeration.skipMessage} Transcript skipped: ${transcriptModeration.skipMessage}`,
|
|
10287
|
-
{
|
|
10566
|
+
{
|
|
10567
|
+
assetId,
|
|
10568
|
+
asset,
|
|
10569
|
+
provider,
|
|
10570
|
+
languageCode,
|
|
10571
|
+
thumbnailModeration,
|
|
10572
|
+
transcriptModeration,
|
|
10573
|
+
transcriptEmptyCause,
|
|
10574
|
+
captionTrackId: captionTrack?.id,
|
|
10575
|
+
scope: effectiveScope,
|
|
10576
|
+
resolvedScope,
|
|
10577
|
+
videoEndTime: duration
|
|
10578
|
+
}
|
|
10288
10579
|
);
|
|
10289
10580
|
}
|
|
10290
10581
|
const [thumbnailScores, transcriptScores] = await Promise.all([
|
|
@@ -10306,15 +10597,17 @@ async function getModerationScores(assetId, options = {}) {
|
|
|
10306
10597
|
const mode = shouldRunThumbnails && shouldRunTranscript ? "combined" : shouldRunTranscript ? "transcript" : "thumbnails";
|
|
10307
10598
|
const thumbnailCount = shouldRunThumbnails ? thumbnailUrls.length : void 0;
|
|
10308
10599
|
const allScores = [
|
|
10309
|
-
...thumbnailScores.map((s) => ({ ...s, label: s.
|
|
10310
|
-
...transcriptScores.map((s) => ({ ...s, error: s.error ?? false, label: `transcript window ${s.startTime}-${s.endTime}s
|
|
10600
|
+
...thumbnailScores.map((s) => ({ ...s, label: s.time === void 0 ? "thumbnail" : `thumbnail at ${s.time}s`, call: "moderate_thumbnails" })),
|
|
10601
|
+
...transcriptScores.map((s) => ({ ...s, error: s.error ?? false, label: `transcript window ${s.startTime}-${s.endTime}s`, call: "moderate_transcript" }))
|
|
10311
10602
|
];
|
|
10312
10603
|
const failed = allScores.filter((s) => s.error);
|
|
10313
10604
|
const successful = allScores.filter((s) => !s.error);
|
|
10314
10605
|
if (successful.length === 0) {
|
|
10315
10606
|
const details = failed.map((s) => `${s.label}: ${s.errorMessage || "Unknown error"}`).join("; ");
|
|
10316
|
-
throw
|
|
10317
|
-
`Moderation failed for all ${allScores.length} sample(s): ${details}
|
|
10607
|
+
throw allSamplesFailedError(
|
|
10608
|
+
`Moderation failed for all ${allScores.length} sample(s): ${details}`,
|
|
10609
|
+
failed,
|
|
10610
|
+
{ provider, ...model && { model }, assetId, sampleCount: allScores.length }
|
|
10318
10611
|
);
|
|
10319
10612
|
}
|
|
10320
10613
|
if (failed.length > 0) {
|
|
@@ -10359,8 +10652,8 @@ async function getModerationScores(assetId, options = {}) {
|
|
|
10359
10652
|
assetId,
|
|
10360
10653
|
mode,
|
|
10361
10654
|
isAudioOnly,
|
|
10362
|
-
thumbnailScores,
|
|
10363
|
-
transcriptScores,
|
|
10655
|
+
thumbnailScores: thumbnailScores.map(withoutFailure),
|
|
10656
|
+
transcriptScores: transcriptScores.map(withoutFailure),
|
|
10364
10657
|
thumbnailModeration,
|
|
10365
10658
|
transcriptModeration,
|
|
10366
10659
|
coverage: {
|
|
@@ -10388,7 +10681,7 @@ async function getModerationScores(assetId, options = {}) {
|
|
|
10388
10681
|
|
|
10389
10682
|
// src/workflows/summarization.ts
|
|
10390
10683
|
import { generateText as generateText8, Output as Output8 } from "ai";
|
|
10391
|
-
import { z as
|
|
10684
|
+
import { z as z13 } from "zod";
|
|
10392
10685
|
|
|
10393
10686
|
// src/lib/markdown-normalization.ts
|
|
10394
10687
|
var ESCAPED_LINE_BREAK_REGEX = /\\r\\n|\\n|\\r/g;
|
|
@@ -10533,17 +10826,17 @@ function createSummarizationGuidance({
|
|
|
10533
10826
|
}
|
|
10534
10827
|
|
|
10535
10828
|
// src/workflows/summarization.ts
|
|
10536
|
-
var summarySchema =
|
|
10537
|
-
keywords:
|
|
10538
|
-
title:
|
|
10539
|
-
description:
|
|
10829
|
+
var summarySchema = z13.object({
|
|
10830
|
+
keywords: z13.array(z13.string().max(200)),
|
|
10831
|
+
title: z13.string().max(500),
|
|
10832
|
+
description: z13.string().max(1e4)
|
|
10540
10833
|
});
|
|
10541
10834
|
function buildSummarySchema(descriptionLength) {
|
|
10542
10835
|
const descriptionMaxChars = Math.max(2e3, descriptionLength * 15);
|
|
10543
|
-
return
|
|
10544
|
-
keywords:
|
|
10545
|
-
title:
|
|
10546
|
-
description:
|
|
10836
|
+
return z13.object({
|
|
10837
|
+
keywords: z13.array(z13.string().max(200)),
|
|
10838
|
+
title: z13.string().max(500),
|
|
10839
|
+
description: z13.string().max(descriptionMaxChars)
|
|
10547
10840
|
});
|
|
10548
10841
|
}
|
|
10549
10842
|
var VALID_TONES = ["neutral", "playful", "professional"];
|
|
@@ -11887,9 +12180,9 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
|
|
|
11887
12180
|
|
|
11888
12181
|
// src/workflows/translate-captions.ts
|
|
11889
12182
|
import { generateText as generateText9, Output as Output9 } from "ai";
|
|
11890
|
-
import { z as
|
|
11891
|
-
var translationSchema =
|
|
11892
|
-
translation:
|
|
12183
|
+
import { z as z14 } from "zod";
|
|
12184
|
+
var translationSchema = z14.object({
|
|
12185
|
+
translation: z14.string()
|
|
11893
12186
|
});
|
|
11894
12187
|
var SYSTEM_PROMPT5 = promptDedent`
|
|
11895
12188
|
You are a subtitle translation expert. Translate VTT subtitle files to the target language specified by the user.
|
|
@@ -12253,8 +12546,8 @@ async function translateCueChunkWithAI({
|
|
|
12253
12546
|
}) {
|
|
12254
12547
|
"use step";
|
|
12255
12548
|
const model = await createLanguageModelFromConfig(provider, modelId, credentials);
|
|
12256
|
-
const schema =
|
|
12257
|
-
translations:
|
|
12549
|
+
const schema = z14.object({
|
|
12550
|
+
translations: z14.array(z14.string().min(1).max(2e3)).length(cues.length)
|
|
12258
12551
|
});
|
|
12259
12552
|
const cuePayload = cues.map((cue, index) => ({
|
|
12260
12553
|
index,
|