@lingjingai/lj-awb-cli 0.4.1 → 0.4.3

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.
@@ -3,6 +3,7 @@ import crypto from 'node:crypto';
3
3
  import fs from 'node:fs/promises';
4
4
  import { tmpdir } from 'node:os';
5
5
  import path from 'node:path';
6
+ import { createInterface } from 'node:readline/promises';
6
7
  import { promisify } from 'node:util';
7
8
  import {
8
9
  API_ORIGIN,
@@ -72,6 +73,38 @@ const REMOTE_VOICE_EXTENSIONS = new Set(['.mp3', '.wav', '.m4a', '.aac', '.ogg',
72
73
  const ASSET_PLATFORM_CODES = ['JIMENG', 'BYTEPLUS'];
73
74
  const ASSET_PLATFORM_CODE_SET = new Set(ASSET_PLATFORM_CODES);
74
75
  const ASSET_PLATFORM_HINT = ASSET_PLATFORM_CODES.join('|');
76
+ const ASSET_TYPE_CODES = Object.freeze({
77
+ Image: 'Image',
78
+ Video: 'Video',
79
+ Audio: 'Audio',
80
+ });
81
+ const ASSET_IMAGE_EXTENSIONS = new Set(['.bmp', '.gif', '.heic', '.heif', '.jpg', '.jpeg', '.png', '.tif', '.tiff', '.webp']);
82
+ const ASSET_VIDEO_EXTENSIONS = new Set(['.mp4', '.mov']);
83
+ const ASSET_AUDIO_EXTENSIONS = new Set(['.mp3', '.wav']);
84
+ const ASSET_IMAGE_MAX_BYTES = 30 * 1024 * 1024;
85
+ const ASSET_VIDEO_MAX_BYTES = 50 * 1024 * 1024;
86
+ const ASSET_MEDIA_MIN_ASPECT = 0.4;
87
+ const ASSET_MEDIA_MAX_ASPECT = 2.5;
88
+ const ASSET_MEDIA_MIN_DIMENSION = 300;
89
+ const ASSET_MEDIA_MAX_DIMENSION = 6000;
90
+ const ASSET_VIDEO_MIN_SECONDS = 2;
91
+ const ASSET_VIDEO_MAX_SECONDS = 15;
92
+ const ASSET_VIDEO_MIN_FPS = 24;
93
+ const ASSET_VIDEO_MAX_FPS = 60;
94
+ const ASSET_VIDEO_MIN_PIXELS = 640 * 640;
95
+ const ASSET_VIDEO_MAX_PIXELS = 834 * 1112;
96
+ const ASSET_AUDIO_MIN_SECONDS = 2;
97
+ const ASSET_AUDIO_MAX_SECONDS = 15;
98
+ let ffprobeCommandCache = null;
99
+ let ffmpegCommandCache = null;
100
+ const PLATFORM_BACKEND_PATH_PREFIXES = [
101
+ 'material/',
102
+ 'material-image-draw/',
103
+ 'material-image-edit/',
104
+ 'material-video-create/',
105
+ 'default/workbench/',
106
+ 'asset-review/',
107
+ ];
75
108
  const CREATE_STANDARD_KWARG_KEYS = new Set([
76
109
  'modelGroupCode',
77
110
  'projectGroupNo',
@@ -1262,7 +1295,7 @@ function assertResourceShapeAgainstModel(resourceDetails = [], resourceRules = [
1262
1295
  if (conversion && !conversion.possible) {
1263
1296
  throw argumentError(
1264
1297
  `素材格式需要转换但无法自动处理:${resourceText(resource)}`,
1265
- `当前格式 ${conversion.fromFormat},目标格式 ${conversion.toFormat};请使用本地文件、http(s) URL 或 material backendPath,asset 资源需先转换后再传。`,
1298
+ `当前格式 ${conversion.fromFormat},目标格式 ${conversion.toFormat};请使用本地文件、http(s) URL 或平台 backendPath,asset 资源需先转换后再传。`,
1266
1299
  );
1267
1300
  }
1268
1301
  if (!conversion && !fileTypeAllowedByRule(rule, format)) {
@@ -1615,7 +1648,11 @@ function mergeModelParamRules(options = [], rawModel = null) {
1615
1648
  function modelParamDefaultValue(option = {}) {
1616
1649
  return option.rules?.defaultValue
1617
1650
  ?? option.defaultValue
1618
- ?? option.rules?.defaultName
1651
+ ?? null;
1652
+ }
1653
+
1654
+ function modelParamDefaultName(option = {}) {
1655
+ return option.rules?.defaultName
1619
1656
  ?? option.defaultName
1620
1657
  ?? null;
1621
1658
  }
@@ -1630,7 +1667,7 @@ function modelParamValueSource(option = {}) {
1630
1667
  function isGenericModelConfigParam(option = {}) {
1631
1668
  const key = trimToNull(option.paramKey);
1632
1669
  if (!key) return false;
1633
- if ([
1670
+ const internalResourceKeys = new Set([
1634
1671
  'generated_mode',
1635
1672
  'resources',
1636
1673
  'iref',
@@ -1639,11 +1676,17 @@ function isGenericModelConfigParam(option = {}) {
1639
1676
  'frames',
1640
1677
  'multi_param',
1641
1678
  'multi_prompt',
1642
- ].includes(key)) return false;
1643
- if (/resource|frame|image|video|audio|subject/i.test(key) && ![
1644
- 'need_audio',
1645
- 'audio',
1646
- ].includes(key)) return false;
1679
+ 'subject',
1680
+ 'subject_reference',
1681
+ 'reference_image',
1682
+ 'reference_audio',
1683
+ 'reference_video',
1684
+ 'first_frame',
1685
+ 'first_last_frame',
1686
+ 'last_frame_only',
1687
+ 'storyboard',
1688
+ ]);
1689
+ if (internalResourceKeys.has(key)) return false;
1647
1690
  const paramType = String(option.paramType || '');
1648
1691
  return Boolean(
1649
1692
  optionAllowedValues(option).length
@@ -1726,7 +1769,7 @@ function createParamForModelOption(option = {}, taskKind = 'image') {
1726
1769
  requestPath: 'promptParams.resources[]',
1727
1770
  materialLegacyKey: 'iref',
1728
1771
  meaning: '图片任务的参考图输入。',
1729
- valueSource: '本地文件、http(s) URL 或 material backendPath。',
1772
+ valueSource: '本地文件、http(s) URL 或平台 backendPath。',
1730
1773
  resourceSyntax: ['image:reference=./ref.png'],
1731
1774
  },
1732
1775
  resources: {
@@ -1735,7 +1778,7 @@ function createParamForModelOption(option = {}, taskKind = 'image') {
1735
1778
  requestPath: 'promptParams.resources[]',
1736
1779
  materialLegacyKey: 'resources',
1737
1780
  meaning: '模型声明的素材输入;CLI 统一用 resources 表达。',
1738
- valueSource: '本地文件、http(s) URL 或 material backendPath。',
1781
+ valueSource: '本地文件、http(s) URL 或平台 backendPath。',
1739
1782
  resourceSyntax: taskKind === 'image' ? ['image:reference=./ref.png'] : ['image:first_frame=./first.png'],
1740
1783
  },
1741
1784
  frames: {
@@ -1744,7 +1787,7 @@ function createParamForModelOption(option = {}, taskKind = 'image') {
1744
1787
  requestPath: 'promptParams.resources[]',
1745
1788
  materialLegacyKey: 'frames',
1746
1789
  meaning: '视频首帧 / 尾帧 / 关键帧输入。',
1747
- valueSource: '首帧/尾帧可用本地文件、http(s) URL、material backendPath 或 asset:<assetId>;keyframe 仅用文件/URL/backendPath。',
1790
+ valueSource: '首帧/尾帧可用本地文件、http(s) URL、平台 backendPath 或 asset:<assetId>;keyframe 仅用文件/URL/backendPath。',
1748
1791
  resourceSyntax: ['image:first_frame=./first.png', 'image:first_frame=asset:<assetId>', 'image:last_frame=asset:<assetId>', 'image:keyframe#1=./key1.png'],
1749
1792
  },
1750
1793
  multi_param: {
@@ -2318,7 +2361,7 @@ function modelOptionParams(options = [], taskKind = 'image') {
2318
2361
  valueType: cliValueType(option, allowedValues),
2319
2362
  values: allowedValues.length ? allowedValues : undefined,
2320
2363
  defaultValue,
2321
- defaultName: rules.defaultName ?? option.defaultName,
2364
+ defaultName: modelParamDefaultName(option),
2322
2365
  maxLength,
2323
2366
  required,
2324
2367
  cliArg: createParam.cliArg,
@@ -2423,7 +2466,7 @@ export function modelInputGuide() {
2423
2466
  { field: 'resources[].type', values: ['image', 'video', 'audio', 'subject'], description: '资源本体类型;subject 表示已创建的主体对象。' },
2424
2467
  { field: 'resources[].usage', values: ['first_frame', 'last_frame', 'reference', 'keyframe'], description: '素材用途。' },
2425
2468
  { field: 'resources[].reference_key', values: ['custom string'], description: '仅视频 reference 资源需要占位绑定时使用;图片生图 image:reference 不使用 reference_key。subject reference 必须传。' },
2426
- { field: 'resources[].source.kind', values: ['url', 'asset_id'], description: '只接受 url、asset_id 两个枚举值。本地文件、http(s) URL、material backendPath 一律传 kind=url,CLI 按 value 自动识别;asset_id 表示平台资产或主体对象 ID。注意:模型 resources[].valueShapes 列出的 local_file / http_url / backendPath 是 value 形状分类,不是 kind 枚举。' },
2469
+ { field: 'resources[].source.kind', values: ['url', 'asset_id'], description: '只接受 url、asset_id 两个枚举值。本地文件、http(s) URL、平台 backendPath 一律传 kind=url,CLI 按 value 自动识别;asset_id 表示平台资产或主体对象 ID。注意:模型 resources[].valueShapes 列出的 local_file / http_url / backendPath 是 value 形状分类,不是 kind 枚举。' },
2427
2470
  { field: 'resources[].source.value', description: '资源值,必填。url 传素材地址;asset_id 传资源 ID。' },
2428
2471
  { field: 'resources[].order', description: '仅 usage=keyframe 时需要,且同一请求内不能重复。' },
2429
2472
  { field: 'resources[].duration', description: '仅 keyframe 场景下用于表达该帧持续时长,可传小数秒。' },
@@ -2562,6 +2605,768 @@ function dryRunBackendPath(filePath, sceneType) {
2562
2605
  return `/${sceneType}/__dry_run__/${safeFileName(filePath)}`;
2563
2606
  }
2564
2607
 
2608
+ function mb(bytes) {
2609
+ return `${(bytes / (1024 * 1024)).toFixed(1).replace(/\.0$/, '')}MB`;
2610
+ }
2611
+
2612
+ function sourceExtension(value) {
2613
+ const text = trimToNull(value);
2614
+ if (!text) return '';
2615
+ if (/^https?:\/\//i.test(text)) {
2616
+ try {
2617
+ return path.extname(decodeURIComponent(new URL(text).pathname)).toLowerCase();
2618
+ } catch {
2619
+ return path.extname(text.split(/[?#]/)[0] || '').toLowerCase();
2620
+ }
2621
+ }
2622
+ return path.extname(text.split(/[?#]/)[0] || '').toLowerCase();
2623
+ }
2624
+
2625
+ function inferAssetTypeFromExtension(ext) {
2626
+ if (ASSET_IMAGE_EXTENSIONS.has(ext)) return ASSET_TYPE_CODES.Image;
2627
+ if (ASSET_VIDEO_EXTENSIONS.has(ext)) return ASSET_TYPE_CODES.Video;
2628
+ if (ASSET_AUDIO_EXTENSIONS.has(ext)) return ASSET_TYPE_CODES.Audio;
2629
+ return null;
2630
+ }
2631
+
2632
+ function inferAssetTypeFromSource(value) {
2633
+ const ext = sourceExtension(value);
2634
+ const assetType = inferAssetTypeFromExtension(ext);
2635
+ if (assetType) return assetType;
2636
+ const suffix = ext || '无扩展名';
2637
+ throw argumentError(
2638
+ `无法判断素材类型:${suffix}`,
2639
+ '素材加白支持图片 jpg/jpeg/png/webp/bmp/tiff/gif/heic/heif,视频 mp4/mov,音频 wav/mp3;请传带正确扩展名的 --file、--url 或 --backend-path。',
2640
+ );
2641
+ }
2642
+
2643
+ function parseFfprobeNumber(value) {
2644
+ const number = Number(value);
2645
+ return Number.isFinite(number) ? number : null;
2646
+ }
2647
+
2648
+ function parseFps(value) {
2649
+ const text = String(value || '').trim();
2650
+ if (!text || text === '0/0') return null;
2651
+ if (text.includes('/')) {
2652
+ const [left, right] = text.split('/').map(Number);
2653
+ return Number.isFinite(left) && Number.isFinite(right) && right !== 0 ? left / right : null;
2654
+ }
2655
+ return parseFfprobeNumber(text);
2656
+ }
2657
+
2658
+ function roundNumber(value, digits = 3) {
2659
+ if (!Number.isFinite(Number(value))) return value;
2660
+ const fixed = Number(value).toFixed(digits);
2661
+ return fixed.replace(/\.?0+$/, '');
2662
+ }
2663
+
2664
+ function normalizeDisplayFormat(value) {
2665
+ const text = trimToNull(value);
2666
+ if (!text) return null;
2667
+ return normalizeFileFormat(text.replace(/^\./, ''));
2668
+ }
2669
+
2670
+ function clampNumber(value, min, max) {
2671
+ return Math.min(max, Math.max(min, value));
2672
+ }
2673
+
2674
+ function evenNumber(value, fallback = 2) {
2675
+ const rounded = Math.max(2, Math.round(value / 2) * 2);
2676
+ return Number.isFinite(rounded) ? rounded : fallback;
2677
+ }
2678
+
2679
+ function roundToStep(value, step = 1) {
2680
+ return Math.round(value / step) * step;
2681
+ }
2682
+
2683
+ function alignUp(value, step = 1) {
2684
+ return Math.ceil(value / step) * step;
2685
+ }
2686
+
2687
+ function alignDown(value, step = 1) {
2688
+ return Math.floor(value / step) * step;
2689
+ }
2690
+
2691
+ function isLegalMediaBox(width, height, options = {}) {
2692
+ const minAspect = options.minAspect ?? ASSET_MEDIA_MIN_ASPECT;
2693
+ const maxAspect = options.maxAspect ?? ASSET_MEDIA_MAX_ASPECT;
2694
+ const minDimension = options.minDimension ?? ASSET_MEDIA_MIN_DIMENSION;
2695
+ const maxDimension = options.maxDimension ?? ASSET_MEDIA_MAX_DIMENSION;
2696
+ if (!Number.isFinite(width) || !Number.isFinite(height)) return false;
2697
+ if (width < minDimension || height < minDimension || width > maxDimension || height > maxDimension) return false;
2698
+ const aspect = width / height;
2699
+ if (aspect < minAspect || aspect > maxAspect) return false;
2700
+ const pixels = width * height;
2701
+ if (options.minPixels != null && pixels < options.minPixels) return false;
2702
+ if (options.maxPixels != null && pixels > options.maxPixels) return false;
2703
+ return true;
2704
+ }
2705
+
2706
+ function legalMediaBoxOrThrow(target, label, options = {}) {
2707
+ if (isLegalMediaBox(target.width, target.height, options)) return target;
2708
+ throw argumentError(
2709
+ `无法计算合法${label}转码尺寸`,
2710
+ `${label}目标尺寸计算结果为 ${target.width}x${target.height},仍不满足平台规格;请手动转换素材后重试。`,
2711
+ );
2712
+ }
2713
+
2714
+ function chooseClosestLegalBox(width, height, options = {}) {
2715
+ const minAspect = options.minAspect ?? ASSET_MEDIA_MIN_ASPECT;
2716
+ const maxAspect = options.maxAspect ?? ASSET_MEDIA_MAX_ASPECT;
2717
+ const minDimension = options.minDimension ?? ASSET_MEDIA_MIN_DIMENSION;
2718
+ const maxDimension = options.maxDimension ?? ASSET_MEDIA_MAX_DIMENSION;
2719
+ const step = options.even ? 2 : 1;
2720
+ const sourceWidth = Math.max(1, Number(width) || minDimension);
2721
+ const sourceHeight = Math.max(1, Number(height) || minDimension);
2722
+ const targetAspect = clampNumber(sourceWidth / sourceHeight, minAspect, maxAspect);
2723
+ const minPixels = options.minPixels;
2724
+ const maxPixels = options.maxPixels;
2725
+ const minArea = minPixels ?? minDimension * minDimension;
2726
+ const maxArea = maxPixels ?? maxDimension * maxDimension;
2727
+ const targetArea = clampNumber(sourceWidth * sourceHeight, minArea, maxArea);
2728
+ let best = null;
2729
+
2730
+ const minHeight = alignUp(minDimension, step);
2731
+ const maxHeight = alignDown(maxDimension, step);
2732
+ for (let candidateHeight = minHeight; candidateHeight <= maxHeight; candidateHeight += step) {
2733
+ const minWidthForAspect = Math.ceil(candidateHeight * minAspect);
2734
+ const maxWidthForAspect = Math.floor(candidateHeight * maxAspect);
2735
+ const minWidthForPixels = minPixels == null ? minDimension : Math.ceil(minPixels / candidateHeight);
2736
+ const maxWidthForPixels = maxPixels == null ? maxDimension : Math.floor(maxPixels / candidateHeight);
2737
+ const minWidth = alignUp(Math.max(minDimension, minWidthForAspect, minWidthForPixels), step);
2738
+ const maxWidth = alignDown(Math.min(maxDimension, maxWidthForAspect, maxWidthForPixels), step);
2739
+ if (minWidth > maxWidth) continue;
2740
+
2741
+ const preferredByAspect = roundToStep(targetAspect * candidateHeight, step);
2742
+ const preferredByArea = roundToStep(targetArea / candidateHeight, step);
2743
+ const candidates = uniqueNonEmpty([
2744
+ preferredByAspect,
2745
+ preferredByArea,
2746
+ minWidth,
2747
+ maxWidth,
2748
+ preferredByAspect - step,
2749
+ preferredByAspect + step,
2750
+ preferredByArea - step,
2751
+ preferredByArea + step,
2752
+ ])
2753
+ .map((item) => Number(item))
2754
+ .filter((item) => Number.isFinite(item))
2755
+ .map((item) => clampNumber(item, minWidth, maxWidth));
2756
+
2757
+ for (const candidateWidth of candidates) {
2758
+ if (!isLegalMediaBox(candidateWidth, candidateHeight, options)) continue;
2759
+ const aspect = candidateWidth / candidateHeight;
2760
+ const area = candidateWidth * candidateHeight;
2761
+ const aspectScore = Math.abs(Math.log(aspect / targetAspect));
2762
+ const areaScore = Math.abs(Math.log(area / targetArea));
2763
+ const sourceScaleScore = Math.abs(Math.log(candidateWidth / sourceWidth)) + Math.abs(Math.log(candidateHeight / sourceHeight));
2764
+ const score = aspectScore * 10 + areaScore + sourceScaleScore * 0.05;
2765
+ if (!best || score < best.score) {
2766
+ best = { width: candidateWidth, height: candidateHeight, pixels: area, score };
2767
+ }
2768
+ }
2769
+ }
2770
+
2771
+ if (!best) {
2772
+ const fallback = options.even ? { width: 640, height: 640, pixels: 640 * 640 } : { width: 300, height: 300, pixels: 300 * 300 };
2773
+ return fallback;
2774
+ }
2775
+ return {
2776
+ width: best.width,
2777
+ height: best.height,
2778
+ pixels: best.pixels,
2779
+ };
2780
+ }
2781
+
2782
+ function mediaSummary(media = {}) {
2783
+ return compactRecord({
2784
+ width: media.width,
2785
+ height: media.height,
2786
+ pixels: media.width && media.height ? media.width * media.height : undefined,
2787
+ aspectRatio: media.width && media.height ? Number(roundNumber(media.width / media.height, 4)) : undefined,
2788
+ duration: media.duration == null ? undefined : Number(roundNumber(media.duration, 3)),
2789
+ fps: media.fps == null ? undefined : Number(roundNumber(media.fps, 3)),
2790
+ });
2791
+ }
2792
+
2793
+ function addAssetViolation(violations, code, message, hint = '') {
2794
+ violations.push(compactRecord({ code, message, hint }));
2795
+ }
2796
+
2797
+ function validateMediaGeometry(violations, media, label, options = {}) {
2798
+ const width = Number(media?.width);
2799
+ const height = Number(media?.height);
2800
+ if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) {
2801
+ addAssetViolation(violations, `${label}_dimensions_unknown`, `${label}宽高无法识别`, `${label}宽高必须在 [300,6000] px,宽高比必须在 [0.4,2.5]。`);
2802
+ return;
2803
+ }
2804
+ const aspectRatio = width / height;
2805
+ if (aspectRatio < ASSET_MEDIA_MIN_ASPECT || aspectRatio > ASSET_MEDIA_MAX_ASPECT) {
2806
+ addAssetViolation(
2807
+ violations,
2808
+ `${label}_aspect_ratio`,
2809
+ `${label}宽高比不支持:${roundNumber(aspectRatio, 4)}`,
2810
+ `${label}宽高比(宽/高)必须在 [0.4,2.5]。`,
2811
+ );
2812
+ }
2813
+ if (
2814
+ width < ASSET_MEDIA_MIN_DIMENSION
2815
+ || height < ASSET_MEDIA_MIN_DIMENSION
2816
+ || width > ASSET_MEDIA_MAX_DIMENSION
2817
+ || height > ASSET_MEDIA_MAX_DIMENSION
2818
+ ) {
2819
+ addAssetViolation(
2820
+ violations,
2821
+ `${label}_dimensions`,
2822
+ `${label}宽高不支持:${width}x${height}`,
2823
+ `${label}宽和高都必须在 [300,6000] px。`,
2824
+ );
2825
+ }
2826
+ if (options.videoPixels) {
2827
+ const pixels = width * height;
2828
+ if (pixels < ASSET_VIDEO_MIN_PIXELS || pixels > ASSET_VIDEO_MAX_PIXELS) {
2829
+ addAssetViolation(
2830
+ violations,
2831
+ 'video_pixels',
2832
+ `视频总像素数不支持:${pixels}`,
2833
+ `视频宽高乘积必须在 [${ASSET_VIDEO_MIN_PIXELS},${ASSET_VIDEO_MAX_PIXELS}]。`,
2834
+ );
2835
+ }
2836
+ }
2837
+ }
2838
+
2839
+ function validateDurationRange(violations, media, label, minSeconds, maxSeconds) {
2840
+ const duration = Number(media?.duration);
2841
+ if (!Number.isFinite(duration) || duration < minSeconds || duration > maxSeconds) {
2842
+ addAssetViolation(
2843
+ violations,
2844
+ `${label}_duration`,
2845
+ `${label}时长不支持:${Number.isFinite(duration) ? `${roundNumber(duration)}s` : 'unknown'}`,
2846
+ `${label}时长必须在 [${minSeconds},${maxSeconds}] 秒。`,
2847
+ );
2848
+ }
2849
+ }
2850
+
2851
+ async function commandSucceeds(command, args = ['--version']) {
2852
+ try {
2853
+ await execFileAsync(command, args, { encoding: 'utf8', timeout: 10_000, maxBuffer: 256 * 1024 });
2854
+ return true;
2855
+ } catch {
2856
+ return false;
2857
+ }
2858
+ }
2859
+
2860
+ function commandCandidates(command) {
2861
+ if (path.isAbsolute(command)) return [command];
2862
+ if (command === 'brew') return ['brew', '/opt/homebrew/bin/brew', '/usr/local/bin/brew'];
2863
+ if (command === 'ffprobe') return ['ffprobe', '/opt/homebrew/bin/ffprobe', '/usr/local/bin/ffprobe'];
2864
+ if (command === 'ffmpeg') return ['ffmpeg', '/opt/homebrew/bin/ffmpeg', '/usr/local/bin/ffmpeg'];
2865
+ return [command];
2866
+ }
2867
+
2868
+ async function findCommand(command, args = ['--version']) {
2869
+ for (const candidate of commandCandidates(command)) {
2870
+ if (await commandSucceeds(candidate, args)) return candidate;
2871
+ }
2872
+ return null;
2873
+ }
2874
+
2875
+ function autoInstallFfprobeEnabled() {
2876
+ const value = String(process.env.LINGJING_AWB_AUTO_INSTALL_FFPROBE ?? '1').trim().toLowerCase();
2877
+ return !['0', 'false', 'no', 'off'].includes(value);
2878
+ }
2879
+
2880
+ async function ensureFfprobeAvailable() {
2881
+ if (ffprobeCommandCache && await commandSucceeds(ffprobeCommandCache, ['-version'])) return ffprobeCommandCache;
2882
+ const existing = await findCommand('ffprobe', ['-version']);
2883
+ if (existing) {
2884
+ ffprobeCommandCache = existing;
2885
+ return existing;
2886
+ }
2887
+ const brewCommand = autoInstallFfprobeEnabled() && process.platform === 'darwin'
2888
+ ? await findCommand('brew', ['--version'])
2889
+ : null;
2890
+ if (brewCommand) {
2891
+ try {
2892
+ await execFileAsync(brewCommand, ['install', 'ffmpeg'], {
2893
+ encoding: 'utf8',
2894
+ timeout: 10 * 60_000,
2895
+ maxBuffer: 8 * 1024 * 1024,
2896
+ });
2897
+ const installed = await findCommand('ffprobe', ['-version']);
2898
+ if (installed) {
2899
+ ffprobeCommandCache = installed;
2900
+ return installed;
2901
+ }
2902
+ } catch (error) {
2903
+ throw argumentError(
2904
+ '缺少 ffprobe,且自动安装 ffmpeg 失败',
2905
+ `CLI 已尝试运行 brew install ffmpeg。请手动安装后重试;如需关闭自动安装,设置 LINGJING_AWB_AUTO_INSTALL_FFPROBE=0。原始错误:${error.message}`,
2906
+ );
2907
+ }
2908
+ }
2909
+ throw argumentError(
2910
+ '缺少 ffprobe',
2911
+ '本地图片 / 音频 / 视频素材加白需要 ffprobe 校验尺寸、时长和视频 FPS。macOS 可运行 brew install ffmpeg;Ubuntu/Debian 可运行 sudo apt-get install ffmpeg。',
2912
+ );
2913
+ }
2914
+
2915
+ async function ensureFfmpegAvailable() {
2916
+ if (ffmpegCommandCache && await commandSucceeds(ffmpegCommandCache, ['-version'])) return ffmpegCommandCache;
2917
+ const existing = await findCommand('ffmpeg', ['-version']);
2918
+ if (existing) {
2919
+ ffmpegCommandCache = existing;
2920
+ return existing;
2921
+ }
2922
+ const brewCommand = autoInstallFfprobeEnabled() && process.platform === 'darwin'
2923
+ ? await findCommand('brew', ['--version'])
2924
+ : null;
2925
+ if (brewCommand) {
2926
+ try {
2927
+ await execFileAsync(brewCommand, ['install', 'ffmpeg'], {
2928
+ encoding: 'utf8',
2929
+ timeout: 10 * 60_000,
2930
+ maxBuffer: 8 * 1024 * 1024,
2931
+ });
2932
+ const installed = await findCommand('ffmpeg', ['-version']);
2933
+ if (installed) {
2934
+ ffmpegCommandCache = installed;
2935
+ return installed;
2936
+ }
2937
+ } catch (error) {
2938
+ throw argumentError(
2939
+ '缺少 ffmpeg,且自动安装 ffmpeg 失败',
2940
+ `CLI 已尝试运行 brew install ffmpeg。请手动安装后重试;如需关闭自动安装,设置 LINGJING_AWB_AUTO_INSTALL_FFPROBE=0。原始错误:${error.message}`,
2941
+ );
2942
+ }
2943
+ }
2944
+ throw argumentError(
2945
+ '缺少 ffmpeg',
2946
+ '素材自动转码需要 ffmpeg。macOS 可运行 brew install ffmpeg;Ubuntu/Debian 可运行 sudo apt-get install ffmpeg。',
2947
+ );
2948
+ }
2949
+
2950
+ async function readMediaMetadata(filePath, assetType) {
2951
+ const ffprobeCommand = await ensureFfprobeAvailable();
2952
+ try {
2953
+ const { stdout } = await execFileAsync(ffprobeCommand, [
2954
+ '-v',
2955
+ 'error',
2956
+ '-print_format',
2957
+ 'json',
2958
+ '-show_format',
2959
+ '-show_streams',
2960
+ filePath,
2961
+ ], { encoding: 'utf8', timeout: 15_000, maxBuffer: 2 * 1024 * 1024 });
2962
+ const data = JSON.parse(stdout);
2963
+ const streams = Array.isArray(data.streams) ? data.streams : [];
2964
+ const wantedStreamType = assetType === ASSET_TYPE_CODES.Audio ? 'audio' : 'video';
2965
+ const stream = streams.find((item) => item.codec_type === wantedStreamType);
2966
+ if (!stream) {
2967
+ throw new Error(`缺少 ${wantedStreamType} stream`);
2968
+ }
2969
+ const duration = parseFfprobeNumber(stream.duration) ?? parseFfprobeNumber(data.format?.duration);
2970
+ return compactRecord({
2971
+ duration,
2972
+ width: parseFfprobeNumber(stream.width),
2973
+ height: parseFfprobeNumber(stream.height),
2974
+ fps: parseFps(stream.avg_frame_rate) ?? parseFps(stream.r_frame_rate),
2975
+ });
2976
+ } catch (error) {
2977
+ const mediaLabel = assetType === ASSET_TYPE_CODES.Audio ? '音频' : (assetType === ASSET_TYPE_CODES.Video ? '视频' : '图片');
2978
+ throw argumentError(
2979
+ `无法读取${mediaLabel}素材信息`,
2980
+ `请确认文件可被 ffprobe 解析且本机已安装 ffprobe。原始错误:${error.message}`,
2981
+ );
2982
+ }
2983
+ }
2984
+
2985
+ async function readImageMetadata(filePath) {
2986
+ const inspected = await inspectLocalFile(filePath);
2987
+ if (Number.isFinite(inspected.width) && Number.isFinite(inspected.height)) {
2988
+ return compactRecord({
2989
+ width: inspected.width,
2990
+ height: inspected.height,
2991
+ format: inspected.format ?? null,
2992
+ });
2993
+ }
2994
+ const media = await readMediaMetadata(filePath, ASSET_TYPE_CODES.Image);
2995
+ return compactRecord({
2996
+ width: media.width,
2997
+ height: media.height,
2998
+ format: inspected.format ?? null,
2999
+ });
3000
+ }
3001
+
3002
+ function chooseLegalMediaBox(width, height, options = {}) {
3003
+ return legalMediaBoxOrThrow(chooseClosestLegalBox(width, height, options), '图片', options);
3004
+ }
3005
+
3006
+ function chooseLegalVideoBox(width, height) {
3007
+ const options = {
3008
+ even: true,
3009
+ minPixels: ASSET_VIDEO_MIN_PIXELS,
3010
+ maxPixels: ASSET_VIDEO_MAX_PIXELS,
3011
+ };
3012
+ return legalMediaBoxOrThrow(chooseClosestLegalBox(width, height, options), '视频', options);
3013
+ }
3014
+
3015
+ function validateAssetViolations(assetType, inspected, media = null) {
3016
+ const violations = [];
3017
+ const format = normalizeFileFormat(inspected.format ?? path.extname(inspected.filePath));
3018
+ if (assetType === ASSET_TYPE_CODES.Image) {
3019
+ if (inspected.size >= ASSET_IMAGE_MAX_BYTES) {
3020
+ addAssetViolation(violations, 'image_size', `图片素材过大:${mb(inspected.size)}`, '单张图片必须小于 30MB。');
3021
+ }
3022
+ if (!media?.width || !media?.height) {
3023
+ addAssetViolation(violations, 'image_dimensions_unknown', '图片宽高无法识别', '请确认文件可被 ffprobe 或本地图片解析器解析。');
3024
+ } else {
3025
+ validateMediaGeometry(violations, media, '图片');
3026
+ }
3027
+ } else if (assetType === ASSET_TYPE_CODES.Video) {
3028
+ if (inspected.size > ASSET_VIDEO_MAX_BYTES) {
3029
+ addAssetViolation(violations, 'video_size', `视频素材过大:${mb(inspected.size)}`, '单个视频不能超过 50MB。');
3030
+ }
3031
+ if (!media?.width || !media?.height) {
3032
+ addAssetViolation(violations, 'video_dimensions_unknown', '视频宽高无法识别', '请确认文件可被 ffprobe 解析。');
3033
+ } else {
3034
+ validateMediaGeometry(violations, media, '视频', { videoPixels: true });
3035
+ }
3036
+ if (media?.fps == null || media.fps + 0.05 < ASSET_VIDEO_MIN_FPS || media.fps - 0.05 > ASSET_VIDEO_MAX_FPS) {
3037
+ addAssetViolation(
3038
+ violations,
3039
+ 'video_fps',
3040
+ `视频帧率不支持:${media?.fps == null ? 'unknown' : `${roundNumber(media.fps)}fps`}`,
3041
+ '视频 FPS 必须在 [24,60]。',
3042
+ );
3043
+ }
3044
+ if (media?.duration == null || media.duration < ASSET_VIDEO_MIN_SECONDS || media.duration > ASSET_VIDEO_MAX_SECONDS) {
3045
+ addAssetViolation(
3046
+ violations,
3047
+ 'video_duration',
3048
+ `视频时长不支持:${media?.duration == null ? 'unknown' : `${roundNumber(media.duration)}s`}`,
3049
+ '单个视频时长必须在 [2,15] 秒。',
3050
+ );
3051
+ }
3052
+ } else if (assetType === ASSET_TYPE_CODES.Audio) {
3053
+ if (media?.duration == null || media.duration < ASSET_AUDIO_MIN_SECONDS || media.duration > ASSET_AUDIO_MAX_SECONDS) {
3054
+ addAssetViolation(
3055
+ violations,
3056
+ 'audio_duration',
3057
+ `音频时长不支持:${media?.duration == null ? 'unknown' : `${roundNumber(media.duration)}s`}`,
3058
+ '单个音频时长必须在 [2,15] 秒。',
3059
+ );
3060
+ }
3061
+ }
3062
+ return {
3063
+ legal: violations.length === 0,
3064
+ assetType,
3065
+ format,
3066
+ inspected,
3067
+ media: media ? compactRecord(media) : null,
3068
+ violations,
3069
+ };
3070
+ }
3071
+
3072
+ function buildAssetConversionPlan(validation) {
3073
+ const { assetType, media, inspected } = validation;
3074
+ if (!media?.width && assetType !== ASSET_TYPE_CODES.Audio) return null;
3075
+ if (assetType === ASSET_TYPE_CODES.Image) {
3076
+ const target = chooseLegalMediaBox(media.width, media.height);
3077
+ return compactRecord({
3078
+ assetType,
3079
+ fromFormat: normalizeDisplayFormat(inspected.format ?? path.extname(inspected.filePath)) || 'unknown',
3080
+ toFormat: 'jpg',
3081
+ targetWidth: target.width,
3082
+ targetHeight: target.height,
3083
+ sourceFile: inspected.filePath,
3084
+ reason: validation.violations.map((item) => item.message).join(';'),
3085
+ filters: `scale=${target.width}:${target.height}:force_original_aspect_ratio=decrease,pad=${target.width}:${target.height}:(ow-iw)/2:(oh-ih)/2:black,setsar=1`,
3086
+ });
3087
+ }
3088
+ if (assetType === ASSET_TYPE_CODES.Video) {
3089
+ const target = chooseLegalVideoBox(media.width, media.height);
3090
+ const targetFps = clampNumber(Number(media.fps ?? ASSET_VIDEO_MIN_FPS), ASSET_VIDEO_MIN_FPS, ASSET_VIDEO_MAX_FPS);
3091
+ const targetDuration = clampNumber(Number(media.duration ?? ASSET_VIDEO_MIN_SECONDS), ASSET_VIDEO_MIN_SECONDS, ASSET_VIDEO_MAX_SECONDS);
3092
+ const filters = [
3093
+ `fps=${roundNumber(targetFps, 3)}`,
3094
+ `scale=${target.width}:${target.height}:force_original_aspect_ratio=decrease`,
3095
+ `pad=${target.width}:${target.height}:(ow-iw)/2:(oh-ih)/2:black`,
3096
+ 'setsar=1',
3097
+ ];
3098
+ if (media.duration != null && media.duration < ASSET_VIDEO_MIN_SECONDS) {
3099
+ filters.push(`tpad=stop_mode=clone:stop_duration=${roundNumber(ASSET_VIDEO_MIN_SECONDS - media.duration, 3)}`);
3100
+ }
3101
+ return compactRecord({
3102
+ assetType,
3103
+ fromFormat: normalizeDisplayFormat(inspected.format ?? path.extname(inspected.filePath)) || 'unknown',
3104
+ toFormat: 'mp4',
3105
+ sourceDuration: media.duration,
3106
+ targetWidth: target.width,
3107
+ targetHeight: target.height,
3108
+ targetPixels: target.width * target.height,
3109
+ targetFps: Number(roundNumber(targetFps, 3)),
3110
+ targetDuration,
3111
+ sourceFile: inspected.filePath,
3112
+ reason: validation.violations.map((item) => item.message).join(';'),
3113
+ filters: filters.join(','),
3114
+ });
3115
+ }
3116
+ if (assetType === ASSET_TYPE_CODES.Audio) {
3117
+ return compactRecord({
3118
+ assetType,
3119
+ fromFormat: normalizeDisplayFormat(inspected.format ?? path.extname(inspected.filePath)) || 'unknown',
3120
+ toFormat: 'wav',
3121
+ sourceDuration: media?.duration,
3122
+ targetDuration: clampNumber(Number(media?.duration ?? ASSET_AUDIO_MIN_SECONDS), ASSET_AUDIO_MIN_SECONDS, ASSET_AUDIO_MAX_SECONDS),
3123
+ sourceFile: inspected.filePath,
3124
+ reason: validation.violations.map((item) => item.message).join(';'),
3125
+ });
3126
+ }
3127
+ return null;
3128
+ }
3129
+
3130
+ function dryRunAssetFileName(source) {
3131
+ const plan = source.conversionPlan;
3132
+ if (!plan?.toFormat) return source.localFile?.filePath;
3133
+ return forceFileExtension(source.localFile?.fileName || source.localFile?.filePath || 'asset', `.${conversionOutputExtension(plan.toFormat)}`);
3134
+ }
3135
+
3136
+ async function convertLocalVideoFile(filePath, plan) {
3137
+ const ffmpegCommand = await ensureFfmpegAvailable();
3138
+ const outputPath = path.join(tmpdir(), `lj-awb-${crypto.randomUUID()}.mp4`);
3139
+ const args = [
3140
+ '-y',
3141
+ '-hide_banner',
3142
+ '-loglevel',
3143
+ 'error',
3144
+ '-i',
3145
+ filePath,
3146
+ '-vf',
3147
+ plan.filters,
3148
+ '-map',
3149
+ '0:v:0',
3150
+ '-map',
3151
+ '0:a?',
3152
+ '-c:v',
3153
+ 'libx264',
3154
+ '-pix_fmt',
3155
+ 'yuv420p',
3156
+ '-preset',
3157
+ 'medium',
3158
+ '-crf',
3159
+ '20',
3160
+ '-movflags',
3161
+ '+faststart',
3162
+ ];
3163
+ if (Number.isFinite(Number(plan.sourceDuration)) && plan.sourceDuration > ASSET_VIDEO_MAX_SECONDS) {
3164
+ args.push('-t', String(ASSET_VIDEO_MAX_SECONDS));
3165
+ } else if (Number.isFinite(Number(plan.sourceDuration)) && plan.sourceDuration < ASSET_VIDEO_MIN_SECONDS) {
3166
+ args.push('-t', String(ASSET_VIDEO_MIN_SECONDS));
3167
+ }
3168
+ args.push('-c:a', 'aac', '-b:a', '128k', outputPath);
3169
+ try {
3170
+ await execFileAsync(ffmpegCommand, args, { timeout: 15 * 60_000, maxBuffer: 8 * 1024 * 1024 });
3171
+ } catch (error) {
3172
+ await fs.rm(outputPath, { force: true }).catch(() => {});
3173
+ throw argumentError(
3174
+ `视频格式转换失败:${path.basename(filePath)}`,
3175
+ `请确认本机可用 ffmpeg,或手动转换后重试。${error?.message ? ` 原因:${error.message}` : ''}`,
3176
+ );
3177
+ }
3178
+ const inspected = await inspectLocalFile(outputPath);
3179
+ if (!inspected.exists) {
3180
+ throw argumentError(`视频格式转换失败:${path.basename(filePath)}`, '未生成目标视频文件。');
3181
+ }
3182
+ return inspected;
3183
+ }
3184
+
3185
+ async function convertLocalAudioFile(filePath, plan) {
3186
+ const ffmpegCommand = await ensureFfmpegAvailable();
3187
+ const outputPath = path.join(tmpdir(), `lj-awb-${crypto.randomUUID()}.wav`);
3188
+ const args = [
3189
+ '-y',
3190
+ '-hide_banner',
3191
+ '-loglevel',
3192
+ 'error',
3193
+ '-i',
3194
+ filePath,
3195
+ ];
3196
+ if (Number.isFinite(Number(plan.sourceDuration)) && plan.sourceDuration < ASSET_AUDIO_MIN_SECONDS) {
3197
+ args.push('-af', 'apad');
3198
+ args.push('-t', String(ASSET_AUDIO_MIN_SECONDS));
3199
+ } else if (Number.isFinite(Number(plan.sourceDuration)) && plan.sourceDuration > ASSET_AUDIO_MAX_SECONDS) {
3200
+ args.push('-t', String(ASSET_AUDIO_MAX_SECONDS));
3201
+ }
3202
+ args.push('-c:a', 'pcm_s16le', outputPath);
3203
+ try {
3204
+ await execFileAsync(ffmpegCommand, args, { timeout: 15 * 60_000, maxBuffer: 8 * 1024 * 1024 });
3205
+ } catch (error) {
3206
+ await fs.rm(outputPath, { force: true }).catch(() => {});
3207
+ throw argumentError(
3208
+ `音频格式转换失败:${path.basename(filePath)}`,
3209
+ `请确认本机可用 ffmpeg,或手动转换后重试。${error?.message ? ` 原因:${error.message}` : ''}`,
3210
+ );
3211
+ }
3212
+ const inspected = await inspectLocalFile(outputPath);
3213
+ if (!inspected.exists) {
3214
+ throw argumentError(`音频格式转换失败:${path.basename(filePath)}`, '未生成目标音频文件。');
3215
+ }
3216
+ return inspected;
3217
+ }
3218
+
3219
+ async function convertLocalImageFile(filePath, targetFormat, options = {}) {
3220
+ const ffmpegCommand = await ensureFfmpegAvailable();
3221
+ const target = normalizeFileFormat(targetFormat) || 'jpg';
3222
+ const outputPath = options.outputPath || path.join(tmpdir(), `lj-awb-${crypto.randomUUID()}.${conversionOutputExtension(target)}`);
3223
+ const codecArgs = target === 'jpg' ? ['-q:v', String(options.quality ?? 2)] : [];
3224
+ const filterArgs = options.filters ? ['-vf', options.filters] : [];
3225
+ try {
3226
+ await execFileAsync(ffmpegCommand, [
3227
+ '-y',
3228
+ '-hide_banner',
3229
+ '-loglevel',
3230
+ 'error',
3231
+ '-i',
3232
+ filePath,
3233
+ ...filterArgs,
3234
+ '-frames:v',
3235
+ '1',
3236
+ ...codecArgs,
3237
+ outputPath,
3238
+ ], { timeout: 10 * 60_000, maxBuffer: 8 * 1024 * 1024 });
3239
+ } catch (error) {
3240
+ await fs.rm(outputPath, { force: true }).catch(() => {});
3241
+ throw argumentError(
3242
+ `图片格式转换失败:${path.basename(filePath)}`,
3243
+ `需要把该图片转换为 ${target} 后提交。请确认本机可用 ffmpeg,或手动转换后重试。${error?.message ? ` 原因:${error.message}` : ''}`,
3244
+ );
3245
+ }
3246
+ const inspected = await inspectLocalFile(outputPath);
3247
+ if (!inspected.exists) {
3248
+ throw argumentError(`图片格式转换失败:${path.basename(filePath)}`, `未生成 ${target} 文件。`);
3249
+ }
3250
+ return inspected;
3251
+ }
3252
+
3253
+ async function inspectAssetLocalFile(localFile) {
3254
+ const inspected = await inspectLocalFile(localFile);
3255
+ if (!inspected.exists) throw argumentError(`文件不存在:${localFile}`);
3256
+ const ext = sourceExtension(inspected.filePath);
3257
+ const assetType = inferAssetTypeFromSource(inspected.filePath);
3258
+ if (assetType === ASSET_TYPE_CODES.Image) {
3259
+ const media = await readImageMetadata(inspected.filePath);
3260
+ const validation = validateAssetViolations(assetType, inspected, media);
3261
+ return {
3262
+ ...validation,
3263
+ localFile: inspected,
3264
+ media,
3265
+ conversionPlan: validation.legal ? null : buildAssetConversionPlan(validation),
3266
+ };
3267
+ }
3268
+ if (assetType === ASSET_TYPE_CODES.Video) {
3269
+ const media = await readMediaMetadata(inspected.filePath, assetType);
3270
+ const validation = validateAssetViolations(assetType, inspected, media);
3271
+ return {
3272
+ ...validation,
3273
+ localFile: inspected,
3274
+ media,
3275
+ conversionPlan: validation.legal ? null : buildAssetConversionPlan(validation),
3276
+ };
3277
+ }
3278
+ if (assetType === ASSET_TYPE_CODES.Audio) {
3279
+ const media = await readMediaMetadata(inspected.filePath, assetType);
3280
+ const validation = validateAssetViolations(assetType, inspected, media);
3281
+ return {
3282
+ ...validation,
3283
+ localFile: inspected,
3284
+ media,
3285
+ conversionPlan: validation.legal ? null : buildAssetConversionPlan(validation),
3286
+ };
3287
+ }
3288
+ throw argumentError(`不支持的素材格式:${ext}`);
3289
+ }
3290
+
3291
+ function assetValidationSummary(validation) {
3292
+ return validation.violations.map((item) => item.message).join(';');
3293
+ }
3294
+
3295
+ function assetConversionUnavailableError(validation) {
3296
+ const summary = assetValidationSummary(validation);
3297
+ return argumentError(
3298
+ `素材不符合 JIMENG 加白规格:${summary || '规格不合法'}`,
3299
+ 'CLI 无法自动生成转码计划,请手动转换为合法图片 / 视频 / 音频规格后重试。',
3300
+ );
3301
+ }
3302
+
3303
+ async function confirmAssetConversion(validation) {
3304
+ if (process.stdin.isTTY !== true || process.stderr.isTTY !== true) {
3305
+ throw argumentError(
3306
+ `素材不符合 JIMENG 加白规格:${assetValidationSummary(validation)}`,
3307
+ '非交互终端不会自动询问。请在终端中重试并确认转码,或追加 --auto-convert 自动转换后继续。',
3308
+ );
3309
+ }
3310
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
3311
+ try {
3312
+ const answer = await rl.question(`素材不符合 JIMENG 加白规格:${assetValidationSummary(validation)}\n是否自动转码为合法规格后继续?[y/N] `);
3313
+ return ['y', 'yes'].includes(String(answer || '').trim().toLowerCase());
3314
+ } finally {
3315
+ rl.close();
3316
+ }
3317
+ }
3318
+
3319
+ async function convertAssetLocalFile(validation) {
3320
+ const plan = validation.conversionPlan;
3321
+ if (!plan) throw assetConversionUnavailableError(validation);
3322
+ let converted;
3323
+ if (validation.assetType === ASSET_TYPE_CODES.Image) {
3324
+ converted = await convertLocalImageFile(validation.localFile.filePath, plan.toFormat, { filters: plan.filters });
3325
+ } else if (validation.assetType === ASSET_TYPE_CODES.Video) {
3326
+ converted = await convertLocalVideoFile(validation.localFile.filePath, plan);
3327
+ } else if (validation.assetType === ASSET_TYPE_CODES.Audio) {
3328
+ converted = await convertLocalAudioFile(validation.localFile.filePath, plan);
3329
+ } else {
3330
+ throw assetConversionUnavailableError(validation);
3331
+ }
3332
+ const nextValidation = await inspectAssetLocalFile(converted.filePath);
3333
+ if (!nextValidation.legal) {
3334
+ await fs.rm(converted.filePath, { force: true }).catch(() => {});
3335
+ throw argumentError(
3336
+ `素材自动转码后仍不符合加白规格:${assetValidationSummary(nextValidation)}`,
3337
+ '请手动转换为合法规格后重试,或检查原始素材是否损坏。',
3338
+ );
3339
+ }
3340
+ return {
3341
+ ...nextValidation,
3342
+ originalLocalFile: validation.localFile,
3343
+ conversion: compactRecord({
3344
+ ...plan,
3345
+ converted: true,
3346
+ convertedFile: converted.filePath,
3347
+ convertedSize: converted.size,
3348
+ originalSize: validation.localFile.size,
3349
+ }),
3350
+ };
3351
+ }
3352
+
3353
+ async function resolveInvalidAssetLocalFile(validation, kwargs = {}) {
3354
+ if (validation.legal) return validation;
3355
+ if (!validation.conversionPlan) throw assetConversionUnavailableError(validation);
3356
+ const shouldConvert = toBool(kwargs.autoConvert) || await confirmAssetConversion(validation);
3357
+ if (!shouldConvert) {
3358
+ throw argumentError(
3359
+ `素材不符合 JIMENG 加白规格:${assetValidationSummary(validation)}`,
3360
+ '已取消自动转码。请手动转换素材,或追加 --auto-convert 自动转换后继续。',
3361
+ );
3362
+ }
3363
+ return await convertAssetLocalFile(validation);
3364
+ }
3365
+
3366
+ function validateAssetRemoteSource(assetPath) {
3367
+ return { assetType: inferAssetTypeFromSource(assetPath) };
3368
+ }
3369
+
2565
3370
  export async function uploadFilesCommand(kwargs = {}) {
2566
3371
  const specs = await collectFileSpecs(kwargs, trimToNull(kwargs.sceneType));
2567
3372
  if (!specs.length) throw argumentError('缺少上传文件', '传 --file <path> 或 --files a.png,b.mp4。');
@@ -2644,14 +3449,26 @@ function isHttpUrl(value) {
2644
3449
  return /^https?:\/\//i.test(String(value || '').trim());
2645
3450
  }
2646
3451
 
3452
+ function backendObjectName(value) {
3453
+ const text = trimToNull(value);
3454
+ if (!text) return null;
3455
+ return text.replace(/^\/+/, '');
3456
+ }
3457
+
3458
+ function isPlatformBackendPath(value) {
3459
+ const objectName = backendObjectName(value);
3460
+ if (!objectName || /^[a-z][a-z0-9+.-]*:\/\//i.test(objectName)) return false;
3461
+ return PLATFORM_BACKEND_PATH_PREFIXES.some((prefix) => objectName.startsWith(prefix));
3462
+ }
3463
+
2647
3464
  function isUploadedMaterialReference(value) {
2648
3465
  const text = trimToNull(value);
2649
3466
  if (!text) return false;
2650
- if (text.startsWith('material/') || text.startsWith('/material/')) return true;
3467
+ if (isPlatformBackendPath(text)) return true;
2651
3468
  if (!isHttpUrl(text)) return false;
2652
3469
  try {
2653
3470
  const url = new URL(text);
2654
- return url.hostname.endsWith('.myqcloud.com');
3471
+ return url.hostname.endsWith('.myqcloud.com') && isPlatformBackendPath(decodeURIComponent(url.pathname));
2655
3472
  } catch {
2656
3473
  return false;
2657
3474
  }
@@ -2752,8 +3569,8 @@ async function resolveRemoteResourceDownloadUrl(value) {
2752
3569
  const text = trimToNull(value);
2753
3570
  if (!text) throw argumentError('远程图片来源为空');
2754
3571
  if (/^https?:\/\//i.test(text)) return text;
2755
- if (text.startsWith('material/') || text.startsWith('/material/')) {
2756
- const objectName = text.replace(/^\/+/, '');
3572
+ if (isPlatformBackendPath(text)) {
3573
+ const objectName = backendObjectName(text);
2757
3574
  const signed = await awbApi.fetchObjectSignUrl(objectName);
2758
3575
  const signedUrl = firstHttpUrl(signed);
2759
3576
  if (signedUrl) return signedUrl;
@@ -2765,7 +3582,7 @@ async function resolveRemoteResourceDownloadUrl(value) {
2765
3582
  }
2766
3583
  throw argumentError(
2767
3584
  `远程图片来源不支持自动转换:${text}`,
2768
- '请传 http(s) URL、material backendPath,或先下载为本地文件后重试。',
3585
+ '请传 http(s) URL、平台 backendPath,或先下载为本地文件后重试。',
2769
3586
  );
2770
3587
  }
2771
3588
 
@@ -2826,7 +3643,7 @@ async function downloadRemoteImageFileToTemp(sourceValue, options = {}) {
2826
3643
  throw new LingjingAwbCliError(`下载远程图片失败:${error.message}`, {
2827
3644
  type: 'network_error',
2828
3645
  exitCode: 30,
2829
- hint: isAbort ? `远程下载超过 ${timeoutMs}ms,请改用本地文件或已上传 material 路径。` : '',
3646
+ hint: isAbort ? `远程下载超过 ${timeoutMs}ms,请改用本地文件或已上传平台 backendPath。` : '',
2830
3647
  details: { url: sourceValue, causeCode: error?.cause?.code },
2831
3648
  });
2832
3649
  } finally {
@@ -2888,7 +3705,7 @@ async function downloadRemoteFileToTemp(remoteUrl, options = {}) {
2888
3705
  throw new LingjingAwbCliError(`下载远程音频失败:${error.message}`, {
2889
3706
  type: 'network_error',
2890
3707
  exitCode: 30,
2891
- hint: isAbort ? `远程下载超过 ${timeoutMs}ms,请改用本地 --file 或已上传 material 路径。` : '',
3708
+ hint: isAbort ? `远程下载超过 ${timeoutMs}ms,请改用本地 --file 或已上传平台 backendPath。` : '',
2892
3709
  details: { url: remoteUrl, causeCode: error?.cause?.code },
2893
3710
  });
2894
3711
  } finally {
@@ -2964,7 +3781,7 @@ function parseModelParamAssignments(value) {
2964
3781
  }
2965
3782
 
2966
3783
  async function collectGenericModelParams(kwargs = {}) {
2967
- const fromJson = await parseModelParamsJsonArg(kwargs.modelParamsJson);
3784
+ const fromJson = await parseModelParamsJsonArg(kwargs.modelParamsJson ?? kwargs.model_params_json);
2968
3785
  const fromObject = kwargs.modelParams && typeof kwargs.modelParams === 'object' && !Array.isArray(kwargs.modelParams)
2969
3786
  ? kwargs.modelParams
2970
3787
  : {};
@@ -3022,7 +3839,7 @@ function normalizeResourceSource(source, type, index, options = {}) {
3022
3839
  if (!['url', 'asset_id'].includes(kind)) {
3023
3840
  throw argumentError(
3024
3841
  `resource[${index}] source.kind 不支持:${explicitKind}`,
3025
- '只支持 url、asset_id 两个值。本地文件 / http(s) URL / material backendPath 都统一传 kind=url(CLI 按 value 自动识别);平台资产或主体对象传 kind=asset_id。',
3842
+ '只支持 url、asset_id 两个值。本地文件 / http(s) URL / 平台 backendPath 都统一传 kind=url(CLI 按 value 自动识别);平台资产或主体对象传 kind=asset_id。',
3026
3843
  );
3027
3844
  }
3028
3845
  const value = kind === 'asset_id' ? assetValue : rawValue;
@@ -3183,17 +4000,16 @@ function isRemoteOrBackendPath(value) {
3183
4000
  if (!text) return false;
3184
4001
  return /^https?:\/\//i.test(text)
3185
4002
  || /^[a-z][a-z0-9+.-]*:\/\//i.test(text)
3186
- || text.startsWith('material/')
3187
- || text.startsWith('/material/');
4003
+ || isPlatformBackendPath(text);
3188
4004
  }
3189
4005
 
3190
- function normalizeMaterialUrlValue(value) {
4006
+ function normalizeBackendPathUrlValue(value) {
3191
4007
  const text = trimToNull(value);
3192
4008
  if (!text) return text;
3193
4009
  if (/^https?:\/\//i.test(text)) {
3194
4010
  try {
3195
4011
  const pathname = decodeURIComponent(new URL(text).pathname);
3196
- if (pathname.startsWith('/material/')) return pathname;
4012
+ if (isPlatformBackendPath(pathname)) return pathname;
3197
4013
  } catch {}
3198
4014
  }
3199
4015
  return text;
@@ -3217,37 +4033,6 @@ function conversionOutputExtension(format) {
3217
4033
  return normalized || 'jpg';
3218
4034
  }
3219
4035
 
3220
- async function convertLocalImageFile(filePath, targetFormat) {
3221
- const target = normalizeFileFormat(targetFormat) || 'jpg';
3222
- const outputPath = path.join(tmpdir(), `lj-awb-${crypto.randomUUID()}.${conversionOutputExtension(target)}`);
3223
- const codecArgs = target === 'jpg' ? ['-q:v', '2'] : [];
3224
- try {
3225
- await execFileAsync('ffmpeg', [
3226
- '-y',
3227
- '-hide_banner',
3228
- '-loglevel',
3229
- 'error',
3230
- '-i',
3231
- filePath,
3232
- '-frames:v',
3233
- '1',
3234
- ...codecArgs,
3235
- outputPath,
3236
- ]);
3237
- } catch (error) {
3238
- await fs.rm(outputPath, { force: true }).catch(() => {});
3239
- throw argumentError(
3240
- `图片格式转换失败:${path.basename(filePath)}`,
3241
- `需要把该帧图片转换为 ${target} 后提交。请确认本机可用 ffmpeg,或手动转换后重试。${error?.message ? ` 原因:${error.message}` : ''}`,
3242
- );
3243
- }
3244
- const inspected = await inspectLocalFile(outputPath);
3245
- if (!inspected.exists) {
3246
- throw argumentError(`图片格式转换失败:${path.basename(filePath)}`, `未生成 ${target} 文件。`);
3247
- }
3248
- return inspected;
3249
- }
3250
-
3251
4036
  async function resolveResourceFileValue(resource, options = {}) {
3252
4037
  if (resource.type === 'subject') {
3253
4038
  if (resource._source.kind !== 'asset_id') throw argumentError('subject resource 必须使用 asset_id,例如 subject:reference:hero=asset:element_123');
@@ -3329,13 +4114,13 @@ async function resolveResourceFileValue(resource, options = {}) {
3329
4114
  await fs.rm(downloaded.dir, { recursive: true, force: true }).catch(() => {});
3330
4115
  }
3331
4116
  }
3332
- return { resource: { ...base, source: { kind: 'url', value: normalizeMaterialUrlValue(value) } }, upload: null, localFile: null };
4117
+ return { resource: { ...base, source: { kind: 'url', value: normalizeBackendPathUrlValue(value) } }, upload: null, localFile: null };
3333
4118
  }
3334
4119
  const inspected = await inspectLocalFile(value);
3335
4120
  if (!inspected.exists) {
3336
4121
  throw argumentError(
3337
4122
  `资源文件不存在:${value}`,
3338
- 'source.kind=url 只接受完整 http(s) URL、material backendPath,或当前工作目录下存在的本地文件路径。',
4123
+ 'source.kind=url 只接受完整 http(s) URL、平台 backendPath,或当前工作目录下存在的本地文件路径。',
3339
4124
  );
3340
4125
  }
3341
4126
  const conversion = options.resourceRules
@@ -3818,6 +4603,7 @@ function normalizeTaskBatchItem(item, kind, index) {
3818
4603
  if (next.need_audio != null && next.needAudio == null) next.needAudio = next.need_audio;
3819
4604
  if (next.model_param != null && next.modelParam == null) next.modelParam = next.model_param;
3820
4605
  if (next.model_params != null && next.modelParams == null) next.modelParams = next.model_params;
4606
+ if (next.model_params_json != null && next.modelParamsJson == null) next.modelParamsJson = next.model_params_json;
3821
4607
  return next;
3822
4608
  }
3823
4609
 
@@ -4072,7 +4858,8 @@ function normalizeCosAssetPath(value) {
4072
4858
  if (!text) return null;
4073
4859
  if (/^https?:\/\//i.test(text)) {
4074
4860
  try {
4075
- return decodeURIComponent(new URL(text).pathname.replace(/^\/+/, ''));
4861
+ const pathname = decodeURIComponent(new URL(text).pathname);
4862
+ return isPlatformBackendPath(pathname) ? pathname.replace(/^\/+/, '') : text;
4076
4863
  } catch {
4077
4864
  return text.replace(/^\/+/, '');
4078
4865
  }
@@ -4360,37 +5147,68 @@ export async function assetRegister(kwargs = {}) {
4360
5147
  const localFile = trimToNull(kwargs.file);
4361
5148
  const assetPath = trimToNull(kwargs.backendPath) ?? normalizeCosAssetPath(kwargs.url);
4362
5149
  if (!localFile && !assetPath) throw argumentError('缺少素材路径', '传 --file、--backend-path 或 --url。');
5150
+ let source = localFile ? await inspectAssetLocalFile(localFile) : validateAssetRemoteSource(assetPath);
4363
5151
  if (toBool(kwargs.dryRun)) {
5152
+ const dryRunFileName = localFile ? dryRunAssetFileName(source) : null;
5153
+ const url = localFile ? normalizeCosAssetPath(dryRunBackendPath(dryRunFileName, TASK_UPLOAD_SCENE.ASSET_REVIEW)) : assetPath;
4364
5154
  return {
4365
5155
  dryRun: true,
4366
5156
  action: 'create asset',
5157
+ groupId,
5158
+ name,
5159
+ platform,
5160
+ assetType: source.assetType,
5161
+ assetPath: url,
4367
5162
  request: {
4368
5163
  assetGroupsId: groupId,
4369
- url: localFile ? normalizeCosAssetPath(dryRunBackendPath(localFile, TASK_UPLOAD_SCENE.ASSET_REVIEW)) : assetPath,
5164
+ url,
4370
5165
  name,
4371
5166
  platform,
5167
+ assetType: source.assetType,
4372
5168
  },
4373
- localFile: localFile ? await inspectLocalFile(localFile) : null,
5169
+ localFile: source.localFile ?? null,
5170
+ originalLocalFile: source.originalLocalFile ?? null,
5171
+ media: source.media ?? null,
5172
+ validation: source.legal === false ? {
5173
+ legal: false,
5174
+ violations: source.violations,
5175
+ } : { legal: true },
5176
+ conversionPlan: source.conversionPlan ?? null,
4374
5177
  };
4375
5178
  }
4376
- ensureConfirmed(kwargs, '注册素材是云端写入动作,需要确认', { action: 'create asset', groupId, name });
4377
- const uploaded = localFile ? await uploadLocalFile(localFile, { sceneType: TASK_UPLOAD_SCENE.ASSET_REVIEW }) : null;
4378
- const body = {
4379
- assetGroupsId: groupId,
4380
- url: normalizeCosAssetPath(uploaded?.backendPath ?? assetPath),
4381
- name,
4382
- platform,
4383
- };
4384
- const payload = await awbApi.registerAsset(body);
4385
- return {
4386
- registered: true,
4387
- assetId: extractAssetId(payload),
4388
- groupId,
4389
- name,
4390
- platform,
4391
- assetPath: body.url,
4392
- ...(uploaded ? { upload: uploaded } : {}),
4393
- };
5179
+ if (localFile && source.legal === false) {
5180
+ source = await resolveInvalidAssetLocalFile(source, kwargs);
5181
+ }
5182
+ ensureConfirmed(kwargs, '注册素材是云端写入动作,需要确认', { action: 'create asset', groupId, name, assetType: source.assetType });
5183
+ const uploadPath = source.localFile?.filePath ?? localFile;
5184
+ let uploaded = null;
5185
+ try {
5186
+ uploaded = localFile ? await uploadLocalFile(uploadPath, { sceneType: TASK_UPLOAD_SCENE.ASSET_REVIEW }) : null;
5187
+ const body = {
5188
+ assetGroupsId: groupId,
5189
+ url: normalizeCosAssetPath(uploaded?.backendPath ?? assetPath),
5190
+ name,
5191
+ platform,
5192
+ assetType: source.assetType,
5193
+ };
5194
+ const payload = await awbApi.registerAsset(body);
5195
+ return {
5196
+ registered: true,
5197
+ assetId: extractAssetId(payload),
5198
+ groupId,
5199
+ name,
5200
+ platform,
5201
+ assetType: source.assetType,
5202
+ assetPath: body.url,
5203
+ media: source.media ?? null,
5204
+ ...(source.conversion ? { conversion: source.conversion } : {}),
5205
+ ...(uploaded ? { upload: uploaded } : {}),
5206
+ };
5207
+ } finally {
5208
+ if (source.conversion?.convertedFile) {
5209
+ await fs.rm(source.conversion.convertedFile, { force: true }).catch(() => {});
5210
+ }
5211
+ }
4394
5212
  }
4395
5213
 
4396
5214
  export async function subjectList(kwargs = {}) {
@@ -4931,3 +5749,99 @@ export async function subtitleStatus(kwargs = {}) {
4931
5749
  taskType: 'VIDEO_SUBTITLE_REMOVAL',
4932
5750
  });
4933
5751
  }
5752
+
5753
+ export async function videoSuperResolutionStatus(kwargs = {}) {
5754
+ const taskId = requireValue(kwargs, 'taskId', 'task-id');
5755
+ return taskStatus({
5756
+ ...kwargs,
5757
+ taskId,
5758
+ taskType: 'VIDEO_SUPER_RESOLUTION',
5759
+ });
5760
+ }
5761
+
5762
+ async function buildVideoSuperResolutionRequest(kwargs = {}, options = {}) {
5763
+ const objectName = trimToNull(kwargs.objectName);
5764
+ if (!objectName) {
5765
+ throw argumentError('缺少视频对象路径', '传 --object-name <objectName>;通常是 material 的 backendPath 或 COS 对象路径。');
5766
+ }
5767
+ const dryRun = Boolean(options.dryRun);
5768
+ const projectGroupNo = await resolveProjectGroupNo(kwargs.projectGroupNo, {
5769
+ allowNull: true,
5770
+ noNetwork: dryRun,
5771
+ noSave: dryRun,
5772
+ }).catch((error) => {
5773
+ if (dryRun) return null;
5774
+ throw error;
5775
+ });
5776
+ return {
5777
+ objectName,
5778
+ projectGroupNo,
5779
+ request: compactRecord({
5780
+ objectName,
5781
+ projectGroupNo,
5782
+ }),
5783
+ };
5784
+ }
5785
+
5786
+ export async function videoSuperResolutionFee(kwargs = {}) {
5787
+ const built = await buildVideoSuperResolutionRequest(kwargs, { dryRun: toBool(kwargs.dryRun) });
5788
+ if (toBool(kwargs.dryRun)) {
5789
+ return {
5790
+ dryRun: true,
5791
+ action: 'create video-super-resolution-fee',
5792
+ objectName: built.objectName,
5793
+ projectGroupNo: built.projectGroupNo,
5794
+ request: built.request,
5795
+ materialEndpoint: '/api/material/creation/videoUpResolutionCal',
5796
+ taskType: 'VIDEO_SUPER_RESOLUTION',
5797
+ };
5798
+ }
5799
+ const payload = await awbApi.fetchVideoSuperResolutionFee(built.request);
5800
+ return {
5801
+ objectName: built.objectName,
5802
+ projectGroupNo: built.projectGroupNo,
5803
+ data: payload,
5804
+ ...(await pointEstimate(payload, built.projectGroupNo)),
5805
+ };
5806
+ }
5807
+
5808
+ export async function videoSuperResolution(kwargs = {}) {
5809
+ const built = await buildVideoSuperResolutionRequest(kwargs, { dryRun: toBool(kwargs.dryRun) });
5810
+ if (toBool(kwargs.dryRun)) {
5811
+ return {
5812
+ dryRun: true,
5813
+ action: 'create video-super-resolution',
5814
+ objectName: built.objectName,
5815
+ projectGroupNo: built.projectGroupNo,
5816
+ request: built.request,
5817
+ materialEndpoint: '/api/material/creation/videoUpResolution',
5818
+ taskType: 'VIDEO_SUPER_RESOLUTION',
5819
+ };
5820
+ }
5821
+ ensureConfirmed(kwargs, '正式视频超分会通过 material 创建任务并消耗积分,需要确认', {
5822
+ action: 'create video-super-resolution',
5823
+ objectName: built.objectName,
5824
+ });
5825
+ const feePayload = await awbApi.fetchVideoSuperResolutionFee(built.request).catch(() => null);
5826
+ const estimate = await pointEstimate(feePayload, built.projectGroupNo).catch(() => ({}));
5827
+ const payload = await awbApi.createVideoSuperResolutionTask(built.request);
5828
+ const result = normalizeCreatedTask(payload, {
5829
+ ...estimate,
5830
+ submitted: true,
5831
+ taskType: 'VIDEO_SUPER_RESOLUTION',
5832
+ objectName: built.objectName,
5833
+ projectGroupNo: built.projectGroupNo,
5834
+ });
5835
+ await appendTaskRecord(kwargs, {
5836
+ taskId: result.taskId,
5837
+ taskType: 'VIDEO_SUPER_RESOLUTION',
5838
+ projectGroupNo: built.projectGroupNo,
5839
+ promptSummary: `视频超分 objectName=${built.objectName}`,
5840
+ });
5841
+ return {
5842
+ ...result,
5843
+ nextCommand: result.taskId
5844
+ ? `lj-awb task video-super-resolution-status --task-id ${result.taskId}${built.projectGroupNo ? ` --project-group-no ${built.projectGroupNo}` : ''} -f json`
5845
+ : null,
5846
+ };
5847
+ }