Repository navigation
Expand file tree
/
Copy pathcli.py
More file actions
1911 lines (1737 loc) · 70.8 KB
/
Copy pathcli.py
File metadata and controls
1911 lines (1737 loc) · 70.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import argparse
import copy
import json
import math
import os
import re
import shutil
import sys
from typing import TYPE_CHECKING, Any, Sequence
from uuid import UUID, uuid4
from loguru import logger
if TYPE_CHECKING:
from app.models.schema import MaterialInfo, VideoParams
DEFAULT_VOICE_NAME = "zh-CN-XiaoxiaoNeural-Female"
# 对应 webui/Main.py 的 VOICE_MODE_NONE 和 VOICE_MODE_UPLOAD。两端目前没有
# 共享这些常量,因此在这里保留字面值并注明来源。
UI_VOICE_MODE_NONE = "none"
# 字幕位置的内置默认值。VideoParams 也有同名默认值,但它是 Pydantic 字段
# 默认,只在模块导入时读取一次 config.ui:此时 config.toml 里的非法值会被
# 直接冻结进模型,既不会校验也无法在测试中替换。CLI 因此自己保存一份,
# 保证“非法保存值回退到默认值”对命令行始终成立。
DEFAULT_SUBTITLE_POSITION = "bottom"
DEFAULT_CUSTOM_POSITION = 70.0
UI_VOICE_MODE_UPLOAD = "upload"
# 这两种保存的配音方式都表示不要自动配音。
UI_VOICE_MODES_WITHOUT_TTS = frozenset({UI_VOICE_MODE_NONE, UI_VOICE_MODE_UPLOAD})
_PIPELINE_STAGES = ("script", "terms", "audio", "subtitle", "materials", "video")
_CUSTOM_AUDIO_EXTENSIONS = {".mp3", ".wav", ".m4a", ".aac", ".flac", ".ogg"}
_BATCH_FILE_MAX_BYTES = 1024 * 1024
_BATCH_TASK_MAX_COUNT = 100
# 单任务 argparse 和批量清单必须共享同一来源集合。此前两处手工维护导致
# openai_image 只在单任务入口可用;集中定义后,新增 Provider 不会再次遗漏
# 批量校验。这里仅包含 CLI 已公开支持的来源,不强行暴露 WebUI 专属流程。
_CLI_VIDEO_SOURCES = (
"pexels",
"pixabay",
"coverr",
"aigei",
"wavespeed",
"volcengine_seedance",
"ofox",
"infistar",
"jalapeno",
"metaso_minimax",
"muapi",
"useapi",
"openai_image",
"codex_image",
"useapi_image",
"local",
)
class _CliHelpFormatter(
argparse.ArgumentDefaultsHelpFormatter,
argparse.RawDescriptionHelpFormatter,
):
"""在保留多行示例排版的同时,自动展示有意义的默认值。"""
def _get_help_string(self, action):
help_text = action.help or ""
if (
"%(default)" not in help_text
and action.default not in (None, "", argparse.SUPPRESS)
and action.option_strings
and "default:" not in help_text.lower()
):
help_text += " (default: %(default)s)"
return help_text
def _positive_int(value: str) -> int:
parsed = int(value)
if parsed < 1:
raise argparse.ArgumentTypeError(f"value must be >= 1, got {parsed}")
return parsed
def _paragraph_count(value: str) -> int:
parsed = int(value)
if parsed < 1 or parsed > 10:
raise argparse.ArgumentTypeError(
f"paragraph-number must be between 1 and 10, got {parsed}"
)
return parsed
def _non_negative_float(value: str) -> float:
parsed = float(value)
if not math.isfinite(parsed) or parsed < 0:
raise argparse.ArgumentTypeError(f"value must be a finite number >= 0, got {value!r}")
return parsed
def _positive_float(value: str) -> float:
parsed = float(value)
if not math.isfinite(parsed) or parsed <= 0:
raise argparse.ArgumentTypeError(f"value must be a finite number > 0, got {value!r}")
return parsed
# 片段播放速度的取值范围。app/utils/utils.py 的 normalize_clip_speed() 用同一
# 范围做限幅,webui/Main.py 的滑块也使用 0.5~2.0。集中定义后,单任务参数、
# 批量清单校验和 [ui] 保存值不会再次出现取值不一致。
_CLIP_SPEED_MIN = 0.5
_CLIP_SPEED_MAX = 2.0
def _clip_speed(value: str) -> float:
parsed = float(value)
if not math.isfinite(parsed) or not _CLIP_SPEED_MIN <= parsed <= _CLIP_SPEED_MAX:
raise argparse.ArgumentTypeError(
"video-clip-speed must be a finite number between "
f"{_CLIP_SPEED_MIN} and {_CLIP_SPEED_MAX}, got {value!r}"
)
return parsed
def _percent_position(value: str) -> float:
parsed = float(value)
if not math.isfinite(parsed) or parsed < 0 or parsed > 100:
raise argparse.ArgumentTypeError(
f"custom-position must be a finite number between 0 and 100, got {value!r}"
)
return parsed
def _hex_color(value: str) -> str:
if not re.fullmatch(r"#[0-9a-fA-F]{6}", value):
raise argparse.ArgumentTypeError(
f"color must use #RRGGBB format, got {value!r}"
)
return value
def _subtitle_position(value: str) -> str:
"""校验保存的字幕位置,取值范围与命令行参数保持一致。"""
if value not in _SUBTITLE_POSITION_VALUES:
raise argparse.ArgumentTypeError(
"subtitle-position must be one of: "
f"{', '.join(_SUBTITLE_POSITION_VALUES)}, got {value!r}"
)
return value
def _subtitle_display_mode(value: str) -> str:
"""校验保存的字幕展示模式,取值范围与命令行参数保持一致。"""
if value not in _SUBTITLE_DISPLAY_MODE_VALUES:
raise argparse.ArgumentTypeError(
"subtitle-display-mode must be one of: "
f"{', '.join(_SUBTITLE_DISPLAY_MODE_VALUES)}, got {value!r}"
)
return value
def _subtitle_animation(value: str) -> str:
"""校验保存的字幕动画,取值范围与命令行参数保持一致。"""
if value not in _SUBTITLE_ANIMATION_VALUES:
raise argparse.ArgumentTypeError(
"subtitle-animation must be one of: "
f"{', '.join(_SUBTITLE_ANIMATION_VALUES)}, got {value!r}"
)
return value
def _task_id(value: str) -> str:
"""CLI 自定义任务标识只接受 UUID,避免该值被解释为文件系统路径。"""
try:
return str(UUID(value.strip()))
except (AttributeError, ValueError) as exc:
raise argparse.ArgumentTypeError(
f"task-id must be a valid UUID, got {value!r}"
) from exc
_TRANSITION_MODE_VALUES = {
"none": None,
"shuffle": "Shuffle",
"fade-in": "FadeIn",
"fade-out": "FadeOut",
"slide-in": "SlideIn",
"slide-out": "SlideOut",
"zoom-in": "ZoomIn",
"zoom-out": "ZoomOut",
}
# 单任务 argparse 和批量清单必须共享同一份字幕位置取值,避免再次出现
# 「WebUI 能保存、CLI 却拒绝」的落差。取值需与 app/services/video.py 的
# 渲染分支及 webui/Main.py 的下拉框保持一致。
_SUBTITLE_POSITION_VALUES = (
"top",
"center",
"bottom",
"two_thirds_bottom",
"custom",
)
# 字幕展示模式与入场动画由 WebUI 保存进 [ui]。两者随「逐词字幕 + 弹跳动画」
# 加入时只改了 WebUI 与模型字段默认值,命令行一直缺少开关。取值需与
# app/models/schema.py 的 _SUBTITLE_DISPLAY_MODES / _SUBTITLE_ANIMATIONS 一致。
_SUBTITLE_DISPLAY_MODE_VALUES = ("sentence", "word_by_word")
_SUBTITLE_ANIMATION_VALUES = ("none", "pop_spring")
def _transition_mode(value: str) -> str | None:
normalized = value.strip().lower()
if normalized not in _TRANSITION_MODE_VALUES:
allowed = ", ".join(_TRANSITION_MODE_VALUES)
raise argparse.ArgumentTypeError(
f"video-transition-mode must be one of: {allowed}"
)
return _TRANSITION_MODE_VALUES[normalized]
def _video_fit_mode(value: str) -> str:
normalized = value.strip().lower()
if normalized not in {"cover", "contain"}:
raise argparse.ArgumentTypeError(
"video-fit-mode must be one of: cover, contain"
)
return normalized
def _image_motion(value: str) -> str:
normalized = value.strip().lower()
if normalized not in {"static", "zoom"}:
raise argparse.ArgumentTypeError("image-motion must be one of: static, zoom")
return normalized
# 只有这些取值会请求外部音乐生成服务,因此只有它们消费配乐提示词。取值需与
# app/services/task.py 的 _VIDEO_MUSIC_PROVIDERS 保持一致;集中定义后,新增
# 配乐供应商不会再次遗漏 --bgm-type 校验、批量校验和提示词参数。
_CLI_MUSIC_BGM_TYPES = ("sonilo", "elevenlabs")
_BGM_TYPE_CHOICES_TEXT = "none, random, custom, " + ", ".join(_CLI_MUSIC_BGM_TYPES)
_BGM_TYPE_METAVAR = "{none,random,custom," + ",".join(_CLI_MUSIC_BGM_TYPES) + "}"
def _bgm_type(value: str) -> str:
normalized = value.strip().lower()
if normalized == "none":
return ""
if normalized in {"", "random", "custom", *_CLI_MUSIC_BGM_TYPES}:
return normalized
raise argparse.ArgumentTypeError(
f"bgm-type must be one of: {_BGM_TYPE_CHOICES_TEXT}"
)
def _useapi_image_needs_confirmation() -> bool:
"""Kling image models spend Kling credits; Nano Banana models do not."""
from app.services import useapi
return useapi.image_requires_confirmation()
def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
command = "mpt cli" if __name__ == "app.cli" else "uv run python cli.py"
parser = argparse.ArgumentParser(
prog="mpt cli" if __name__ == "app.cli" else None,
description=(
"Generate MoneyPrinterTurbo videos without the WebUI.\n\n"
"Provider settings and credentials are read from config.toml.\n"
"Default full-video generation requires a configured LLM and Pexels API key.\n"
"The default Edge TTS voice requires no API key."
),
epilog="""
Examples:
Generate a complete video with the default Edge TTS voice:
uv run python cli.py --video-subject "How AI is changing everyday life"
Generate from local files. Relative paths use the current working directory;
absolute paths are also accepted:
uv run python cli.py --video-subject "How AI is changing everyday life" \\
--video-source local --video-materials "./1.mp4,./2.mp4"
Generate with a prepared script and no voiceover:
uv run python cli.py --video-script "Your complete script" \\
--voice-name no-voice --stop-at video
Stop after script generation:
uv run python cli.py --video-subject "How AI is changing everyday life" --stop-at script
Run a JSON array or JSONL manifest. CLI options provide defaults and each object
overrides VideoParams fields for one task:
uv run python cli.py --batch-file ./tasks.jsonl --stop-at script
Pipeline stages:
script Generate or return the script.
terms Generate material search terms; unavailable with local materials.
audio Generate TTS, silent audio, or use --custom-audio-file.
subtitle Generate subtitles when enabled.
materials Download online materials or preprocess local files.
video Generate the final video and run configured cross-posting.
The command stops immediately after the selected stage and prints that stage's result.
Output and exit status:
Task files are written to storage/tasks/<task-id>/. A successful command prints one
JSON object to stdout and exits with 0. Batch mode prints one JSON summary after all
tasks finish. Task failures exit with 1; argument or manifest errors exit with 2
before any batch task starts. Runtime logs are written to stderr.
Batch manifests:
--batch-file accepts a UTF-8 JSON array or JSONL file with one object per non-empty
line (up to 100 tasks and 1 MiB). Objects may override VideoParams fields; unknown
fields are rejected. Every merged task needs video_subject or video_script.
The manifest path is relative to the current working directory. Relative
custom_audio_file and local video_materials[].url values declared in a manifest are
relative to the manifest directory. Relative paths supplied by CLI options remain
relative to the current working directory. bgm_file and font_name keep their managed
storage/resource lookup rules. --stop-at is a batch-wide CLI option. The summary has
total, succeeded, failed, and tasks keys; every task entry has index, task_id,
status, result, failed_stage, and error.
""".replace("uv run python cli.py", command),
formatter_class=_CliHelpFormatter,
)
content_group = parser.add_argument_group("script and content")
content_group.add_argument(
"--video-subject",
default="",
help="video topic; required unless --video-script is provided",
)
content_group.add_argument(
"--video-script",
default="",
help="complete script; skips LLM script generation when provided",
)
content_group.add_argument(
"--video-terms",
default=None,
help="comma-separated material search terms; generated automatically when omitted",
)
content_group.add_argument(
"--video-language",
default=None,
help=(
"script language code, such as zh-CN or en-US (default: auto-detect)"
),
)
content_group.add_argument(
"--paragraph-number",
type=_paragraph_count,
default=None,
help="number of generated script paragraphs, from 1 to 10 (default: 1)",
)
content_group.add_argument(
"--video-script-prompt",
default=None,
help="additional requirements for LLM script generation",
)
content_group.add_argument(
"--custom-system-prompt",
default=None,
help="replace the default LLM system prompt for script generation",
)
material_group = parser.add_argument_group("materials and pipeline")
material_group.add_argument(
"--video-source",
default="pexels",
choices=_CLI_VIDEO_SOURCES,
help="video material provider; online providers require matching API keys in config.toml",
)
material_group.add_argument(
"--video-materials",
default="",
metavar="PATH[,PATH...]",
help=(
"comma-separated local image/video paths for --video-source local; relative "
"paths use the current working directory, then storage/local_videos as a "
"compatibility fallback; absolute paths are accepted"
),
)
material_group.add_argument(
"--stop-at",
default="video",
choices=_PIPELINE_STAGES,
help="stop after this pipeline stage; see the stage order below",
)
material_group.add_argument(
"--confirm-aigei-charge",
action="store_true",
help="allow Aigei to charge copper coins for stock video downloads",
)
material_group.add_argument(
"--confirm-wavespeed-charge",
action="store_true",
help=(
"confirm that WaveSpeed video generation creates paid tasks; required "
"with --video-source wavespeed for materials or video output"
),
)
material_group.add_argument(
"--confirm-seedance-charge",
action="store_true",
help=(
"confirm that Volcano Engine Seedance creates paid Ark tasks; required "
"with --video-source volcengine_seedance for materials or video output"
),
)
material_group.add_argument(
"--confirm-jalapeno-charge", action="store_true",
help="confirm paid Jalapeno Cloud video generation for materials or video output",
)
material_group.add_argument(
"--confirm-infistar-charge", action="store_true",
help="confirm paid Infistar video generation for materials or video output",
)
material_group.add_argument(
"--confirm-ofox-charge",
action="store_true",
help=(
"confirm that OFox video generation creates paid tasks; required "
"with --video-source ofox for materials or video output"
),
)
material_group.add_argument(
"--confirm-metaso-minimax-charge",
action="store_true",
help=(
"confirm that Metaso MiniMax H3 creates paid video tasks; required "
"with --video-source metaso_minimax for materials or video output"
),
)
material_group.add_argument(
"--confirm-muapi-charge",
action="store_true",
help=(
"confirm that MuAPI video generation creates paid tasks; required "
"with --video-source muapi for materials or video output"
),
)
material_group.add_argument(
"--confirm-useapi-charge",
action="store_true",
help=(
"confirm that useapi.net videos and Kling images spend credits on "
"your own Google AI plan, Kling AI account or Dreamina account; "
"required with --video-source useapi, and with useapi_image when "
"useapi_image_model is a Kling model, for materials or video output"
),
)
video_group = parser.add_argument_group("video output")
video_group.add_argument(
"--video-count",
type=_positive_int,
default=1,
help="number of output videos, at least 1",
)
video_group.add_argument(
"--video-aspect",
choices=["9:16", "16:9", "1:1"],
default="9:16",
help="output aspect ratio: portrait, landscape, or square",
)
video_group.add_argument(
"--video-fit-mode",
type=_video_fit_mode,
choices=["cover", "contain"],
default=None,
help=(
"fit mismatched source clips by filling and center-cropping (cover) "
"or preserving the full frame with black bars (contain); default: cover"
),
)
video_group.add_argument(
"--video-concat-mode",
choices=["random", "sequential"],
default=None,
help="source clip concatenation order (default: random)",
)
video_group.add_argument(
"--image-motion",
type=_image_motion,
choices=["static", "zoom"],
default=None,
help="motion for local or AI-generated images (default: zoom)",
)
video_group.add_argument(
"--video-transition-mode",
type=_transition_mode,
default=None,
metavar="{none,shuffle,fade-in,fade-out,slide-in,slide-out,zoom-in,zoom-out}",
help="transition applied between source clips (default: none)",
)
video_group.add_argument(
"--video-clip-duration",
type=_positive_int,
default=None,
help=(
"maximum duration of each source clip in seconds, at least 1 (default: 5)"
),
)
video_group.add_argument(
"--video-clip-speed",
type=_clip_speed,
default=None,
help=(
"playback speed multiplier applied to every source clip, between "
"0.5 and 2.0 (default: 1.0)"
),
)
video_group.add_argument(
"--match-materials-to-script",
default=None,
action=argparse.BooleanOptionalAction,
help=(
"preserve script keyword order while selecting and concatenating materials "
"(default: disabled)"
),
)
video_group.add_argument(
"--n-threads",
type=_positive_int,
default=None,
help="FFmpeg worker thread count, at least 1 (default: 2)",
)
audio_group = parser.add_argument_group("voiceover and background music")
audio_group.add_argument(
"--voice-name",
default=None,
help=(
f"TTS voice identifier. Defaults to [ui].voice_name from "
f"config.toml, otherwise {DEFAULT_VOICE_NAME}. A saved "
"[ui].voice_mode of 'none' or 'upload' resolves to no-voice "
"instead, unless this option is given. "
"Use 'no-voice' for silent output. Provider-specific identifiers "
"use prefixes such as gemini:, mimo:, elevenlabs:, chatterbox:, "
"kokoro:, and voxcpm:"
),
)
audio_group.add_argument(
"--voice-volume",
type=_non_negative_float,
default=None,
help=(
"final voiceover volume multiplier, a finite number >= 0 (default: "
"[ui].voice_volume from config.toml; 1.0 when unset)"
),
)
audio_group.add_argument(
"--voice-rate",
type=_positive_float,
default=None,
help=(
"speech rate multiplier, a finite number > 0 (default: "
"[ui].voice_rate from config.toml; 1.0 when unset)"
),
)
audio_group.add_argument(
"--custom-audio-file",
default=None,
metavar="PATH",
help=(
"existing MP3/WAV/M4A/AAC/FLAC/OGG voiceover; relative paths use the "
"current working directory. This skips TTS; set subtitle_provider=whisper "
"to transcribe it"
),
)
audio_group.add_argument(
"--bgm-type",
type=_bgm_type,
default=None,
metavar=_BGM_TYPE_METAVAR,
help=(
"background music mode; Sonilo reads its API key from config.toml or "
"SONILO_API_KEY, ElevenLabs from config.toml or ELEVENLABS_API_KEY; "
"--bgm-file implies custom when omitted (default: random)"
),
)
audio_group.add_argument(
"--sonilo-bgm-prompt",
default=None,
help="optional music style prompt for Sonilo, up to 2000 characters",
)
audio_group.add_argument(
"--video-music-prompt",
default=None,
help=(
"optional music style prompt for the selected AI background music "
"provider (sonilo or elevenlabs); the provider's own length limit "
"is enforced before generation"
),
)
audio_group.add_argument(
"--bgm-file",
default=None,
metavar="PATH",
help=(
"custom supported audio file inside storage/bgm or resource/songs; "
"accepts a filename or an allowed managed path"
),
)
audio_group.add_argument(
"--bgm-volume",
type=_non_negative_float,
default=None,
help=(
"background music volume multiplier, a finite number >= 0 (default: 0.2)"
),
)
subtitle_group = parser.add_argument_group("subtitles")
subtitle_group.add_argument(
"--subtitle-enabled",
default=None,
action=argparse.BooleanOptionalAction,
help=(
"enable subtitles; use --no-subtitle-enabled to disable "
"(default: [ui].subtitle_enabled from config.toml; enabled when "
"unset)"
),
)
subtitle_group.add_argument(
"--font-name",
default=None,
help=(
"subtitle font filename inside resource/fonts "
"(default: [ui].font_name from config.toml; "
"STHeitiMedium.ttc when unset)"
),
)
subtitle_group.add_argument(
"--subtitle-position",
choices=_SUBTITLE_POSITION_VALUES,
default=None,
help=(
"subtitle vertical position (default: [ui].subtitle_position from "
"config.toml; bottom when unset)"
),
)
subtitle_group.add_argument(
"--subtitle-display-mode",
choices=_SUBTITLE_DISPLAY_MODE_VALUES,
default=None,
help=(
"subtitle timing: sentence by sentence, or one word at a time "
"(default: [ui].subtitle_display_mode from config.toml; sentence)"
),
)
subtitle_group.add_argument(
"--subtitle-animation",
choices=_SUBTITLE_ANIMATION_VALUES,
default=None,
help=(
"subtitle entrance animation (default: [ui].subtitle_animation from "
"config.toml; none when unset)"
),
)
subtitle_group.add_argument(
"--custom-position",
type=_percent_position,
default=None,
help=(
"custom position as percent from top, 0-100; requires "
"--subtitle-position custom (default: [ui].custom_position from "
"config.toml; 70 when unset)"
),
)
subtitle_group.add_argument(
"--text-fore-color",
type=_hex_color,
default=None,
help=(
"subtitle text color in #RRGGBB format; quote the value in shells "
"that treat # as a comment (default: [ui].text_fore_color from "
"config.toml; #FFFFFF when unset)"
),
)
subtitle_group.add_argument(
"--font-size",
type=_positive_int,
default=None,
help=(
"subtitle font size (default: [ui].font_size from config.toml; "
"60 when unset)"
),
)
subtitle_group.add_argument(
"--stroke-color",
type=_hex_color,
default=None,
help=(
"subtitle outline color in #RRGGBB format (default: "
"[ui].stroke_color from config.toml; #000000 when unset)"
),
)
subtitle_group.add_argument(
"--stroke-width",
type=_non_negative_float,
default=None,
help=(
"subtitle outline width, a finite number >= 0 (default: "
"[ui].stroke_width from config.toml; 1.5 when unset)"
),
)
subtitle_group.add_argument(
"--subtitle-background-enabled",
default=None,
action=argparse.BooleanOptionalAction,
help=(
"enable subtitle background; use --no-subtitle-background-enabled to "
"disable (default: [ui].subtitle_background_enabled from "
"config.toml; disabled when unset)"
),
)
subtitle_group.add_argument(
"--subtitle-background-color",
type=_hex_color,
default=None,
help=(
"subtitle background color in #RRGGBB format (default: "
"[ui].subtitle_background_color from config.toml)"
),
)
subtitle_group.add_argument(
"--rounded-subtitle-background",
default=None,
action=argparse.BooleanOptionalAction,
help=(
"use a rounded subtitle background (default: "
"[ui].rounded_subtitle_background from config.toml; "
"disabled when unset)"
),
)
execution_group = parser.add_argument_group("execution")
execution_mode = execution_group.add_mutually_exclusive_group()
execution_mode.add_argument(
"--task-id",
type=_task_id,
default=None,
help="custom UUID used for storage/tasks/<task-id>; generated automatically when omitted",
)
execution_mode.add_argument(
"--batch-file",
default=None,
metavar="PATH",
help=(
"UTF-8 JSON array or JSONL task manifest; conflicts with --task-id and "
"generates a UUID for every task"
),
)
args = parser.parse_args(argv)
if (
not args.batch_file
and not args.video_subject.strip()
and not args.video_script.strip()
):
parser.error("one of --video-subject or --video-script is required")
if not args.batch_file and args.video_source == "local" and args.stop_at == "terms":
parser.error(
"--stop-at terms has no effect with --video-source local "
"(search terms are not generated for local sources)"
)
stage_requires_materials = args.stop_at in {"materials", "video"}
has_video_materials = bool((args.video_materials or "").strip())
if (
not args.batch_file
and args.video_source == "local"
and stage_requires_materials
and not has_video_materials
):
parser.error(
"--video-materials is required with --video-source local when "
"--stop-at is materials or video"
)
if not args.batch_file and args.video_source != "local" and has_video_materials:
parser.error("--video-materials can only be used with --video-source local")
if (
not args.batch_file and args.video_source == "aigei"
and stage_requires_materials and not args.confirm_aigei_charge
):
parser.error("--confirm-aigei-charge is required with --video-source aigei")
if (
not args.batch_file
and args.video_source == "wavespeed"
and stage_requires_materials
and not args.confirm_wavespeed_charge
):
parser.error(
"--confirm-wavespeed-charge is required with "
"--video-source wavespeed"
)
if (
not args.batch_file
and args.video_source == "volcengine_seedance"
and stage_requires_materials
and not args.confirm_seedance_charge
):
parser.error(
"--confirm-seedance-charge is required with "
"--video-source volcengine_seedance"
)
if (
not args.batch_file
and args.video_source == "ofox"
and stage_requires_materials
and not args.confirm_ofox_charge
):
parser.error(
"--confirm-ofox-charge is required with --video-source ofox"
)
if (
not args.batch_file
and args.video_source == "metaso_minimax"
and stage_requires_materials
and not args.confirm_metaso_minimax_charge
):
parser.error(
"--confirm-metaso-minimax-charge is required with "
"--video-source metaso_minimax"
)
if (
not args.batch_file
and args.video_source == "muapi"
and stage_requires_materials
and not args.confirm_muapi_charge
):
parser.error(
"--confirm-muapi-charge is required with --video-source muapi"
)
if (
not args.batch_file
and args.video_source == "useapi"
and stage_requires_materials
and not args.confirm_useapi_charge
):
parser.error(
"--confirm-useapi-charge is required with --video-source useapi"
)
if (
not args.batch_file
and args.video_source == "useapi_image"
and stage_requires_materials
and not args.confirm_useapi_charge
and _useapi_image_needs_confirmation()
):
parser.error(
"--confirm-useapi-charge is required with --video-source "
"useapi_image when useapi_image_model is a Kling model"
)
if (not args.batch_file and args.video_source == "infistar"
and stage_requires_materials and not args.confirm_infistar_charge):
parser.error("--confirm-infistar-charge is required with --video-source infistar")
if (not args.batch_file and args.video_source == "jalapeno"
and stage_requires_materials and not args.confirm_jalapeno_charge):
parser.error("--confirm-jalapeno-charge is required with --video-source jalapeno")
if args.bgm_file:
if args.bgm_type in (None, "custom"):
args.bgm_type = "custom"
elif not args.batch_file:
parser.error("--bgm-file can only be combined with --bgm-type custom")
if args.sonilo_bgm_prompt:
if args.bgm_type in (None, "sonilo"):
args.bgm_type = "sonilo"
elif not args.batch_file:
parser.error(
"--sonilo-bgm-prompt can only be combined with --bgm-type sonilo"
)
# 提示词字段本身与供应商无关,所以不像 Sonilo 专用参数那样推断 bgm_type:
# 推断出来的供应商可能不是用户想要的那个。必须显式选择 AI 配乐供应商,
# 否则该提示词会被静默丢弃。批量清单仍可按任务单独设置该字段。
if (
not args.batch_file
and args.video_music_prompt
and args.bgm_type not in _CLI_MUSIC_BGM_TYPES
):
parser.error(
"--video-music-prompt requires --bgm-type sonilo or elevenlabs"
)
if (
not args.batch_file
and args.custom_position is not None
and args.subtitle_position != "custom"
):
parser.error("--custom-position requires --subtitle-position custom")
# 只有显式的 --no-subtitle-enabled 才算冲突。默认值现在是 None,
# 保存的关闭状态在 build_video_params 中处理,不应在这里报参数错误。
if (
not args.batch_file
and args.stop_at == "subtitle"
and args.subtitle_enabled is False
):
parser.error("--stop-at subtitle cannot be combined with --no-subtitle-enabled")
if not args.batch_file and args.subtitle_background_enabled is False and (
args.subtitle_background_color is not None
or args.rounded_subtitle_background is True
):
parser.error(
"subtitle background color or rounding cannot be enabled together with "
"--no-subtitle-background-enabled"
)
return args
def _ui_config_value(ui_config, key: str, expected_type, checker=None):
"""
读取 ``[ui]`` 中保存的 WebUI 设置,取不到可用值时返回 ``None``。
该配置段也可能被手工编辑,因此这里直接丢弃不可用的条目,让调用方回退到
内置默认值,而不是把脏数据继续传下去,触发 traceback 或 ``VideoParams``
的校验错误。
``checker`` 复用命令行使用的同一批类型函数(如 ``_hex_color``),因此保存
值和命令行参数遵循完全相同的取值规则,例如音量不能为负、颜色必须是
``#RRGGBB``。
"""
value = ui_config.get(key)
if value is None:
return None
# ``isinstance(True, int)`` 为真,所以在期望数字时必须显式排除 bool。
if isinstance(value, bool) != (expected_type is bool):
return None
# TOML 中的 ``1`` 是整数,但对音量、语速这类字段同样是合法取值。
if expected_type is float and isinstance(value, int):
value = float(value)
if not isinstance(value, expected_type):
return None
if expected_type is str and not value.strip():
return None
if checker is not None:
try:
return checker(str(value))
except argparse.ArgumentTypeError:
return None
return value
def _resolve_subtitle_enabled(args: argparse.Namespace, ui_config) -> bool:
"""
按优先级解析字幕开关:命令行 > WebUI 保存值 > 默认开启。
``--stop-at subtitle`` 明确要求生成字幕,因此保存的关闭状态不能让该阶段
变成空操作;显式的 --no-subtitle-enabled 与该阶段的组合在参数校验中已被
拒绝,所以这里只需处理保存值。
"""
if args.subtitle_enabled is not None:
return args.subtitle_enabled
if args.stop_at == "subtitle":
return True
saved = _ui_config_value(ui_config, "subtitle_enabled", bool)
return True if saved is None else saved
def _resolve_voice_name(args: argparse.Namespace, ui_config) -> str:
"""
按优先级解析音色:命令行 > WebUI 保存的配音方式和音色 > 内置默认值。
WebUI 把“无配音”保存为独立的 voice_mode,同时保留用户上一次真正选择的
音色,以便切回自动配音后恢复。所以这里不能只读 voice_name,否则保存的
无配音状态会被忽略,并可能重新触发付费供应商请求。
"""
from app.services.voice import NO_VOICE_NAME
if args.voice_name:
return args.voice_name
# 无配音和上传自备音频都表示用户不想要自动配音。上传模式的文件路径不会
# 写入 [ui],CLI 无法复现该上传;此时沿用保存的音色会静默触发付费 TTS
# 请求,因此两种模式都映射为 no-voice,需要配音时显式传 --voice-name。
if _ui_config_value(ui_config, "voice_mode", str) in UI_VOICE_MODES_WITHOUT_TTS:
return NO_VOICE_NAME
return _ui_config_value(ui_config, "voice_name", str) or DEFAULT_VOICE_NAME
def build_video_params(args: argparse.Namespace) -> VideoParams:
# 参数帮助和校验不需要加载应用配置。仅在真正构建任务参数时导入模型,
# 避免执行 ``cli.py -h`` 时产生配置初始化日志。
from app.config import config
from app.models.schema import MaterialInfo, VideoParams
ui_config = config.ui
video_terms = args.video_terms
if video_terms:
video_terms = [
term.strip() for term in re.split(r"[,,]", video_terms) if term.strip()
]
video_materials = None
materials_arg = args.video_materials or ""
if materials_arg.strip():