HAIM / scripts /generation /gen_musicgen_large.py
seonghyeongo's picture
scripts: add generation pipeline (A2/B/C) with secrets removed
b347b70 verified
Raw
History Blame Contribute Delete
4.09 kB
#!/usr/bin/env python3
"""Generate MusicGen large tracks to fill up to 2000."""
import json, os, torch
import numpy as np
from pathlib import Path
from uuid import uuid4
from scipy.io import wavfile
from tqdm import tqdm
from transformers import AutoProcessor, MusicgenForConditionalGeneration
OUT_DIR = Path("/ssd_data/dataset/haim_dataset/fake/musicgen/large")
TARGET = 2000
PROMPTS = [
"epic orchestral film score", "lo-fi hip hop beats", "jazz piano trio",
"heavy metal guitar riff", "ambient electronic soundscape", "acoustic folk ballad",
"funk bass groove", "classical string quartet", "reggae dub", "edm festival drop",
"bossa nova guitar", "cinematic trailer music", "blues harmonica solo",
"k-pop dance track", "country western guitar", "synthwave retro",
"celtic folk melody", "arabic oud music", "drum and bass", "chillwave dreampop",
"gospel choir", "psychedelic rock", "minimal techno", "flamenco guitar",
"bollywood dance music", "afrobeat percussion", "latin salsa", "grunge rock",
"neo soul r&b", "baroque harpsichord", "trap beat with 808s",
"new age meditation music", "punk rock energy", "smooth jazz saxophone",
"progressive rock epic with time signature changes",
"chiptune 8-bit video game music", "world music fusion",
"deep house with warm pads", "indie rock with jangly guitars",
"hip hop boom bap beat",
]
def main():
# Count existing
existing = len(list(OUT_DIR.glob("*.wav"))) + len(list(OUT_DIR.glob("*.mp3")))
remaining = TARGET - existing
if remaining <= 0:
print(f"Already at {existing}/{TARGET}")
return
print(f"Existing: {existing}, generating {remaining} more")
# Load model with CPU offload to save GPU memory
processor = AutoProcessor.from_pretrained("facebook/musicgen-large")
model = MusicgenForConditionalGeneration.from_pretrained(
"facebook/musicgen-large",
torch_dtype=torch.float16,
).to("cuda")
device = "cuda"
sr = int(model.config.audio_encoder.sampling_rate)
# Load existing metadata
meta_path = OUT_DIR / "metadata.jsonl"
existing_meta = []
if meta_path.exists():
with open(meta_path) as f:
existing_meta = [json.loads(l) for l in f if l.strip()]
added = 0
with open(meta_path, "a", encoding="utf-8") as meta_f:
for i in tqdm(range(remaining), desc="MusicGen-large"):
prompt = PROMPTS[(existing + i) % len(PROMPTS)]
try:
inputs = processor(text=[prompt], padding=True, return_tensors="pt").to(device)
with torch.no_grad():
audio = model.generate(**inputs, max_new_tokens=500)
wav = audio[0, 0].cpu().float().numpy()
del audio, inputs
torch.cuda.empty_cache()
# Save
tid = str(uuid4())
fname = f"{tid}.wav"
out_path = OUT_DIR / fname
wav_int16 = np.int16(np.clip(wav, -1.0, 1.0) * 32767)
wavfile.write(str(out_path), sr, wav_int16)
meta = {
"track_id": tid,
"filename": fname,
"category": "A_opensource",
"subcategory": "musicgen_large",
"source_platform": "musicgen",
"model_name": "MusicGen",
"model_version": "large",
"duration_sec": len(wav) / sr,
"sample_rate": sr,
"prompt": prompt,
"collection_method": "generate",
}
meta_f.write(json.dumps(meta, ensure_ascii=False) + "\n")
meta_f.flush()
added += 1
except Exception as e:
import traceback
print(f"Error: {e}")
traceback.print_exc()
torch.cuda.empty_cache()
continue
print(f"Done: added {added}, total {existing + added}/{TARGET}")
if __name__ == "__main__":
main()