Spaces:
Paused
Paused
File size: 2,177 Bytes
b8d9590 9ab4e1d b8d9590 9ab4e1d b8d9590 | 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 | import dataclasses
import subprocess
import tempfile
from pathlib import Path
import spaces
import torch
from yue2 import YuE2Pipeline
SONG_MODEL_ID = "m-a-p/YuE2-3B"
def _load_pipeline() -> YuE2Pipeline:
# ZeroGPU emulates CUDA outside @spaces.GPU calls. The pipeline's constructor queries the
# current device, which fails under that emulation unless the memory-fraction call is a no-op.
original = torch.cuda.set_per_process_memory_fraction
torch.cuda.set_per_process_memory_fraction = lambda *args, **kwargs: None
try:
return YuE2Pipeline.from_pretrained(SONG_MODEL_ID, device="cuda")
finally:
torch.cuda.set_per_process_memory_fraction = original
PIPELINE = _load_pipeline()
def gpu_seconds(style, lyrics, seed, cot, steps, abc=None) -> int:
"""Longer lyrics and 32-step rendering need more GPU time; ZeroGPU caps a call at 300s."""
base = 120 + len(lyrics or "") // 12 + (60 if int(steps) > 16 else 0)
return min(300, max(120, base))
@spaces.GPU(duration=gpu_seconds)
def render_song(
style: str,
lyrics: str,
seed: int,
cot: str,
steps: int,
abc: str | None = None,
) -> tuple[str, str | None]:
"""Render a song to mp3. Returns the mp3 path and the ABC score the song was built on.
Passing `abc` reuses an earlier score, which keeps that song's melody (and chords with
cot="full") while the lyrics change.
"""
original_config = PIPELINE.generation_config
PIPELINE.generation_config = dataclasses.replace(original_config, ode_steps=int(steps))
try:
song = PIPELINE(style=style, lyrics=lyrics, cot=cot, seed=int(seed), abc=abc)
finally:
PIPELINE.generation_config = original_config
out_dir = Path(tempfile.mkdtemp(prefix="tune-studio-"))
flac_path = out_dir / "song.flac"
mp3_path = out_dir / "song.mp3"
song.save(str(flac_path))
subprocess.run(
[
"ffmpeg", "-y", "-loglevel", "error",
"-i", str(flac_path),
"-codec:a", "libmp3lame", "-b:a", "256k",
str(mp3_path),
],
check=True,
)
flac_path.unlink()
return str(mp3_path), song.abc
|