forked from facebookresearch/audiocraft
-
Notifications
You must be signed in to change notification settings - Fork 63
/
app.py
1835 lines (1498 loc) · 93.5 KB
/
app.py
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# Updated to account for UI changes from https://github.com/rkfg/audiocraft/blob/long/app.py
# also released under the MIT license.
import argparse
from concurrent.futures import ProcessPoolExecutor
import os
from pathlib import Path
import subprocess as sp
from tempfile import NamedTemporaryFile
import time
import warnings
import glob
import re
from PIL import Image
from pydub import AudioSegment
from datetime import datetime
import json
import shutil
import taglib
import torch
import torchaudio
import gradio as gr
import numpy as np
import typing as tp
from audiocraft.data.audio_utils import convert_audio
from audiocraft.data.audio import audio_write
from audiocraft.models import AudioGen, MusicGen, MultiBandDiffusion
from audiocraft.utils import ui
import random, string
version = "2.0.1"
theme = gr.themes.Base(
primary_hue="lime",
secondary_hue="lime",
neutral_hue="neutral",
).set(
button_primary_background_fill_hover='*primary_500',
button_primary_background_fill_hover_dark='*primary_500',
button_secondary_background_fill_hover='*primary_500',
button_secondary_background_fill_hover_dark='*primary_500'
)
MODEL = None # Last used model
MODELS = None
UNLOAD_MODEL = False
MOVE_TO_CPU = False
IS_BATCHED = "facebook/MusicGen" in os.environ.get('SPACE_ID', '')
print(IS_BATCHED)
MAX_BATCH_SIZE = 12
BATCHED_DURATION = 15
INTERRUPTING = False
MBD = None
# We have to wrap subprocess call to clean a bit the log when using gr.make_waveform
_old_call = sp.call
def generate_random_string(length):
characters = string.ascii_letters + string.digits
return ''.join(random.choice(characters) for _ in range(length))
def resize_video(input_path, output_path, target_width, target_height):
ffmpeg_cmd = [
'ffmpeg',
'-y',
'-i', input_path,
'-vf', f'scale={target_width}:{target_height}',
'-c:a', 'copy',
output_path
]
sp.run(ffmpeg_cmd)
def _call_nostderr(*args, **kwargs):
# Avoid ffmpeg vomiting on the logs.
kwargs['stderr'] = sp.DEVNULL
kwargs['stdout'] = sp.DEVNULL
_old_call(*args, **kwargs)
sp.call = _call_nostderr
# Preallocating the pool of processes.
pool = ProcessPoolExecutor(4)
pool.__enter__()
def interrupt():
global INTERRUPTING
INTERRUPTING = True
class FileCleaner:
def __init__(self, file_lifetime: float = 3600):
self.file_lifetime = file_lifetime
self.files = []
def add(self, path: tp.Union[str, Path]):
self._cleanup()
self.files.append((time.time(), Path(path)))
def _cleanup(self):
now = time.time()
for time_added, path in list(self.files):
if now - time_added > self.file_lifetime:
if path.exists():
path.unlink()
self.files.pop(0)
else:
break
file_cleaner = FileCleaner()
def make_waveform(*args, **kwargs):
# Further remove some warnings.
be = time.time()
with warnings.catch_warnings():
warnings.simplefilter('ignore')
height = kwargs.pop('height')
width = kwargs.pop('width')
if height < 256:
height = 256
if width < 256:
width = 256
waveform_video = gr.make_waveform(*args, **kwargs)
out = f"{generate_random_string(12)}.mp4"
image = kwargs.get('bg_image', None)
if image is None:
resize_video(waveform_video, out, 900, 300)
else:
resize_video(waveform_video, out, width, height)
print("Make a video took", time.time() - be)
return out
def load_model(version='GrandaddyShmax/musicgen-melody', custom_model=None, gen_type="music"):
global MODEL, MODELS
print("Loading model", version)
if MODELS is None:
if version == 'GrandaddyShmax/musicgen-custom':
MODEL = MusicGen.get_pretrained(custom_model)
else:
if gen_type == "music":
MODEL = MusicGen.get_pretrained(version)
elif gen_type == "audio":
MODEL = AudioGen.get_pretrained(version)
return
else:
t1 = time.monotonic()
if MODEL is not None:
MODEL.to('cpu') # move to cache
print("Previous model moved to CPU in %.2fs" % (time.monotonic() - t1))
t1 = time.monotonic()
if version != 'GrandaddyShmax/musicgen-custom' and MODELS.get(version) is None:
print("Loading model %s from disk" % version)
if gen_type == "music":
result = MusicGen.get_pretrained(version)
elif gen_type == "audio":
result = AudioGen.get_pretrained(version)
MODELS[version] = result
print("Model loaded in %.2fs" % (time.monotonic() - t1))
MODEL = result
return
result = MODELS[version].to('cuda')
print("Cached model loaded in %.2fs" % (time.monotonic() - t1))
MODEL = result
def get_audio_info(audio_path):
if audio_path is not None:
if audio_path.name.endswith(".wav") or audio_path.name.endswith(".mp4") or audio_path.name.endswith(".json"):
if not audio_path.name.endswith(".json"):
with taglib.File(audio_path.name, save_on_exit=False) as song:
if 'COMMENT' not in song.tags:
return "No tags found. Either the file is not generated by MusicGen+ V1.2.7 and higher or the tags are corrupted. (Discord removes metadata from mp4 and wav files, so you can't use them)"
json_string = song.tags['COMMENT'][0]
data = json.loads(json_string)
global_prompt = str("\nGlobal Prompt: " + (data['global_prompt'] if data['global_prompt'] != "" else "none")) if 'global_prompt' in data else ""
bpm = str("\nBPM: " + data['bpm']) if 'bpm' in data else ""
key = str("\nKey: " + data['key']) if 'key' in data else ""
scale = str("\nScale: " + data['scale']) if 'scale' in data else ""
prompts = str("\nPrompts: " + (data['texts'] if data['texts'] != "['']" else "none")) if 'texts' in data else ""
duration = str("\nDuration: " + data['duration']) if 'duration' in data else ""
overlap = str("\nOverlap: " + data['overlap']) if 'overlap' in data else ""
seed = str("\nSeed: " + data['seed']) if 'seed' in data else ""
audio_mode = str("\nAudio Mode: " + data['audio_mode']) if 'audio_mode' in data else ""
input_length = str("\nInput Length: " + data['input_length']) if 'input_length' in data else ""
channel = str("\nChannel: " + data['channel']) if 'channel' in data else ""
sr_select = str("\nSample Rate: " + data['sr_select']) if 'sr_select' in data else ""
gen_type = str(data['generator'] + "gen-") if 'generator' in data else ""
model = str("\nModel: " + gen_type + data['model']) if 'model' in data else ""
custom_model = str("\nCustom Model: " + data['custom_model']) if 'custom_model' in data else ""
decoder = str("\nDecoder: " + data['decoder']) if 'decoder' in data else ""
topk = str("\nTopk: " + data['topk']) if 'topk' in data else ""
topp = str("\nTopp: " + data['topp']) if 'topp' in data else ""
temperature = str("\nTemperature: " + data['temperature']) if 'temperature' in data else ""
cfg_coef = str("\nClassifier Free Guidance: " + data['cfg_coef']) if 'cfg_coef' in data else ""
version = str("Version: " + data['version']) if 'version' in data else "Version: Unknown"
info = str(version + global_prompt + bpm + key + scale + prompts + duration + overlap + seed + audio_mode + input_length + channel + sr_select + model + custom_model + decoder + topk + topp + temperature + cfg_coef)
if info == "":
return "No tags found. Either the file is not generated by MusicGen+ V1.2.7 and higher or the tags are corrupted. (Discord removes metadata from mp4 and wav files, so you can't use them)"
return info
else:
with open(audio_path.name) as json_file:
data = json.load(json_file)
#if 'global_prompt' not in data:
#return "No tags found. Either the file is not generated by MusicGen+ V1.2.8a and higher or the tags are corrupted."
global_prompt = str("\nGlobal Prompt: " + (data['global_prompt'] if data['global_prompt'] != "" else "none")) if 'global_prompt' in data else ""
bpm = str("\nBPM: " + data['bpm']) if 'bpm' in data else ""
key = str("\nKey: " + data['key']) if 'key' in data else ""
scale = str("\nScale: " + data['scale']) if 'scale' in data else ""
prompts = str("\nPrompts: " + (data['texts'] if data['texts'] != "['']" else "none")) if 'texts' in data else ""
duration = str("\nDuration: " + data['duration']) if 'duration' in data else ""
overlap = str("\nOverlap: " + data['overlap']) if 'overlap' in data else ""
seed = str("\nSeed: " + data['seed']) if 'seed' in data else ""
audio_mode = str("\nAudio Mode: " + data['audio_mode']) if 'audio_mode' in data else ""
input_length = str("\nInput Length: " + data['input_length']) if 'input_length' in data else ""
channel = str("\nChannel: " + data['channel']) if 'channel' in data else ""
sr_select = str("\nSample Rate: " + data['sr_select']) if 'sr_select' in data else ""
gen_type = str(data['generator'] + "gen-") if 'generator' in data else ""
model = str("\nModel: " + gen_type + data['model']) if 'model' in data else ""
custom_model = str("\nCustom Model: " + data['custom_model']) if 'custom_model' in data else ""
decoder = str("\nDecoder: " + data['decoder']) if 'decoder' in data else ""
topk = str("\nTopk: " + data['topk']) if 'topk' in data else ""
topp = str("\nTopp: " + data['topp']) if 'topp' in data else ""
temperature = str("\nTemperature: " + data['temperature']) if 'temperature' in data else ""
cfg_coef = str("\nClassifier Free Guidance: " + data['cfg_coef']) if 'cfg_coef' in data else ""
version = str("Version: " + data['version']) if 'version' in data else "Version: Unknown"
info = str(version + global_prompt + bpm + key + scale + prompts + duration + overlap + seed + audio_mode + input_length + channel + sr_select + model + custom_model + decoder + topk + topp + temperature + cfg_coef)
if info == "":
return "No tags found. Either the file is not generated by MusicGen+ V1.2.7 and higher or the tags are corrupted."
return info
else:
return "Only .wav ,.mp4 and .json files are supported"
else:
return None
def info_to_params(audio_path):
if audio_path is not None:
if audio_path.name.endswith(".wav") or audio_path.name.endswith(".mp4") or audio_path.name.endswith(".json"):
if not audio_path.name.endswith(".json"):
with taglib.File(audio_path.name, save_on_exit=False) as song:
if 'COMMENT' not in song.tags:
return "Default", False, "", 120, "C", "Major", "large", None, 1, "", "", "", "", "", "", "", "", "", "", 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, "sample", 10, 250, 0, 1.0, 5.0, -1, 12, "stereo", "48000"
json_string = song.tags['COMMENT'][0]
data = json.loads(json_string)
struc_prompt = (False if data['bpm'] == "none" else True) if 'bpm' in data else False
global_prompt = data['global_prompt'] if 'global_prompt' in data else ""
bpm = (120 if data['bpm'] == "none" else int(data['bpm'])) if 'bpm' in data else 120
key = ("C" if data['key'] == "none" else data['key']) if 'key' in data else "C"
scale = ("Major" if data['scale'] == "none" else data['scale']) if 'scale' in data else "Major"
model = data['model'] if 'model' in data else "large"
custom_model = (data['custom_model'] if (data['custom_model']) in get_available_folders() else None) if 'custom_model' in data else None
decoder = data['decoder'] if 'decoder' in data else "Default"
if 'texts' not in data:
unique_prompts = 1
text = ["", "", "", "", "", "", "", "", "", ""]
repeat = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
else:
s = data['texts']
s = re.findall(r"'(.*?)'", s)
text = []
repeat = []
i = 0
for elem in s:
if elem.strip():
if i == 0 or elem != s[i-1]:
text.append(elem)
repeat.append(1)
else:
repeat[-1] += 1
i += 1
text.extend([""] * (10 - len(text)))
repeat.extend([1] * (10 - len(repeat)))
unique_prompts = len([t for t in text if t])
audio_mode = ("sample" if data['audio_mode'] == "none" else data['audio_mode']) if 'audio_mode' in data else "sample"
duration = int(data['duration']) if 'duration' in data else 10
topk = float(data['topk']) if 'topk' in data else 250
topp = float(data['topp']) if 'topp' in data else 0
temperature = float(data['temperature']) if 'temperature' in data else 1.0
cfg_coef = float(data['cfg_coef']) if 'cfg_coef' in data else 5.0
seed = int(data['seed']) if 'seed' in data else -1
overlap = int(data['overlap']) if 'overlap' in data else 12
channel = data['channel'] if 'channel' in data else "stereo"
sr_select = data['sr_select'] if 'sr_select' in data else "48000"
return decoder, struc_prompt, global_prompt, bpm, key, scale, model, custom_model, unique_prompts, text[0], text[1], text[2], text[3], text[4], text[5], text[6], text[7], text[8], text[9], repeat[0], repeat[1], repeat[2], repeat[3], repeat[4], repeat[5], repeat[6], repeat[7], repeat[8], repeat[9], audio_mode, duration, topk, topp, temperature, cfg_coef, seed, overlap, channel, sr_select
else:
with open(audio_path.name) as json_file:
data = json.load(json_file)
struc_prompt = (False if data['bpm'] == "none" else True) if 'bpm' in data else False
global_prompt = data['global_prompt'] if 'global_prompt' in data else ""
bpm = (120 if data['bpm'] == "none" else int(data['bpm'])) if 'bpm' in data else 120
key = ("C" if data['key'] == "none" else data['key']) if 'key' in data else "C"
scale = ("Major" if data['scale'] == "none" else data['scale']) if 'scale' in data else "Major"
model = data['model'] if 'model' in data else "large"
custom_model = (data['custom_model'] if data['custom_model'] in get_available_folders() else None) if 'custom_model' in data else None
decoder = data['decoder'] if 'decoder' in data else "Default"
if 'texts' not in data:
unique_prompts = 1
text = ["", "", "", "", "", "", "", "", "", ""]
repeat = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
else:
s = data['texts']
s = re.findall(r"'(.*?)'", s)
text = []
repeat = []
i = 0
for elem in s:
if elem.strip():
if i == 0 or elem != s[i-1]:
text.append(elem)
repeat.append(1)
else:
repeat[-1] += 1
i += 1
text.extend([""] * (10 - len(text)))
repeat.extend([1] * (10 - len(repeat)))
unique_prompts = len([t for t in text if t])
audio_mode = ("sample" if data['audio_mode'] == "none" else data['audio_mode']) if 'audio_mode' in data else "sample"
duration = int(data['duration']) if 'duration' in data else 10
topk = float(data['topk']) if 'topk' in data else 250
topp = float(data['topp']) if 'topp' in data else 0
temperature = float(data['temperature']) if 'temperature' in data else 1.0
cfg_coef = float(data['cfg_coef']) if 'cfg_coef' in data else 5.0
seed = int(data['seed']) if 'seed' in data else -1
overlap = int(data['overlap']) if 'overlap' in data else 12
channel = data['channel'] if 'channel' in data else "stereo"
sr_select = data['sr_select'] if 'sr_select' in data else "48000"
return decoder, struc_prompt, global_prompt, bpm, key, scale, model, custom_model, unique_prompts, text[0], text[1], text[2], text[3], text[4], text[5], text[6], text[7], text[8], text[9], repeat[0], repeat[1], repeat[2], repeat[3], repeat[4], repeat[5], repeat[6], repeat[7], repeat[8], repeat[9], audio_mode, duration, topk, topp, temperature, cfg_coef, seed, overlap, channel, sr_select
else:
return "Default", False, "", 120, "C", "Major", "large", None, 1, "", "", "", "", "", "", "", "", "", "", 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, "sample", 10, 250, 0, 1.0, 5.0, -1, 12, "stereo", "48000"
else:
return "Default", False, "", 120, "C", "Major", "large", None, 1, "", "", "", "", "", "", "", "", "", "", 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, "sample", 10, 250, 0, 1.0, 5.0, -1, 12, "stereo", "48000"
def info_to_params_a(audio_path):
if audio_path is not None:
if audio_path.name.endswith(".wav") or audio_path.name.endswith(".mp4") or audio_path.name.endswith(".json"):
if not audio_path.name.endswith(".json"):
with taglib.File(audio_path.name, save_on_exit=False) as song:
if 'COMMENT' not in song.tags:
return "Default", False, "", 1, "", "", "", "", "", "", "", "", "", "", 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 10, 250, 0, 1.0, 5.0, -1, 12, "stereo", "48000"
json_string = song.tags['COMMENT'][0]
data = json.loads(json_string)
struc_prompt = (False if data['global_prompt'] == "" else True) if 'global_prompt' in data else False
global_prompt = data['global_prompt'] if 'global_prompt' in data else ""
decoder = data['decoder'] if 'decoder' in data else "Default"
if 'texts' not in data:
unique_prompts = 1
text = ["", "", "", "", "", "", "", "", "", ""]
repeat = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
else:
s = data['texts']
s = re.findall(r"'(.*?)'", s)
text = []
repeat = []
i = 0
for elem in s:
if elem.strip():
if i == 0 or elem != s[i-1]:
text.append(elem)
repeat.append(1)
else:
repeat[-1] += 1
i += 1
text.extend([""] * (10 - len(text)))
repeat.extend([1] * (10 - len(repeat)))
unique_prompts = len([t for t in text if t])
duration = int(data['duration']) if 'duration' in data else 10
topk = float(data['topk']) if 'topk' in data else 250
topp = float(data['topp']) if 'topp' in data else 0
temperature = float(data['temperature']) if 'temperature' in data else 1.0
cfg_coef = float(data['cfg_coef']) if 'cfg_coef' in data else 5.0
seed = int(data['seed']) if 'seed' in data else -1
overlap = int(data['overlap']) if 'overlap' in data else 12
channel = data['channel'] if 'channel' in data else "stereo"
sr_select = data['sr_select'] if 'sr_select' in data else "48000"
return decoder, struc_prompt, global_prompt, unique_prompts, text[0], text[1], text[2], text[3], text[4], text[5], text[6], text[7], text[8], text[9], repeat[0], repeat[1], repeat[2], repeat[3], repeat[4], repeat[5], repeat[6], repeat[7], repeat[8], repeat[9], duration, topk, topp, temperature, cfg_coef, seed, overlap, channel, sr_select
else:
with open(audio_path.name) as json_file:
data = json.load(json_file)
struc_prompt = (False if data['global_prompt'] == "" else True) if 'global_prompt' in data else False
global_prompt = data['global_prompt'] if 'global_prompt' in data else ""
decoder = data['decoder'] if 'decoder' in data else "Default"
if 'texts' not in data:
unique_prompts = 1
text = ["", "", "", "", "", "", "", "", "", ""]
repeat = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
else:
s = data['texts']
s = re.findall(r"'(.*?)'", s)
text = []
repeat = []
i = 0
for elem in s:
if elem.strip():
if i == 0 or elem != s[i-1]:
text.append(elem)
repeat.append(1)
else:
repeat[-1] += 1
i += 1
text.extend([""] * (10 - len(text)))
repeat.extend([1] * (10 - len(repeat)))
unique_prompts = len([t for t in text if t])
duration = int(data['duration']) if 'duration' in data else 10
topk = float(data['topk']) if 'topk' in data else 250
topp = float(data['topp']) if 'topp' in data else 0
temperature = float(data['temperature']) if 'temperature' in data else 1.0
cfg_coef = float(data['cfg_coef']) if 'cfg_coef' in data else 5.0
seed = int(data['seed']) if 'seed' in data else -1
overlap = int(data['overlap']) if 'overlap' in data else 12
channel = data['channel'] if 'channel' in data else "stereo"
sr_select = data['sr_select'] if 'sr_select' in data else "48000"
return decoder, struc_prompt, global_prompt, unique_prompts, text[0], text[1], text[2], text[3], text[4], text[5], text[6], text[7], text[8], text[9], repeat[0], repeat[1], repeat[2], repeat[3], repeat[4], repeat[5], repeat[6], repeat[7], repeat[8], repeat[9], duration, topk, topp, temperature, cfg_coef, seed, overlap, channel, sr_select
else:
return "Default", False, "", 1, "", "", "", "", "", "", "", "", "", "", 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 10, 250, 0, 1.0, 5.0, -1, 12, "stereo", "48000"
else:
return "Default", False, "", 1, "", "", "", "", "", "", "", "", "", "", 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 10, 250, 0, 1.0, 5.0, -1, 12, "stereo", "48000"
def make_pseudo_stereo (filename, sr_select, pan, delay):
if pan:
temp = AudioSegment.from_wav(filename)
if sr_select != "32000":
temp = temp.set_frame_rate(int(sr_select))
left = temp.pan(-0.5) - 5
right = temp.pan(0.6) - 5
temp = left.overlay(right, position=5)
temp.export(filename, format="wav")
if delay:
waveform, sample_rate = torchaudio.load(filename) # load mono WAV file
delay_seconds = 0.01 # set delay 10ms
delay_samples = int(delay_seconds * sample_rate) # Calculating delay value in number of samples
stereo_waveform = torch.stack([waveform[0], torch.cat((torch.zeros(delay_samples), waveform[0][:-delay_samples]))]) # Generate a stereo file with original mono audio and delayed version
torchaudio.save(filename, stereo_waveform, sample_rate)
return
def normalize_audio(audio_data):
audio_data = audio_data.astype(np.float32)
max_value = np.max(np.abs(audio_data))
audio_data /= max_value
return audio_data
def load_diffusion():
global MBD
if MBD is None:
print("loading MBD")
MBD = MultiBandDiffusion.get_mbd_musicgen()
def unload_diffusion():
global MBD
if MBD is not None:
print("unloading MBD")
MBD = None
def _do_predictions(gen_type, texts, melodies, sample, trim_start, trim_end, duration, image, height, width, background, bar1, bar2, channel, sr_select, progress=False, **gen_kwargs):
if gen_type == "music":
maximum_size = 29.5
elif gen_type == "audio":
maximum_size = 9.5
cut_size = 0
input_length = 0
sampleP = None
if sample is not None:
globalSR, sampleM = sample[0], sample[1]
sampleM = normalize_audio(sampleM)
sampleM = torch.from_numpy(sampleM).t()
if sampleM.dim() == 1:
sampleM = sampleM.unsqueeze(0)
sample_length = sampleM.shape[sampleM.dim() - 1] / globalSR
if trim_start >= sample_length:
trim_start = sample_length - 0.5
if trim_end >= sample_length:
trim_end = sample_length - 0.5
if trim_start + trim_end >= sample_length:
tmp = sample_length - 0.5
trim_start = tmp / 2
trim_end = tmp / 2
sampleM = sampleM[..., int(globalSR * trim_start):int(globalSR * (sample_length - trim_end))]
sample_length = sample_length - (trim_start + trim_end)
if sample_length > maximum_size:
cut_size = sample_length - maximum_size
sampleP = sampleM[..., :int(globalSR * cut_size)]
sampleM = sampleM[..., int(globalSR * cut_size):]
if sample_length >= duration:
duration = sample_length + 0.5
input_length = sample_length
global MODEL
MODEL.set_generation_params(duration=(duration - cut_size), **gen_kwargs)
print("new batch", len(texts), texts, [None if m is None else (m[0], m[1].shape) for m in melodies], [None if sample is None else (sample[0], sample[1].shape)])
be = time.time()
processed_melodies = []
if gen_type == "music":
target_sr = 32000
elif gen_type == "audio":
target_sr = 16000
target_ac = 1
for melody in melodies:
if melody is None:
processed_melodies.append(None)
else:
sr, melody = melody[0], torch.from_numpy(melody[1]).to(MODEL.device).float().t()
if melody.dim() == 1:
melody = melody[None]
melody = melody[..., :int(sr * duration)]
melody = convert_audio(melody, sr, target_sr, target_ac)
processed_melodies.append(melody)
if sample is not None:
if sampleP is None:
if gen_type == "music":
outputs = MODEL.generate_continuation(
prompt=sampleM,
prompt_sample_rate=globalSR,
descriptions=texts,
progress=progress,
return_tokens=USE_DIFFUSION
)
elif gen_type == "audio":
outputs = MODEL.generate_continuation(
prompt=sampleM,
prompt_sample_rate=globalSR,
descriptions=texts,
progress=progress
)
else:
if sampleP.dim() > 1:
sampleP = convert_audio(sampleP, globalSR, target_sr, target_ac)
sampleP = sampleP.to(MODEL.device).float().unsqueeze(0)
if gen_type == "music":
outputs = MODEL.generate_continuation(
prompt=sampleM,
prompt_sample_rate=globalSR,
descriptions=texts,
progress=progress,
return_tokens=USE_DIFFUSION
)
elif gen_type == "audio":
outputs = MODEL.generate_continuation(
prompt=sampleM,
prompt_sample_rate=globalSR,
descriptions=texts,
progress=progress
)
outputs = torch.cat([sampleP, outputs], 2)
elif any(m is not None for m in processed_melodies):
if gen_type == "music":
outputs = MODEL.generate_with_chroma(
descriptions=texts,
melody_wavs=processed_melodies,
melody_sample_rate=target_sr,
progress=progress,
return_tokens=USE_DIFFUSION
)
elif gen_type == "audio":
outputs = MODEL.generate_with_chroma(
descriptions=texts,
melody_wavs=processed_melodies,
melody_sample_rate=target_sr,
progress=progress
)
else:
if gen_type == "music":
outputs = MODEL.generate(texts, progress=progress, return_tokens=USE_DIFFUSION)
elif gen_type == "audio":
outputs = MODEL.generate(texts, progress=progress)
if USE_DIFFUSION:
print("outputs: " + str(outputs))
outputs_diffusion = MBD.tokens_to_wav(outputs[1])
outputs = torch.cat([outputs[0], outputs_diffusion], dim=0)
outputs = outputs.detach().cpu().float()
backups = outputs
if channel == "stereo":
outputs = convert_audio(outputs, target_sr, int(sr_select), 2)
elif channel == "mono" and sr_select != "32000":
outputs = convert_audio(outputs, target_sr, int(sr_select), 1)
out_files = []
out_audios = []
out_backup = []
for output in outputs:
with NamedTemporaryFile("wb", suffix=".wav", delete=False) as file:
audio_write(
file.name, output, (MODEL.sample_rate if channel == "stereo effect" else int(sr_select)), strategy="loudness",
loudness_headroom_db=16, loudness_compressor=True, add_suffix=False)
if channel == "stereo effect":
make_pseudo_stereo(file.name, sr_select, pan=True, delay=True);
out_files.append(pool.submit(make_waveform, file.name, bg_image=image, bg_color=background, bars_color=(bar1, bar2), fg_alpha=1.0, bar_count=75, height=height, width=width))
out_audios.append(file.name)
file_cleaner.add(file.name)
print(f'wav: {file.name}')
for backup in backups:
with NamedTemporaryFile("wb", suffix=".wav", delete=False) as file:
audio_write(
file.name, backup, MODEL.sample_rate, strategy="loudness",
loudness_headroom_db=16, loudness_compressor=True, add_suffix=False)
out_backup.append(file.name)
file_cleaner.add(file.name)
res = [out_file.result() for out_file in out_files]
res_audio = out_audios
res_backup = out_backup
for file in res:
file_cleaner.add(file)
print(f'video: {file}')
print("batch finished", len(texts), time.time() - be)
print("Tempfiles currently stored: ", len(file_cleaner.files))
if MOVE_TO_CPU:
MODEL.to('cpu')
if UNLOAD_MODEL:
MODEL = None
torch.cuda.empty_cache()
torch.cuda.ipc_collect()
return res, res_audio, res_backup, input_length
def predict_batched(texts, melodies):
max_text_length = 512
texts = [text[:max_text_length] for text in texts]
load_model('melody')
res = _do_predictions(texts, melodies, BATCHED_DURATION)
return res
def add_tags(filename, tags):
json_string = None
data = {
"global_prompt": tags[0],
"bpm": tags[1],
"key": tags[2],
"scale": tags[3],
"texts": tags[4],
"duration": tags[5],
"overlap": tags[6],
"seed": tags[7],
"audio_mode": tags[8],
"input_length": tags[9],
"channel": tags[10],
"sr_select": tags[11],
"model": tags[12],
"custom_model": tags[13],
"decoder": tags[14],
"topk": tags[15],
"topp": tags[16],
"temperature": tags[17],
"cfg_coef": tags[18],
"generator": tags[19],
"version": version
}
json_string = json.dumps(data)
if os.path.exists(filename):
with taglib.File(filename, save_on_exit=True) as song:
song.tags = {'COMMENT': json_string }
json_file = open(tags[7] + '.json', 'w')
json_file.write(json_string)
json_file.close()
return json_file.name;
def save_outputs(mp4, wav_tmp, tags, gen_type):
# mp4: .mp4 file name in root running folder of app.py
# wav_tmp: temporary wav file located in %TEMP% folder
# seed - used seed
# exanple BgnJtr4Pn1AJ.mp4, C:\Users\Alex\AppData\Local\Temp\tmp4ermrebs.wav, 195123182343465
# procedure read generated .mp4 and wav files, rename it by using seed as name,
# and will store it to ./output/today_date/wav and ./output/today_date/mp4 folders.
# if file with same seed number already exist its make postfix in name like seed(n)
# where is n - consiqunce number 1-2-3-4 and so on
# then we store generated mp4 and wav into destination folders.
current_date = datetime.now().strftime("%Y%m%d")
wav_directory = os.path.join(os.getcwd(), 'output', current_date, gen_type,'wav')
mp4_directory = os.path.join(os.getcwd(), 'output', current_date, gen_type,'mp4')
json_directory = os.path.join(os.getcwd(), 'output', current_date, gen_type,'json')
os.makedirs(wav_directory, exist_ok=True)
os.makedirs(mp4_directory, exist_ok=True)
os.makedirs(json_directory, exist_ok=True)
filename = str(tags[7]) + '.wav'
target = os.path.join(wav_directory, filename)
counter = 1
while os.path.exists(target):
filename = str(tags[7]) + f'({counter})' + '.wav'
target = os.path.join(wav_directory, filename)
counter += 1
shutil.copyfile(wav_tmp, target); # make copy of original file
json_file = add_tags(target, tags);
wav_target=target;
target=target.replace('wav', 'mp4');
mp4_target=target;
mp4=r'./' +mp4;
shutil.copyfile(mp4, target); # make copy of original file
_ = add_tags(target, tags);
target=target.replace('mp4', 'json'); # change the extension to json
json_target=target; # store the json target
with open(target, 'w') as f: # open a writable file object
shutil.copyfile(json_file, target); # make copy of original file
os.remove(json_file)
return wav_target, mp4_target, json_target;
def clear_cash():
# delete all temporary files genegated my system
current_date = datetime.now().date()
current_directory = os.getcwd()
files = glob.glob(os.path.join(current_directory, '*.mp4'))
for file in files:
creation_date = datetime.fromtimestamp(os.path.getctime(file)).date()
if creation_date == current_date:
os.remove(file)
temp_directory = os.environ.get('TEMP')
files = glob.glob(os.path.join(temp_directory, 'tmp*.mp4'))
for file in files:
creation_date = datetime.fromtimestamp(os.path.getctime(file)).date()
if creation_date == current_date:
os.remove(file)
files = glob.glob(os.path.join(temp_directory, 'tmp*.wav'))
for file in files:
creation_date = datetime.fromtimestamp(os.path.getctime(file)).date()
if creation_date == current_date:
os.remove(file)
files = glob.glob(os.path.join(temp_directory, 'tmp*.png'))
for file in files:
creation_date = datetime.fromtimestamp(os.path.getctime(file)).date()
if creation_date == current_date:
os.remove(file)
return
def s2t(seconds, seconds2):
# convert seconds to time format
# seconds - time in seconds
# return time in format 00:00
m, s = divmod(seconds, 60)
m2, s2 = divmod(seconds2, 60)
if seconds != 0 and seconds < seconds2:
s = s + 1
return ("%02d:%02d - %02d:%02d" % (m, s, m2, s2))
def calc_time(gen_type, s, duration, overlap, d0, d1, d2, d3, d4, d5, d6, d7, d8, d9):
# calculate the time of generation
# overlap - overlap in seconds
# d0-d9 - drag
# return time in seconds
d_amount = [int(d0), int(d1), int(d2), int(d3), int(d4), int(d5), int(d6), int(d7), int(d8), int(d9)]
calc = []
tracks = []
time = 0
s = s - 1
max_time = duration
max_limit = 0
if gen_type == "music":
max_limit = 30
elif gen_type == "audio":
max_limit = 10
track_add = max_limit - overlap
tracks.append(max_limit + ((d_amount[0] - 1) * track_add))
for i in range(1, 10):
tracks.append(d_amount[i] * track_add)
if tracks[0] >= max_time or s == 0:
calc.append(s2t(time, max_time))
time = max_time
else:
calc.append(s2t(time, tracks[0]))
time = tracks[0]
for i in range(1, 10):
if time + tracks[i] >= max_time or i == s:
calc.append(s2t(time, max_time))
time = max_time
else:
calc.append(s2t(time, time + tracks[i]))
time = time + tracks[i]
return calc[0], calc[1], calc[2], calc[3], calc[4], calc[5], calc[6], calc[7], calc[8], calc[9]
def predict_full(gen_type, model, decoder, custom_model, prompt_amount, struc_prompt, bpm, key, scale, global_prompt, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, audio, mode, trim_start, trim_end, duration, topk, topp, temperature, cfg_coef, seed, overlap, image, height, width, background, bar1, bar2, channel, sr_select, progress=gr.Progress()):
global INTERRUPTING
global USE_DIFFUSION
INTERRUPTING = False
if gen_type == "audio":
custom_model = None
custom_model_shrt = "none"
elif gen_type == "music":
custom_model_shrt = custom_model
custom_model = "models/" + custom_model
if temperature < 0:
raise gr.Error("Temperature must be >= 0.")
if topk < 0:
raise gr.Error("Topk must be non-negative.")
if topp < 0:
raise gr.Error("Topp must be non-negative.")
if trim_start < 0:
trim_start = 0
if trim_end < 0:
trim_end = 0
topk = int(topk)
if decoder == "MultiBand_Diffusion":
USE_DIFFUSION = True
load_diffusion()
else:
USE_DIFFUSION = False
unload_diffusion()
if gen_type == "music":
model_shrt = model
model = "GrandaddyShmax/musicgen-" + model
elif gen_type == "audio":
model_shrt = model
model = "GrandaddyShmax/audiogen-" + model
if MODEL is None or MODEL.name != (model):
load_model(model, custom_model, gen_type)
else:
if MOVE_TO_CPU:
MODEL.to('cuda')
if seed < 0:
seed = random.randint(0, 0xffff_ffff_ffff)
torch.manual_seed(seed)
def _progress(generated, to_generate):
progress((min(generated, to_generate), to_generate))
if INTERRUPTING:
raise gr.Error("Interrupted.")
MODEL.set_custom_progress_callback(_progress)
audio_mode = "none"
melody = None
sample = None
if audio:
audio_mode = mode
if mode == "sample":
sample = audio
elif mode == "melody":
melody = audio
custom_model_shrt = "none" if model != "GrandaddyShmax/musicgen-custom" else custom_model_shrt
text_cat = [p0, p1, p2, p3, p4, p5, p6, p7, p8, p9]
drag_cat = [d0, d1, d2, d3, d4, d5, d6, d7, d8, d9]
texts = []
raw_texts = []
ind = 0
ind2 = 0
while ind < prompt_amount:
for ind2 in range(int(drag_cat[ind])):
if not struc_prompt:
texts.append(text_cat[ind])
global_prompt = "none"
bpm = "none"
key = "none"
scale = "none"
raw_texts.append(text_cat[ind])
else:
if gen_type == "music":
bpm_str = str(bpm) + " bpm"
key_str = ", " + str(key) + " " + str(scale)
global_str = (", " + str(global_prompt)) if str(global_prompt) != "" else ""
elif gen_type == "audio":
bpm_str = ""
key_str = ""
global_str = (str(global_prompt)) if str(global_prompt) != "" else ""
texts_str = (", " + str(text_cat[ind])) if str(text_cat[ind]) != "" else ""
texts.append(bpm_str + key_str + global_str + texts_str)
raw_texts.append(text_cat[ind])
ind2 = 0
ind = ind + 1
outs, outs_audio, outs_backup, input_length = _do_predictions(
gen_type, [texts], [melody], sample, trim_start, trim_end, duration, image, height, width, background, bar1, bar2, channel, sr_select, progress=True,
top_k=topk, top_p=topp, temperature=temperature, cfg_coef=cfg_coef, extend_stride=MODEL.max_duration-overlap)
tags = [str(global_prompt), str(bpm), str(key), str(scale), str(raw_texts), str(duration), str(overlap), str(seed), str(audio_mode), str(input_length), str(channel), str(sr_select), str(model_shrt), str(custom_model_shrt), str(decoder), str(topk), str(topp), str(temperature), str(cfg_coef), str(gen_type)]
wav_target, mp4_target, json_target = save_outputs(outs[0], outs_audio[0], tags, gen_type);
# Removes the temporary files.
for out in outs:
os.remove(out)
for out in outs_audio:
os.remove(out)
return mp4_target, wav_target, outs_backup[0], [mp4_target, wav_target, json_target], seed
max_textboxes = 10
#def get_available_models():
#return sorted([re.sub('.pt$', '', item.name) for item in list(Path('models/').glob('*')) if item.name.endswith('.pt')])
def get_available_folders():
models_dir = "models"
folders = [f for f in os.listdir(models_dir) if os.path.isdir(os.path.join(models_dir, f))]
return sorted(folders)
def toggle_audio_src(choice):
if choice == "mic":
return gr.update(source="microphone", value=None, label="Microphone")
else:
return gr.update(source="upload", value=None, label="File")
def ui_full(launch_kwargs):
with gr.Blocks(title='AudioCraft Plus', theme=theme) as interface:
gr.Markdown(
"""
# AudioCraft Plus - v2.0.1
### An All-in-One AudioCraft WebUI
Thanks to: facebookresearch, Camenduru, rkfg, oobabooga, AlexHK and GrandaddyShmax
"""
)
with gr.Tab("MusicGen"):
gr.Markdown(
"""
### MusicGen
"""
)
with gr.Row():
with gr.Column():
with gr.Tab("Generation"):
with gr.Accordion("Structure Prompts", open=False):
with gr.Column():
with gr.Row():
struc_prompts = gr.Checkbox(label="Enable", value=False, interactive=True, container=False)
bpm = gr.Number(label="BPM", value=120, interactive=True, scale=1, precision=0)
key = gr.Dropdown(["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "Bb", "B"], label="Key", value="C", interactive=True)
scale = gr.Dropdown(["Major", "Minor"], label="Scale", value="Major", interactive=True)
with gr.Row():
global_prompt = gr.Text(label="Global Prompt", interactive=True, scale=3)
with gr.Row():
s = gr.Slider(1, max_textboxes, value=1, step=1, label="Prompts:", interactive=True, scale=2)
#s_mode = gr.Radio(["segmentation", "batch"], value="segmentation", interactive=True, scale=1, label="Generation Mode")
with gr.Column():
textboxes = []
prompts = []
repeats = []
calcs = []
with gr.Row():
text0 = gr.Text(label="Input Text", interactive=True, scale=4)
prompts.append(text0)
drag0 = gr.Number(label="Repeat", value=1, interactive=True, scale=1)
repeats.append(drag0)
calc0 = gr.Text(interactive=False, value="00:00 - 00:00", scale=1, label="Time")
calcs.append(calc0)
for i in range(max_textboxes):
with gr.Row(visible=False) as t:
text = gr.Text(label="Input Text", interactive=True, scale=3)
repeat = gr.Number(label="Repeat", minimum=1, value=1, interactive=True, scale=1)
calc = gr.Text(interactive=False, value="00:00 - 00:00", scale=1, label="Time")
textboxes.append(t)
prompts.append(text)
repeats.append(repeat)
calcs.append(calc)