-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathgenerate_ace.py
More file actions
1457 lines (1251 loc) · 53.8 KB
/
generate_ace.py
File metadata and controls
1457 lines (1251 loc) · 53.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 os
import sys
import random
import threading
import inspect
from pathlib import Path
from typing import Dict, Any, Optional, Callable, List
# Make HF Hub use real files instead of symlinks (Windows privilege issue)
os.environ.setdefault("HF_HUB_DISABLE_SYMLINKS", "1")
# ---------------------------------------------------------------------------
# Critical: Import lzma EARLY (before any ACE-Step imports)
# This matches CI execution where lzma is available when py3langid needs it
# ---------------------------------------------------------------------------
try:
import lzma
import _lzma # C extension - ensure it's loaded
# Test that lzma is functional (critical for py3langid in LangSegment)
_lzma_test_data = b"test_lzma_init"
_lzma_compressed = lzma.compress(_lzma_test_data)
_lzma_decompressed = lzma.decompress(_lzma_compressed)
if _lzma_decompressed == _lzma_test_data:
# Only print in frozen apps to avoid cluttering CI logs
if getattr(sys, 'frozen', False):
print("[generate_ace] lzma module initialized successfully (required for py3langid).", flush=True)
else:
print("[generate_ace] WARNING: lzma module test failed.", flush=True)
except ImportError as e:
print(f"[generate_ace] WARNING: Failed to import lzma module: {e}", flush=True)
print("[generate_ace] Language detection (py3langid) may fail.", flush=True)
except Exception as e:
print(f"[generate_ace] WARNING: lzma module initialization error: {e}", flush=True)
from pydub import AudioSegment
from ace_model_setup import ensure_ace_models
# ---------------------------------------------------------------------------
# Torchaudio → WAV shim (bypass torchcodec / FFmpeg issues)
# ---------------------------------------------------------------------------
try:
import torch
import torchaudio
import wave
import numpy as np
def _candy_torchaudio_save(
filepath,
src,
sample_rate: int,
format: str | None = None,
backend: str | None = None,
**kwargs: Any,
) -> None:
"""
Minimal replacement for torchaudio.save that writes 16-bit PCM WAVs
without going through torchcodec / FFmpeg.
Only intended for the ACE-Step pipeline in this app.
"""
if src is None:
raise ValueError("torchaudio.save: got None tensor")
# src is typically [channels, num_samples] (or [num_samples] / [B, C, T])
if hasattr(src, "detach"):
wav = src.detach().cpu()
else:
raise TypeError("torchaudio.save: expected a torch.Tensor-like object")
if wav.ndim == 1:
wav = wav.unsqueeze(0) # [T] -> [1, T]
elif wav.ndim == 3:
wav = wav[0] # [B, C, T] -> [C, T]
if wav.ndim != 2:
raise ValueError(f"torchaudio.save: unexpected tensor shape {tuple(wav.shape)}")
# Clamp to [-1, 1] and convert to int16 PCM
wav = wav.clamp(-1.0, 1.0)
wav_i16 = (wav * 32767.0).to(torch.int16).numpy()
channels, num_samples = wav_i16.shape
# Ensure parent dir exists
parent = os.path.dirname(str(filepath)) or "."
os.makedirs(parent, exist_ok=True)
# Write a vanilla RIFF/WAVE file
with wave.open(str(filepath), "wb") as fh:
fh.setnchannels(int(channels))
fh.setsampwidth(2) # 16-bit
fh.setframerate(int(sample_rate))
fh.writeframes(wav_i16.T.tobytes())
def _candy_torchaudio_load(
filepath,
frame_offset: int = 0,
num_frames: int = -1,
normalize: bool = True,
channels_first: bool = True,
format: str | None = None,
):
"""
Minimal replacement for torchaudio.load that reads 16-bit PCM WAVs
without going through torchcodec / FFmpeg.
Only intended for ACE-Step's reference / edit audio paths in this app.
"""
path_str = str(filepath)
# Read the entire WAV (or a slice) using built-in wave
with wave.open(path_str, "rb") as fh:
n_channels = fh.getnchannels()
sample_rate = fh.getframerate()
n_frames_total = fh.getnframes()
# Clamp starting position
if frame_offset < 0:
frame_offset = 0
if frame_offset > n_frames_total:
frame_offset = n_frames_total
fh.setpos(frame_offset)
# Decide how many frames to read
if num_frames is None or num_frames < 0:
frames_to_read = n_frames_total - frame_offset
else:
frames_to_read = min(num_frames, n_frames_total - frame_offset)
raw_bytes = fh.readframes(frames_to_read)
if not raw_bytes:
# Empty audio tensor
empty = torch.zeros((n_channels, 0), dtype=torch.float32)
return empty if channels_first else empty.t(), sample_rate
# Convert bytes → int16 → float32
audio_i16 = np.frombuffer(raw_bytes, dtype=np.int16)
# Shape: [num_samples, channels]
if n_channels > 0:
audio = audio_i16.reshape(-1, n_channels).astype("float32")
else:
audio = audio_i16.astype("float32").reshape(-1, 1)
n_channels = 1
if normalize:
audio /= 32768.0
audio_tensor = torch.from_numpy(audio) # [num_samples, channels]
if channels_first:
audio_tensor = audio_tensor.t() # [channels, num_samples]
return audio_tensor, sample_rate
# Monkey-patch torchaudio.save/load before ACE-Step uses them
torchaudio.save = _candy_torchaudio_save # type: ignore[assignment]
torchaudio.load = _candy_torchaudio_load # type: ignore[assignment]
except Exception as _ta_err:
# If this somehow fails, we fall back to the original torchaudio.load/save,
# in which case you'll still see the torchcodec error.
pass
# ACE-Step pipeline (using cdmf_pipeline_ace_step.py)
_ACE_IMPORT_ERROR = None # <-- MUST exist before the try
try:
from cdmf_pipeline_ace_step import ACEStepPipeline
except Exception as e: # import-time diagnostics only
ACEStepPipeline = None # type: ignore[assignment]
_ACE_IMPORT_ERROR = e
# Print import error immediately for debugging frozen apps
print(f"[ACE] WARNING: Failed to import ACEStepPipeline: {type(e).__name__}: {e}", flush=True)
# -----------------------------------------------------------------------------
# Basic config
# -----------------------------------------------------------------------------
import cdmf_paths
# Default target length + fades (UI can override)
DEFAULT_TARGET_SECONDS = 150.0
DEFAULT_FADE_IN_SECONDS = 0.5
DEFAULT_FADE_OUT_SECONDS = 0.5
# Where this script lives
APP_DIR = Path(__file__).parent.resolve()
# Force Hugging Face cache into the configured models folder
HF_HOME = cdmf_paths.get_models_folder()
os.environ.setdefault("HF_HOME", str(HF_HOME))
# Default output root if none is explicitly provided
DEFAULT_OUTPUT_ROOT = APP_DIR / "generated"
# Subfolder where ACE-Step input_params JSONs will be stored, relative to each
# output directory (e.g. generated/input_params_record).
INPUT_PARAMS_SUBDIR_NAME = "input_params_record"
# If you decide to call a local ACE-Step repo via infer-api.py instead of
# importing its Python API, you can point to it here:
ACE_STEP_REPO_DIR = Path(os.environ.get("ACE_STEP_REPO_DIR", APP_DIR / "ACE-Step")).resolve()
# Force ACE-Step to look for checkpoints inside the configured models folder
os.environ.setdefault(
"ACE_STEP_CACHE_DIR",
str(cdmf_paths.get_models_folder().resolve())
)
# -----------------------------------------------------------------------------
# Progress callback plumbing (UI can hook into this)
# -----------------------------------------------------------------------------
ProgressCallback = Callable[[float, str], None]
# Job progress: (fraction, stage, steps_current, steps_total, eta_seconds)
JobProgressCallback = Callable[[float, str, Optional[int], Optional[int], Optional[float]], None]
_PROGRESS_CALLBACK: Optional[ProgressCallback] = None
_JOB_PROGRESS_CALLBACK: Optional[JobProgressCallback] = None
def register_progress_callback(cb: Optional[ProgressCallback]) -> None:
"""
Register a callback that receives (fraction, stage) during generation.
fraction: 0.0 → 1.0
stage: arbitrary label ("ace", "fades", etc.)
"""
global _PROGRESS_CALLBACK
_PROGRESS_CALLBACK = cb
def register_job_progress_callback(cb: Optional[JobProgressCallback]) -> None:
"""
Register a callback for API job progress: (fraction, stage, steps_current,
steps_total, eta_seconds). Used to update per-job progress and ETA in the API.
"""
global _JOB_PROGRESS_CALLBACK
_JOB_PROGRESS_CALLBACK = cb
def _report_progress(
fraction: float,
stage: str = "ace",
steps_current: Optional[int] = None,
steps_total: Optional[int] = None,
eta_seconds: Optional[float] = None,
) -> None:
"""
Internal helper to report progress to the UI and optional job progress callback.
"""
try:
frac = float(fraction)
except Exception:
frac = 0.0
if _PROGRESS_CALLBACK is not None:
try:
_PROGRESS_CALLBACK(frac, stage)
except Exception:
pass
if _JOB_PROGRESS_CALLBACK is not None:
try:
_JOB_PROGRESS_CALLBACK(frac, stage, steps_current, steps_total, eta_seconds)
except Exception:
pass
# -----------------------------------------------------------------------------
# ACE-Step pipeline singleton
# -----------------------------------------------------------------------------
_ACE_PIPELINE: Optional["ACEStepPipeline"] = None
_ACE_PIPELINE_LOCK = threading.Lock()
_ACE_GENERATION_LOCK = threading.Lock()
def _monkeypatch_ace_tqdm() -> None:
"""
Patch ACE-Step's internal `tqdm` so its diffusion/decoding loops
feed into our `_report_progress` callback.
This makes the front-end progress bar track *actual* backend work
instead of just a couple of coarse jumps.
"""
if ACEStepPipeline is None:
return
try:
import cdmf_pipeline_ace_step as ace_mod
except Exception:
# If the module isn't importable for some reason, just bail out.
return
# Avoid double-patching if `_get_ace_pipeline()` is called more than once.
if getattr(ace_mod, "_candy_tqdm_patched", False):
return
orig_tqdm = ace_mod.tqdm
# Map ACE internal function names → (global_progress_start, global_progress_end)
# These ranges sit inside [0.0, 1.0] for the overall job.
STAGE_RANGES = {
# Main diffusion / editing loops
"text2music_diffusion_process": (0.20, 0.80),
"flowedit_diffusion_process": (0.20, 0.80),
# Latents → waveform decode
"latents2audio": (0.80, 0.90),
}
def candy_tqdm(iterable=None, *args, **kwargs):
"""
Wrapper around ACE's original `tqdm` that:
- figures out which ACE function is using it (via call stack),
- maps inner progress 0..1 to a global 0..1 window,
- forwards updates to `_report_progress`,
- otherwise behaves like a normal tqdm over `iterable`.
"""
stage_name = "ace"
start, end = 0.20, 0.90 # default fallback span
try:
stack = inspect.stack()
# Look a few frames up the stack for a known ACE function name
for frame_info in stack[1:6]:
fn = frame_info.function
if fn in STAGE_RANGES:
start, end = STAGE_RANGES[fn]
stage_name = fn
break
except Exception:
# If inspection fails, we still run the original tqdm
pass
# If tqdm is used in "manual" mode (no iterable), just delegate.
if iterable is None:
return orig_tqdm(*args, **kwargs)
# Try to get a total if not explicitly provided
total = kwargs.get("total")
if total is None:
try:
total = len(iterable)
except Exception:
total = None
inner = orig_tqdm(iterable, *args, **kwargs)
def generator():
# Protect against division-by-zero
span = max(0.0, float(end) - float(start))
idx = 0
denom = float(total) if total else None
for item in inner:
idx += 1
if denom:
frac_local = idx / denom # 0..1 within this stage
frac_global = start + span * frac_local
steps_cur = getattr(inner, "n", idx)
steps_tot = getattr(inner, "total", None)
eta_sec = None
try:
fd = getattr(inner, "format_dict", None)
if fd and isinstance(fd, dict):
eta_sec = fd.get("remaining")
if eta_sec is not None and not isinstance(eta_sec, (int, float)):
eta_sec = None
except Exception:
pass
try:
_report_progress(
frac_global,
stage=stage_name,
steps_current=steps_cur if steps_tot is not None else None,
steps_total=int(steps_tot) if steps_tot is not None else None,
eta_seconds=float(eta_sec) if eta_sec is not None else None,
)
except Exception:
pass
yield item
return generator()
ace_mod.tqdm = candy_tqdm
ace_mod._candy_tqdm_patched = True
def _get_ace_pipeline() -> "ACEStepPipeline":
"""
Lazily construct and cache a single ACEStepPipeline instance.
We explicitly point it at our app-local ACE cache so it reuses the
model that the "Download Models" button fetched, instead of trying to
re-download into the user's home directory.
"""
global _ACE_PIPELINE
if _ACE_PIPELINE is not None:
return _ACE_PIPELINE
if ACEStepPipeline is None:
# Check if running as frozen app (macOS .app bundle)
is_frozen = getattr(sys, 'frozen', False)
# Format error details
error_type = type(_ACE_IMPORT_ERROR).__name__ if _ACE_IMPORT_ERROR else "Unknown"
error_msg_detail = str(_ACE_IMPORT_ERROR) if _ACE_IMPORT_ERROR else "No error details available"
if is_frozen:
# For frozen app, acestep should already be bundled
error_msg = (
"ACEStepPipeline could not be imported from cdmf_pipeline_ace_step.py.\n\n"
"This is unexpected in a frozen app bundle - the ace-step package\n"
"should have been bundled during the build process.\n\n"
"Possible causes:\n"
"- The app bundle was built without ace-step installed\n"
"- A dependency is missing or incompatible\n\n"
"Try downloading a fresh copy of AceForge from:\n"
" https://github.com/audiohacking/AceForge/releases\n\n"
f"Original import error ({error_type}):\n{error_msg_detail}"
)
else:
# For running from source
error_msg = (
"ACEStepPipeline could not be imported from cdmf_pipeline_ace_step.py.\n\n"
"This usually means the ace-step package is not installed.\n"
"ACE-Step must be installed from GitHub (not PyPI) using:\n"
' pip install "git+https://github.com/ace-step/ACE-Step.git" --no-deps\n\n'
"Or run the setup using the launcher script (CDMF.sh / CDMF.bat) which\n"
"will handle all dependencies automatically.\n\n"
f"Original import error ({error_type}):\n{error_msg_detail}"
)
raise RuntimeError(error_msg)
with _ACE_PIPELINE_LOCK:
if _ACE_PIPELINE is not None:
return _ACE_PIPELINE
print(
"[ACE] Initializing ACEStepPipeline (first time will download/load checkpoints)...",
flush=True,
)
_report_progress(0.05, "ace_load")
# Make sure our dedicated ACE cache under ace_models/checkpoints is ready.
try:
checkpoint_root = ensure_ace_models()
except Exception as exc:
raise RuntimeError(
"Failed to prepare ACE-Step checkpoints. "
"See the console logs above for details."
) from exc
# Wire ACE's internal progress bars into our callback before heavy work starts.
_monkeypatch_ace_tqdm()
# Tell ACE-Step to use our cache root as its checkpoint_dir so it
# doesn't try to re-download into ~/.cache/ace-step/checkpoints.
pipeline = ACEStepPipeline(checkpoint_dir=str(checkpoint_root))
_ACE_PIPELINE = pipeline
print("[ACE] ACEStepPipeline ready.", flush=True)
return _ACE_PIPELINE
# -----------------------------------------------------------------------------
# Vibe tags (mapped into ACE "Tags" field)
# -----------------------------------------------------------------------------
ACE_VIBE_TAGS: Dict[str, List[str]] = {
"lofi_dreamy": [
"lofi", "downtempo", "dreamy", "soft beats", "chill"
],
"chiptunes_upbeat": [
"chiptune", "8-bit", "upbeat", "retro game soundtrack"
],
"chiptunes_zelda": [
"chiptune", "fantasy", "adventure", "RPG", "game soundtrack"
],
"fantasy": [
"fantasy", "orchestral", "cinematic", "RPG background music"
],
"cyberpunk": [
"cyberpunk", "synthwave", "electronic", "neon", "dark"
],
"misc": [],
"any": [],
}
# -----------------------------------------------------------------------------
# Helpers
# -----------------------------------------------------------------------------
def _choose_effective_seed(seed: int) -> int:
if seed and seed > 0:
return int(seed)
eff = random.randint(1, 2**31 - 1)
print(f"[ACE] No seed or seed=0 provided → using random seed {eff}")
return eff
def _next_available_output_path(out_dir: Path, basename: str, ext: str = ".wav") -> Path:
"""Use shared helper to avoid overwriting existing files (-1, -2, -3, ...)."""
stem = Path(basename).stem if basename else "output"
return cdmf_paths.get_next_available_output_path(out_dir, stem, ext)
def _apply_vibe_to_tags(prompt: str, seed_vibe: str) -> str:
"""
Take the user's freeform style prompt and merge it with a seed-vibe tag set.
This ends up in ACE-Step's "Tags" field.
"""
prompt = (prompt or "").strip()
key = (seed_vibe or "").strip() or "any"
tags = ACE_VIBE_TAGS.get(key, [])
tag_text = ", ".join(tags) if tags else ""
if tag_text and prompt:
return f"{tag_text}, {prompt}"
return prompt or tag_text
def _ensure_reference_wav(src_audio_path: str | None) -> str:
"""
Normalise a reference audio path so ACE-Step can consume it.
- Ensures the file exists.
- If it's already a .wav, returns the absolute path.
- If it's another audio type (e.g. .mp3), converts it to .wav next to
the original file and returns that path.
"""
if not src_audio_path:
raise ValueError(
"Audio2Audio / retake / repaint / extend modes require a reference audio file."
)
src = Path(src_audio_path).expanduser()
if not src.is_file():
raise FileNotFoundError(f"Reference audio not found: {src}")
if src.suffix.lower() == ".wav":
return str(src.resolve())
# Convert to WAV using pydub so ACE-Step always sees a .wav file.
try:
audio = AudioSegment.from_file(str(src))
except Exception as e:
raise RuntimeError(f"Failed to read reference audio {src}: {e}") from e
wav_path = src.with_suffix(".wav")
try:
wav_path.parent.mkdir(parents=True, exist_ok=True)
audio.export(str(wav_path), format="wav")
except Exception as e:
raise RuntimeError(f"Failed to convert {src} to WAV: {e}") from e
print(f"[ACE] Converted reference audio to WAV for ACE-Step: {wav_path}", flush=True)
return str(wav_path.resolve())
def _prepare_reference_audio(
task: str,
audio2audio_enable: bool,
src_audio_path: str | None,
) -> tuple[str, bool, Optional[str]]:
"""
Normalise the ACE-Step edit / audio2audio mode (task_type, reference_audio, src_audio per Tutorial/INFERENCE):
- Task (task_type) is clamped to one of: text2music / retake / repaint / extend.
- UI tasks "cover" and "audio2audio" are mapped to "retake" (ACE-Step
then uses ref_audio_input and sets task to "audio2audio" internally).
- If Audio2Audio is enabled while task is still 'text2music', we
internally flip it to 'retake' (this is how ACE-Step expects edits).
- For any edit mode (retake/repaint/extend) we prefer to have a
reference audio file and make sure ACE-Step sees a .wav path.
If no reference is provided, we *gracefully* fall back to
text2music instead of throwing.
"""
task_norm = (task or "text2music").strip().lower()
if task_norm not in ("text2music", "retake", "repaint", "extend", "cover", "audio2audio", "lego", "extract", "complete"):
task_norm = "text2music"
# Map UI task names to pipeline task: cover and audio2audio both run as retake
# (pipeline will set task to "audio2audio" when ref_audio_input is passed).
if task_norm in ("cover", "audio2audio"):
task_norm = "retake"
# Audio2Audio is effectively an edit of an existing clip. If the user
# left the task on "Text → music", run it as a retake under the hood.
if audio2audio_enable and task_norm == "text2music":
task_norm = "retake"
# Any of the edit-style tasks imply some form of Audio2Audio or source-backed (lego/extract/complete).
audio2audio_flag = bool(
audio2audio_enable or task_norm in ("retake", "repaint", "extend")
)
needs_src_path = audio2audio_flag or task_norm in ("lego", "extract", "complete")
# If we need source/reference audio but none was provided, fall back to text2music (or fail for lego/extract/complete).
if needs_src_path and not src_audio_path:
if task_norm in ("lego", "extract", "complete"):
raise ValueError(
f"Task '{task_norm}' requires backing/source audio. Please provide it in the Lego tab or Custom audio card."
)
print(
"[ACE] Audio2Audio / edit task requested but no reference audio "
"was provided — falling back to plain text2music.",
flush=True,
)
task_norm = "text2music"
audio2audio_flag = False
return task_norm, audio2audio_flag, None
if audio2audio_flag:
ref_path = _ensure_reference_wav(src_audio_path)
elif task_norm in ("lego", "extract", "complete"):
ref_path = _ensure_reference_wav(src_audio_path) # pipeline uses this as src_audio_path
else:
ref_path = None
return task_norm, audio2audio_flag, ref_path
def _apply_fades_in_place(
wav_path: Path,
fade_in_seconds: float,
fade_out_seconds: float,
) -> float:
audio = AudioSegment.from_file(wav_path)
duration_ms = len(audio)
if duration_ms <= 0:
return 0.0
fi = max(0.0, float(fade_in_seconds))
fo = max(0.0, float(fade_out_seconds))
half_sec = (duration_ms / 1000.0) / 2.0
fi = min(fi, half_sec)
fo = min(fo, half_sec)
if fi > 0:
audio = audio.fade_in(int(fi * 1000.0))
if fo > 0:
audio = audio.fade_out(int(fo * 1000.0))
audio.export(str(wav_path), format="wav")
return duration_ms / 1000.0
def _apply_vocal_instrumental_mix_if_requested(
wav_path: Path,
vocal_gain_db: float,
instrumental_gain_db: float,
) -> None:
"""
Optional post-process step:
If either gain is non-zero, use `audio-separator` to split the track into
Vocals + Instrumental stems, apply the requested dB changes, then write
the mixed result back into ``wav_path`` in-place.
If audio-separator (or its model/FFmpeg deps) aren't available, this
quietly logs and does nothing.
"""
try:
vg = float(vocal_gain_db)
ig = float(instrumental_gain_db)
except Exception:
return
# Nothing to do if both sliders are effectively at 0 dB.
if abs(vg) < 0.1 and abs(ig) < 0.1:
return
wav_path = Path(wav_path)
if not wav_path.exists():
print(f"[ACE] Stem mix requested but file does not exist: {wav_path}", flush=True)
return
try:
from audio_separator.separator import Separator # type: ignore[import]
except Exception as exc:
print(
"[ACE] Vocal/instrumental sliders requested but the "
"'audio-separator' package is not available; skipping stem mix: "
f"{exc}",
flush=True,
)
return
tmp_dir = wav_path.parent / "_cdmf_stems_tmp"
try:
tmp_dir.mkdir(parents=True, exist_ok=True)
except Exception as exc:
print(f"[ACE] Could not create temporary stem folder {tmp_dir}: {exc}", flush=True)
return
try:
# Keep models cached in tmp_dir/models so we don't re-download every time.
models_dir = tmp_dir / "models"
models_dir.mkdir(parents=True, exist_ok=True)
separator = Separator(
model_file_dir=str(models_dir),
output_dir=str(tmp_dir),
output_format="wav",
)
separator.load_model()
except Exception as exc:
print(f"[ACE] Failed to load audio-separator model; skipping stem mix: {exc}", flush=True)
return
output_names = {
"Vocals": "cdmf_vocals",
"Instrumental": "cdmf_instrumental",
}
try:
separator.separate(str(wav_path), output_names)
except Exception as exc:
print(f"[ACE] audio-separator failed on {wav_path}: {exc}", flush=True)
return
vocal_file = tmp_dir / "cdmf_vocals.wav"
inst_file = tmp_dir / "cdmf_instrumental.wav"
if not vocal_file.exists() or not inst_file.exists():
print(
"[ACE] audio-separator did not produce expected stems "
f"({vocal_file}, {inst_file}); skipping stem mix.",
flush=True,
)
return
try:
vocal_seg = AudioSegment.from_file(vocal_file)
inst_seg = AudioSegment.from_file(inst_file)
except Exception as exc:
print(f"[ACE] Failed to read separated stems: {exc}", flush=True)
return
# Align durations by padding the shorter clip with silence.
max_len = max(len(vocal_seg), len(inst_seg))
if len(vocal_seg) < max_len:
vocal_seg = vocal_seg + AudioSegment.silent(duration=max_len - len(vocal_seg))
if len(inst_seg) < max_len:
inst_seg = inst_seg + AudioSegment.silent(duration=max_len - len(inst_seg))
# pydub's '+' operator is dB gain.
if abs(vg) > 0.05:
vocal_seg = vocal_seg + vg
if abs(ig) > 0.05:
inst_seg = inst_seg + ig
mixed = inst_seg.overlay(vocal_seg)
try:
mixed.export(str(wav_path), format="wav")
print(
"[ACE] Applied vocal/instrumental mix: "
f"vocals {vg:+.1f} dB, instrumental {ig:+.1f} dB.",
flush=True,
)
except Exception as exc:
print(f"[ACE] Failed to write mixed stem back to {wav_path}: {exc}", flush=True)
# Best-effort cleanup
try:
for p in tmp_dir.glob("*"):
try:
p.unlink()
except Exception:
pass
tmp_dir.rmdir()
except Exception:
pass
# ACE-Step 1.5 LM planner dir names (same as api/ace_step_models.ACESTEP15_LM_IDS)
_ACE_STEP_LM_DIRS = {"0.6B": "acestep-5Hz-lm-0.6B", "1.7B": "acestep-5Hz-lm-1.7B", "4B": "acestep-5Hz-lm-4B"}
def _resolve_lm_checkpoint_path(ace_step_lm: str, checkpoints_root: Optional[Path] = None) -> Optional[Path]:
"""
Resolve the LM planner checkpoint path from Settings (ace_step_lm).
Returns None if ace_step_lm is 'none' or not in map, or if the dir is not present.
Uses checkpoints_root if provided, else get_models_folder()/checkpoints.
No external LLM: this is the path to the downloaded ACE-Step 5Hz LM.
"""
if not ace_step_lm or (ace_step_lm or "").strip().lower() == "none":
return None
lm_id = (ace_step_lm or "").strip()
dir_name = _ACE_STEP_LM_DIRS.get(lm_id)
if not dir_name:
return None
if checkpoints_root is None:
checkpoints_root = Path(cdmf_paths.get_models_folder()) / "checkpoints"
path = checkpoints_root / dir_name
if not path.is_dir():
return None
return path
# -----------------------------------------------------------------------------
# ACE-Step bridge (to be wired to the real API)
# -----------------------------------------------------------------------------
def _run_ace_text2music(
*,
tags: str,
lyrics: str,
seconds: float,
seed: int,
output_path: Path,
steps: int = 85,
guidance_scale: float = 10.0,
# --- Advanced knobs (exposed via Advanced panel) -----------------------
scheduler_type: str = "euler",
cfg_type: str = "apg",
omega_scale: float = 5.0,
guidance_interval: float = 1.0,
guidance_interval_decay: float = 0.25,
min_guidance_scale: float = 7.0,
use_erg_tag: bool = True,
use_erg_lyric: bool = True,
use_erg_diffusion: bool = True,
oss_steps: str | list[int] | None = None,
# Retake / repaint / extend controls
task: str = "text2music",
repaint_start: float = 0.0,
repaint_end: float = 0.0,
retake_variance: float = 0.2, # MCP retake/repaint use 0.2
src_audio_path: str | None = None,
# Audio2Audio + LoRA (ref_audio_strength 0.5 matches ACE-Step-MCP / pipeline default)
audio2audio_enable: bool = False,
ref_audio_strength: float = 0.5,
lora_name_or_path: str | None = None,
lora_weight: float = 0.75,
cancel_check: Optional[Callable[[], bool]] = None,
vocal_language: str | None = None,
# Thinking / LM / CoT (passed to pipeline; used when LM path is integrated)
thinking: bool = False,
use_cot_metas: bool = True,
use_cot_caption: bool = True,
use_cot_language: bool = True,
lm_temperature: float = 0.85,
lm_cfg_scale: float = 2.0,
lm_top_k: int = 0,
lm_top_p: float = 0.9,
lm_negative_prompt: str = "NO USER INPUT",
lm_checkpoint_path: Optional[Path] = None,
) -> None:
"""
Call ACE-Step Text2Music and render a single track into ``output_path``.
Mapping to ACEStepPipeline.__call__:
• Candy “genre_prompt” (+ vibe tags) → ACE ``prompt`` (aka Tags)
• Candy ``lyrics`` → ACE ``lyrics``
(we pass ``[inst]`` for instrumentals upstream)
• ``seconds`` → ``audio_duration``
• ``steps`` → ``infer_step``
• ``guidance_scale`` → ``guidance_scale``
• ``scheduler_type`` → ``scheduler_type`` (euler / heun / pingpong)
• ``cfg_type`` → ``cfg_type`` (apg / cfg / cfg_star)
• ``omega_scale`` → ``omega_scale`` (granularity)
• ``guidance_interval*`` → guidance window / decay controls
• ``use_erg_*`` → ERG tag / lyric / diffusion toggles
• ``oss_steps`` → custom sigma steps
• ``task`` / repaint_* / variance → retake / repaint / extend behaviour
• ``audio2audio_*`` → reference-audio remix strength / source
• ``lora_*`` → LoRA adapter selection / strength
• ``seed`` → ``manual_seeds``
Any *_input_params.json file returned by ACE-Step is moved into
APP_DIR / "input_params_record". No .wav files are kept there.
"""
pipeline = _get_ace_pipeline()
tags = (tags or "").strip()
lyrics = (lyrics or "").strip()
if not tags:
raise ValueError("ACE-Step: tags/prompt cannot be empty.")
seconds = max(1.0, float(seconds))
steps = max(1, int(steps))
guidance_scale = float(guidance_scale)
omega_scale = float(omega_scale)
guidance_interval = float(guidance_interval)
guidance_interval_decay = float(guidance_interval_decay)
min_guidance_scale = float(min_guidance_scale)
retake_variance = float(retake_variance)
ref_audio_strength = float(ref_audio_strength)
lora_weight = float(lora_weight)
# Hard guard: normalise edit / Audio2Audio combination here as well so that
# ACE-Step never sees an invalid (task, src_audio_path) pair that would
# trigger its internal assertion.
task, audio2audio_enable, src_audio_path = _prepare_reference_audio(
task,
bool(audio2audio_enable),
src_audio_path,
)
# Debug print so we can see exactly what we are sending into ACE-Step.
try:
print(
f"[ACE] _run_ace_text2music: task={task}, "
f"audio2audio={audio2audio_enable}, "
f"src_audio_path={src_audio_path!r}",
flush=True,
)
except Exception:
pass
manual_seed = int(seed) if seed is not None else 0
# Ensure parent dir exists for the final WAV output
output_path = Path(output_path)
output_path.parent.mkdir(parents=True, exist_ok=True)
# One-at-a-time generation so we don't fight over the GPU.
with _ACE_GENERATION_LOCK:
_report_progress(0.25, "ace_infer")
# ACEStepPipeline.__call__ returns [audio_path(s)..., input_params_json]
# We tell it to save into the *final* output_path directory.
# Build kwargs so we can conditionally include LoRA config only when set.
call_kwargs: Dict[str, Any] = {
"format": "wav",
"audio_duration": seconds,
"prompt": tags,
"lyrics": lyrics,
"infer_step": steps,
"guidance_scale": guidance_scale,
"scheduler_type": scheduler_type,
"cfg_type": cfg_type,
"omega_scale": omega_scale,
"guidance_interval": guidance_interval,
"guidance_interval_decay": guidance_interval_decay,
"min_guidance_scale": min_guidance_scale,
"use_erg_tag": use_erg_tag,
"use_erg_lyric": use_erg_lyric,
"use_erg_diffusion": use_erg_diffusion,
"oss_steps": oss_steps,
"manual_seeds": manual_seed if manual_seed > 0 else None,
# Retake / repaint / extend (no-op for plain text2music defaults)
"task": task,
"repaint_start": repaint_start,
"repaint_end": repaint_end,
"retake_variance": retake_variance,
# Audio2Audio / reference audio
"audio2audio_enable": bool(audio2audio_enable),
"ref_audio_strength": ref_audio_strength,
"batch_size": 1,
"save_path": str(output_path),
"debug": False,
"shift": 6.0,
}
if vocal_language is not None and (vocal_language or "").strip():
call_kwargs["vocal_language"] = (vocal_language or "").strip()
call_kwargs["thinking"] = thinking
call_kwargs["use_cot_metas"] = use_cot_metas
call_kwargs["use_cot_caption"] = use_cot_caption
call_kwargs["use_cot_language"] = use_cot_language
call_kwargs["lm_temperature"] = lm_temperature
call_kwargs["lm_cfg_scale"] = lm_cfg_scale
call_kwargs["lm_top_k"] = lm_top_k
call_kwargs["lm_top_p"] = lm_top_p
call_kwargs["lm_negative_prompt"] = (lm_negative_prompt or "").strip() or "NO USER INPUT"
if lm_checkpoint_path is not None and lm_checkpoint_path:
call_kwargs["lm_checkpoint_path"] = str(lm_checkpoint_path)
if cancel_check is not None:
call_kwargs["cancel_check"] = cancel_check
# Wire up reference vs source audio per ACE-Step pipeline:
#
# - retake / cover / audio2audio / lego / extract / complete: use ref_audio_input so the pipeline
# gets backing latents. For lego we use LOW ref_audio_strength (API default 0.3) so diffusion
# starts from noisy backing and denoises toward the prompt (new instrument), matching timing.
# - repaint / extend: use src_audio_path (pipeline uses src_latents for repaint/extend segment).
# - text2music: leave both unset (None).
if not src_audio_path:
call_kwargs["ref_audio_input"] = None
call_kwargs["src_audio_path"] = None
elif task in ("repaint", "extend"):
call_kwargs["src_audio_path"] = src_audio_path
call_kwargs["ref_audio_input"] = None
else:
# retake, cover, audio2audio, lego, extract, complete: backing as ref (lego uses low ref_audio_strength)
call_kwargs["ref_audio_input"] = src_audio_path
call_kwargs["src_audio_path"] = None
# Only forward LoRA configuration if an adapter path/name was provided.
lora_path = (lora_name_or_path or "").strip() if isinstance(lora_name_or_path, str) else ""
if lora_path:
call_kwargs["lora_name_or_path"] = lora_path
call_kwargs["lora_weight"] = lora_weight