-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
2006 lines (1814 loc) · 86.6 KB
/
cli.py
File metadata and controls
2006 lines (1814 loc) · 86.6 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
import argparse
import re
import ast
import os
import sys
import toml
from pathlib import Path
from typing import List, Optional, Tuple
# Load environment variables from .env or .env.example (if available)
try:
from dotenv import load_dotenv
_current_file = os.path.abspath(__file__)
_project_root = os.path.dirname(_current_file)
_env_path = os.path.join(_project_root, '.env')
_env_example_path = os.path.join(_project_root, '.env.example')
if os.path.exists(_env_path):
load_dotenv(_env_path)
print(f"Loaded configuration from {_env_path}")
elif os.path.exists(_env_example_path):
load_dotenv(_env_example_path)
print(f"Loaded configuration from {_env_example_path} (fallback)")
except ImportError:
pass
# Clear proxy settings that may affect network behavior
for _proxy_var in ['http_proxy', 'https_proxy', 'HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY']:
os.environ.pop(_proxy_var, None)
def _configure_logging(
level: Optional[str] = None,
suppress_audio_tokens: Optional[bool] = None,
) -> None:
try:
from loguru import logger
except Exception:
return
if suppress_audio_tokens is None:
suppress_audio_tokens = os.environ.get("ACE_STEP_SUPPRESS_AUDIO_TOKENS", "1") not in {"0", "false", "False"}
if level is None:
level = "INFO"
level = str(level).upper()
def _log_filter(record) -> bool:
message = record.get("message", "")
# Suppress duplicate DiT prompt logs (we print a single final prompt in cli.py)
if (
"DiT TEXT ENCODER INPUT" in message
or "text_prompt:" in message
or (message.strip() and set(message.strip()) == {"="})
):
return False
if not suppress_audio_tokens:
return True
return "<|audio_code_" not in message
logger.remove()
logger.add(sys.stderr, level=level, filter=_log_filter)
_configure_logging()
from acestep.handler import AceStepHandler
from acestep.llm_inference import LLMHandler
from acestep.inference import GenerationParams, GenerationConfig, generate_music, create_sample, format_sample
from acestep.constants import DEFAULT_DIT_INSTRUCTION, TASK_INSTRUCTIONS
from acestep.gpu_config import get_gpu_config, set_global_gpu_config, GPUConfig, GPU_TIER_CONFIGS
import torch
TRACK_CHOICES = [
"vocals",
"backing_vocals",
"drums",
"bass",
"guitar",
"keyboard",
"percussion",
"strings",
"synth",
"fx",
"brass",
"woodwinds",
]
def _get_project_root() -> str:
return os.path.dirname(os.path.abspath(__file__))
def _parse_description_hints(description: str) -> tuple[Optional[str], bool]:
import re
if not description:
return None, False
description_lower = description.lower().strip()
language_mapping = {
'english': 'en', 'en': 'en',
'chinese': 'zh', '中文': 'zh', 'zh': 'zh', 'mandarin': 'zh',
'japanese': 'ja', '日本語': 'ja', 'ja': 'ja',
'korean': 'ko', '한국어': 'ko', 'ko': 'ko',
'spanish': 'es', 'español': 'es', 'es': 'es',
'french': 'fr', 'français': 'fr', 'fr': 'fr',
'german': 'de', 'deutsch': 'de', 'de': 'de',
'italian': 'it', 'italiano': 'it', 'it': 'it',
'portuguese': 'pt', 'português': 'pt', 'pt': 'pt',
'russian': 'ru', 'русский': 'ru', 'ru': 'ru',
'bengali': 'bn', 'bn': 'bn',
'hindi': 'hi', 'hi': 'hi',
'arabic': 'ar', 'ar': 'ar',
'thai': 'th', 'th': 'th',
'vietnamese': 'vi', 'vi': 'vi',
'indonesian': 'id', 'id': 'id',
'turkish': 'tr', 'tr': 'tr',
'dutch': 'nl', 'nl': 'nl',
'polish': 'pl', 'pl': 'pl',
}
detected_language = None
for lang_name, lang_code in language_mapping.items():
if len(lang_name) <= 2:
pattern = r'(?:^|\s|[.,;:!?])' + re.escape(lang_name) + r'(?:$|\s|[.,;:!?])'
else:
pattern = r'\b' + re.escape(lang_name) + r'\b'
if re.search(pattern, description_lower):
detected_language = lang_code
break
is_instrumental = False
if 'instrumental' in description_lower:
is_instrumental = True
elif 'pure music' in description_lower or 'pure instrument' in description_lower:
is_instrumental = True
elif description_lower.endswith(' solo') or description_lower == 'solo':
is_instrumental = True
return detected_language, is_instrumental
def _prompt_non_empty(prompt: str) -> str:
value = input(prompt).strip()
while not value:
value = input(prompt).strip()
return value
def _prompt_with_default(prompt: str, default: Optional[str] = None, required: bool = False) -> str:
while True:
suffix = f" [{default}]" if default not in (None, "") else ""
value = input(f"{prompt}{suffix}: ").strip()
if value:
return value
if default not in (None, ""):
return str(default)
if not required:
return ""
print("This value is required. Please try again.")
def _prompt_bool(prompt: str, default: bool) -> bool:
default_str = "y" if default else "n"
while True:
value = input(f"{prompt} (y/n) [default: {default_str}]: ").strip().lower()
if not value:
return default
if value in {"y", "yes", "1", "true"}:
return True
if value in {"n", "no", "0", "false"}:
return False
print("Please enter 'y' or 'n'.")
def _prompt_choice_from_list(
prompt: str,
options: List[str],
default: Optional[str] = None,
allow_custom: bool = True,
custom_validator=None,
custom_error: Optional[str] = None,
) -> Optional[str]:
if not options:
return default
print("\n" + prompt)
for idx, option in enumerate(options, start=1):
print(f"{idx}. {option}")
default_display = default if default not in (None, "") else "auto"
while True:
choice = input(f"Choose a model (number or name) [default: {default_display}]: ").strip()
if not choice:
return None if default_display == "auto" else default
if choice.lower() == "auto":
return None
if choice.isdigit():
idx = int(choice)
if 1 <= idx <= len(options):
return options[idx - 1]
print("Invalid selection. Please choose a valid number.")
continue
if allow_custom:
if custom_validator and not custom_validator(choice):
print(custom_error or "Invalid selection. Please try again.")
continue
if choice not in options:
print("Unknown model. Using as-is.")
return choice
print("Please choose a valid option.")
def _edit_formatted_prompt_via_file(formatted_prompt: str, instruction_path: str) -> str:
"""Write formatted prompt to file, wait for user edits, then read back."""
try:
with open(instruction_path, "w", encoding="utf-8") as f:
f.write(formatted_prompt)
except Exception as e:
print(f"WARNING: Failed to write {instruction_path}: {e}")
return formatted_prompt
print("\n--- Final Draft Saved ---")
print(f"Saved to {instruction_path}")
print("Edit the file now. Press Enter when ready to continue.")
input()
try:
with open(instruction_path, "r", encoding="utf-8") as f:
return f.read()
except Exception as e:
print(f"WARNING: Failed to read {instruction_path}: {e}")
return formatted_prompt
def _extract_caption_lyrics_from_formatted_prompt(formatted_prompt: str) -> Tuple[Optional[str], Optional[str]]:
"""Best-effort extraction of caption/lyrics from a formatted prompt string."""
matches = list(re.finditer(r"# Caption\n(.*?)\n+# Lyric\n(.*)", formatted_prompt, re.DOTALL))
if not matches:
return None, None
caption = matches[-1].group(1).strip()
lyrics = matches[-1].group(2)
# Trim lyrics if chat-template markers appear after the user message.
cut_markers = ["<|eot_id|>", "<|start_header_id|>", "<|assistant|>", "<|user|>", "<|system|>"]
cut_at = len(lyrics)
for marker in cut_markers:
pos = lyrics.find(marker)
if pos != -1:
cut_at = min(cut_at, pos)
lyrics = lyrics[:cut_at].rstrip()
return caption or None, lyrics or None
def _extract_instruction_from_formatted_prompt(formatted_prompt: str) -> Optional[str]:
"""Best-effort extraction of instruction text from a formatted prompt string."""
match = re.search(r"# Instruction\n(.*?)\n\n", formatted_prompt, re.DOTALL)
if not match:
return None
instruction = match.group(1).strip()
return instruction or None
def _extract_cot_metadata_from_formatted_prompt(formatted_prompt: str) -> dict:
"""Best-effort extraction of COT metadata from a formatted prompt string."""
matches = list(re.finditer(r"<think>\n(.*?)\n</think>", formatted_prompt, re.DOTALL))
if not matches:
return {}
block = matches[-1].group(1)
metadata = {}
for line in block.splitlines():
line = line.strip()
if not line or ":" not in line:
continue
key, value = line.split(":", 1)
key = key.strip().lower()
value = value.strip()
if key:
metadata[key] = value
return metadata
def _parse_number(value: str) -> Optional[float]:
try:
match = re.search(r"[-+]?\d*\.?\d+", value)
if not match:
return None
return float(match.group(0))
except Exception:
return None
def _parse_timesteps_input(value) -> Optional[List[float]]:
if value is None:
return None
if isinstance(value, list):
if all(isinstance(t, (int, float)) for t in value):
return [float(t) for t in value]
return None
if not isinstance(value, str):
return None
raw = value.strip()
if not raw:
return None
if raw.startswith("[") or raw.startswith("("):
try:
parsed = ast.literal_eval(raw)
except Exception:
return None
if isinstance(parsed, list) and all(isinstance(t, (int, float)) for t in parsed):
return [float(t) for t in parsed]
return None
try:
return [float(t.strip()) for t in raw.split(",") if t.strip()]
except Exception:
return None
def _install_prompt_edit_hook(
llm_handler: LLMHandler,
instruction_path: str,
preloaded_prompt: Optional[str] = None,
) -> None:
"""Intercept formatted prompt generation to allow user editing before audio tokens."""
original = llm_handler.build_formatted_prompt_with_cot
cache = {}
def wrapped(caption, lyrics, cot_text, is_negative_prompt=False, negative_prompt="NO USER INPUT"):
prompt = original(
caption,
lyrics,
cot_text,
is_negative_prompt=is_negative_prompt,
negative_prompt=negative_prompt,
)
if is_negative_prompt:
conditional_prompt = original(
caption,
lyrics,
cot_text,
is_negative_prompt=False,
negative_prompt=negative_prompt,
)
cached = cache.get(conditional_prompt)
if cached and (cached.get("edited_caption") or cached.get("edited_lyrics")):
edited_caption = cached.get("edited_caption") or caption
edited_lyrics = cached.get("edited_lyrics") or lyrics
return original(
edited_caption,
edited_lyrics,
cot_text,
is_negative_prompt=True,
negative_prompt=negative_prompt,
)
return prompt
cached = cache.get(prompt)
if cached:
return cached["edited_prompt"]
if getattr(llm_handler, "_skip_prompt_edit", False):
cache[prompt] = {
"edited_prompt": prompt,
"edited_caption": None,
"edited_lyrics": None,
}
return prompt
if preloaded_prompt is not None:
edited = preloaded_prompt
else:
edited = _edit_formatted_prompt_via_file(prompt, instruction_path)
edited_caption, edited_lyrics = _extract_caption_lyrics_from_formatted_prompt(edited)
if edited != prompt:
print("INFO: Using edited draft for audio-token prompt.")
if edited_caption or edited_lyrics:
llm_handler._edited_caption = edited_caption
llm_handler._edited_lyrics = edited_lyrics
edited_instruction = _extract_instruction_from_formatted_prompt(edited)
if edited_instruction:
llm_handler._edited_instruction = edited_instruction
edited_metas = _extract_cot_metadata_from_formatted_prompt(edited)
if edited_metas:
llm_handler._edited_metas = edited_metas
cache[prompt] = {
"edited_prompt": edited,
"edited_caption": edited_caption,
"edited_lyrics": edited_lyrics,
}
return edited
llm_handler.build_formatted_prompt_with_cot = wrapped
def _prompt_int(prompt: str, default: Optional[int] = None, min_value: Optional[int] = None,
max_value: Optional[int] = None) -> Optional[int]:
default_display = "auto" if default is None else default
while True:
value = input(f"{prompt} [{default_display}]: ").strip()
if not value:
return default
try:
parsed = int(value)
except ValueError:
print("Invalid input. Please enter an integer.")
continue
if min_value is not None and parsed < min_value:
print(f"Please enter a value >= {min_value}.")
continue
if max_value is not None and parsed > max_value:
print(f"Please enter a value <= {max_value}.")
continue
return parsed
def _prompt_float(prompt: str, default: Optional[float] = None, min_value: Optional[float] = None,
max_value: Optional[float] = None) -> Optional[float]:
default_display = "auto" if default is None else default
while True:
value = input(f"{prompt} [{default_display}]: ").strip()
if not value:
return default
try:
parsed = float(value)
except ValueError:
print("Invalid input. Please enter a number.")
continue
if min_value is not None and parsed < min_value:
print(f"Please enter a value >= {min_value}.")
continue
if max_value is not None and parsed > max_value:
print(f"Please enter a value <= {max_value}.")
continue
return parsed
def _prompt_existing_file(prompt: str, default: Optional[str] = None) -> str:
while True:
suffix = f" [{default}]" if default else ""
path = input(f"{prompt}{suffix}: ").strip()
if not path and default:
path = default
if os.path.isfile(path):
return _expand_audio_path(path)
print("Invalid file path. Please try again.")
def _expand_audio_path(path_str: Optional[str]) -> Optional[str]:
if not path_str or not isinstance(path_str, str):
return path_str
try:
return Path(path_str).expanduser().resolve(strict=False).as_posix()
except Exception:
return Path(path_str).expanduser().absolute().as_posix()
def _parse_bool(value: str) -> bool:
return str(value).lower() in {"true", "1", "yes", "y"}
def _resolve_device(device: str) -> str:
if device == "auto":
if hasattr(torch, 'xpu') and torch.xpu.is_available():
return "xpu"
if torch.cuda.is_available():
return "cuda"
if hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
return "mps"
return "cpu"
return device
def _get_mps_wired_limit_mb() -> Optional[int]:
"""Best-effort read of iogpu.wired_limit_mb on macOS (may be unavailable)."""
try:
import subprocess
out = subprocess.check_output(["sysctl", "iogpu.wired_limit_mb"], text=True).strip()
# Expected: "iogpu.wired_limit_mb: 12345"
parts = out.split(":")
if len(parts) == 2:
value = parts[1].strip()
return int(value)
except Exception:
pass
return None
def _default_instruction_for_task(task_type: str, tracks: Optional[List[str]] = None) -> str:
if task_type == "lego":
track = tracks[0] if tracks else "guitar"
return TASK_INSTRUCTIONS["lego"].format(TRACK_NAME=track.upper())
if task_type == "extract":
track = tracks[0] if tracks else "vocals"
return TASK_INSTRUCTIONS["extract"].format(TRACK_NAME=track.upper())
if task_type == "complete":
tracks_list = ", ".join(tracks) if tracks else "drums, bass, guitar"
return TASK_INSTRUCTIONS["complete"].format(TRACK_CLASSES=tracks_list)
return DEFAULT_DIT_INSTRUCTION
def _apply_optional_defaults(args, params_defaults: GenerationParams, config_defaults: GenerationConfig) -> None:
optional_defaults = {
"duration": params_defaults.duration,
"bpm": params_defaults.bpm,
"keyscale": params_defaults.keyscale,
"timesignature": params_defaults.timesignature,
"vocal_language": params_defaults.vocal_language,
"inference_steps": params_defaults.inference_steps,
"seed": params_defaults.seed,
"guidance_scale": params_defaults.guidance_scale,
"use_adg": params_defaults.use_adg,
"cfg_interval_start": params_defaults.cfg_interval_start,
"cfg_interval_end": params_defaults.cfg_interval_end,
"shift": 3.0,
"infer_method": params_defaults.infer_method,
"timesteps": None,
"repainting_start": params_defaults.repainting_start,
"repainting_end": params_defaults.repainting_end,
"audio_cover_strength": params_defaults.audio_cover_strength,
"thinking": params_defaults.thinking,
"lm_temperature": params_defaults.lm_temperature,
"lm_cfg_scale": params_defaults.lm_cfg_scale,
"lm_top_k": params_defaults.lm_top_k,
"lm_top_p": params_defaults.lm_top_p,
"lm_negative_prompt": params_defaults.lm_negative_prompt,
"use_cot_metas": params_defaults.use_cot_metas,
"use_cot_caption": params_defaults.use_cot_caption,
"use_cot_lyrics": params_defaults.use_cot_lyrics,
"use_cot_language": params_defaults.use_cot_language,
"use_constrained_decoding": params_defaults.use_constrained_decoding,
"batch_size": config_defaults.batch_size,
"allow_lm_batch": config_defaults.allow_lm_batch,
"use_random_seed": config_defaults.use_random_seed,
"seeds": config_defaults.seeds,
"lm_batch_chunk_size": config_defaults.lm_batch_chunk_size,
"constrained_decoding_debug": config_defaults.constrained_decoding_debug,
"audio_format": config_defaults.audio_format,
"sample_mode": False,
"sample_query": "",
"use_format": False,
}
for key, default_value in optional_defaults.items():
if getattr(args, key, None) is None:
setattr(args, key, default_value)
def _summarize_lyrics(lyrics: Optional[str]) -> str:
if not lyrics:
return "none"
if isinstance(lyrics, str):
stripped = lyrics.strip()
if not stripped:
return "none"
if os.path.isfile(stripped):
return f"file: {os.path.basename(stripped)}"
if len(stripped) <= 60:
return stripped.replace("\n", " ")
return f"text ({len(stripped)} chars)"
return "provided"
def _print_final_parameters(
args,
params: GenerationParams,
config: GenerationConfig,
params_defaults: GenerationParams,
config_defaults: GenerationConfig,
compact: bool,
resolved_device: Optional[str] = None,
) -> None:
if not compact:
print("\n--- Final Parameters (Args) ---")
for k in sorted(vars(args).keys()):
print(f"{k}: {getattr(args, k)}")
print("------------------------------")
print("\n--- Final Parameters (GenerationParams) ---")
for k in sorted(vars(params).keys()):
print(f"{k}: {getattr(params, k)}")
print("-------------------------------------------")
print("\n--- Final Parameters (GenerationConfig) ---")
for k in sorted(vars(config).keys()):
print(f"{k}: {getattr(config, k)}")
print("-------------------------------------------\n")
return
device_display = args.device
if resolved_device and resolved_device != args.device:
device_display = f"{args.device} -> {resolved_device}"
print("\n--- Final Parameters (Summary) ---")
print(f"task_type: {params.task_type}")
print(f"caption: {params.caption or 'none'}")
print(f"lyrics: {_summarize_lyrics(params.lyrics)}")
print(f"duration: {params.duration}s")
print(f"outputs: {config.batch_size}")
if params.bpm not in (None, params_defaults.bpm):
print(f"bpm: {params.bpm}")
if params.keyscale not in (None, params_defaults.keyscale):
print(f"keyscale: {params.keyscale}")
if params.timesignature not in (None, params_defaults.timesignature):
print(f"timesignature: {params.timesignature}")
print(f"instrumental: {params.instrumental}")
print(f"thinking: {params.thinking}")
print(f"lm_model: {args.lm_model_path or 'auto'}")
print(f"dit_model: {args.config_path or 'auto'}")
print(f"backend: {args.backend}")
print(f"device: {device_display}")
print(f"audio_format: {config.audio_format}")
print(f"save_dir: {args.save_dir}")
if config.seeds:
print(f"seeds: {config.seeds}")
else:
print(f"seed: {params.seed} (random={config.use_random_seed})")
print("-------------------------------\n")
def _build_meta_dict(params: GenerationParams) -> Optional[dict]:
meta = {}
if params.bpm is not None:
meta["bpm"] = params.bpm
if params.timesignature:
meta["timesignature"] = params.timesignature
if params.keyscale:
meta["keyscale"] = params.keyscale
if params.duration is not None:
meta["duration"] = params.duration
return meta or None
def _print_dit_prompt(dit_handler: "AceStepHandler", params: GenerationParams) -> None:
meta = _build_meta_dict(params)
caption_input, lyrics_input = dit_handler.build_dit_inputs(
task=params.task_type,
instruction=params.instruction,
caption=params.caption or "",
lyrics=params.lyrics or "",
metas=meta,
vocal_language=params.vocal_language or "unknown",
)
print("\n--- Final DiT Prompt (Caption Branch) ---")
print(caption_input)
print("\n--- Final DiT Prompt (Lyrics Branch) ---")
print(lyrics_input)
print("----------------------------------------\n")
def run_wizard(args, configure_only: bool = False, default_config_path: Optional[str] = None,
params_defaults: Optional[GenerationParams] = None,
config_defaults: Optional[GenerationConfig] = None):
"""
Runs an interactive wizard to set generation parameters.
"""
print("Welcome to the ACE-Step Music Generation Wizard!")
print("This will guide you through creating your music.")
print("Press Ctrl+C at any time to exit.")
print("Note: Required models will be auto-downloaded if missing.")
print("-" * 30)
try:
# Task selection
print("\n--- Task Type ---")
print("1. text2music - generate music from text/lyrics.")
print("2. cover - transform existing audio into a new style.")
print("3. repaint - regenerate a specific time segment of audio.")
print("4. lego - generate a specific instrument track in context.")
print("5. extract - isolate a specific instrument track from a mix.")
print("6. complete - complete/extend partial tracks with new instruments.")
task_map = {
"1": "text2music",
"2": "cover",
"3": "repaint",
"4": "lego",
"5": "extract",
"6": "complete",
}
current_task = args.task_type or "text2music"
task_default = next((k for k, v in task_map.items() if v == current_task), "1")
task_choice = input(f"Choose a task (1-6) [default: {task_default}]: ").strip()
if not task_choice:
task_choice = task_default
args.task_type = task_map.get(task_choice, "text2music")
if args.task_type in {"lego", "extract", "complete"}:
print("Note: This task requires a base DiT model (acestep-v15-base). It will be auto-downloaded if missing.")
# Model selection (DiT)
dit_handler = AceStepHandler()
available_dit_models = dit_handler.get_available_acestep_v15_models()
base_only = args.task_type in {"lego", "extract", "complete"}
if base_only and available_dit_models:
available_dit_models = [m for m in available_dit_models if "base" in m.lower()]
if base_only and args.config_path and "base" not in str(args.config_path).lower():
args.config_path = None
if base_only:
if available_dit_models:
if args.config_path in available_dit_models:
selected = args.config_path
else:
selected = available_dit_models[0]
args.config_path = selected
print(f"\nNote: This task requires a base model. Using: {selected}")
else:
print("\nNote: This task requires a base model (e.g., 'acestep-v15-base'). It will be auto-downloaded if missing.")
elif available_dit_models:
selected = _prompt_choice_from_list(
"--- Available DiT Models ---",
available_dit_models,
default=args.config_path,
allow_custom=True,
)
if selected is not None:
args.config_path = selected
else:
print("\nNote: No local DiT models found. The main model will be auto-downloaded during initialization.")
# Model selection (LM)
llm_handler = LLMHandler()
available_lm_models = llm_handler.get_available_5hz_lm_models()
if available_lm_models:
selected_lm = _prompt_choice_from_list(
"--- Available LM Models ---",
available_lm_models,
default=args.lm_model_path,
allow_custom=True,
)
if selected_lm is not None:
args.lm_model_path = selected_lm
else:
print("\nNote: No local LM models found. If LM features are enabled, a default LM will be auto-downloaded.")
# Task-specific inputs
if args.task_type in {"cover", "repaint", "lego", "extract", "complete"}:
args.src_audio = _prompt_existing_file("Enter path to source audio file", default=args.src_audio)
if args.task_type == "repaint":
args.repainting_start = _prompt_float(
"Repaint start time in seconds", args.repainting_start
)
args.repainting_end = _prompt_float(
"Repaint end time in seconds", args.repainting_end
)
if args.task_type in {"lego", "extract"}:
print("\nAvailable tracks:")
print(", ".join(TRACK_CHOICES))
track_default = args.lego_track if args.task_type == "lego" else args.extract_track
track = _prompt_with_default("Choose a track", track_default, required=True)
if track not in TRACK_CHOICES:
print("Unknown track. Using as-is.")
if args.task_type == "lego":
args.lego_track = track
else:
args.extract_track = track
if not args.instruction or args.instruction == DEFAULT_DIT_INSTRUCTION:
args.instruction = _default_instruction_for_task(args.task_type, [track])
args.instruction = _prompt_with_default("Instruction", args.instruction, required=True)
if args.task_type == "complete":
print("\nAvailable tracks:")
print(", ".join(TRACK_CHOICES))
tracks_raw = _prompt_with_default("Choose tracks (comma-separated)", args.complete_tracks, required=True)
tracks = [t.strip() for t in tracks_raw.split(",") if t.strip()]
args.complete_tracks = ",".join(tracks)
if not args.instruction or args.instruction == DEFAULT_DIT_INSTRUCTION:
args.instruction = _default_instruction_for_task(args.task_type, tracks)
args.instruction = _prompt_with_default("Instruction", args.instruction, required=True)
if args.task_type in {"cover", "repaint", "lego", "complete"}:
args.caption = _prompt_with_default(
"Enter a music description (e.g., 'upbeat electronic dance music')",
args.caption,
required=True,
)
elif args.task_type == "text2music":
args.sample_mode = _prompt_bool("Use Simple Mode (auto-generate caption/lyrics via LM)", args.sample_mode)
if args.sample_mode:
args.sample_query = _prompt_with_default(
"Describe the music you want (for auto-generation)",
args.sample_query,
required=False,
)
if not args.sample_mode:
caption = _prompt_with_default(
"Enter a music description (optional if you provide lyrics)",
args.caption,
required=False,
)
if caption:
args.caption = caption
# Lyrics
if args.task_type in {"text2music", "cover", "repaint", "lego", "complete"} and not args.sample_mode:
print("\n--- Lyrics Options ---")
print("1. Instrumental (no lyrics).")
print("2. Generate lyrics automatically.")
print("3. Provide path to a .txt file.")
print("4. Paste lyrics directly.")
if args.instrumental or args.lyrics == "[Instrumental]":
default_choice = "1"
elif args.use_cot_lyrics:
default_choice = "2"
elif args.lyrics and isinstance(args.lyrics, str) and os.path.isfile(args.lyrics):
default_choice = "3"
elif args.lyrics:
default_choice = "4"
else:
default_choice = "1"
choice = input(f"Your choice (1-4) [default: {default_choice}]: ").strip()
if not choice:
choice = default_choice
if choice == "1": # Instrumental
args.instrumental = True
args.lyrics = "[Instrumental]"
args.use_cot_lyrics = False
print("Instrumental music will be generated.")
elif choice == "2": # Generate lyrics automatically
args.use_cot_lyrics = True
args.lyrics = ""
args.instrumental = False
print("Lyrics will be generated automatically.")
elif choice == "3":
args.instrumental = False
args.use_cot_lyrics = False
default_lyrics_path = args.lyrics if isinstance(args.lyrics, str) and os.path.isfile(args.lyrics) else None
while True:
lyrics_path = _prompt_existing_file("Please enter the path to your .txt lyrics file", default_lyrics_path)
if lyrics_path.endswith('.txt'):
args.lyrics = lyrics_path
print(f"Lyrics will be loaded from: {lyrics_path}")
break
print("Invalid file path or not a .txt file. Please try again.")
elif choice == "4":
args.instrumental = False
args.use_cot_lyrics = False
default_lyrics = args.lyrics if isinstance(args.lyrics, str) and args.lyrics and not os.path.isfile(args.lyrics) else None
args.lyrics = _prompt_with_default("Paste lyrics (single line or use \\n)", default_lyrics, required=True)
if not args.instrumental:
lang = _prompt_with_default(
"Vocal language (e.g., 'en', 'zh', 'unknown')",
args.vocal_language,
required=False
).lower()
if lang:
args.vocal_language = lang
if args.use_cot_lyrics:
if not args.caption:
args.caption = _prompt_non_empty("Enter a music description for lyric generation: ")
if not args.thinking:
print("INFO: Automatic lyric generation requires the LM handler. Enabling LM 'thinking'.")
args.thinking = True
args.batch_size = _prompt_int(
"Number of outputs (audio clips) to generate",
args.batch_size if args.batch_size is not None else 1,
min_value=1,
)
advanced = input("\nConfigure advanced parameters? (y/n) [default: n]: ").lower()
if advanced == 'y':
if args.task_type == "text2music" and not args.sample_mode:
args.use_format = _prompt_bool("Use format_sample to enhance caption/lyrics", args.use_format)
print("\n--- Optional Metadata ---")
args.duration = _prompt_float("Duration in seconds (10-600)", args.duration, min_value=10, max_value=600)
args.bpm = _prompt_int("BPM (30-300, empty for auto)", args.bpm, min_value=30, max_value=300)
args.keyscale = _prompt_with_default("Keyscale (e.g., 'C Major', empty for auto)", args.keyscale)
args.timesignature = _prompt_with_default("Time signature (e.g., '4/4', empty for auto)", args.timesignature)
args.vocal_language = _prompt_with_default("Vocal language (e.g., 'en', 'zh', 'unknown')", args.vocal_language)
print("\n--- Advanced DiT Settings ---")
args.seed = _prompt_int("Random seed (-1 for random)", args.seed)
args.inference_steps = _prompt_int("Inference steps", args.inference_steps, min_value=1)
if args.config_path and 'base' in args.config_path:
args.guidance_scale = _prompt_float("Guidance scale (for base models)", args.guidance_scale)
args.use_adg = _prompt_bool("Enable Adaptive Dual Guidance (ADG)", args.use_adg)
args.cfg_interval_start = _prompt_float("CFG interval start (0.0-1.0)", args.cfg_interval_start, 0.0, 1.0)
args.cfg_interval_end = _prompt_float("CFG interval end (0.0-1.0)", args.cfg_interval_end, 0.0, 1.0)
args.shift = _prompt_float("Timestep shift (1.0-5.0)", args.shift, 1.0, 5.0)
args.infer_method = _prompt_with_default("Inference method (ode/sde)", args.infer_method)
timesteps_input = _prompt_with_default(
"Custom timesteps list (e.g., [0.97, 0.5, 0])",
args.timesteps,
required=False,
)
if timesteps_input:
args.timesteps = timesteps_input
if args.task_type == "cover":
args.audio_cover_strength = _prompt_float(
"Audio cover strength (0.0-1.0)", args.audio_cover_strength, 0.0, 1.0
)
print("\n--- Advanced LM Settings ---")
args.thinking = _prompt_bool("Enable LM 'thinking'", args.thinking)
args.lm_temperature = _prompt_float("LM temperature (0.0-2.0)", args.lm_temperature, 0.0, 2.0)
args.lm_cfg_scale = _prompt_float("LM CFG scale", args.lm_cfg_scale)
args.lm_top_k = _prompt_int("LM top-k (0 disables)", args.lm_top_k, min_value=0)
args.lm_top_p = _prompt_float("LM top-p (0.0-1.0)", args.lm_top_p, 0.0, 1.0)
args.lm_negative_prompt = _prompt_with_default("LM negative prompt", args.lm_negative_prompt)
args.use_cot_metas = _prompt_bool("Use CoT for metadata", args.use_cot_metas)
args.use_cot_caption = _prompt_bool("Use CoT for caption refinement", args.use_cot_caption)
args.use_cot_lyrics = _prompt_bool("Use CoT for lyrics generation", args.use_cot_lyrics)
args.use_cot_language = _prompt_bool("Use CoT for language detection", args.use_cot_language)
args.use_constrained_decoding = _prompt_bool("Use constrained decoding", args.use_constrained_decoding)
print("\n--- Output Settings ---")
args.save_dir = _prompt_with_default("Save directory", args.save_dir)
args.audio_format = _prompt_with_default("Audio format (mp3/wav/flac)", args.audio_format)
# Batch size already captured above.
args.use_random_seed = _prompt_bool("Use random seed per batch", args.use_random_seed)
seeds_input = _prompt_with_default(
"Custom seeds (comma/space separated, leave empty for random)",
"",
required=False,
)
if seeds_input:
seeds = [s for s in seeds_input.replace(",", " ").split() if s.strip()]
try:
args.seeds = [int(s) for s in seeds]
except ValueError:
print("Invalid seeds input. Ignoring custom seeds.")
args.allow_lm_batch = _prompt_bool("Allow LM batch processing", args.allow_lm_batch)
args.lm_batch_chunk_size = _prompt_int("LM batch chunk size", args.lm_batch_chunk_size, min_value=1)
args.constrained_decoding_debug = _prompt_bool("Constrained decoding debug", args.constrained_decoding_debug)
else:
if params_defaults and config_defaults:
_apply_optional_defaults(args, params_defaults, config_defaults)
# Ensure LM thinking is enabled when lyric generation is requested.
if args.use_cot_lyrics and not args.thinking:
print("INFO: Automatic lyric generation requires the LM handler. Enabling LM 'thinking'.")
args.thinking = True
print("\n--- Summary ---")
print(f"Task: {args.task_type}")
if args.caption:
print(f"Description: {args.caption}")
if args.task_type in {"lego", "extract", "complete"}:
print(f"Instruction: {args.instruction}")
if args.src_audio:
print(f"Source audio: {args.src_audio}")
print(f"Duration: {args.duration}s")
print(f"Outputs: {args.batch_size}")
if args.instrumental:
print("Lyrics: Instrumental")
elif args.use_cot_lyrics:
print(f"Lyrics: Auto-generated ({args.vocal_language})")
elif args.lyrics and os.path.isfile(args.lyrics):
print(f"Lyrics: Provided from file ({args.lyrics})")
elif args.lyrics:
print(f"Lyrics: Provided as text")
print("-" * 30)
if not configure_only:
confirm = input("Start generation with these settings? (y/n) [default: y]: ").lower()
if confirm == 'n':
print("Generation cancelled.")
sys.exit(0)
default_filename = default_config_path or "config.toml"
config_filename = input(f"\nEnter filename to save configuration [{default_filename}]: ")
if not config_filename:
config_filename = default_filename
if not config_filename.endswith(".toml"):
config_filename += ".toml"
try:
config_to_save = {
k: v for k, v in vars(args).items()
if k not in ['config'] and not k.startswith('_')
}
with open(config_filename, 'w') as f:
toml.dump(config_to_save, f)
print(f"Configuration saved to {config_filename}")
print(f"You can reuse it next time with: python cli.py -c {config_filename}")
except Exception as e:
print(f"Error saving configuration: {e}. Please try again.")
except (KeyboardInterrupt, EOFError):
print("\nWizard cancelled. Exiting.")
sys.exit(0)
return args, not configure_only
def main():
"""
Main function to run ACE-Step music generation from the command line.
"""
gpu_config = get_gpu_config()
# Override tier thresholds in CLI without modifying gpu_config.py.
# For MPS, use iogpu.wired_limit_mb as a proxy for memory when available.
mem_gib = None
if gpu_config.gpu_memory_gb > 0:
mem_gib = gpu_config.gpu_memory_gb
else:
mps_available = hasattr(torch.backends, "mps") and torch.backends.mps.is_available()