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