Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -67,206 +67,44 @@ import time
|
|
| 67 |
import copy
|
| 68 |
from collections import Counter
|
| 69 |
from models.soundstream_hubert_new import SoundStream
|
| 70 |
-
from vocoder import build_codec_model, process_audio
|
| 71 |
-
from post_process_audio import replace_low_freq_with_energy_matched
|
| 72 |
|
| 73 |
device = "cuda:0"
|
| 74 |
|
| 75 |
-
stage2_model = "m-a-p/YuE-s2-1B-general"
|
| 76 |
-
model_stage2 = AutoModelForCausalLM.from_pretrained(
|
| 77 |
-
stage2_model,
|
| 78 |
-
torch_dtype=torch.float16,
|
| 79 |
-
attn_implementation="flash_attention_2"
|
| 80 |
-
).to(device)
|
| 81 |
-
model_stage2.eval()
|
| 82 |
-
|
| 83 |
model = AutoModelForCausalLM.from_pretrained(
|
| 84 |
"m-a-p/YuE-s1-7B-anneal-en-cot",
|
| 85 |
torch_dtype=torch.float16,
|
| 86 |
attn_implementation="flash_attention_2",
|
|
|
|
| 87 |
).to(device)
|
| 88 |
model.eval()
|
| 89 |
|
| 90 |
basic_model_config = './xcodec_mini_infer/final_ckpt/config.yaml'
|
| 91 |
resume_path = './xcodec_mini_infer/final_ckpt/ckpt_00360000.pth'
|
| 92 |
-
config_path = './xcodec_mini_infer/decoders/config.yaml'
|
| 93 |
-
vocal_decoder_path = './xcodec_mini_infer/decoders/decoder_131000.pth'
|
| 94 |
-
inst_decoder_path = './xcodec_mini_infer/decoders/decoder_151000.pth'
|
| 95 |
|
| 96 |
mmtokenizer = _MMSentencePieceTokenizer("./mm_tokenizer_v0.2_hf/tokenizer.model")
|
| 97 |
|
| 98 |
codectool = CodecManipulator("xcodec", 0, 1)
|
| 99 |
-
codectool_stage2 = CodecManipulator("xcodec", 0, 8)
|
| 100 |
model_config = OmegaConf.load(basic_model_config)
|
| 101 |
# Load codec model
|
| 102 |
codec_model = eval(model_config.generator.name)(**model_config.generator.config).to(device)
|
| 103 |
parameter_dict = torch.load(resume_path, map_location='cpu')
|
| 104 |
codec_model.load_state_dict(parameter_dict['codec_model'])
|
|
|
|
| 105 |
codec_model.eval()
|
| 106 |
|
| 107 |
-
# Preload and compile vocoders
|
| 108 |
-
vocal_decoder, inst_decoder = build_codec_model(config_path, vocal_decoder_path, inst_decoder_path)
|
| 109 |
-
vocal_decoder.to(device)
|
| 110 |
-
inst_decoder.to(device)
|
| 111 |
-
vocal_decoder.
|
| 112 |
-
inst_decoder.
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
class BlockTokenRangeProcessor(LogitsProcessor):
|
| 116 |
-
def __init__(self, start_id, end_id):
|
| 117 |
-
self.blocked_token_ids = list(range(start_id, end_id))
|
| 118 |
-
|
| 119 |
-
def __call__(self, input_ids, scores):
|
| 120 |
-
scores[:, self.blocked_token_ids] = -float("inf")
|
| 121 |
-
return scores
|
| 122 |
-
|
| 123 |
-
def load_audio_mono(filepath, sampling_rate=16000):
|
| 124 |
-
audio, sr = torchaudio.load(filepath)
|
| 125 |
-
# Convert to mono
|
| 126 |
-
audio = torch.mean(audio, dim=0, keepdim=True)
|
| 127 |
-
# Resample if needed
|
| 128 |
-
if sr != sampling_rate:
|
| 129 |
-
resampler = Resample(orig_freq=sr, new_freq=sampling_rate)
|
| 130 |
-
audio = resampler(audio)
|
| 131 |
-
return audio
|
| 132 |
-
|
| 133 |
-
def split_lyrics(lyrics: str):
|
| 134 |
-
pattern = r"\[(\w+)\](.*?)\n(?=\[|\Z)"
|
| 135 |
-
segments = re.findall(pattern, lyrics, re.DOTALL)
|
| 136 |
-
structured_lyrics = [f"[{seg[0]}]\n{seg[1].strip()}\n\n" for seg in segments]
|
| 137 |
-
return structured_lyrics
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
def stage2_generate(model, prompt, batch_size=1): # set batch_size=1 for gradio demo
|
| 141 |
-
codec_ids = codectool.unflatten(prompt, n_quantizer=1)
|
| 142 |
-
codec_ids = codectool.offset_tok_ids(
|
| 143 |
-
codec_ids,
|
| 144 |
-
global_offset=codectool.global_offset,
|
| 145 |
-
codebook_size=codectool.codebook_size,
|
| 146 |
-
num_codebooks=codectool.num_codebooks,
|
| 147 |
-
).astype(np.int32)
|
| 148 |
-
|
| 149 |
-
# Prepare prompt_ids based on batch size or single input
|
| 150 |
-
if batch_size > 1:
|
| 151 |
-
codec_list = []
|
| 152 |
-
for i in range(batch_size):
|
| 153 |
-
idx_begin = i * 300
|
| 154 |
-
idx_end = (i + 1) * 300
|
| 155 |
-
codec_list.append(codec_ids[:, idx_begin:idx_end])
|
| 156 |
-
|
| 157 |
-
codec_ids = np.concatenate(codec_list, axis=0)
|
| 158 |
-
prompt_ids = np.concatenate(
|
| 159 |
-
[
|
| 160 |
-
np.tile([mmtokenizer.soa, mmtokenizer.stage_1], (batch_size, 1)),
|
| 161 |
-
codec_ids,
|
| 162 |
-
np.tile([mmtokenizer.stage_2], (batch_size, 1)),
|
| 163 |
-
],
|
| 164 |
-
axis=1
|
| 165 |
-
)
|
| 166 |
-
else:
|
| 167 |
-
prompt_ids = np.concatenate([
|
| 168 |
-
np.array([mmtokenizer.soa, mmtokenizer.stage_1]),
|
| 169 |
-
codec_ids.flatten(), # Flatten the 2D array to 1D
|
| 170 |
-
np.array([mmtokenizer.stage_2])
|
| 171 |
-
]).astype(np.int32)
|
| 172 |
-
prompt_ids = prompt_ids[np.newaxis, ...]
|
| 173 |
-
|
| 174 |
-
codec_ids = torch.as_tensor(codec_ids).to(device)
|
| 175 |
-
prompt_ids = torch.as_tensor(prompt_ids).to(device)
|
| 176 |
-
len_prompt = prompt_ids.shape[-1]
|
| 177 |
-
|
| 178 |
-
block_list = LogitsProcessorList([BlockTokenRangeProcessor(0, 46358), BlockTokenRangeProcessor(53526, mmtokenizer.vocab_size)])
|
| 179 |
-
|
| 180 |
-
# Teacher forcing generate loop
|
| 181 |
-
for frames_idx in range(codec_ids.shape[1]):
|
| 182 |
-
cb0 = codec_ids[:, frames_idx:frames_idx+1]
|
| 183 |
-
prompt_ids = torch.cat([prompt_ids, cb0], dim=1)
|
| 184 |
-
input_ids = prompt_ids
|
| 185 |
-
|
| 186 |
-
with torch.no_grad():
|
| 187 |
-
stage2_output = model.generate(input_ids=input_ids,
|
| 188 |
-
min_new_tokens=7,
|
| 189 |
-
max_new_tokens=7,
|
| 190 |
-
eos_token_id=mmtokenizer.eoa,
|
| 191 |
-
pad_token_id=mmtokenizer.eoa,
|
| 192 |
-
logits_processor=block_list,
|
| 193 |
-
)
|
| 194 |
-
|
| 195 |
-
assert stage2_output.shape[1] - prompt_ids.shape[1] == 7, f"output new tokens={stage2_output.shape[1]-prompt_ids.shape[1]}"
|
| 196 |
-
prompt_ids = stage2_output
|
| 197 |
-
|
| 198 |
-
# Return output based on batch size
|
| 199 |
-
if batch_size > 1:
|
| 200 |
-
output = prompt_ids.cpu().numpy()[:, len_prompt:]
|
| 201 |
-
output_list = [output[i] for i in range(batch_size)]
|
| 202 |
-
output = np.concatenate(output_list, axis=0)
|
| 203 |
-
else:
|
| 204 |
-
output = prompt_ids[0].cpu().numpy()[len_prompt:]
|
| 205 |
-
|
| 206 |
-
return output
|
| 207 |
-
|
| 208 |
-
def stage2_inference(model, stage1_output_set, stage2_output_dir, batch_size=1): # set batch_size=1 for gradio demo
|
| 209 |
-
stage2_result = []
|
| 210 |
-
for i in tqdm(range(len(stage1_output_set))):
|
| 211 |
-
output_filename = os.path.join(stage2_output_dir, os.path.basename(stage1_output_set[i]))
|
| 212 |
-
|
| 213 |
-
if os.path.exists(output_filename):
|
| 214 |
-
print(f'{output_filename} stage2 has done.')
|
| 215 |
-
continue
|
| 216 |
-
|
| 217 |
-
# Load the prompt
|
| 218 |
-
prompt = np.load(stage1_output_set[i]).astype(np.int32)
|
| 219 |
-
|
| 220 |
-
# Only accept 6s segments
|
| 221 |
-
output_duration = prompt.shape[-1] // 50 // 6 * 6
|
| 222 |
-
num_batch = output_duration // 6
|
| 223 |
-
|
| 224 |
-
if output_duration <= 0:
|
| 225 |
-
print(f'{output_filename} stage1 output is too short, skipping stage2.')
|
| 226 |
-
continue
|
| 227 |
-
|
| 228 |
-
if num_batch <= batch_size:
|
| 229 |
-
# If num_batch is less than or equal to batch_size, we can infer the entire prompt at once
|
| 230 |
-
output = stage2_generate(model, prompt[:, :output_duration*50], batch_size=num_batch)
|
| 231 |
-
else:
|
| 232 |
-
# If num_batch is greater than batch_size, process in chunks of batch_size
|
| 233 |
-
segments = []
|
| 234 |
-
num_segments = (num_batch // batch_size) + (1 if num_batch % batch_size != 0 else 0)
|
| 235 |
-
|
| 236 |
-
for seg in range(num_segments):
|
| 237 |
-
start_idx = seg * batch_size * 300
|
| 238 |
-
# Ensure the end_idx does not exceed the available length
|
| 239 |
-
end_idx = min((seg + 1) * batch_size * 300, output_duration*50) # Adjust the last segment
|
| 240 |
-
current_batch_size = batch_size if seg != num_segments-1 or num_batch % batch_size == 0 else num_batch % batch_size
|
| 241 |
-
segment = stage2_generate(
|
| 242 |
-
model,
|
| 243 |
-
prompt[:, start_idx:end_idx],
|
| 244 |
-
batch_size=current_batch_size
|
| 245 |
-
)
|
| 246 |
-
segments.append(segment)
|
| 247 |
-
|
| 248 |
-
# Concatenate all the segments
|
| 249 |
-
output = np.concatenate(segments, axis=0)
|
| 250 |
-
|
| 251 |
-
# Process the ending part of the prompt
|
| 252 |
-
if output_duration*50 != prompt.shape[-1]:
|
| 253 |
-
ending = stage2_generate(model, prompt[:, output_duration*50:], batch_size=1)
|
| 254 |
-
output = np.concatenate([output, ending], axis=0)
|
| 255 |
-
output = codectool_stage2.ids2npy(output)
|
| 256 |
-
|
| 257 |
-
# Fix invalid codes (a dirty solution, which may harm the quality of audio)
|
| 258 |
-
# We are trying to find better one
|
| 259 |
-
fixed_output = copy.deepcopy(output)
|
| 260 |
-
for i, line in enumerate(output):
|
| 261 |
-
for j, element in enumerate(line):
|
| 262 |
-
if element < 0 or element > 1023:
|
| 263 |
-
counter = Counter(line)
|
| 264 |
-
most_frequant = sorted(counter.items(), key=lambda x: x[1], reverse=True)[0][0]
|
| 265 |
-
fixed_output[i, j] = most_frequant
|
| 266 |
-
# save output
|
| 267 |
-
np.save(output_filename, fixed_output)
|
| 268 |
-
stage2_result.append(output_filename)
|
| 269 |
-
return stage2_result
|
| 270 |
|
| 271 |
|
| 272 |
@spaces.GPU(duration=120)
|
|
@@ -289,10 +127,33 @@ def generate_music(
|
|
| 289 |
|
| 290 |
with tempfile.TemporaryDirectory() as output_dir:
|
| 291 |
stage1_output_dir = os.path.join(output_dir, f"stage1")
|
| 292 |
-
stage2_output_dir = stage1_output_dir.replace('stage1', 'stage2')
|
| 293 |
os.makedirs(stage1_output_dir, exist_ok=True)
|
| 294 |
-
os.makedirs(stage2_output_dir, exist_ok=True)
|
| 295 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 296 |
stage1_output_set = []
|
| 297 |
|
| 298 |
genres = genre_txt.strip()
|
|
@@ -407,10 +268,6 @@ def generate_music(
|
|
| 407 |
stage1_output_set.append(vocal_save_path)
|
| 408 |
stage1_output_set.append(inst_save_path)
|
| 409 |
|
| 410 |
-
print("Stage 2 inference...")
|
| 411 |
-
stage2_result = stage2_inference(model_stage2, stage1_output_set, stage2_output_dir, batch_size=1) # set batch_size=1 for gradio demo
|
| 412 |
-
print('Stage 2 DONE.\n')
|
| 413 |
-
|
| 414 |
print("Converting to Audio...")
|
| 415 |
|
| 416 |
# convert audio tokens to audio
|
|
@@ -423,14 +280,14 @@ def generate_music(
|
|
| 423 |
wav = wav * min(limit / max_val, 1) if rescale else wav.clamp(-limit, limit)
|
| 424 |
torchaudio.save(str(path), wav, sample_rate=sample_rate, encoding='PCM_S', bits_per_sample=16)
|
| 425 |
|
| 426 |
-
# reconstruct tracks
|
| 427 |
-
recons_output_dir = os.path.join(output_dir, "
|
| 428 |
recons_mix_dir = os.path.join(recons_output_dir, 'mix')
|
| 429 |
os.makedirs(recons_mix_dir, exist_ok=True)
|
| 430 |
-
|
| 431 |
for npy in stage1_output_set:
|
| 432 |
codec_result = np.load(npy)
|
| 433 |
-
decodec_rlt=[]
|
| 434 |
with torch.no_grad():
|
| 435 |
decoded_waveform = codec_model.decode(
|
| 436 |
torch.as_tensor(codec_result.astype(np.int16), dtype=torch.long).unsqueeze(0).permute(1, 0, 2).to(
|
|
@@ -438,61 +295,11 @@ def generate_music(
|
|
| 438 |
decoded_waveform = decoded_waveform.cpu().squeeze(0)
|
| 439 |
decodec_rlt.append(torch.as_tensor(decoded_waveform))
|
| 440 |
decodec_rlt = torch.cat(decodec_rlt, dim=-1)
|
| 441 |
-
save_path = os.path.join(recons_output_dir, os.path.splitext(os.path.basename(npy))[0] + "
|
| 442 |
-
|
| 443 |
save_audio(decodec_rlt, save_path, 16000)
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
recons_output_dir = os.path.join(output_dir, "recons_stage2_vocoder") # changed folder name to recons_stage2_vocoder
|
| 447 |
-
recons_mix_dir = os.path.join(recons_output_dir, 'mix')
|
| 448 |
-
os.makedirs(recons_mix_dir, exist_ok=True)
|
| 449 |
-
tracks_stage2_vocoder = [] # changed variable name to tracks_stage2_vocoder
|
| 450 |
-
vocoder_stems_dir = os.path.join(recons_output_dir, 'stems') # vocoder output stems in recons_stage2_vocoder
|
| 451 |
-
os.makedirs(vocoder_stems_dir, exist_ok=True)
|
| 452 |
-
|
| 453 |
-
vocal_output = None # initialize for mix error handling
|
| 454 |
-
instrumental_output = None # initialize for mix error handling
|
| 455 |
-
|
| 456 |
-
for npy in stage2_result:
|
| 457 |
-
if 'instrumental' in npy:
|
| 458 |
-
# Process instrumental
|
| 459 |
-
instrumental_output = process_audio(
|
| 460 |
-
npy,
|
| 461 |
-
os.path.join(vocoder_stems_dir, 'instrumental.mp3'), # vocoder output to vocoder_stems_dir
|
| 462 |
-
rescale,
|
| 463 |
-
None, # Removed args, use default vocoder args
|
| 464 |
-
inst_decoder,
|
| 465 |
-
codec_model
|
| 466 |
-
)
|
| 467 |
-
else:
|
| 468 |
-
# Process vocal
|
| 469 |
-
vocal_output = process_audio(
|
| 470 |
-
npy,
|
| 471 |
-
os.path.join(vocoder_stems_dir, 'vocal.mp3'), # vocoder output to vocoder_stems_dir
|
| 472 |
-
rescale,
|
| 473 |
-
None, # Removed args, use default vocoder args
|
| 474 |
-
vocal_decoder,
|
| 475 |
-
codec_model
|
| 476 |
-
)
|
| 477 |
-
|
| 478 |
-
# mix tracks from vocoder output
|
| 479 |
-
try:
|
| 480 |
-
mix_output = instrumental_output + vocal_output
|
| 481 |
-
vocoder_mix = os.path.join(recons_mix_dir, 'mixed_stage2_vocoder.mp3') # mixed output in recons_stage2_vocoder, changed filename
|
| 482 |
-
save_audio(mix_output, vocoder_mix, 44100, rescale)
|
| 483 |
-
print(f"Created mix: {vocoder_mix}")
|
| 484 |
-
tracks_stage2_vocoder.append(vocoder_mix) # add mixed vocoder output path
|
| 485 |
-
except RuntimeError as e:
|
| 486 |
-
print(e)
|
| 487 |
-
vocoder_mix = None # set to None if mix failed
|
| 488 |
-
print(f"mix {vocoder_mix} failed! inst: {instrumental_output.shape if instrumental_output is not None else 'None'}, vocal: {vocal_output.shape if vocal_output is not None else 'None'}")
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
# mix tracks from stage 1
|
| 492 |
-
mixed_stage1_path = None
|
| 493 |
-
vocal_stage1_path = None
|
| 494 |
-
instrumental_stage1_path = None
|
| 495 |
-
for inst_path in tracks_stage1: # changed variable name to tracks_stage1
|
| 496 |
try:
|
| 497 |
if (inst_path.endswith('.wav') or inst_path.endswith('.mp3')) \
|
| 498 |
and 'instrumental' in inst_path:
|
|
@@ -501,45 +308,17 @@ def generate_music(
|
|
| 501 |
if not os.path.exists(vocal_path):
|
| 502 |
continue
|
| 503 |
# mix
|
| 504 |
-
recons_mix = os.path.join(recons_mix_dir, os.path.basename(inst_path).replace('
|
| 505 |
-
vocal_stem, sr = sf.read(
|
| 506 |
-
instrumental_stem, _ = sf.read(
|
| 507 |
mix_stem = (vocal_stem + instrumental_stem) / 1
|
| 508 |
-
|
| 509 |
-
sf.write(recons_mix, mix_stem, sr)
|
| 510 |
-
mixed_stage1_path = recons_mix # store mixed stage 1 path
|
| 511 |
-
vocal_stage1_path = vocal_path # store vocal stage 1 path
|
| 512 |
-
instrumental_stage1_path = inst_path # store instrumental stage 1 path
|
| 513 |
-
|
| 514 |
except Exception as e:
|
| 515 |
print(e)
|
|
|
|
| 516 |
|
| 517 |
|
| 518 |
-
|
| 519 |
-
# recons_mix_final_path = os.path.join(output_dir, os.path.basename(mixed_stage1_path).replace('_stage1', '_final')) # final output path
|
| 520 |
-
# replace_low_freq_with_energy_matched(
|
| 521 |
-
# a_file=mixed_stage1_path, # 16kHz
|
| 522 |
-
# b_file=vocoder_mix, # 48kHz
|
| 523 |
-
# c_file=recons_mix_final_path,
|
| 524 |
-
# cutoff_freq=5500.0
|
| 525 |
-
# )
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
if vocoder_mix is not None: # return vocoder mix if successful
|
| 529 |
-
mixed_audio_data, sr_vocoder_mix = sf.read(vocoder_mix)
|
| 530 |
-
vocal_audio_data = None # stage 2 vocoder stems are not mixed and returned in this demo, set to None
|
| 531 |
-
instrumental_audio_data = None # stage 2 vocoder stems are not mixed and returned in this demo, set to None
|
| 532 |
-
return (sr_vocoder_mix, (mixed_audio_data * 32767).astype(np.int16)), vocal_audio_data, instrumental_audio_data
|
| 533 |
-
elif mixed_stage1_path is not None: # if vocoder failed, return stage 1 mix
|
| 534 |
-
mixed_audio_data_stage1, sr_stage1_mix = sf.read(mixed_stage1_path)
|
| 535 |
-
vocal_audio_data_stage1, sr_vocal_stage1 = sf.read(vocal_stage1_path)
|
| 536 |
-
instrumental_audio_data_stage1, sr_inst_stage1 = sf.read(instrumental_stage1_path)
|
| 537 |
-
return (sr_stage1_mix, (mixed_audio_data_stage1 * 32767).astype(np.int16)), (sr_vocal_stage1, (vocal_audio_data_stage1 * 32767).astype(np.int16)), (sr_inst_stage1, (instrumental_audio_data_stage1 * 32767).astype(np.int16))
|
| 538 |
-
else: # if both failed, return None
|
| 539 |
-
return None, None, None
|
| 540 |
-
|
| 541 |
-
|
| 542 |
-
def infer(genre_txt_content, lyrics_txt_content, num_segments=2, max_new_tokens=5):
|
| 543 |
# Execute the command
|
| 544 |
try:
|
| 545 |
mixed_audio_data, vocal_audio_data, instrumental_audio_data = generate_music(genre_txt=genre_txt_content, lyrics_txt=lyrics_txt_content, run_n_segments=num_segments,
|
|
@@ -579,10 +358,10 @@ with gr.Blocks() as demo:
|
|
| 579 |
max_new_tokens = gr.Slider(label="Duration of song", minimum=1, maximum=30, step=1, value=15, interactive=True)
|
| 580 |
submit_btn = gr.Button("Submit")
|
| 581 |
|
| 582 |
-
music_out = gr.Audio(label="Mixed Audio Result
|
| 583 |
-
with gr.Accordion(label="
|
| 584 |
-
vocal_out = gr.Audio(label="Vocal Audio
|
| 585 |
-
instrumental_out = gr.Audio(label="Instrumental Audio
|
| 586 |
|
| 587 |
gr.Examples(
|
| 588 |
examples=[
|
|
|
|
| 67 |
import copy
|
| 68 |
from collections import Counter
|
| 69 |
from models.soundstream_hubert_new import SoundStream
|
| 70 |
+
#from vocoder import build_codec_model, process_audio # removed vocoder
|
| 71 |
+
#from post_process_audio import replace_low_freq_with_energy_matched # removed post process
|
| 72 |
|
| 73 |
device = "cuda:0"
|
| 74 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
model = AutoModelForCausalLM.from_pretrained(
|
| 76 |
"m-a-p/YuE-s1-7B-anneal-en-cot",
|
| 77 |
torch_dtype=torch.float16,
|
| 78 |
attn_implementation="flash_attention_2",
|
| 79 |
+
# low_cpu_mem_usage=True,
|
| 80 |
).to(device)
|
| 81 |
model.eval()
|
| 82 |
|
| 83 |
basic_model_config = './xcodec_mini_infer/final_ckpt/config.yaml'
|
| 84 |
resume_path = './xcodec_mini_infer/final_ckpt/ckpt_00360000.pth'
|
| 85 |
+
#config_path = './xcodec_mini_infer/decoders/config.yaml' # removed vocoder
|
| 86 |
+
#vocal_decoder_path = './xcodec_mini_infer/decoders/decoder_131000.pth' # removed vocoder
|
| 87 |
+
#inst_decoder_path = './xcodec_mini_infer/decoders/decoder_151000.pth' # removed vocoder
|
| 88 |
|
| 89 |
mmtokenizer = _MMSentencePieceTokenizer("./mm_tokenizer_v0.2_hf/tokenizer.model")
|
| 90 |
|
| 91 |
codectool = CodecManipulator("xcodec", 0, 1)
|
|
|
|
| 92 |
model_config = OmegaConf.load(basic_model_config)
|
| 93 |
# Load codec model
|
| 94 |
codec_model = eval(model_config.generator.name)(**model_config.generator.config).to(device)
|
| 95 |
parameter_dict = torch.load(resume_path, map_location='cpu')
|
| 96 |
codec_model.load_state_dict(parameter_dict['codec_model'])
|
| 97 |
+
# codec_model = torch.compile(codec_model)
|
| 98 |
codec_model.eval()
|
| 99 |
|
| 100 |
+
# Preload and compile vocoders # removed vocoder
|
| 101 |
+
#vocal_decoder, inst_decoder = build_codec_model(config_path, vocal_decoder_path, inst_decoder_path)
|
| 102 |
+
#vocal_decoder.to(device)
|
| 103 |
+
#inst_decoder.to(device)
|
| 104 |
+
#vocal_decoder = torch.compile(vocal_decoder)
|
| 105 |
+
#inst_decoder = torch.compile(inst_decoder)
|
| 106 |
+
#vocal_decoder.eval()
|
| 107 |
+
#inst_decoder.eval()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
|
| 109 |
|
| 110 |
@spaces.GPU(duration=120)
|
|
|
|
| 127 |
|
| 128 |
with tempfile.TemporaryDirectory() as output_dir:
|
| 129 |
stage1_output_dir = os.path.join(output_dir, f"stage1")
|
|
|
|
| 130 |
os.makedirs(stage1_output_dir, exist_ok=True)
|
|
|
|
| 131 |
|
| 132 |
+
class BlockTokenRangeProcessor(LogitsProcessor):
|
| 133 |
+
def __init__(self, start_id, end_id):
|
| 134 |
+
self.blocked_token_ids = list(range(start_id, end_id))
|
| 135 |
+
|
| 136 |
+
def __call__(self, input_ids, scores):
|
| 137 |
+
scores[:, self.blocked_token_ids] = -float("inf")
|
| 138 |
+
return scores
|
| 139 |
+
|
| 140 |
+
def load_audio_mono(filepath, sampling_rate=16000):
|
| 141 |
+
audio, sr = torchaudio.load(filepath)
|
| 142 |
+
# Convert to mono
|
| 143 |
+
audio = torch.mean(audio, dim=0, keepdim=True)
|
| 144 |
+
# Resample if needed
|
| 145 |
+
if sr != sampling_rate:
|
| 146 |
+
resampler = Resample(orig_freq=sr, new_freq=sampling_rate)
|
| 147 |
+
audio = resampler(audio)
|
| 148 |
+
return audio
|
| 149 |
+
|
| 150 |
+
def split_lyrics(lyrics: str):
|
| 151 |
+
pattern = r"\[(\w+)\](.*?)\n(?=\[|\Z)"
|
| 152 |
+
segments = re.findall(pattern, lyrics, re.DOTALL)
|
| 153 |
+
structured_lyrics = [f"[{seg[0]}]\n{seg[1].strip()}\n\n" for seg in segments]
|
| 154 |
+
return structured_lyrics
|
| 155 |
+
|
| 156 |
+
# Call the function and print the result
|
| 157 |
stage1_output_set = []
|
| 158 |
|
| 159 |
genres = genre_txt.strip()
|
|
|
|
| 268 |
stage1_output_set.append(vocal_save_path)
|
| 269 |
stage1_output_set.append(inst_save_path)
|
| 270 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 271 |
print("Converting to Audio...")
|
| 272 |
|
| 273 |
# convert audio tokens to audio
|
|
|
|
| 280 |
wav = wav * min(limit / max_val, 1) if rescale else wav.clamp(-limit, limit)
|
| 281 |
torchaudio.save(str(path), wav, sample_rate=sample_rate, encoding='PCM_S', bits_per_sample=16)
|
| 282 |
|
| 283 |
+
# reconstruct tracks
|
| 284 |
+
recons_output_dir = os.path.join(output_dir, "recons")
|
| 285 |
recons_mix_dir = os.path.join(recons_output_dir, 'mix')
|
| 286 |
os.makedirs(recons_mix_dir, exist_ok=True)
|
| 287 |
+
tracks = []
|
| 288 |
for npy in stage1_output_set:
|
| 289 |
codec_result = np.load(npy)
|
| 290 |
+
decodec_rlt = []
|
| 291 |
with torch.no_grad():
|
| 292 |
decoded_waveform = codec_model.decode(
|
| 293 |
torch.as_tensor(codec_result.astype(np.int16), dtype=torch.long).unsqueeze(0).permute(1, 0, 2).to(
|
|
|
|
| 295 |
decoded_waveform = decoded_waveform.cpu().squeeze(0)
|
| 296 |
decodec_rlt.append(torch.as_tensor(decoded_waveform))
|
| 297 |
decodec_rlt = torch.cat(decodec_rlt, dim=-1)
|
| 298 |
+
save_path = os.path.join(recons_output_dir, os.path.splitext(os.path.basename(npy))[0] + ".mp3")
|
| 299 |
+
tracks.append(save_path)
|
| 300 |
save_audio(decodec_rlt, save_path, 16000)
|
| 301 |
+
# mix tracks
|
| 302 |
+
for inst_path in tracks:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 303 |
try:
|
| 304 |
if (inst_path.endswith('.wav') or inst_path.endswith('.mp3')) \
|
| 305 |
and 'instrumental' in inst_path:
|
|
|
|
| 308 |
if not os.path.exists(vocal_path):
|
| 309 |
continue
|
| 310 |
# mix
|
| 311 |
+
recons_mix = os.path.join(recons_mix_dir, os.path.basename(inst_path).replace('instrumental', 'mixed'))
|
| 312 |
+
vocal_stem, sr = sf.read(inst_path)
|
| 313 |
+
instrumental_stem, _ = sf.read(vocal_path)
|
| 314 |
mix_stem = (vocal_stem + instrumental_stem) / 1
|
| 315 |
+
return (sr, (mix_stem * 32767).astype(np.int16)), (sr, (vocal_stem * 32767).astype(np.int16)), (sr, (instrumental_stem * 32767).astype(np.int16))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 316 |
except Exception as e:
|
| 317 |
print(e)
|
| 318 |
+
return None, None, None
|
| 319 |
|
| 320 |
|
| 321 |
+
def infer(genre_txt_content, lyrics_txt_content, num_segments=2, max_new_tokens=15):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 322 |
# Execute the command
|
| 323 |
try:
|
| 324 |
mixed_audio_data, vocal_audio_data, instrumental_audio_data = generate_music(genre_txt=genre_txt_content, lyrics_txt=lyrics_txt_content, run_n_segments=num_segments,
|
|
|
|
| 358 |
max_new_tokens = gr.Slider(label="Duration of song", minimum=1, maximum=30, step=1, value=15, interactive=True)
|
| 359 |
submit_btn = gr.Button("Submit")
|
| 360 |
|
| 361 |
+
music_out = gr.Audio(label="Mixed Audio Result")
|
| 362 |
+
with gr.Accordion(label="Vocal and Instrumental Result", open=False):
|
| 363 |
+
vocal_out = gr.Audio(label="Vocal Audio")
|
| 364 |
+
instrumental_out = gr.Audio(label="Instrumental Audio")
|
| 365 |
|
| 366 |
gr.Examples(
|
| 367 |
examples=[
|