@lingjingai/lj-awb-cli 0.5.6 → 0.5.9

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.
@@ -120,6 +120,18 @@ const CREATE_STANDARD_KWARG_KEYS = new Set([
120
120
  'duration',
121
121
  'needAudio',
122
122
  'need_audio',
123
+ 'audioFormat',
124
+ 'audio_format',
125
+ 'sampleRate',
126
+ 'sample_rate',
127
+ 'speechRate',
128
+ 'speech_rate',
129
+ 'loudnessRate',
130
+ 'loudness_rate',
131
+ 'pitchRate',
132
+ 'pitch_rate',
133
+ 'enableSubtitle',
134
+ 'enable_subtitle',
123
135
  'resource',
124
136
  'resources',
125
137
  'resourcesJson',
@@ -802,6 +814,10 @@ export async function createProjectGroupCommand(kwargs = {}) {
802
814
  });
803
815
  const before = normalizeRows(await awbApi.fetchProjectGroups().catch(() => []));
804
816
  const allUsers = await awbApi.fetchProjectGroupUsers();
817
+ const missing = parseListArg(kwargs.userIds).filter((id) => !allUsers.some((user) => user.userId === id));
818
+ if (missing.length) {
819
+ throw argumentError(`成员不在当前团队中:${missing.join(', ')}`, '请先把成员加入项目所属团队。');
820
+ }
805
821
  const groupUser = buildProjectGroupUsersFromArgs(kwargs, allUsers);
806
822
  if (!groupUser.length) {
807
823
  throw argumentError('未解析到项目组成员', '请先运行 project users,或传 --members-json / --user-ids。');
@@ -843,8 +859,21 @@ export async function updateProjectGroupCommand(kwargs = {}) {
843
859
  if (kwargs.point != null && String(kwargs.point).trim() !== '') {
844
860
  body.point = toInt(kwargs.point, 0);
845
861
  }
862
+ if (kwargs.addUserIds != null) {
863
+ const selectedIds = new Set(parseListArg(kwargs.addUserIds));
864
+ if (!selectedIds.size) throw argumentError('追加成员不能为空', '请传 --add-user-ids <id1,id2>。');
865
+ const users = normalizeRows(await awbApi.fetchProjectGroupUsers(projectGroupNo));
866
+ const availableIds = new Set(users.map((user) => user.userId));
867
+ const missing = [...selectedIds].filter((id) => !availableIds.has(id));
868
+ if (missing.length) {
869
+ throw argumentError(`成员不在当前团队中:${missing.join(', ')}`, '请先把成员加入项目所属团队。');
870
+ }
871
+ body.groupUser = users
872
+ .filter((user) => user.isCheck || selectedIds.has(user.userId))
873
+ .map((user) => ({ userId: user.userId, role: user.isCheck ? user.role : 'USER' }));
874
+ }
846
875
  if (Object.keys(body).length === 1) {
847
- throw argumentError('缺少项目组更新字段', '至少传 --name 或 --point。');
876
+ throw argumentError('缺少项目组更新字段', '至少传 --name、--point 或 --add-user-ids。');
848
877
  }
849
878
  if (toBool(kwargs.dryRun)) {
850
879
  return {
@@ -875,6 +904,7 @@ export async function ensureProjectGroupCommand(kwargs = {}) {
875
904
  projectGroupName: name,
876
905
  point: toInt(kwargs.point, 0),
877
906
  selectExisting: kwargs.selectExisting !== false,
907
+ userIds: parseListArg(kwargs.userIds),
878
908
  },
879
909
  note: 'dry-run 不联网判断是否已存在;正式执行会先查找同名项目组。',
880
910
  };
@@ -886,6 +916,13 @@ export async function ensureProjectGroupCommand(kwargs = {}) {
886
916
  action: 'project ensure',
887
917
  projectGroupNo: existing.projectGroupNo,
888
918
  });
919
+ if (parseListArg(kwargs.userIds).length) {
920
+ await updateProjectGroupCommand({
921
+ projectGroupNo: existing.projectGroupNo,
922
+ addUserIds: kwargs.userIds,
923
+ yes: kwargs.yes,
924
+ });
925
+ }
889
926
  await awbApi.selectProjectGroup(existing.projectGroupNo).catch(() => {});
890
927
  return {
891
928
  ...(await fetchProjectGroupSummary(existing.projectGroupNo)),
@@ -1073,6 +1110,14 @@ export async function creditsUsageSummary(kwargs = {}) {
1073
1110
 
1074
1111
  function modelListMetadata(kind, paramKeys = [], rulesByKey = new Map()) {
1075
1112
  const keys = new Set(paramKeys);
1113
+ if (kind === 'audio') {
1114
+ return {
1115
+ inputModes: keys.has('resources') ? ['prompt_only', 'reference'] : ['prompt_only'],
1116
+ controls: ['duration', 'audio_format', 'sample_rate', 'speech_rate', 'loudness_rate', 'pitch_rate', 'enable_subtitle']
1117
+ .filter((key) => keys.has(key)),
1118
+ resourceParams: keys.has('resources') ? ['resources'] : [],
1119
+ };
1120
+ }
1076
1121
  const imageReferenceParams = ['cref', 'sref', 'iref', 'resources'].filter((key) => keys.has(key));
1077
1122
  const videoResourceParams = ['frames', 'multi_param', 'multi_prompt'].filter((key) => keys.has(key));
1078
1123
  const inputModes = createSpecSupportedIntents(createSpecInputModes(kind, keys, rulesByKey), kind)
@@ -1171,6 +1216,7 @@ function normalizeModelRows(payload, kind, options = {}) {
1171
1216
  const MODEL_USAGE_FAMILY = {
1172
1217
  image: { default: 'IMAGE_CREATE', allow: new Set(['IMAGE_CREATE']) },
1173
1218
  video: { default: 'VIDEO_CREATE', allow: new Set(['VIDEO_CREATE']) },
1219
+ audio: { default: 'AUDIO_CREATE', allow: new Set(['AUDIO_CREATE']) },
1174
1220
  };
1175
1221
 
1176
1222
  export function resolveModelUsage(kind, kwargs = {}) {
@@ -1318,9 +1364,10 @@ export async function assetReviewModels(kwargs = {}) {
1318
1364
 
1319
1365
  async function findModelGroup(modelGroupCode, options = {}) {
1320
1366
  const includeRaw = Boolean(options.includeRaw);
1321
- const [imageResult, videoResult] = await Promise.allSettled([
1367
+ const [imageResult, videoResult, audioResult] = await Promise.allSettled([
1322
1368
  awbApi.fetchModelsByUsage('IMAGE_CREATE', {}),
1323
1369
  awbApi.fetchModelsByUsage('VIDEO_CREATE', {}),
1370
+ awbApi.fetchModelsByUsage('AUDIO_CREATE', {}),
1324
1371
  ]);
1325
1372
  const imageModels = imageResult.status === 'fulfilled'
1326
1373
  ? normalizeModelRows(imageResult.value, 'image', { includeRaw, includeInternal: true }).map((item) => ({ ...item, kind: 'image' }))
@@ -1328,13 +1375,16 @@ async function findModelGroup(modelGroupCode, options = {}) {
1328
1375
  const videoModels = videoResult.status === 'fulfilled'
1329
1376
  ? normalizeModelRows(videoResult.value, 'video', { includeRaw, includeInternal: true }).map((item) => ({ ...item, kind: 'video' }))
1330
1377
  : [];
1331
- return [...imageModels, ...videoModels].find((item) => item.modelGroupCode === modelGroupCode) ?? null;
1378
+ const audioModels = audioResult.status === 'fulfilled'
1379
+ ? normalizeModelRows(audioResult.value, 'audio', { includeRaw, includeInternal: true }).map((item) => ({ ...item, kind: 'audio' }))
1380
+ : [];
1381
+ return [...imageModels, ...videoModels, ...audioModels].find((item) => item.modelGroupCode === modelGroupCode) ?? null;
1332
1382
  }
1333
1383
 
1334
1384
  function resolveTaskModel(kind, kwargs = {}) {
1335
1385
  const modelGroupCode = trimToNull(kwargs.modelGroupCode);
1336
1386
  if (!modelGroupCode) {
1337
- throw argumentError('缺少模型组编码', '传 --model-group-code <code>;推荐先运行 model image-models / model video-models。');
1387
+ throw argumentError('缺少模型组编码', '传 --model-group-code <code>;推荐先运行对应的 model image-models / video-models / audio-models。');
1338
1388
  }
1339
1389
  return {
1340
1390
  kind,
@@ -1931,7 +1981,7 @@ function constraintConditionMatches(condition = {}, promptParams = {}) {
1931
1981
  return String(actual ?? '') === String(condition.value ?? '');
1932
1982
  }
1933
1983
 
1934
- function assertParamsAgainstModel(promptParams = {}, params = [], constraints = []) {
1984
+ function assertParamsAgainstModel(promptParams = {}, params = [], constraints = [], taskKind = null) {
1935
1985
  const paramByKey = new Map(params.map((item) => [item.key, item]));
1936
1986
  for (const key of providedPromptParamKeys(promptParams)) {
1937
1987
  const param = paramByKey.get(key);
@@ -1945,6 +1995,18 @@ function assertParamsAgainstModel(promptParams = {}, params = [], constraints =
1945
1995
  if (param.maxLength != null && typeof value === 'string' && value.length > param.maxLength) {
1946
1996
  throw argumentError(`参数 ${key} 超过模型长度限制:${value.length}/${param.maxLength}`);
1947
1997
  }
1998
+ if (taskKind === 'audio' && (param.minValue != null || param.maxValue != null)) {
1999
+ const numericValue = Number(value);
2000
+ if (!Number.isFinite(numericValue)) {
2001
+ throw argumentError(`参数 ${key} 必须是数字:${value}`);
2002
+ }
2003
+ if (param.minValue != null && numericValue < param.minValue) {
2004
+ throw argumentError(`参数 ${key} 小于模型最小值:${numericValue}/${param.minValue}`);
2005
+ }
2006
+ if (param.maxValue != null && numericValue > param.maxValue) {
2007
+ throw argumentError(`参数 ${key} 超过模型最大值:${numericValue}/${param.maxValue}`);
2008
+ }
2009
+ }
1948
2010
  }
1949
2011
 
1950
2012
  for (const constraint of constraints) {
@@ -1971,7 +2033,7 @@ async function validateCreateRequestAgainstModel(kind, modelGroupCode, promptPar
1971
2033
  const params = modelOptionParams(context.options, context.taskKind);
1972
2034
  const resources = modelOptionsResources(context.inputModes);
1973
2035
  const effectiveResources = applyResourceLimitProfileConstraints(resources, context.constraints, resourceDetails);
1974
- assertParamsAgainstModel(promptParams, params, context.constraints);
2036
+ assertParamsAgainstModel(promptParams, params, context.constraints, kind);
1975
2037
  assertResourceShapeAgainstModel(resourceDetails, effectiveResources);
1976
2038
  assertResourceCountsAgainstModel(resourceDetails, effectiveResources);
1977
2039
  if (kind === 'video') {
@@ -2330,11 +2392,54 @@ function inferTaskKind(found, optionKeys) {
2330
2392
  if (found?.kind) return found.kind;
2331
2393
  if (found?.usage === 'IMAGE_CREATE') return 'image';
2332
2394
  if (found?.usage === 'VIDEO_CREATE') return 'video';
2395
+ if (found?.usage === 'AUDIO_CREATE') return 'audio';
2333
2396
  return ['generated_time', 'frames', 'multi_param', 'multi_prompt', 'generated_mode', 'need_audio']
2334
2397
  .some((key) => optionKeys.has(key)) ? 'video' : 'image';
2335
2398
  }
2336
2399
 
2337
2400
  function createSpecInputModes(taskKind, optionKeys, rulesByKey = new Map()) {
2401
+ if (taskKind === 'audio') {
2402
+ const hasPrompt = optionKeys.has('prompt');
2403
+ const hasResources = optionKeys.has('resources');
2404
+ const resourceRules = rulesByKey.get('resources') || {};
2405
+ const typedResourceRules = Array.isArray(resourceRules.resources) ? resourceRules.resources : [];
2406
+ const supportsResourceType = (mediaType) => !typedResourceRules.length
2407
+ || typedResourceRules.some((item) => String(item?.mediaType || '').toUpperCase() === mediaType);
2408
+ const resourceLimits = (mediaType) => typedResourceRules.length
2409
+ ? mediaRuleFromMultiParam(resourceRules, mediaType)
2410
+ : normalizeMediaRule(resourceRules);
2411
+ return [
2412
+ {
2413
+ mode: 'prompt_only',
2414
+ supported: hasPrompt,
2415
+ intent: '文本生成音频',
2416
+ requiredArgs: ['--model-group-code', '--prompt', '--duration'],
2417
+ userInput: '提供 prompt 和生成时长,不提供参考素材。',
2418
+ },
2419
+ {
2420
+ mode: 'reference_audio',
2421
+ supported: hasResources && supportsResourceType('AUDIO'),
2422
+ intent: '参考音频生成',
2423
+ requiredArgs: ['--model-group-code', '--prompt', '--duration', '--resource audio:reference=...'],
2424
+ userInput: '最多提供三段参考音频。',
2425
+ resourceSyntax: ['audio:reference=./reference.mp3'],
2426
+ requiredResources: ['audio:reference'],
2427
+ sourceKinds: ['local_file', 'http_url', 'backendPath'],
2428
+ resourceLimits: resourceLimits('AUDIO'),
2429
+ },
2430
+ {
2431
+ mode: 'reference_image',
2432
+ supported: hasResources && supportsResourceType('IMAGE'),
2433
+ intent: '参考图片生成音频',
2434
+ requiredArgs: ['--model-group-code', '--prompt', '--duration', '--resource image:reference=...'],
2435
+ userInput: '提供一张参考图片,不能与参考音频混用。',
2436
+ resourceSyntax: ['image:reference=./reference.png'],
2437
+ requiredResources: ['image:reference'],
2438
+ sourceKinds: ['local_file', 'http_url', 'backendPath'],
2439
+ resourceLimits: resourceLimits('IMAGE'),
2440
+ },
2441
+ ];
2442
+ }
2338
2443
  const hasPrompt = optionKeys.has('prompt');
2339
2444
  const hasImageReference = ['iref', 'cref', 'sref', 'resources'].some((key) => optionKeys.has(key));
2340
2445
  const hasFrames = optionKeys.has('frames');
@@ -2545,6 +2650,17 @@ function createSpecSupportedIntents(inputModes, taskKind = null) {
2545
2650
  promptBinding: 'none',
2546
2651
  promptPlaceholder: '图片任务不使用 reference_key 或 <<<key>>>;在 prompt 中用自然语言指代参考图。',
2547
2652
  }));
2653
+ } else if (taskKind === 'audio') {
2654
+ intents.push(compactRecord({
2655
+ mode: 'reference',
2656
+ intent: '参考素材生成音频',
2657
+ userInput: `用户提供${referenceLabels.join('、')}作为参考素材;参考音频与参考图片不能混用。`,
2658
+ requiredArgs: ['--model-group-code', '--prompt', '--duration', '--resource <audio|image>:reference=...'],
2659
+ resourceUsages: ['reference'],
2660
+ resourceSyntax: uniqueNonEmpty(referenceModes.flatMap((item) => item.resourceSyntax || [])),
2661
+ promptBinding: 'none',
2662
+ promptPlaceholder: '音频任务不使用 reference_key 或 <<<key>>>。',
2663
+ }));
2548
2664
  } else {
2549
2665
  intents.push(compactRecord({
2550
2666
  mode: 'reference',
@@ -2721,16 +2837,20 @@ function createSpecParameterControls(createParams, inputModes = []) {
2721
2837
  function createSpecAgentGuidance(taskKind, inputRequirement) {
2722
2838
  const keyParamGuidance = taskKind === 'video'
2723
2839
  ? 'fee 或 create --dry-run 前,必须先确认用户未提供的价格 / 效果关键参数:quality、duration、约束后仍可选的 ratio;needAudio 普通模型只在用户明确要输出音效时确认。可灵 3o / Kling 3.0 支持 needAudio 时 CLI 默认开声音,用户明确不要声音时传 --need-audio false。不要静默使用 defaultValue 先估价。'
2724
- : 'fee 或 create --dry-run 前,必须先确认用户未提供的价格 / 效果关键参数:quality、ratio、generateNum。不要静默使用 defaultValue 先估价。';
2840
+ : (taskKind === 'audio'
2841
+ ? 'fee 或 create --dry-run 前,必须确认 duration;audioFormat 未提供时默认 mp3,其余音频参数以 model options 为准。'
2842
+ : 'fee 或 create --dry-run 前,必须先确认用户未提供的价格 / 效果关键参数:quality、ratio、generateNum。不要静默使用 defaultValue 先估价。');
2725
2843
  const guidance = [
2726
2844
  '先用 model options 获取枚举值、文件类型、数量、大小、时长和条件约束;create-spec 只负责创建方式。',
2727
2845
  '用 inputRequirement 和 supportedIntents 在 prompt_only、reference、frames、storyboard 中选择一种输入模式;不要按媒体类型拆成多个任务。',
2728
2846
  ];
2729
2847
  if (taskKind === 'image') {
2730
2848
  guidance.push('图片任务不使用 reference_key 或 <<<key>>>。参考图只用 --resource image:reference=... 传入,prompt 用“图一 / 图二 / 参考图 / 白发女 / 背景图”等自然语言指代。');
2731
- } else {
2849
+ } else if (taskKind === 'video') {
2732
2850
  guidance.push('reference_key 是视频参考资源的可选绑定;prompt 可以不写占位符。如果 prompt 写了 <<<key>>>,必须能匹配同名 reference 资源。');
2733
2851
  guidance.push('只有 model options.resources[] 存在 media=AUDIO usage=reference 时,音频文件 / URL / asset 才能走 --resource audio:reference=...;是否需要输出音效才使用 --need-audio true/false。');
2852
+ } else {
2853
+ guidance.push('音频任务只接受 reference 用途的音频或图片;最多 3 个参考音频或 1 张参考图片,两类不能混用,也不使用 reference_key。');
2734
2854
  }
2735
2855
  guidance.push(
2736
2856
  keyParamGuidance,
@@ -2756,16 +2876,21 @@ function createSpecValidationRules(taskKind) {
2756
2876
  if (taskKind === 'video') {
2757
2877
  rules.splice(4, 0, 'reference_key 仅用于视频 reference 资源的可选 prompt 占位符绑定;prompt 中出现 <<<key>>> 时,必须有同名 reference 资源。');
2758
2878
  rules.push('subject reference 必须使用 asset:<externalId>,externalId 应来自 create subject + create subject-wait。');
2759
- } else {
2879
+ } else if (taskKind === 'image') {
2760
2880
  rules.push('图片任务 resources 只接受 image reference,且不接受 reference_key 或 <<<key>>>;请用自然 prompt 描述图一、图二、参考图、主体等映射。');
2881
+ } else {
2882
+ rules.push('音频任务 resources 只接受 audio/image reference;最多 3 个参考音频或 1 张参考图片,不能混用,也不接受 reference_key。');
2761
2883
  }
2762
2884
  return rules;
2763
2885
  }
2764
2886
 
2765
2887
  function createSpecPreflight(taskKind) {
2766
- const modelListCommand = taskKind === 'image' ? 'model image-models' : 'model video-models';
2767
- const feeCommand = taskKind === 'image' ? 'create image-fee' : 'create video-fee';
2768
- const createCommand = taskKind === 'image' ? 'create image' : 'create video';
2888
+ const commands = {
2889
+ image: ['model image-models', 'create image-fee', 'create image'],
2890
+ video: ['model video-models', 'create video-fee', 'create video'],
2891
+ audio: ['model audio-models', 'create audio-fee', 'create audio'],
2892
+ };
2893
+ const [modelListCommand, feeCommand, createCommand] = commands[taskKind] || commands.image;
2769
2894
  return [
2770
2895
  'doctor --verify',
2771
2896
  `${modelListCommand} --model <keyword>`,
@@ -2786,7 +2911,7 @@ function createSpecExamples(taskKind, supportedIntents) {
2786
2911
  if (taskKind === 'image') {
2787
2912
  if (hasIntent('prompt_only')) examples.push('lj-awb create image --model-group-code <code> --prompt "品牌吉祥物表情包四宫格" --ratio 1:1 --quality 1K --dry-run');
2788
2913
  if (hasIntent('reference')) examples.push('lj-awb create image --model-group-code <code> --prompt "保持参考图主体,生成海报" --resource image:reference=./ref.png --dry-run');
2789
- } else {
2914
+ } else if (taskKind === 'video') {
2790
2915
  if (hasIntent('prompt_only')) examples.push('lj-awb create video --model-group-code <code> --prompt "机器人站在白色展台中央,缓慢转身" --duration 6 --dry-run');
2791
2916
  if (hasIntent('reference')) {
2792
2917
  const referenceIntent = supportedIntents.find((item) => item.mode === 'reference');
@@ -2804,6 +2929,9 @@ function createSpecExamples(taskKind, supportedIntents) {
2804
2929
  }
2805
2930
  }
2806
2931
  if (hasIntent('storyboard')) examples.push('lj-awb create video --model-group-code <code> --resources-json ./storyboard.json --duration 5 --dry-run');
2932
+ } else {
2933
+ if (hasIntent('prompt_only')) examples.push('lj-awb create audio --model-group-code <code> --prompt "轻快明亮的电子音乐" --duration 6 --dry-run');
2934
+ if (hasIntent('reference')) examples.push('lj-awb create audio --model-group-code <code> --prompt "保持参考音色,生成舒缓配乐" --duration 6 --resource audio:reference=./reference.mp3 --dry-run');
2807
2935
  }
2808
2936
  return examples;
2809
2937
  }
@@ -2829,6 +2957,12 @@ function modelOptionParams(options = [], taskKind = 'image') {
2829
2957
  const maxLength = option.paramType === 'Prompt'
2830
2958
  ? ruleNumber(rules.maxValue ?? rules.maxLength ?? rules.maxPromptLength)
2831
2959
  : undefined;
2960
+ const minValue = taskKind !== 'audio' || option.paramType === 'Prompt'
2961
+ ? undefined
2962
+ : ruleNumber(rules.minValue ?? rules.min);
2963
+ const maxValue = taskKind !== 'audio' || option.paramType === 'Prompt'
2964
+ ? undefined
2965
+ : ruleNumber(rules.maxValue ?? rules.max);
2832
2966
  return compactRecord({
2833
2967
  key: createParam.key,
2834
2968
  label: option.paramName,
@@ -2837,6 +2971,8 @@ function modelOptionParams(options = [], taskKind = 'image') {
2837
2971
  defaultValue,
2838
2972
  defaultName: modelParamDefaultName(option),
2839
2973
  maxLength,
2974
+ minValue,
2975
+ maxValue,
2840
2976
  required,
2841
2977
  cliArg: createParam.cliArg,
2842
2978
  genericModelParam: createParam.genericModelParam || undefined,
@@ -2995,13 +3131,19 @@ export async function modelCreateSpec(kwargs = {}) {
2995
3131
  const context = await loadModelOptionContext(modelGroupCode, { includeRaw });
2996
3132
  const supportedIntents = createSpecSupportedIntents(context.inputModes, context.taskKind);
2997
3133
  const inputRequirement = createSpecInputRequirement(context.taskKind, context.inputModes, supportedIntents);
3134
+ const commandByTaskKind = {
3135
+ image: { create: 'create image', fee: 'create image-fee', taskType: 'IMAGE_CREATE' },
3136
+ video: { create: 'create video', fee: 'create video-fee', taskType: 'VIDEO_GROUP' },
3137
+ audio: { create: 'create audio', fee: 'create audio-fee', taskType: 'AUDIO_CREATE' },
3138
+ };
3139
+ const commands = commandByTaskKind[context.taskKind] || commandByTaskKind.image;
2998
3140
  return compactRecord({
2999
3141
  schemaVersion: 1,
3000
3142
  modelGroupCode,
3001
3143
  taskKind: context.taskKind,
3002
- createCommand: context.taskKind === 'image' ? 'create image' : 'create video',
3003
- feeCommand: context.taskKind === 'image' ? 'create image-fee' : 'create video-fee',
3004
- statusCommandTaskType: context.taskKind === 'image' ? 'IMAGE_CREATE' : 'VIDEO_GROUP',
3144
+ createCommand: commands.create,
3145
+ feeCommand: commands.fee,
3146
+ statusCommandTaskType: commands.taskType,
3005
3147
  optionsCommand: `model options --model-group-code ${modelGroupCode}`,
3006
3148
  model: context.model,
3007
3149
  inputRequirement,
@@ -3039,6 +3181,7 @@ const AUDIO_VIDEO_EXTENSIONS = new Set([
3039
3181
  '.oga',
3040
3182
  '.ogg',
3041
3183
  '.ogv',
3184
+ '.pcm',
3042
3185
  '.wav',
3043
3186
  '.webm',
3044
3187
  ]);
@@ -4194,7 +4337,7 @@ const RESOURCE_SOURCE_KEYS = new Set(['kind', 'value']);
4194
4337
  const RESOURCE_TYPES = new Set(['image', 'video', 'audio', 'subject']);
4195
4338
  const RESOURCE_USAGES = new Set(['reference', 'first_frame', 'last_frame', 'keyframe']);
4196
4339
 
4197
- function parseIntegerParam(value, name, minValue) {
4340
+ function parseIntegerParam(value, name, minValue, maxValue = null) {
4198
4341
  if (value == null || value === '') return null;
4199
4342
  const text = String(value).trim();
4200
4343
  if (!/^[+-]?\d+$/.test(text)) {
@@ -4207,6 +4350,9 @@ function parseIntegerParam(value, name, minValue) {
4207
4350
  if (parsed < minValue) {
4208
4351
  throw argumentError(`${name} 必须是${minValue === 0 ? '非负整数' : '正整数'}`);
4209
4352
  }
4353
+ if (maxValue != null && parsed > maxValue) {
4354
+ throw argumentError(`${name} 不能超过 ${maxValue}`);
4355
+ }
4210
4356
  return parsed;
4211
4357
  }
4212
4358
 
@@ -4447,6 +4593,21 @@ async function collectResourceSpecs(kwargs = {}, options = {}) {
4447
4593
  });
4448
4594
  if (Array.isArray(resourcesJson)) items.push(...resourcesJson);
4449
4595
  return items.map((item, index) => normalizeResourceObject(item, index)).filter((item) => {
4596
+ if (options.kind === 'audio') {
4597
+ if (!['audio', 'image'].includes(item.type)) {
4598
+ throw argumentError('音频任务 resource 只支持 type=audio 或 type=image');
4599
+ }
4600
+ if (item.usage !== 'reference') {
4601
+ throw argumentError('音频任务 resource 只支持 usage=reference');
4602
+ }
4603
+ if (item.reference_key) {
4604
+ throw argumentError('音频任务 reference 不支持 reference_key');
4605
+ }
4606
+ if (item._source.kind !== 'url') {
4607
+ throw argumentError('音频任务 resource 暂只支持 url,本地文件会自动上传为 url');
4608
+ }
4609
+ return true;
4610
+ }
4450
4611
  if (options.kind !== 'image') return true;
4451
4612
  if (item.type !== 'image') {
4452
4613
  throw argumentError('图片任务 resource 只支持 type=image');
@@ -4910,7 +5071,7 @@ async function buildVideoRequest(kwargs = {}, options = {}) {
4910
5071
  if (shouldDefaultNeedAudioForVideoModel(validation.context.model, validation.params, promptParams)) {
4911
5072
  defaultParams.need_audio = true;
4912
5073
  promptParams = normalizeUnifiedPromptParams(defaultParams);
4913
- assertParamsAgainstModel(promptParams, validation.params, validation.context.constraints);
5074
+ assertParamsAgainstModel(promptParams, validation.params, validation.context.constraints, validation.context.taskKind);
4914
5075
  }
4915
5076
  const resolvedResources = await resolveResources(kwargs, {
4916
5077
  dryRun,
@@ -5002,6 +5163,146 @@ export async function videoCreate(kwargs = {}) {
5002
5163
  };
5003
5164
  }
5004
5165
 
5166
+ async function buildAudioRequest(kwargs = {}, options = {}) {
5167
+ const dryRun = Boolean(options.dryRun);
5168
+ const model = resolveTaskModel('audio', kwargs);
5169
+ const prompt = trimToNull(kwargs.prompt);
5170
+ if (!prompt) throw argumentError('缺少音频生成提示词', '传 --prompt <text>。');
5171
+
5172
+ const duration = parseIntegerParam(kwargs.duration, '--duration', 1, 120);
5173
+ if (duration == null) throw argumentError('缺少音频生成时长', '传 --duration <seconds>,支持 1-120 秒。');
5174
+
5175
+ const validationResources = await resolveResources(kwargs, {
5176
+ dryRun: true,
5177
+ kind: 'audio',
5178
+ sceneType: TASK_UPLOAD_SCENE.AUDIO_CREATE,
5179
+ });
5180
+ const audioReferenceCount = validationResources.resources.filter((item) => item.type === 'audio').length;
5181
+ const imageReferenceCount = validationResources.resources.filter((item) => item.type === 'image').length;
5182
+ if (audioReferenceCount > 3) throw argumentError('参考音频最多支持 3 个');
5183
+ if (imageReferenceCount > 1) throw argumentError('参考图片最多支持 1 张');
5184
+ if (audioReferenceCount && imageReferenceCount) {
5185
+ throw argumentError('参考音频和参考图片不能混用');
5186
+ }
5187
+ const genericModelParams = await collectGenericModelParams(kwargs);
5188
+ const defaultParams = {
5189
+ ...genericModelParams,
5190
+ prompt,
5191
+ duration,
5192
+ audio_format: trimToNull(kwargs.audioFormat ?? kwargs.audio_format) ?? 'mp3',
5193
+ resources: validationResources.resources,
5194
+ };
5195
+ const integerOptions = [
5196
+ ['sample_rate', kwargs.sampleRate ?? kwargs.sample_rate, 1],
5197
+ ['speech_rate', kwargs.speechRate ?? kwargs.speech_rate, -50],
5198
+ ['loudness_rate', kwargs.loudnessRate ?? kwargs.loudness_rate, -50],
5199
+ ['pitch_rate', kwargs.pitchRate ?? kwargs.pitch_rate, -12],
5200
+ ];
5201
+ for (const [key, value, min] of integerOptions) {
5202
+ if (value != null && value !== '') defaultParams[key] = parseIntegerParam(value, `--${key.replaceAll('_', '-')}`, min);
5203
+ }
5204
+ const enableSubtitle = kwargs.enableSubtitle ?? kwargs.enable_subtitle;
5205
+ if (enableSubtitle != null && enableSubtitle !== '') defaultParams.enable_subtitle = toBool(enableSubtitle);
5206
+
5207
+ const promptParams = normalizeUnifiedPromptParams(defaultParams);
5208
+ const validation = await validateCreateRequestAgainstModel(
5209
+ 'audio', model.modelGroupCode, promptParams, validationResources.resourceDetails,
5210
+ );
5211
+ const resolvedResources = await resolveResources(kwargs, {
5212
+ dryRun,
5213
+ kind: 'audio',
5214
+ sceneType: TASK_UPLOAD_SCENE.AUDIO_CREATE,
5215
+ resourceRules: validation.resourceRules,
5216
+ });
5217
+ const requestPromptParams = normalizeUnifiedPromptParams({
5218
+ ...defaultParams,
5219
+ resources: resolvedResources.resources,
5220
+ });
5221
+ const projectGroupNo = await resolveProjectGroupNo(kwargs.projectGroupNo, {
5222
+ allowNull: dryRun,
5223
+ noNetwork: dryRun,
5224
+ noSave: dryRun,
5225
+ });
5226
+ return {
5227
+ model,
5228
+ projectGroupNo,
5229
+ uploads: resolvedResources.uploads,
5230
+ localFiles: resolvedResources.localFiles,
5231
+ resourceConversions: resolvedResources.resourceConversions,
5232
+ request: {
5233
+ requestSource: REQUEST_SOURCE_CLI,
5234
+ modelGroupCode: model.modelGroupCode,
5235
+ promptParams: requestPromptParams,
5236
+ ...(projectGroupNo ? { projectGroupNo } : {}),
5237
+ },
5238
+ };
5239
+ }
5240
+
5241
+ export async function audioFee(kwargs = {}) {
5242
+ if (toBool(kwargs.dryRun)) {
5243
+ const built = await buildAudioRequest(kwargs, { dryRun: true });
5244
+ return compactRecord({
5245
+ dryRun: true,
5246
+ action: 'create audio-fee',
5247
+ request: built.request,
5248
+ ...(built.resourceConversions.length ? { resourceConversions: built.resourceConversions } : {}),
5249
+ });
5250
+ }
5251
+ const built = await buildAudioRequest(kwargs);
5252
+ const payload = await awbApi.fetchAudioFee(built.request);
5253
+ return {
5254
+ data: payload,
5255
+ ...(await pointEstimate(payload, built.projectGroupNo)),
5256
+ };
5257
+ }
5258
+
5259
+ export async function audioCreate(kwargs = {}) {
5260
+ if (toBool(kwargs.dryRun)) {
5261
+ const built = await buildAudioRequest(kwargs, { dryRun: true });
5262
+ return compactRecord({
5263
+ dryRun: true,
5264
+ action: 'create audio',
5265
+ request: built.request,
5266
+ ...(built.localFiles.length ? { localFiles: built.localFiles } : {}),
5267
+ ...(built.resourceConversions.length ? { resourceConversions: built.resourceConversions } : {}),
5268
+ });
5269
+ }
5270
+ ensureConfirmed(kwargs, '正式生成音频会消耗积分,需要确认', { action: 'create audio' });
5271
+ const built = await buildAudioRequest(kwargs);
5272
+ const feePayload = await awbApi.fetchAudioFee(built.request).catch(() => null);
5273
+ const estimate = await pointEstimate(feePayload, built.projectGroupNo).catch(() => ({}));
5274
+ const payload = await awbApi.createAudioTask(built.request);
5275
+ const result = normalizeCreatedTask(payload, {
5276
+ ...estimate,
5277
+ projectGroupNo: built.projectGroupNo,
5278
+ modelGroupCode: built.request.modelGroupCode,
5279
+ ...(built.uploads.length ? { uploads: normalizeCreateUploads(built.uploads) } : {}),
5280
+ });
5281
+ await appendTaskRecord(kwargs, {
5282
+ taskId: result.taskId,
5283
+ taskType: 'AUDIO_CREATE',
5284
+ projectGroupNo: built.projectGroupNo,
5285
+ modelGroupCode: built.request.modelGroupCode,
5286
+ promptSummary: taskPromptSummary({ prompt: built.request.promptParams?.prompt }),
5287
+ });
5288
+ if (toInt(kwargs.waitSeconds, 0) > 0 && result.taskId) {
5289
+ return {
5290
+ ...result,
5291
+ waited: await waitTask({
5292
+ taskId: result.taskId,
5293
+ taskType: 'AUDIO_CREATE',
5294
+ projectGroupNo: built.projectGroupNo,
5295
+ waitSeconds: kwargs.waitSeconds,
5296
+ pollIntervalMs: kwargs.pollIntervalMs,
5297
+ }),
5298
+ };
5299
+ }
5300
+ return {
5301
+ ...result,
5302
+ nextCommand: result.taskId ? `lj-awb task wait --task-id ${result.taskId} -f json` : null,
5303
+ };
5304
+ }
5305
+
5005
5306
  export async function loadBatchItems(inputFile, mode = 'generic') {
5006
5307
  const filePath = trimToNull(inputFile);
5007
5308
  if (!filePath) throw argumentError('缺少批量输入文件', '传 --input-file <json|jsonl|txt>。');