File size: 8,040 Bytes
d0831da 12bbde9 d0831da 071f018 d0831da 071f018 d0831da 12bbde9 d0831da 12bbde9 d0831da 12bbde9 d0831da |
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 |
import os
from pathlib import Path
from typing import List, Tuple
import uuid
import json
import argparse
import gradio as gr
import torch
import torchaudio
from safetensors.torch import load_file
from tqdm import tqdm
from model import LocalSongModel
from acestep.music_dcae.music_dcae_pipeline import MusicDCAE
class TagEmbedder:
def __init__(self, mapping_file: str = "checkpoints/tag_mapping.json"):
with open(mapping_file, 'r', encoding='utf-8') as f:
self.tag_mapping = json.load(f)
self.num_classes = 2304
class AudioVAE:
def __init__(self, device: torch.device):
self.model = MusicDCAE().to(device)
self.model.eval()
self.device = device
self.latent_mean = torch.tensor(
[0.1207, -0.0186, -0.0947, -0.3779, 0.5956, 0.3422, 0.1796, -0.0526],
device=device,
).view(1, -1, 1, 1)
self.latent_std = torch.tensor(
[0.4638, 0.3154, 0.6244, 1.5078, 0.4696, 0.4633, 0.5614, 0.2707],
device=device,
).view(1, -1, 1, 1)
def decode(self, latents: torch.Tensor) -> torch.Tensor:
with torch.no_grad():
latents = latents * self.latent_std + self.latent_mean
sr, audio_list = self.model.decode(latents, sr=48000)
audio_batch = torch.stack(audio_list).to(self.device)
return audio_batch
class RF:
def __init__(self, model: torch.nn.Module):
self.model = model
def sample(
self,
z: torch.Tensor,
cond: List[List[int]],
null_cond: List[List[int]] | None = None,
sample_steps: int = 100,
cfg: float = 3.0,
) -> List[torch.Tensor]:
batch = z.size(0)
dt = 1.0 / sample_steps
dt = torch.tensor([dt] * batch, device=z.device).view([batch, *([1] * len(z.shape[1:]))])
images = [z]
for i in tqdm(range(sample_steps, 0, -1), desc="Generating", unit="step"):
t = torch.tensor([i / sample_steps] * batch, device=z.device)
if null_cond is not None:
z_batched = torch.cat([z, z], dim=0)
t_batched = torch.cat([t, t], dim=0)
cond_batched = cond + null_cond
v_batched = self.model(z_batched, t_batched, cond_batched)
vc, vu = v_batched.chunk(2, dim=0)
vc = vu + cfg * (vc - vu)
else:
vc = self.model(z, t, cond)
z = z - dt * vc
images.append(z)
return images
model: torch.nn.Module | None = None
vae: AudioVAE | None = None
tag_embedder: TagEmbedder | None = None
rf_sampler: RF | None = None
device: torch.device | None = None
_available_tags: List[str] | None = None
def load_resources(checkpoint_path) -> List[str]:
torch.set_float32_matmul_precision('high')
global model, vae, tag_embedder, rf_sampler, device, _available_tags
if _available_tags is not None:
return _available_tags
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
tag_embedder = TagEmbedder()
model = LocalSongModel(
in_channels=8,
num_groups=16,
hidden_size=1024,
decoder_hidden_size=2048,
num_blocks=36,
patch_size=(16, 1),
num_classes=tag_embedder.num_classes,
max_tags=8,
).to(device)
print(f"Loading checkpoint: {checkpoint_path}")
state_dict = load_file(checkpoint_path, device=str(device))
model.load_state_dict(state_dict, strict=True)
model.eval()
vae = AudioVAE(device)
rf_sampler = RF(model)
_available_tags = sorted(tag_embedder.tag_mapping.keys())
return _available_tags
def _tags_to_indices(tags: List[str]) -> List[int]:
assert tag_embedder is not None
indices = []
for tag in tags:
tag_lower = tag.lower().strip()
if tag_lower in tag_embedder.tag_mapping:
indices.append(tag_embedder.tag_mapping[tag_lower])
return indices
def generate_audio(
tags: List[str],
cfg: float,
sample_steps: int,
) -> Tuple[Tuple[int, object], str]:
assert model is not None and vae is not None and rf_sampler is not None and device is not None
if not tags:
tags = []
if len(tags) > 8:
raise gr.Error("A maximum of 8 tags is supported.")
tag_indices = _tags_to_indices(tags)
batch = 1
channels = 8
height = 16
width = 512
z = torch.randn(batch, channels, height, width, device=device)
cond = [tag_indices]
null_cond = [[]]
with torch.no_grad():
sampled_latents = rf_sampler.sample(
z=z,
cond=cond,
null_cond=null_cond,
sample_steps=sample_steps,
cfg=cfg,
)[-1]
audio = vae.decode(sampled_latents)
audio_tensor = audio[0].cpu()
sr = 48000
audio_numpy = audio_tensor.transpose(0, 1).numpy()
os.makedirs("generated", exist_ok=True)
output_path = f"generated/generated_{uuid.uuid4().hex}.wav"
torchaudio.save(str(output_path), audio_tensor, sr)
return (sr, audio_numpy), str(output_path)
def build_interface(checkpoint_path) -> gr.Blocks:
available_tags = load_resources(checkpoint_path)
# Define preset tag combinations
presets = [
["soundtrack1", "female vocalist","rock","melodic"],
["soundtrack", "chrono trigger", "emotional", "piano", "strings"],
["soundtrack", "touhou 10", "trumpet"],
["soundtrack", "christmas music","winter","melodic"],
["soundtrack2", "male vocalist","pop","melodic","acoustic guitar","ballad"],
]
with gr.Blocks(title="LocalSong") as demo:
gr.Markdown("# LocalSong")
with gr.Row():
tag_input = gr.Dropdown(
label="Tags (select up to 8)",
choices=available_tags,
multiselect=True,
max_choices=8,
value=presets[0],
)
gr.Markdown("**Presets:**")
with gr.Row():
for preset in presets:
btn = gr.Button(f"{' + '.join(preset)}", size="sm")
def make_preset_fn(p):
return lambda: p
btn.click(fn=make_preset_fn(preset), inputs=None, outputs=tag_input)
with gr.Row():
cfg_slider = gr.Slider(
label="CFG Scale",
minimum=1.0,
maximum=7.0,
step=0.5,
value=3.5,
)
sample_steps_slider = gr.Slider(
label="Sample Steps",
minimum=50,
maximum=200,
step=10,
value=200,
)
with gr.Row():
seed_input = gr.Number(
label="Seed",
value=45,
precision=0,
)
generate_button = gr.Button("Generate Audio", variant="primary")
audio_output = gr.Audio(label="Generated Audio", type="numpy")
download_output = gr.File(label="Download WAV")
def generate_wrapper(tags, cfg, steps, seed):
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed(seed)
return generate_audio(tags, cfg, steps)
generate_button.click(
fn=generate_wrapper,
inputs=[
tag_input,
cfg_slider,
sample_steps_slider,
seed_input,
],
outputs=[
audio_output,
download_output,
],
)
return demo
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="LocalSong Gradio Interface")
parser.add_argument(
"--checkpoint",
type=str,
default="checkpoints/checkpoint_461260.safetensors",
help="Path to the model checkpoint"
)
args = parser.parse_args()
demo = build_interface(args.checkpoint)
demo.launch()
|