@lingjingai/lj-awb-cli 0.4.2 → 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,30 @@ 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;
75
100
  const PLATFORM_BACKEND_PATH_PREFIXES = [
76
101
  'material/',
77
102
  'material-image-draw/',
@@ -2580,6 +2605,768 @@ function dryRunBackendPath(filePath, sceneType) {
2580
2605
  return `/${sceneType}/__dry_run__/${safeFileName(filePath)}`;
2581
2606
  }
2582
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
+
2583
3370
  export async function uploadFilesCommand(kwargs = {}) {
2584
3371
  const specs = await collectFileSpecs(kwargs, trimToNull(kwargs.sceneType));
2585
3372
  if (!specs.length) throw argumentError('缺少上传文件', '传 --file <path> 或 --files a.png,b.mp4。');
@@ -3246,37 +4033,6 @@ function conversionOutputExtension(format) {
3246
4033
  return normalized || 'jpg';
3247
4034
  }
3248
4035
 
3249
- async function convertLocalImageFile(filePath, targetFormat) {
3250
- const target = normalizeFileFormat(targetFormat) || 'jpg';
3251
- const outputPath = path.join(tmpdir(), `lj-awb-${crypto.randomUUID()}.${conversionOutputExtension(target)}`);
3252
- const codecArgs = target === 'jpg' ? ['-q:v', '2'] : [];
3253
- try {
3254
- await execFileAsync('ffmpeg', [
3255
- '-y',
3256
- '-hide_banner',
3257
- '-loglevel',
3258
- 'error',
3259
- '-i',
3260
- filePath,
3261
- '-frames:v',
3262
- '1',
3263
- ...codecArgs,
3264
- outputPath,
3265
- ]);
3266
- } catch (error) {
3267
- await fs.rm(outputPath, { force: true }).catch(() => {});
3268
- throw argumentError(
3269
- `图片格式转换失败:${path.basename(filePath)}`,
3270
- `需要把该帧图片转换为 ${target} 后提交。请确认本机可用 ffmpeg,或手动转换后重试。${error?.message ? ` 原因:${error.message}` : ''}`,
3271
- );
3272
- }
3273
- const inspected = await inspectLocalFile(outputPath);
3274
- if (!inspected.exists) {
3275
- throw argumentError(`图片格式转换失败:${path.basename(filePath)}`, `未生成 ${target} 文件。`);
3276
- }
3277
- return inspected;
3278
- }
3279
-
3280
4036
  async function resolveResourceFileValue(resource, options = {}) {
3281
4037
  if (resource.type === 'subject') {
3282
4038
  if (resource._source.kind !== 'asset_id') throw argumentError('subject resource 必须使用 asset_id,例如 subject:reference:hero=asset:element_123');
@@ -4391,37 +5147,68 @@ export async function assetRegister(kwargs = {}) {
4391
5147
  const localFile = trimToNull(kwargs.file);
4392
5148
  const assetPath = trimToNull(kwargs.backendPath) ?? normalizeCosAssetPath(kwargs.url);
4393
5149
  if (!localFile && !assetPath) throw argumentError('缺少素材路径', '传 --file、--backend-path 或 --url。');
5150
+ let source = localFile ? await inspectAssetLocalFile(localFile) : validateAssetRemoteSource(assetPath);
4394
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;
4395
5154
  return {
4396
5155
  dryRun: true,
4397
5156
  action: 'create asset',
5157
+ groupId,
5158
+ name,
5159
+ platform,
5160
+ assetType: source.assetType,
5161
+ assetPath: url,
4398
5162
  request: {
4399
5163
  assetGroupsId: groupId,
4400
- url: localFile ? normalizeCosAssetPath(dryRunBackendPath(localFile, TASK_UPLOAD_SCENE.ASSET_REVIEW)) : assetPath,
5164
+ url,
4401
5165
  name,
4402
5166
  platform,
5167
+ assetType: source.assetType,
4403
5168
  },
4404
- 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,
4405
5177
  };
4406
5178
  }
4407
- ensureConfirmed(kwargs, '注册素材是云端写入动作,需要确认', { action: 'create asset', groupId, name });
4408
- const uploaded = localFile ? await uploadLocalFile(localFile, { sceneType: TASK_UPLOAD_SCENE.ASSET_REVIEW }) : null;
4409
- const body = {
4410
- assetGroupsId: groupId,
4411
- url: normalizeCosAssetPath(uploaded?.backendPath ?? assetPath),
4412
- name,
4413
- platform,
4414
- };
4415
- const payload = await awbApi.registerAsset(body);
4416
- return {
4417
- registered: true,
4418
- assetId: extractAssetId(payload),
4419
- groupId,
4420
- name,
4421
- platform,
4422
- assetPath: body.url,
4423
- ...(uploaded ? { upload: uploaded } : {}),
4424
- };
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
+ }
4425
5212
  }
4426
5213
 
4427
5214
  export async function subjectList(kwargs = {}) {
@@ -4962,3 +5749,99 @@ export async function subtitleStatus(kwargs = {}) {
4962
5749
  taskType: 'VIDEO_SUBTITLE_REMOVAL',
4963
5750
  });
4964
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
+ }