KingNish commited on
Commit
9897c6e
·
verified ·
1 Parent(s): c06dce9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +166 -118
app.py CHANGED
@@ -46,7 +46,6 @@ except FileNotFoundError:
46
  sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'xcodec_mini_infer'))
47
  sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'xcodec_mini_infer', 'descriptaudiocodec'))
48
 
49
-
50
  # don't change above code
51
 
52
  import argparse
@@ -106,7 +105,6 @@ codec_model.eval()
106
  #vocal_decoder.eval()
107
  #inst_decoder.eval()
108
 
109
-
110
  @spaces.GPU(duration=120)
111
  def generate_music(
112
  max_new_tokens=5,
@@ -119,6 +117,7 @@ def generate_music(
119
  prompt_end_time=30.0,
120
  cuda_idx=0,
121
  rescale=False,
 
122
  ):
123
  if use_audio_prompt and not audio_prompt_path:
124
  raise FileNotFoundError("Please offer audio prompt filepath using '--audio_prompt_path', when you enable 'use_audio_prompt'!")
@@ -155,7 +154,8 @@ def generate_music(
155
 
156
  # Call the function and print the result
157
  stage1_output_set = []
158
-
 
159
  genres = genre_txt.strip()
160
  lyrics = split_lyrics(lyrics_txt + "\n")
161
  # intruction
@@ -163,139 +163,188 @@ def generate_music(
163
  prompt_texts = [f"Generate music from the given lyrics segment by segment.\n[Genre] {genres}\n{full_lyrics}"]
164
  prompt_texts += lyrics
165
 
166
- random_id = uuid.uuid4()
167
- output_seq = None
168
- # Here is suggested decoding config
169
- top_p = 0.93
170
- temperature = 1.0
171
- repetition_penalty = 1.2
172
  # special tokens
173
  start_of_segment = mmtokenizer.tokenize('[start_of_segment]')
174
  end_of_segment = mmtokenizer.tokenize('[end_of_segment]')
175
 
176
- raw_output = None
177
-
178
  # Format text prompt
179
  run_n_segments = min(run_n_segments + 1, len(lyrics))
180
-
181
- print(list(enumerate(tqdm(prompt_texts[:run_n_segments]))))
182
-
183
- for i, p in enumerate(tqdm(prompt_texts[:run_n_segments])):
184
- section_text = p.replace('[start_of_segment]', '').replace('[end_of_segment]', '')
185
- guidance_scale = 1.5 if i <= 1 else 1.2
186
- if i == 0:
187
- continue
188
- if i == 1:
189
- if use_audio_prompt:
190
- audio_prompt = load_audio_mono(audio_prompt_path)
191
- audio_prompt.unsqueeze_(0)
192
- with torch.no_grad():
193
- raw_codes = codec_model.encode(audio_prompt.to(device), target_bw=0.5)
194
- raw_codes = raw_codes.transpose(0, 1)
195
- raw_codes = raw_codes.cpu().numpy().astype(np.int16)
196
- # Format audio prompt
197
- code_ids = codectool.npy2ids(raw_codes[0])
198
- audio_prompt_codec = code_ids[int(prompt_start_time * 50): int(prompt_end_time * 50)] # 50 is tps of xcodec
199
- audio_prompt_codec_ids = [mmtokenizer.soa] + codectool.sep_ids + audio_prompt_codec + [
200
- mmtokenizer.eoa]
201
- sentence_ids = mmtokenizer.tokenize("[start_of_reference]") + audio_prompt_codec_ids + mmtokenizer.tokenize(
202
- "[end_of_reference]")
203
- head_id = mmtokenizer.tokenize(prompt_texts[0]) + sentence_ids
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
204
  else:
205
- head_id = mmtokenizer.tokenize(prompt_texts[0])
206
- prompt_ids = head_id + start_of_segment + mmtokenizer.tokenize(section_text) + [mmtokenizer.soa] + codectool.sep_ids
207
- else:
208
- prompt_ids = end_of_segment + start_of_segment + mmtokenizer.tokenize(section_text) + [mmtokenizer.soa] + codectool.sep_ids
209
-
210
- prompt_ids = torch.as_tensor(prompt_ids).unsqueeze(0).to(device)
211
- input_ids = torch.cat([raw_output, prompt_ids], dim=1) if i > 1 else prompt_ids
212
- # Use window slicing in case output sequence exceeds the context of model
213
- max_context = 16384 - max_new_tokens - 1
214
- if input_ids.shape[-1] > max_context:
215
- print(
216
- f'Section {i}: output length {input_ids.shape[-1]} exceeding context length {max_context}, now using the last {max_context} tokens.')
217
- input_ids = input_ids[:, -(max_context):]
218
- with torch.inference_mode(), torch.autocast(device_type='cuda', dtype=torch.float16):
219
- output_seq = model.generate(
220
- input_ids=input_ids,
221
- max_new_tokens=max_new_tokens,
222
- min_new_tokens=100,
223
- do_sample=True,
224
- top_p=top_p,
225
- temperature=temperature,
226
- repetition_penalty=repetition_penalty,
227
- eos_token_id=mmtokenizer.eoa,
228
- pad_token_id=mmtokenizer.eoa,
229
- logits_processor=LogitsProcessorList([BlockTokenRangeProcessor(0, 32002), BlockTokenRangeProcessor(32016, 32016)]),
230
- guidance_scale=guidance_scale,
231
- use_cache=True
232
- )
233
- if output_seq[0][-1].item() != mmtokenizer.eoa:
234
- tensor_eoa = torch.as_tensor([[mmtokenizer.eoa]]).to(model.device)
235
- output_seq = torch.cat((output_seq, tensor_eoa), dim=1)
236
- if i > 1:
237
- raw_output = torch.cat([raw_output, prompt_ids, output_seq[:, input_ids.shape[-1]:]], dim=1)
238
- else:
239
- raw_output = output_seq
240
- print(len(raw_output))
241
-
242
- # save raw output and check sanity
243
- ids = raw_output[0].cpu().numpy()
244
- soa_idx = np.where(ids == mmtokenizer.soa)[0].tolist()
245
- eoa_idx = np.where(ids == mmtokenizer.eoa)[0].tolist()
246
- if len(soa_idx) != len(eoa_idx):
247
- raise ValueError(f'invalid pairs of soa and eoa, Num of soa: {len(soa_idx)}, Num of eoa: {len(eoa_idx)}')
248
-
249
- vocals = []
250
- instrumentals = []
251
- range_begin = 1 if use_audio_prompt else 0
252
- for i in range(range_begin, len(soa_idx)):
253
- codec_ids = ids[soa_idx[i] + 1:eoa_idx[i]]
254
- if codec_ids[0] == 32016:
255
- codec_ids = codec_ids[1:]
256
- codec_ids = codec_ids[:2 * (codec_ids.shape[0] // 2)]
257
- vocals_ids = codectool.ids2npy(rearrange(codec_ids, "(n b) -> b n", b=2)[0])
258
- vocals.append(vocals_ids)
259
- instrumentals_ids = codectool.ids2npy(rearrange(codec_ids, "(n b) -> b n", b=2)[1])
260
- instrumentals.append(instrumentals_ids)
261
-
262
- vocals = np.concatenate(vocals, axis=1)
263
- instrumentals = np.concatenate(instrumentals, axis=1)
264
 
265
  print("Converting to Audio...")
266
 
267
- # batching audio
268
- def decode_audio_batch(codec_result, batch_size=4):
269
- decoded_waveforms = []
270
- with torch.no_grad():
271
- for i in range(0, codec_result.shape[-1], batch_size):
272
- batch = codec_result[:,i:i+batch_size]
273
- batch_tensor = torch.as_tensor(batch.astype(np.int16), dtype=torch.long).unsqueeze(0).permute(1, 0, 2).to(device)
274
- decoded_waveform = codec_model.decode(batch_tensor)
275
- decoded_waveforms.append(decoded_waveform)
276
- decoded_waveforms = torch.cat(decoded_waveforms, dim=-1).squeeze(0).cpu()
277
- return decoded_waveforms
278
-
279
 
280
  # reconstruct tracks
281
- vocal_waveform = decode_audio_batch(vocals)
282
- instrumental_waveform = decode_audio_batch(instrumentals)
283
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
284
  # mix tracks
285
- try:
286
- mix_waveform = (vocal_waveform + instrumental_waveform) / 1
287
- return (16000, (mix_waveform * 32767).numpy().astype(np.int16)), (16000, (vocal_waveform * 32767).numpy().astype(np.int16)), (16000, (instrumental_waveform * 32767).numpy().astype(np.int16))
288
- except Exception as e:
289
- print(e)
290
- return None, None, None
291
-
292
 
 
 
 
293
 
294
  def infer(genre_txt_content, lyrics_txt_content, num_segments=2, max_new_tokens=15):
295
  # Execute the command
296
  try:
297
  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,
298
- cuda_idx=0, max_new_tokens=max_new_tokens)
299
  return mixed_audio_data, vocal_audio_data, instrumental_audio_data
300
  except Exception as e:
301
  gr.Warning("An Error Occured: " + str(e))
@@ -303,7 +352,6 @@ def infer(genre_txt_content, lyrics_txt_content, num_segments=2, max_new_tokens=
303
  finally:
304
  print("Temporary files deleted.")
305
 
306
-
307
  # Gradio
308
  with gr.Blocks() as demo:
309
  with gr.Column():
 
46
  sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'xcodec_mini_infer'))
47
  sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'xcodec_mini_infer', 'descriptaudiocodec'))
48
 
 
49
  # don't change above code
50
 
51
  import argparse
 
105
  #vocal_decoder.eval()
106
  #inst_decoder.eval()
107
 
 
108
  @spaces.GPU(duration=120)
109
  def generate_music(
110
  max_new_tokens=5,
 
117
  prompt_end_time=30.0,
118
  cuda_idx=0,
119
  rescale=False,
120
+ batch_size=1
121
  ):
122
  if use_audio_prompt and not audio_prompt_path:
123
  raise FileNotFoundError("Please offer audio prompt filepath using '--audio_prompt_path', when you enable 'use_audio_prompt'!")
 
154
 
155
  # Call the function and print the result
156
  stage1_output_set = []
157
+ vocals_list = []
158
+ instrumentals_list = []
159
  genres = genre_txt.strip()
160
  lyrics = split_lyrics(lyrics_txt + "\n")
161
  # intruction
 
163
  prompt_texts = [f"Generate music from the given lyrics segment by segment.\n[Genre] {genres}\n{full_lyrics}"]
164
  prompt_texts += lyrics
165
 
 
 
 
 
 
 
166
  # special tokens
167
  start_of_segment = mmtokenizer.tokenize('[start_of_segment]')
168
  end_of_segment = mmtokenizer.tokenize('[end_of_segment]')
169
 
 
 
170
  # Format text prompt
171
  run_n_segments = min(run_n_segments + 1, len(lyrics))
172
+
173
+ batches = [prompt_texts[i:i + batch_size] for i in range(0, run_n_segments, batch_size)]
174
+
175
+ print(batches)
176
+
177
+ for batch_idx, batch in enumerate(tqdm(batches)):
178
+ random_ids = [uuid.uuid4() for _ in range(len(batch))]
179
+ raw_outputs = [None] * len(batch)
180
+
181
+ # Here is suggested decoding config
182
+ top_p = 0.93
183
+ temperature = 1.0
184
+ repetition_penalty = 1.2
185
+
186
+ for i, p in enumerate(batch):
187
+ section_text = p.replace('[start_of_segment]', '').replace('[end_of_segment]', '')
188
+ # Adjust guidance scale for the first two sections to be lower
189
+ guidance_scale = 1.5 if (batch_idx*batch_size + i) <= 1 else 1.2
190
+
191
+ if (batch_idx*batch_size + i) == 0:
192
+ continue # Skip the first instruction
193
+
194
+ if (batch_idx * batch_size + i) == 1:
195
+ if use_audio_prompt:
196
+ audio_prompt = load_audio_mono(audio_prompt_path)
197
+ audio_prompt.unsqueeze_(0)
198
+ with torch.no_grad():
199
+ raw_codes = codec_model.encode(audio_prompt.to(device), target_bw=0.5)
200
+ raw_codes = raw_codes.transpose(0, 1)
201
+ raw_codes = raw_codes.cpu().numpy().astype(np.int16)
202
+ # Format audio prompt
203
+ code_ids = codectool.npy2ids(raw_codes[0])
204
+ audio_prompt_codec = code_ids[int(prompt_start_time * 50): int(prompt_end_time * 50)] # 50 is tps of xcodec
205
+ audio_prompt_codec_ids = [mmtokenizer.soa] + codectool.sep_ids + audio_prompt_codec + [
206
+ mmtokenizer.eoa]
207
+ sentence_ids = mmtokenizer.tokenize("[start_of_reference]") + audio_prompt_codec_ids + mmtokenizer.tokenize(
208
+ "[end_of_reference]")
209
+ head_id = mmtokenizer.tokenize(prompt_texts[0]) + sentence_ids
210
+ else:
211
+ head_id = mmtokenizer.tokenize(prompt_texts[0])
212
+ prompt_ids = head_id + start_of_segment + mmtokenizer.tokenize(section_text) + [
213
+ mmtokenizer.soa] + codectool.sep_ids
214
+ else:
215
+ prompt_ids = end_of_segment + start_of_segment + mmtokenizer.tokenize(section_text) + [
216
+ mmtokenizer.soa] + codectool.sep_ids
217
+
218
+ prompt_ids = torch.as_tensor(prompt_ids).unsqueeze(0).to(device)
219
+ input_ids = torch.cat([raw_outputs[i], prompt_ids], dim=1) if (batch_idx * batch_size + i) > 1 else prompt_ids
220
+
221
+ # Use window slicing in case output sequence exceeds the context of model
222
+ max_context = 16384 - max_new_tokens - 1
223
+ if input_ids.shape[-1] > max_context:
224
+ print(
225
+ f'Section {(batch_idx * batch_size + i)}: output length {input_ids.shape[-1]} exceeding context length {max_context}, now using the last {max_context} tokens.')
226
+ input_ids = input_ids[:, -(max_context):]
227
+
228
+ with torch.inference_mode(), torch.autocast(device_type='cuda', dtype=torch.float16):
229
+ output_seq = model.generate(
230
+ input_ids=input_ids,
231
+ max_new_tokens=max_new_tokens,
232
+ min_new_tokens=100,
233
+ do_sample=True,
234
+ top_p=top_p,
235
+ temperature=temperature,
236
+ repetition_penalty=repetition_penalty,
237
+ eos_token_id=mmtokenizer.eoa,
238
+ pad_token_id=mmtokenizer.eoa,
239
+ logits_processor=LogitsProcessorList(
240
+ [BlockTokenRangeProcessor(0, 32002), BlockTokenRangeProcessor(32016, 32016)]),
241
+ guidance_scale=guidance_scale,
242
+ use_cache=True
243
+ )
244
+ if output_seq[0][-1].item() != mmtokenizer.eoa:
245
+ tensor_eoa = torch.as_tensor([[mmtokenizer.eoa]]).to(model.device)
246
+ output_seq = torch.cat((output_seq, tensor_eoa), dim=1)
247
+
248
+ if (batch_idx * batch_size + i) > 1:
249
+ raw_outputs[i] = torch.cat([raw_outputs[i], prompt_ids, output_seq[:, input_ids.shape[-1]:]], dim=1)
250
  else:
251
+ raw_outputs[i] = output_seq
252
+
253
+ for i, raw_output in enumerate(raw_outputs):
254
+ # save raw output and check sanity
255
+ ids = raw_output[0].cpu().numpy()
256
+ soa_idx = np.where(ids == mmtokenizer.soa)[0].tolist()
257
+ eoa_idx = np.where(ids == mmtokenizer.eoa)[0].tolist()
258
+ if len(soa_idx) != len(eoa_idx):
259
+ raise ValueError(f'invalid pairs of soa and eoa, Num of soa: {len(soa_idx)}, Num of eoa: {len(eoa_idx)}')
260
+
261
+ range_begin = 1 if use_audio_prompt and batch_idx == 0 else 0
262
+
263
+ vocals_batch = []
264
+ instrumentals_batch = []
265
+ for j in range(range_begin, len(soa_idx)):
266
+ codec_ids = ids[soa_idx[j] + 1:eoa_idx[j]]
267
+ if codec_ids[0] == 32016:
268
+ codec_ids = codec_ids[1:]
269
+ codec_ids = codec_ids[:2 * (codec_ids.shape[0] // 2)]
270
+ vocals_ids = codectool.ids2npy(rearrange(codec_ids, "(n b) -> b n", b=2)[0])
271
+ vocals_batch.append(vocals_ids)
272
+ instrumentals_ids = codectool.ids2npy(rearrange(codec_ids, "(n b) -> b n", b=2)[1])
273
+ instrumentals_batch.append(instrumentals_ids)
274
+
275
+ vocals_batch = np.concatenate(vocals_batch, axis=1)
276
+ instrumentals_batch = np.concatenate(instrumentals_batch, axis=1)
277
+
278
+ vocals_list.append(vocals_batch)
279
+ instrumentals_list.append(instrumentals_batch)
280
+
281
+ vocals = np.concatenate(vocals_list, axis=1)
282
+ instrumentals = np.concatenate(instrumentals_list, axis=1)
283
+
284
+ vocal_save_path = os.path.join(stage1_output_dir, f"vocal_{random_ids[0]}".replace('.', '@') + '.npy')
285
+ inst_save_path = os.path.join(stage1_output_dir, f"instrumental_{random_ids[0]}".replace('.', '@') + '.npy')
286
+ np.save(vocal_save_path, vocals)
287
+ np.save(inst_save_path, instrumentals)
288
+ stage1_output_set.append(vocal_save_path)
289
+ stage1_output_set.append(inst_save_path)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
290
 
291
  print("Converting to Audio...")
292
 
293
+ # convert audio tokens to audio
294
+ def save_audio(wav: torch.Tensor, path, sample_rate: int, rescale: bool = False):
295
+ folder_path = os.path.dirname(path)
296
+ if not os.path.exists(folder_path):
297
+ os.makedirs(folder_path)
298
+ limit = 0.99
299
+ max_val = wav.abs().max()
300
+ wav = wav * min(limit / max_val, 1) if rescale else wav.clamp(-limit, limit)
301
+ torchaudio.save(str(path), wav, sample_rate=sample_rate, encoding='PCM_S', bits_per_sample=16)
 
 
 
302
 
303
  # reconstruct tracks
304
+ recons_output_dir = os.path.join(output_dir, "recons")
305
+ recons_mix_dir = os.path.join(recons_output_dir, 'mix')
306
+ os.makedirs(recons_mix_dir, exist_ok=True)
307
+ tracks = []
308
+
309
+ vocal_stem = None
310
+ instrumental_stem = None
311
+ sr = None
312
+
313
+ for npy in stage1_output_set:
314
+ codec_result = np.load(npy)
315
+ decodec_rlt = []
316
+ with torch.no_grad():
317
+ decoded_waveform = codec_model.decode(
318
+ torch.as_tensor(codec_result.astype(np.int16), dtype=torch.long).unsqueeze(0).permute(1, 0, 2).to(
319
+ device))
320
+ decoded_waveform = decoded_waveform.cpu().squeeze(0)
321
+ decodec_rlt.append(torch.as_tensor(decoded_waveform))
322
+ decodec_rlt = torch.cat(decodec_rlt, dim=-1)
323
+
324
+ #save_path = os.path.join(recons_output_dir, os.path.splitext(os.path.basename(npy))[0] + ".mp3")
325
+ #tracks.append(save_path)
326
+ #save_audio(decodec_rlt, save_path, 16000)
327
+ if 'vocal' in npy:
328
+ vocal_stem = decodec_rlt.numpy()
329
+ elif 'instrumental' in npy:
330
+ instrumental_stem = decodec_rlt.numpy()
331
+ sr = 16000
332
+
333
  # mix tracks
334
+ if vocal_stem is not None and instrumental_stem is not None:
335
+ mix_stem = (vocal_stem + instrumental_stem) / 1
336
+ return (sr, (mix_stem * 32767).astype(np.int16)), (sr, (vocal_stem * 32767).astype(np.int16)), (
337
+ sr, (instrumental_stem * 32767).astype(np.int16))
 
 
 
338
 
339
+ else:
340
+ print("Missing Vocal or Instrumental Stem")
341
+ return None, None, None
342
 
343
  def infer(genre_txt_content, lyrics_txt_content, num_segments=2, max_new_tokens=15):
344
  # Execute the command
345
  try:
346
  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,
347
+ cuda_idx=0, max_new_tokens=max_new_tokens, batch_size=4)
348
  return mixed_audio_data, vocal_audio_data, instrumental_audio_data
349
  except Exception as e:
350
  gr.Warning("An Error Occured: " + str(e))
 
352
  finally:
353
  print("Temporary files deleted.")
354
 
 
355
  # Gradio
356
  with gr.Blocks() as demo:
357
  with gr.Column():