File size: 7,225 Bytes
b347b70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3

import argparse
import shutil
import subprocess
import tempfile
from pathlib import Path
from uuid import uuid4

import numpy as np
import torch
from scipy.io import wavfile
from tqdm import tqdm

from utils import *


MODEL_MAP = {
    "base": "ACE-Step/acestep-v15-base",
    "turbo": "ACE-Step/Ace-Step1.5",
}


def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("--variant", choices=["base", "turbo"], default="turbo")
    parser.add_argument("--target", type=int, default=2000)
    parser.add_argument(
        "--output-dir",
        type=Path,
        default=None,
        help="Default: FAKE_DIR/A_opensource/acestep_1.5_{variant}",
    )
    parser.add_argument(
        "--batch-size",
        type=int,
        default=2,
        help="Recommended 1-2 on 24GB VRAM; use smaller values for base model",
    )
    parser.add_argument("--device", choices=["cuda", "cpu"], default="cuda")
    return parser.parse_args()


def to_int16(audio: np.ndarray):
    audio = np.nan_to_num(audio.astype(np.float32), nan=0.0, posinf=0.0, neginf=0.0)
    peak = np.max(np.abs(audio)) if audio.size else 0.0
    if peak > 1.0:
        audio = audio / peak
    return np.int16(np.clip(audio, -1.0, 1.0) * 32767)


def try_build_pipeline(model_id: str, device: str):
    try:
        from transformers import pipeline

        use_cuda = device == "cuda" and torch.cuda.is_available()
        device_index = 0 if use_cuda else -1
        return pipeline("text-to-audio", model=model_id, device=device_index, trust_remote_code=True)
    except Exception:
        return None


def extract_audio_from_pipeline_output(output):
    if isinstance(output, list):
        output = output[0]
    if isinstance(output, dict):
        audio = output.get("audio")
        sr = int(output.get("sampling_rate", 32000))
        if audio is None:
            return None, None
        return np.array(audio), sr
    return None, None


def ensure_repo(models_dir: Path) -> Path:
    repo_dir = models_dir / "ACE-Step-1.5"
    if repo_dir.exists():
        return repo_dir
    models_dir.mkdir(parents=True, exist_ok=True)
    cmd = ["git", "clone", "https://github.com/ace-step/ACE-Step-1.5", str(repo_dir)]
    subprocess.run(cmd, check=True)
    return repo_dir


def run_cli_fallback(
    repo_dir: Path, prompt: str, output_path: Path, model_id: str, device: str
) -> bool:
    with tempfile.TemporaryDirectory() as tmp_dir:
        tmp_dir_path = Path(tmp_dir)
        candidates = [
            [
                "python",
                "infer.py",
                "--prompt",
                prompt,
                "--output",
                str(tmp_dir_path),
                "--model",
                model_id,
                "--device",
                device,
            ],
            [
                "python",
                "inference.py",
                "--prompt",
                prompt,
                "--output_dir",
                str(tmp_dir_path),
                "--model_id",
                model_id,
                "--device",
                device,
            ],
        ]

        for cmd in candidates:
            proc = subprocess.run(cmd, cwd=repo_dir, capture_output=True, text=True)
            if proc.returncode != 0:
                continue

            generated = sorted(
                list(tmp_dir_path.rglob("*.wav")) + list(tmp_dir_path.rglob("*.mp3")),
                key=lambda p: p.stat().st_mtime,
            )
            if generated:
                shutil.move(str(generated[-1]), str(output_path))
                return True
    return False


def main():
    args = parse_args()
    device = "cuda" if args.device == "cuda" and torch.cuda.is_available() else "cpu"
    model_id = MODEL_MAP[args.variant]

    output_dir = args.output_dir or (
        FAKE_DIR / "A_opensource" / f"acestep_1.5_{args.variant}"
    )
    output_dir.mkdir(parents=True, exist_ok=True)

    if not ensure_disk_space():
        raise RuntimeError("Insufficient disk space before generation start.")

    meta_mgr = MetadataManager(output_dir)
    existing = meta_mgr.get_count()
    if existing >= args.target:
        print(f"Target already reached: {existing}/{args.target}")
        return

    prompts = get_diverse_prompts(args.target)
    pipe = try_build_pipeline(model_id, device)
    repo_dir = None
    if pipe is None:
        repo_dir = ensure_repo(BASE_DIR / "models")

    progress = tqdm(
        total=args.target, initial=existing, desc=f"ACE-Step-{args.variant}"
    )
    generated_this_run = 0

    for idx in range(existing, args.target):
        prompt = prompts[idx]
        track_id = str(uuid4())
        filename = f"{track_id}.wav"
        file_path = output_dir / filename

        ok = False
        if pipe is not None:
            try:
                output = pipe(prompt)
                audio, sr = extract_audio_from_pipeline_output(output)
                if audio is not None and sr is not None and audio.size > 0:
                    if audio.ndim > 1:
                        audio = np.mean(audio, axis=0)
                    wavfile.write(file_path, int(sr), to_int16(audio))
                    ok = True
            except Exception:
                ok = False

        if not ok:
            if repo_dir is None:
                repo_dir = ensure_repo(BASE_DIR / "models")
            ok = run_cli_fallback(repo_dir, prompt, file_path, model_id, device)

        if not ok or not file_path.exists():
            continue

        info = get_audio_info(file_path)
        if (
            not info
            or info.get("duration_sec", 0.0) <= 0.5
            or info.get("file_size_bytes", 0) <= 1024
        ):
            file_path.unlink(missing_ok=True)
            continue

        md5_hash = compute_md5(file_path)
        meta = TrackMetadata(
            track_id=track_id,
            filename=filename,
            category="A_opensource",
            subcategory=f"acestep_1.5_{args.variant}",
            source_platform="acestep",
            source_type="open-source",
            model_name="ACE-Step",
            model_version=f"1.5-{args.variant}",
            collection_method="generate",
            audio_format=file_path.suffix.lstrip(".") or "wav",
            prompt=prompt,
            md5_hash=md5_hash,
            duration_sec=info.get("duration_sec"),
            sample_rate=info.get("sample_rate"),
            channels=info.get("channels"),
            bitrate_kbps=info.get("bitrate_kbps"),
            file_size_bytes=info.get("file_size_bytes"),
        )
        meta_mgr.add_track(meta)
        generated_this_run += 1
        progress.update(1)

        if meta_mgr.get_count() % 50 == 0:
            if not ensure_disk_space():
                meta_mgr.update_summary()
                raise RuntimeError("Low disk space, stopping generation.")
            meta_mgr.update_summary()

        if meta_mgr.get_count() >= args.target:
            break

    meta_mgr.update_summary()
    progress.close()
    print(
        f"Generated {generated_this_run} tracks. Total: {meta_mgr.get_count()}/{args.target}"
    )


if __name__ == "__main__":
    main()