chocorico commited on
Commit
e42bbfd
1 Parent(s): 621348b

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +1837 -0
  2. requirements.txt +24 -0
app.py ADDED
@@ -0,0 +1,1837 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ # Updated to account for UI changes from https://github.com/rkfg/audiocraft/blob/long/app.py
8
+ # also released under the MIT license.
9
+
10
+ import argparse
11
+ from concurrent.futures import ProcessPoolExecutor
12
+ import os
13
+ from pathlib import Path
14
+ import subprocess as sp
15
+ from tempfile import NamedTemporaryFile
16
+ import time
17
+ import warnings
18
+ import glob
19
+ import re
20
+ from PIL import Image
21
+ from pydub import AudioSegment
22
+ from datetime import datetime
23
+
24
+ import json
25
+ import shutil
26
+ import taglib
27
+ import torch
28
+ import torchaudio
29
+ import gradio as gr
30
+ import numpy as np
31
+ import typing as tp
32
+
33
+ from audiocraft.data.audio_utils import convert_audio
34
+ from audiocraft.data.audio import audio_write
35
+ from audiocraft.models import AudioGen, MusicGen, MultiBandDiffusion
36
+ from audiocraft.utils import ui
37
+ import random, string
38
+
39
+ version = "2.0.1"
40
+
41
+ theme = gr.themes.Base(
42
+ primary_hue="lime",
43
+ secondary_hue="lime",
44
+ neutral_hue="neutral",
45
+ ).set(
46
+ button_primary_background_fill_hover='*primary_500',
47
+ button_primary_background_fill_hover_dark='*primary_500',
48
+ button_secondary_background_fill_hover='*primary_500',
49
+ button_secondary_background_fill_hover_dark='*primary_500'
50
+ )
51
+
52
+ MODEL = None # Last used model
53
+ MODELS = None
54
+ UNLOAD_MODEL = False
55
+ MOVE_TO_CPU = False
56
+ IS_BATCHED = "facebook/MusicGen" in os.environ.get('SPACE_ID', '')
57
+ print(IS_BATCHED)
58
+ MAX_BATCH_SIZE = None
59
+ BATCHED_DURATION = 15
60
+ INTERRUPTING = False
61
+ MBD = None
62
+ # We have to wrap subprocess call to clean a bit the log when using gr.make_waveform
63
+ _old_call = sp.call
64
+
65
+
66
+ def generate_random_string(length):
67
+ characters = string.ascii_letters + string.digits
68
+ return ''.join(random.choice(characters) for _ in range(length))
69
+
70
+
71
+ def resize_video(input_path, output_path, target_width, target_height):
72
+ ffmpeg_cmd = [
73
+ 'ffmpeg',
74
+ '-y',
75
+ '-i', input_path,
76
+ '-vf', f'scale={target_width}:{target_height}',
77
+ '-c:a', 'copy',
78
+ output_path
79
+ ]
80
+ sp.run(ffmpeg_cmd)
81
+
82
+
83
+ def _call_nostderr(*args, **kwargs):
84
+ # Avoid ffmpeg vomiting on the logs.
85
+ kwargs['stderr'] = sp.DEVNULL
86
+ kwargs['stdout'] = sp.DEVNULL
87
+ _old_call(*args, **kwargs)
88
+
89
+
90
+ sp.call = _call_nostderr
91
+ # Preallocating the pool of processes.
92
+ pool = ProcessPoolExecutor(4)
93
+ pool.__enter__()
94
+
95
+
96
+ def interrupt():
97
+ global INTERRUPTING
98
+ INTERRUPTING = True
99
+
100
+
101
+ class FileCleaner:
102
+ def __init__(self, file_lifetime: float = 3600):
103
+ self.file_lifetime = file_lifetime
104
+ self.files = []
105
+
106
+ def add(self, path: tp.Union[str, Path]):
107
+ self._cleanup()
108
+ self.files.append((time.time(), Path(path)))
109
+
110
+ def _cleanup(self):
111
+ now = time.time()
112
+ for time_added, path in list(self.files):
113
+ if now - time_added > self.file_lifetime:
114
+ if path.exists():
115
+ path.unlink()
116
+ self.files.pop(0)
117
+ else:
118
+ break
119
+
120
+
121
+ file_cleaner = FileCleaner()
122
+
123
+
124
+ def make_waveform(*args, **kwargs):
125
+ # Further remove some warnings.
126
+ be = time.time()
127
+ with warnings.catch_warnings():
128
+ warnings.simplefilter('ignore')
129
+ height = kwargs.pop('height')
130
+ width = kwargs.pop('width')
131
+ if height < 256:
132
+ height = 256
133
+ if width < 256:
134
+ width = 256
135
+ waveform_video = gr.make_waveform(*args, **kwargs)
136
+ out = f"{generate_random_string(12)}.mp4"
137
+ image = kwargs.get('bg_image', None)
138
+ if image is None:
139
+ resize_video(waveform_video, out, 900, 300)
140
+ else:
141
+ resize_video(waveform_video, out, width, height)
142
+ print("Make a video took", time.time() - be)
143
+ return out
144
+
145
+
146
+ def load_model(version='GrandaddyShmax/musicgen-melody', custom_model=None, gen_type="music"):
147
+ global MODEL, MODELS
148
+ print("Loading model", version)
149
+ if MODELS is None:
150
+ if version == 'GrandaddyShmax/musicgen-custom':
151
+ MODEL = MusicGen.get_pretrained(custom_model)
152
+ else:
153
+ if gen_type == "music":
154
+ MODEL = MusicGen.get_pretrained(version)
155
+ elif gen_type == "audio":
156
+ MODEL = AudioGen.get_pretrained(version)
157
+
158
+ return
159
+
160
+ else:
161
+ t1 = time.monotonic()
162
+ if MODEL is not None:
163
+ MODEL.to('cpu') # move to cache
164
+ print("Previous model moved to CPU in %.2fs" % (time.monotonic() - t1))
165
+ t1 = time.monotonic()
166
+ if version != 'GrandaddyShmax/musicgen-custom' and MODELS.get(version) is None:
167
+ print("Loading model %s from disk" % version)
168
+ if gen_type == "music":
169
+ result = MusicGen.get_pretrained(version)
170
+ elif gen_type == "audio":
171
+ result = AudioGen.get_pretrained(version)
172
+ MODELS[version] = result
173
+ print("Model loaded in %.2fs" % (time.monotonic() - t1))
174
+ MODEL = result
175
+ return
176
+ result = MODELS[version].to('cuda')
177
+ print("Cached model loaded in %.2fs" % (time.monotonic() - t1))
178
+ MODEL = result
179
+
180
+ def get_audio_info(audio_path):
181
+ if audio_path is not None:
182
+ if audio_path.name.endswith(".wav") or audio_path.name.endswith(".mp4") or audio_path.name.endswith(".json"):
183
+ if not audio_path.name.endswith(".json"):
184
+ with taglib.File(audio_path.name, save_on_exit=False) as song:
185
+ if 'COMMENT' not in song.tags:
186
+ 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)"
187
+ json_string = song.tags['COMMENT'][0]
188
+ data = json.loads(json_string)
189
+ global_prompt = str("\nGlobal Prompt: " + (data['global_prompt'] if data['global_prompt'] != "" else "none")) if 'global_prompt' in data else ""
190
+ bpm = str("\nBPM: " + data['bpm']) if 'bpm' in data else ""
191
+ key = str("\nKey: " + data['key']) if 'key' in data else ""
192
+ scale = str("\nScale: " + data['scale']) if 'scale' in data else ""
193
+ prompts = str("\nPrompts: " + (data['texts'] if data['texts'] != "['']" else "none")) if 'texts' in data else ""
194
+ duration = str("\nDuration: " + data['duration']) if 'duration' in data else ""
195
+ overlap = str("\nOverlap: " + data['overlap']) if 'overlap' in data else ""
196
+ seed = str("\nSeed: " + data['seed']) if 'seed' in data else ""
197
+ audio_mode = str("\nAudio Mode: " + data['audio_mode']) if 'audio_mode' in data else ""
198
+ input_length = str("\nInput Length: " + data['input_length']) if 'input_length' in data else ""
199
+ channel = str("\nChannel: " + data['channel']) if 'channel' in data else ""
200
+ sr_select = str("\nSample Rate: " + data['sr_select']) if 'sr_select' in data else ""
201
+ gen_type = str(data['generator'] + "gen-") if 'generator' in data else ""
202
+ model = str("\nModel: " + gen_type + data['model']) if 'model' in data else ""
203
+ custom_model = str("\nCustom Model: " + data['custom_model']) if 'custom_model' in data else ""
204
+ decoder = str("\nDecoder: " + data['decoder']) if 'decoder' in data else ""
205
+ topk = str("\nTopk: " + data['topk']) if 'topk' in data else ""
206
+ topp = str("\nTopp: " + data['topp']) if 'topp' in data else ""
207
+ temperature = str("\nTemperature: " + data['temperature']) if 'temperature' in data else ""
208
+ cfg_coef = str("\nClassifier Free Guidance: " + data['cfg_coef']) if 'cfg_coef' in data else ""
209
+ version = str("Version: " + data['version']) if 'version' in data else "Version: Unknown"
210
+ 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)
211
+ if info == "":
212
+ 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)"
213
+ return info
214
+ else:
215
+ with open(audio_path.name) as json_file:
216
+ data = json.load(json_file)
217
+ #if 'global_prompt' not in data:
218
+ #return "No tags found. Either the file is not generated by MusicGen+ V1.2.8a and higher or the tags are corrupted."
219
+ global_prompt = str("\nGlobal Prompt: " + (data['global_prompt'] if data['global_prompt'] != "" else "none")) if 'global_prompt' in data else ""
220
+ bpm = str("\nBPM: " + data['bpm']) if 'bpm' in data else ""
221
+ key = str("\nKey: " + data['key']) if 'key' in data else ""
222
+ scale = str("\nScale: " + data['scale']) if 'scale' in data else ""
223
+ prompts = str("\nPrompts: " + (data['texts'] if data['texts'] != "['']" else "none")) if 'texts' in data else ""
224
+ duration = str("\nDuration: " + data['duration']) if 'duration' in data else ""
225
+ overlap = str("\nOverlap: " + data['overlap']) if 'overlap' in data else ""
226
+ seed = str("\nSeed: " + data['seed']) if 'seed' in data else ""
227
+ audio_mode = str("\nAudio Mode: " + data['audio_mode']) if 'audio_mode' in data else ""
228
+ input_length = str("\nInput Length: " + data['input_length']) if 'input_length' in data else ""
229
+ channel = str("\nChannel: " + data['channel']) if 'channel' in data else ""
230
+ sr_select = str("\nSample Rate: " + data['sr_select']) if 'sr_select' in data else ""
231
+ gen_type = str(data['generator'] + "gen-") if 'generator' in data else ""
232
+ model = str("\nModel: " + gen_type + data['model']) if 'model' in data else ""
233
+ custom_model = str("\nCustom Model: " + data['custom_model']) if 'custom_model' in data else ""
234
+ decoder = str("\nDecoder: " + data['decoder']) if 'decoder' in data else ""
235
+ topk = str("\nTopk: " + data['topk']) if 'topk' in data else ""
236
+ topp = str("\nTopp: " + data['topp']) if 'topp' in data else ""
237
+ temperature = str("\nTemperature: " + data['temperature']) if 'temperature' in data else ""
238
+ cfg_coef = str("\nClassifier Free Guidance: " + data['cfg_coef']) if 'cfg_coef' in data else ""
239
+ version = str("Version: " + data['version']) if 'version' in data else "Version: Unknown"
240
+ 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)
241
+ if info == "":
242
+ return "No tags found. Either the file is not generated by MusicGen+ V1.2.7 and higher or the tags are corrupted."
243
+ return info
244
+ else:
245
+ return "Only .wav ,.mp4 and .json files are supported"
246
+ else:
247
+ return None
248
+
249
+
250
+ def info_to_params(audio_path):
251
+ if audio_path is not None:
252
+ if audio_path.name.endswith(".wav") or audio_path.name.endswith(".mp4") or audio_path.name.endswith(".json"):
253
+ if not audio_path.name.endswith(".json"):
254
+ with taglib.File(audio_path.name, save_on_exit=False) as song:
255
+ if 'COMMENT' not in song.tags:
256
+ 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"
257
+ json_string = song.tags['COMMENT'][0]
258
+ data = json.loads(json_string)
259
+ struc_prompt = (False if data['bpm'] == "none" else True) if 'bpm' in data else False
260
+ global_prompt = data['global_prompt'] if 'global_prompt' in data else ""
261
+ bpm = (120 if data['bpm'] == "none" else int(data['bpm'])) if 'bpm' in data else 120
262
+ key = ("C" if data['key'] == "none" else data['key']) if 'key' in data else "C"
263
+ scale = ("Major" if data['scale'] == "none" else data['scale']) if 'scale' in data else "Major"
264
+ model = data['model'] if 'model' in data else "large"
265
+ custom_model = (data['custom_model'] if (data['custom_model']) in get_available_folders() else None) if 'custom_model' in data else None
266
+ decoder = data['decoder'] if 'decoder' in data else "Default"
267
+ if 'texts' not in data:
268
+ unique_prompts = 1
269
+ text = ["", "", "", "", "", "", "", "", "", ""]
270
+ repeat = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
271
+ else:
272
+ s = data['texts']
273
+ s = re.findall(r"'(.*?)'", s)
274
+ text = []
275
+ repeat = []
276
+ i = 0
277
+ for elem in s:
278
+ if elem.strip():
279
+ if i == 0 or elem != s[i-1]:
280
+ text.append(elem)
281
+ repeat.append(1)
282
+ else:
283
+ repeat[-1] += 1
284
+ i += 1
285
+ text.extend([""] * (10 - len(text)))
286
+ repeat.extend([1] * (10 - len(repeat)))
287
+ unique_prompts = len([t for t in text if t])
288
+ audio_mode = ("sample" if data['audio_mode'] == "none" else data['audio_mode']) if 'audio_mode' in data else "sample"
289
+ duration = int(data['duration']) if 'duration' in data else 10
290
+ topk = float(data['topk']) if 'topk' in data else 250
291
+ topp = float(data['topp']) if 'topp' in data else 0
292
+ temperature = float(data['temperature']) if 'temperature' in data else 1.0
293
+ cfg_coef = float(data['cfg_coef']) if 'cfg_coef' in data else 5.0
294
+ seed = int(data['seed']) if 'seed' in data else -1
295
+ overlap = int(data['overlap']) if 'overlap' in data else 12
296
+ channel = data['channel'] if 'channel' in data else "stereo"
297
+ sr_select = data['sr_select'] if 'sr_select' in data else "48000"
298
+ 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
299
+ else:
300
+ with open(audio_path.name) as json_file:
301
+ data = json.load(json_file)
302
+ struc_prompt = (False if data['bpm'] == "none" else True) if 'bpm' in data else False
303
+ global_prompt = data['global_prompt'] if 'global_prompt' in data else ""
304
+ bpm = (120 if data['bpm'] == "none" else int(data['bpm'])) if 'bpm' in data else 120
305
+ key = ("C" if data['key'] == "none" else data['key']) if 'key' in data else "C"
306
+ scale = ("Major" if data['scale'] == "none" else data['scale']) if 'scale' in data else "Major"
307
+ model = data['model'] if 'model' in data else "large"
308
+ custom_model = (data['custom_model'] if data['custom_model'] in get_available_folders() else None) if 'custom_model' in data else None
309
+ decoder = data['decoder'] if 'decoder' in data else "Default"
310
+ if 'texts' not in data:
311
+ unique_prompts = 1
312
+ text = ["", "", "", "", "", "", "", "", "", ""]
313
+ repeat = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
314
+ else:
315
+ s = data['texts']
316
+ s = re.findall(r"'(.*?)'", s)
317
+ text = []
318
+ repeat = []
319
+ i = 0
320
+ for elem in s:
321
+ if elem.strip():
322
+ if i == 0 or elem != s[i-1]:
323
+ text.append(elem)
324
+ repeat.append(1)
325
+ else:
326
+ repeat[-1] += 1
327
+ i += 1
328
+ text.extend([""] * (10 - len(text)))
329
+ repeat.extend([1] * (10 - len(repeat)))
330
+ unique_prompts = len([t for t in text if t])
331
+ audio_mode = ("sample" if data['audio_mode'] == "none" else data['audio_mode']) if 'audio_mode' in data else "sample"
332
+ duration = int(data['duration']) if 'duration' in data else 10
333
+ topk = float(data['topk']) if 'topk' in data else 250
334
+ topp = float(data['topp']) if 'topp' in data else 0
335
+ temperature = float(data['temperature']) if 'temperature' in data else 1.0
336
+ cfg_coef = float(data['cfg_coef']) if 'cfg_coef' in data else 5.0
337
+ seed = int(data['seed']) if 'seed' in data else -1
338
+ overlap = int(data['overlap']) if 'overlap' in data else 12
339
+ channel = data['channel'] if 'channel' in data else "stereo"
340
+ sr_select = data['sr_select'] if 'sr_select' in data else "48000"
341
+ 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
342
+ else:
343
+ 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"
344
+ else:
345
+ 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"
346
+
347
+
348
+ def info_to_params_a(audio_path):
349
+ if audio_path is not None:
350
+ if audio_path.name.endswith(".wav") or audio_path.name.endswith(".mp4") or audio_path.name.endswith(".json"):
351
+ if not audio_path.name.endswith(".json"):
352
+ with taglib.File(audio_path.name, save_on_exit=False) as song:
353
+ if 'COMMENT' not in song.tags:
354
+ 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"
355
+ json_string = song.tags['COMMENT'][0]
356
+ data = json.loads(json_string)
357
+ struc_prompt = (False if data['global_prompt'] == "" else True) if 'global_prompt' in data else False
358
+ global_prompt = data['global_prompt'] if 'global_prompt' in data else ""
359
+ decoder = data['decoder'] if 'decoder' in data else "Default"
360
+ if 'texts' not in data:
361
+ unique_prompts = 1
362
+ text = ["", "", "", "", "", "", "", "", "", ""]
363
+ repeat = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
364
+ else:
365
+ s = data['texts']
366
+ s = re.findall(r"'(.*?)'", s)
367
+ text = []
368
+ repeat = []
369
+ i = 0
370
+ for elem in s:
371
+ if elem.strip():
372
+ if i == 0 or elem != s[i-1]:
373
+ text.append(elem)
374
+ repeat.append(1)
375
+ else:
376
+ repeat[-1] += 1
377
+ i += 1
378
+ text.extend([""] * (10 - len(text)))
379
+ repeat.extend([1] * (10 - len(repeat)))
380
+ unique_prompts = len([t for t in text if t])
381
+ duration = int(data['duration']) if 'duration' in data else 10
382
+ topk = float(data['topk']) if 'topk' in data else 250
383
+ topp = float(data['topp']) if 'topp' in data else 0
384
+ temperature = float(data['temperature']) if 'temperature' in data else 1.0
385
+ cfg_coef = float(data['cfg_coef']) if 'cfg_coef' in data else 5.0
386
+ seed = int(data['seed']) if 'seed' in data else -1
387
+ overlap = int(data['overlap']) if 'overlap' in data else 12
388
+ channel = data['channel'] if 'channel' in data else "stereo"
389
+ sr_select = data['sr_select'] if 'sr_select' in data else "48000"
390
+ 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
391
+ else:
392
+ with open(audio_path.name) as json_file:
393
+ data = json.load(json_file)
394
+ struc_prompt = (False if data['global_prompt'] == "" else True) if 'global_prompt' in data else False
395
+ global_prompt = data['global_prompt'] if 'global_prompt' in data else ""
396
+ decoder = data['decoder'] if 'decoder' in data else "Default"
397
+ if 'texts' not in data:
398
+ unique_prompts = 1
399
+ text = ["", "", "", "", "", "", "", "", "", ""]
400
+ repeat = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
401
+ else:
402
+ s = data['texts']
403
+ s = re.findall(r"'(.*?)'", s)
404
+ text = []
405
+ repeat = []
406
+ i = 0
407
+ for elem in s:
408
+ if elem.strip():
409
+ if i == 0 or elem != s[i-1]:
410
+ text.append(elem)
411
+ repeat.append(1)
412
+ else:
413
+ repeat[-1] += 1
414
+ i += 1
415
+ text.extend([""] * (10 - len(text)))
416
+ repeat.extend([1] * (10 - len(repeat)))
417
+ unique_prompts = len([t for t in text if t])
418
+ duration = int(data['duration']) if 'duration' in data else 10
419
+ topk = float(data['topk']) if 'topk' in data else 250
420
+ topp = float(data['topp']) if 'topp' in data else 0
421
+ temperature = float(data['temperature']) if 'temperature' in data else 1.0
422
+ cfg_coef = float(data['cfg_coef']) if 'cfg_coef' in data else 5.0
423
+ seed = int(data['seed']) if 'seed' in data else -1
424
+ overlap = int(data['overlap']) if 'overlap' in data else 12
425
+ channel = data['channel'] if 'channel' in data else "stereo"
426
+ sr_select = data['sr_select'] if 'sr_select' in data else "48000"
427
+ 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
428
+
429
+ else:
430
+ 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"
431
+ else:
432
+ 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"
433
+
434
+
435
+ def make_pseudo_stereo (filename, sr_select, pan, delay):
436
+ if pan:
437
+ temp = AudioSegment.from_wav(filename)
438
+ if sr_select != "32000":
439
+ temp = temp.set_frame_rate(int(sr_select))
440
+ left = temp.pan(-0.5) - 5
441
+ right = temp.pan(0.6) - 5
442
+ temp = left.overlay(right, position=5)
443
+ temp.export(filename, format="wav")
444
+ if delay:
445
+ waveform, sample_rate = torchaudio.load(filename) # load mono WAV file
446
+ delay_seconds = 0.01 # set delay 10ms
447
+ delay_samples = int(delay_seconds * sample_rate) # Calculating delay value in number of samples
448
+ 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
449
+ torchaudio.save(filename, stereo_waveform, sample_rate)
450
+ return
451
+
452
+
453
+ def normalize_audio(audio_data):
454
+ audio_data = audio_data.astype(np.float32)
455
+ max_value = np.max(np.abs(audio_data))
456
+ audio_data /= max_value
457
+ return audio_data
458
+
459
+
460
+ def load_diffusion():
461
+ global MBD
462
+ if MBD is None:
463
+ print("loading MBD")
464
+ MBD = MultiBandDiffusion.get_mbd_musicgen()
465
+
466
+
467
+ def unload_diffusion():
468
+ global MBD
469
+ if MBD is not None:
470
+ print("unloading MBD")
471
+ MBD = None
472
+
473
+
474
+ 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):
475
+ if gen_type == "music":
476
+ maximum_size = 29.5
477
+ elif gen_type == "audio":
478
+ maximum_size = 9.5
479
+ cut_size = 0
480
+ input_length = 0
481
+ sampleP = None
482
+ if sample is not None:
483
+ globalSR, sampleM = sample[0], sample[1]
484
+ sampleM = normalize_audio(sampleM)
485
+ sampleM = torch.from_numpy(sampleM).t()
486
+ if sampleM.dim() == 1:
487
+ sampleM = sampleM.unsqueeze(0)
488
+ sample_length = sampleM.shape[sampleM.dim() - 1] / globalSR
489
+ if trim_start >= sample_length:
490
+ trim_start = sample_length - 0.5
491
+ if trim_end >= sample_length:
492
+ trim_end = sample_length - 0.5
493
+ if trim_start + trim_end >= sample_length:
494
+ tmp = sample_length - 0.5
495
+ trim_start = tmp / 2
496
+ trim_end = tmp / 2
497
+ sampleM = sampleM[..., int(globalSR * trim_start):int(globalSR * (sample_length - trim_end))]
498
+ sample_length = sample_length - (trim_start + trim_end)
499
+ if sample_length > maximum_size:
500
+ cut_size = sample_length - maximum_size
501
+ sampleP = sampleM[..., :int(globalSR * cut_size)]
502
+ sampleM = sampleM[..., int(globalSR * cut_size):]
503
+ if sample_length >= duration:
504
+ duration = sample_length + 0.5
505
+ input_length = sample_length
506
+ global MODEL
507
+ MODEL.set_generation_params(duration=(duration - cut_size), **gen_kwargs)
508
+ 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)])
509
+ be = time.time()
510
+ processed_melodies = []
511
+ if gen_type == "music":
512
+ target_sr = 32000
513
+ elif gen_type == "audio":
514
+ target_sr = 16000
515
+ target_ac = 1
516
+
517
+ for melody in melodies:
518
+ if melody is None:
519
+ processed_melodies.append(None)
520
+ else:
521
+ sr, melody = melody[0], torch.from_numpy(melody[1]).to(MODEL.device).float().t()
522
+ if melody.dim() == 1:
523
+ melody = melody[None]
524
+ melody = melody[..., :int(sr * duration)]
525
+ melody = convert_audio(melody, sr, target_sr, target_ac)
526
+ processed_melodies.append(melody)
527
+
528
+ if sample is not None:
529
+ if sampleP is None:
530
+ if gen_type == "music":
531
+ outputs = MODEL.generate_continuation(
532
+ prompt=sampleM,
533
+ prompt_sample_rate=globalSR,
534
+ descriptions=texts,
535
+ progress=progress,
536
+ return_tokens=USE_DIFFUSION
537
+ )
538
+ elif gen_type == "audio":
539
+ outputs = MODEL.generate_continuation(
540
+ prompt=sampleM,
541
+ prompt_sample_rate=globalSR,
542
+ descriptions=texts,
543
+ progress=progress
544
+ )
545
+ else:
546
+ if sampleP.dim() > 1:
547
+ sampleP = convert_audio(sampleP, globalSR, target_sr, target_ac)
548
+ sampleP = sampleP.to(MODEL.device).float().unsqueeze(0)
549
+ if gen_type == "music":
550
+ outputs = MODEL.generate_continuation(
551
+ prompt=sampleM,
552
+ prompt_sample_rate=globalSR,
553
+ descriptions=texts,
554
+ progress=progress,
555
+ return_tokens=USE_DIFFUSION
556
+ )
557
+ elif gen_type == "audio":
558
+ outputs = MODEL.generate_continuation(
559
+ prompt=sampleM,
560
+ prompt_sample_rate=globalSR,
561
+ descriptions=texts,
562
+ progress=progress
563
+ )
564
+ outputs = torch.cat([sampleP, outputs], 2)
565
+
566
+ elif any(m is not None for m in processed_melodies):
567
+ if gen_type == "music":
568
+ outputs = MODEL.generate_with_chroma(
569
+ descriptions=texts,
570
+ melody_wavs=processed_melodies,
571
+ melody_sample_rate=target_sr,
572
+ progress=progress,
573
+ return_tokens=USE_DIFFUSION
574
+ )
575
+ elif gen_type == "audio":
576
+ outputs = MODEL.generate_with_chroma(
577
+ descriptions=texts,
578
+ melody_wavs=processed_melodies,
579
+ melody_sample_rate=target_sr,
580
+ progress=progress
581
+ )
582
+ else:
583
+ if gen_type == "music":
584
+ outputs = MODEL.generate(texts, progress=progress, return_tokens=USE_DIFFUSION)
585
+ elif gen_type == "audio":
586
+ outputs = MODEL.generate(texts, progress=progress)
587
+
588
+ if USE_DIFFUSION:
589
+ print("outputs: " + str(outputs))
590
+ outputs_diffusion = MBD.tokens_to_wav(outputs[1])
591
+ outputs = torch.cat([outputs[0], outputs_diffusion], dim=0)
592
+ outputs = outputs.detach().cpu().float()
593
+ backups = outputs
594
+ if channel == "stereo":
595
+ outputs = convert_audio(outputs, target_sr, int(sr_select), 2)
596
+ elif channel == "mono" and sr_select != "32000":
597
+ outputs = convert_audio(outputs, target_sr, int(sr_select), 1)
598
+ out_files = []
599
+ out_audios = []
600
+ out_backup = []
601
+ for output in outputs:
602
+ with NamedTemporaryFile("wb", suffix=".wav", delete=False) as file:
603
+ audio_write(
604
+ file.name, output, (MODEL.sample_rate if channel == "stereo effect" else int(sr_select)), strategy="loudness",
605
+ loudness_headroom_db=16, loudness_compressor=True, add_suffix=False)
606
+
607
+ if channel == "stereo effect":
608
+ make_pseudo_stereo(file.name, sr_select, pan=True, delay=True);
609
+
610
+ 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))
611
+ out_audios.append(file.name)
612
+ file_cleaner.add(file.name)
613
+ print(f'wav: {file.name}')
614
+ for backup in backups:
615
+ with NamedTemporaryFile("wb", suffix=".wav", delete=False) as file:
616
+ audio_write(
617
+ file.name, backup, MODEL.sample_rate, strategy="loudness",
618
+ loudness_headroom_db=16, loudness_compressor=True, add_suffix=False)
619
+ out_backup.append(file.name)
620
+ file_cleaner.add(file.name)
621
+ res = [out_file.result() for out_file in out_files]
622
+ res_audio = out_audios
623
+ res_backup = out_backup
624
+ for file in res:
625
+ file_cleaner.add(file)
626
+ print(f'video: {file}')
627
+ print("batch finished", len(texts), time.time() - be)
628
+ print("Tempfiles currently stored: ", len(file_cleaner.files))
629
+ if MOVE_TO_CPU:
630
+ MODEL.to('cpu')
631
+ if UNLOAD_MODEL:
632
+ MODEL = None
633
+ torch.cuda.empty_cache()
634
+ torch.cuda.ipc_collect()
635
+ return res, res_audio, res_backup, input_length
636
+
637
+
638
+ def predict_batched(texts, melodies):
639
+ max_text_length = 512
640
+ texts = [text[:max_text_length] for text in texts]
641
+ load_model('melody')
642
+ res = _do_predictions(texts, melodies, BATCHED_DURATION)
643
+ return res
644
+
645
+
646
+ def add_tags(filename, tags):
647
+ json_string = None
648
+
649
+ data = {
650
+ "global_prompt": tags[0],
651
+ "bpm": tags[1],
652
+ "key": tags[2],
653
+ "scale": tags[3],
654
+ "texts": tags[4],
655
+ "duration": tags[5],
656
+ "overlap": tags[6],
657
+ "seed": tags[7],
658
+ "audio_mode": tags[8],
659
+ "input_length": tags[9],
660
+ "channel": tags[10],
661
+ "sr_select": tags[11],
662
+ "model": tags[12],
663
+ "custom_model": tags[13],
664
+ "decoder": tags[14],
665
+ "topk": tags[15],
666
+ "topp": tags[16],
667
+ "temperature": tags[17],
668
+ "cfg_coef": tags[18],
669
+ "generator": tags[19],
670
+ "version": version
671
+ }
672
+
673
+ json_string = json.dumps(data)
674
+
675
+ if os.path.exists(filename):
676
+ with taglib.File(filename, save_on_exit=True) as song:
677
+ song.tags = {'COMMENT': json_string }
678
+
679
+ json_file = open(tags[7] + '.json', 'w')
680
+ json_file.write(json_string)
681
+ json_file.close()
682
+
683
+ return json_file.name
684
+
685
+
686
+ def save_outputs(mp4, wav_tmp, tags, gen_type):
687
+ # mp4: .mp4 file name in root running folder of app.py
688
+ # wav_tmp: temporary wav file located in %TEMP% folder
689
+ # seed - used seed
690
+ # exanple BgnJtr4Pn1AJ.mp4, C:\Users\Alex\AppData\Local\Temp\tmp4ermrebs.wav, 195123182343465
691
+ # procedure read generated .mp4 and wav files, rename it by using seed as name,
692
+ # and will store it to ./output/today_date/wav and ./output/today_date/mp4 folders.
693
+ # if file with same seed number already exist its make postfix in name like seed(n)
694
+ # where is n - consiqunce number 1-2-3-4 and so on
695
+ # then we store generated mp4 and wav into destination folders.
696
+
697
+ current_date = datetime.now().strftime("%Y%m%d")
698
+ wav_directory = os.path.join(os.getcwd(), 'output', current_date, gen_type,'wav')
699
+ mp4_directory = os.path.join(os.getcwd(), 'output', current_date, gen_type,'mp4')
700
+ json_directory = os.path.join(os.getcwd(), 'output', current_date, gen_type,'json')
701
+ os.makedirs(wav_directory, exist_ok=True)
702
+ os.makedirs(mp4_directory, exist_ok=True)
703
+ os.makedirs(json_directory, exist_ok=True)
704
+
705
+ filename = str(tags[7]) + '.wav'
706
+ target = os.path.join(wav_directory, filename)
707
+ counter = 1
708
+ while os.path.exists(target):
709
+ filename = str(tags[7]) + f'({counter})' + '.wav'
710
+ target = os.path.join(wav_directory, filename)
711
+ counter += 1
712
+
713
+ shutil.copyfile(wav_tmp, target); # make copy of original file
714
+ json_file = add_tags(target, tags)
715
+
716
+ wav_target=target
717
+ target=target.replace('wav', 'mp4')
718
+ mp4_target=target
719
+
720
+ mp4=r'./' +mp4;
721
+ shutil.copyfile(mp4, target); # make copy of original file
722
+ _ = add_tags(target, tags)
723
+
724
+ target=target.replace('mp4', 'json'); # change the extension to json
725
+ json_target=target; # store the json target
726
+
727
+ with open(target, 'w') as f: # open a writable file object
728
+ shutil.copyfile(json_file, target); # make copy of original file
729
+
730
+ os.remove(json_file)
731
+
732
+ return wav_target, mp4_target, json_target
733
+
734
+
735
+ def clear_cash():
736
+ # delete all temporary files genegated my system
737
+ current_date = datetime.now().date()
738
+ current_directory = os.getcwd()
739
+ files = glob.glob(os.path.join(current_directory, '*.mp4'))
740
+ for file in files:
741
+ creation_date = datetime.fromtimestamp(os.path.getctime(file)).date()
742
+ if creation_date == current_date:
743
+ os.remove(file)
744
+
745
+ temp_directory = os.environ.get('TEMP')
746
+ files = glob.glob(os.path.join(temp_directory, 'tmp*.mp4'))
747
+ for file in files:
748
+ creation_date = datetime.fromtimestamp(os.path.getctime(file)).date()
749
+ if creation_date == current_date:
750
+ os.remove(file)
751
+
752
+ files = glob.glob(os.path.join(temp_directory, 'tmp*.wav'))
753
+ for file in files:
754
+ creation_date = datetime.fromtimestamp(os.path.getctime(file)).date()
755
+ if creation_date == current_date:
756
+ os.remove(file)
757
+
758
+ files = glob.glob(os.path.join(temp_directory, 'tmp*.png'))
759
+ for file in files:
760
+ creation_date = datetime.fromtimestamp(os.path.getctime(file)).date()
761
+ if creation_date == current_date:
762
+ os.remove(file)
763
+ return
764
+
765
+
766
+ def s2t(seconds, seconds2):
767
+ # convert seconds to time format
768
+ # seconds - time in seconds
769
+ # return time in format 00:00
770
+ m, s = divmod(seconds, 60)
771
+ m2, s2 = divmod(seconds2, 60)
772
+ if seconds != 0 and seconds < seconds2:
773
+ s = s + 1
774
+ return ("%02d:%02d - %02d:%02d" % (m, s, m2, s2))
775
+
776
+
777
+ def calc_time(gen_type, s, duration, overlap, d0, d1, d2, d3, d4, d5, d6, d7, d8, d9):
778
+ # calculate the time of generation
779
+ # overlap - overlap in seconds
780
+ # d0-d9 - drag
781
+ # return time in seconds
782
+ d_amount = [int(d0), int(d1), int(d2), int(d3), int(d4), int(d5), int(d6), int(d7), int(d8), int(d9)]
783
+ calc = []
784
+ tracks = []
785
+ time = 0
786
+ s = s - 1
787
+ max_time = duration
788
+ max_limit = 0
789
+ if gen_type == "music":
790
+ max_limit = 30
791
+ elif gen_type == "audio":
792
+ max_limit = 10
793
+ track_add = max_limit - overlap
794
+ tracks.append(max_limit + ((d_amount[0] - 1) * track_add))
795
+ for i in range(1, 10):
796
+ tracks.append(d_amount[i] * track_add)
797
+
798
+ if tracks[0] >= max_time or s == 0:
799
+ calc.append(s2t(time, max_time))
800
+ time = max_time
801
+ else:
802
+ calc.append(s2t(time, tracks[0]))
803
+ time = tracks[0]
804
+
805
+ for i in range(1, 10):
806
+ if time + tracks[i] >= max_time or i == s:
807
+ calc.append(s2t(time, max_time))
808
+ time = max_time
809
+ else:
810
+ calc.append(s2t(time, time + tracks[i]))
811
+ time = time + tracks[i]
812
+
813
+ return calc[0], calc[1], calc[2], calc[3], calc[4], calc[5], calc[6], calc[7], calc[8], calc[9]
814
+
815
+ 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()):
816
+ global INTERRUPTING
817
+ global USE_DIFFUSION
818
+ INTERRUPTING = False
819
+
820
+ if gen_type == "audio":
821
+ custom_model = None
822
+ custom_model_shrt = "none"
823
+ elif gen_type == "music":
824
+ custom_model_shrt = custom_model
825
+ custom_model = "models/" + custom_model
826
+
827
+ if temperature < 0:
828
+ raise gr.Error("Temperature must be >= 0.")
829
+ if topk < 0:
830
+ raise gr.Error("Topk must be non-negative.")
831
+ if topp < 0:
832
+ raise gr.Error("Topp must be non-negative.")
833
+
834
+ if trim_start < 0:
835
+ trim_start = 0
836
+ if trim_end < 0:
837
+ trim_end = 0
838
+
839
+ topk = int(topk)
840
+
841
+ if decoder == "MultiBand_Diffusion":
842
+ USE_DIFFUSION = True
843
+ load_diffusion()
844
+ else:
845
+ USE_DIFFUSION = False
846
+ unload_diffusion()
847
+
848
+ if gen_type == "music":
849
+ model_shrt = model
850
+ model = "GrandaddyShmax/musicgen-" + model
851
+ elif gen_type == "audio":
852
+ model_shrt = model
853
+ model = "GrandaddyShmax/audiogen-" + model
854
+
855
+ if MODEL is None or MODEL.name != (model):
856
+ load_model(model, custom_model, gen_type)
857
+ else:
858
+ if MOVE_TO_CPU:
859
+ MODEL.to('cuda')
860
+
861
+ if seed < 0:
862
+ seed = random.randint(0, 0xffff_ffff_ffff)
863
+ torch.manual_seed(seed)
864
+
865
+ def _progress(generated, to_generate):
866
+ progress((min(generated, to_generate), to_generate))
867
+ if INTERRUPTING:
868
+ raise gr.Error("Interrupted.")
869
+ MODEL.set_custom_progress_callback(_progress)
870
+
871
+ audio_mode = "none"
872
+ melody = None
873
+ sample = None
874
+ if audio:
875
+ audio_mode = mode
876
+ if mode == "sample":
877
+ sample = audio
878
+ elif mode == "melody":
879
+ melody = audio
880
+
881
+ custom_model_shrt = "none" if model != "GrandaddyShmax/musicgen-custom" else custom_model_shrt
882
+
883
+ text_cat = [p0, p1, p2, p3, p4, p5, p6, p7, p8, p9]
884
+ drag_cat = [d0, d1, d2, d3, d4, d5, d6, d7, d8, d9]
885
+ texts = []
886
+ raw_texts = []
887
+ ind = 0
888
+ ind2 = 0
889
+ while ind < prompt_amount:
890
+ for ind2 in range(int(drag_cat[ind])):
891
+ if not struc_prompt:
892
+ texts.append(text_cat[ind])
893
+ global_prompt = "none"
894
+ bpm = "none"
895
+ key = "none"
896
+ scale = "none"
897
+ raw_texts.append(text_cat[ind])
898
+ else:
899
+ if gen_type == "music":
900
+ bpm_str = str(bpm) + " bpm"
901
+ key_str = ", " + str(key) + " " + str(scale)
902
+ global_str = (", " + str(global_prompt)) if str(global_prompt) != "" else ""
903
+ elif gen_type == "audio":
904
+ bpm_str = ""
905
+ key_str = ""
906
+ global_str = (str(global_prompt)) if str(global_prompt) != "" else ""
907
+ texts_str = (", " + str(text_cat[ind])) if str(text_cat[ind]) != "" else ""
908
+ texts.append(bpm_str + key_str + global_str + texts_str)
909
+ raw_texts.append(text_cat[ind])
910
+ ind2 = 0
911
+ ind = ind + 1
912
+
913
+ outs, outs_audio, outs_backup, input_length = _do_predictions(
914
+ gen_type, [texts], [melody], sample, trim_start, trim_end, duration, image, height, width, background, bar1, bar2, channel, sr_select, progress=True,
915
+ top_k=topk, top_p=topp, temperature=temperature, cfg_coef=cfg_coef, extend_stride=MODEL.max_duration-overlap)
916
+ 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)]
917
+ wav_target, mp4_target, json_target = save_outputs(outs[0], outs_audio[0], tags, gen_type)
918
+ # Removes the temporary files.
919
+ for out in outs:
920
+ os.remove(out)
921
+ for out in outs_audio:
922
+ os.remove(out)
923
+
924
+ return mp4_target, wav_target, outs_backup[0], [mp4_target, wav_target, json_target], seed
925
+
926
+
927
+ max_textboxes = 10
928
+
929
+
930
+ #def get_available_models():
931
+ #return sorted([re.sub('.pt$', '', item.name) for item in list(Path('models/').glob('*')) if item.name.endswith('.pt')])
932
+
933
+
934
+ def get_available_folders():
935
+ models_dir = "models"
936
+ folders = [f for f in os.listdir(models_dir) if os.path.isdir(os.path.join(models_dir, f))]
937
+ return sorted(folders)
938
+
939
+
940
+ def toggle_audio_src(choice):
941
+ if choice == "mic":
942
+ return gr.update(source="microphone", value=None, label="Microphone")
943
+ else:
944
+ return gr.update(source="upload", value=None, label="File")
945
+
946
+
947
+ def ui_full(launch_kwargs): # 編集時の目印
948
+ with gr.Blocks(title='AudioCraft Plus', theme=theme) as interface:
949
+ gr.Markdown(
950
+ """
951
+ # AudioCraft Plus - v2.0.1
952
+
953
+ ### An All-in-One AudioCraft WebUI
954
+
955
+ Thanks to: facebookresearch, Camenduru, rkfg, oobabooga, AlexHK and GrandaddyShmax
956
+ """
957
+ )
958
+ with gr.Tab("MusicGen"):
959
+ gr.Markdown(
960
+ """
961
+ ### MusicGen
962
+ """
963
+ )
964
+ with gr.Row():
965
+ with gr.Column():
966
+ with gr.Tab("Generation"):
967
+ with gr.Accordion("Structure Prompts", open=True):
968
+ with gr.Column():
969
+ with gr.Row():
970
+ struc_prompts = gr.Checkbox(label="Enable", value=True, interactive=True, container=False)
971
+ bpm = gr.Number(label="BPM", value=180, interactive=True, scale=1, precision=0)
972
+ ### key = gr.Dropdown(["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "Bb", "B"], label="Key", value="E", interactive=True)
973
+ key = gr.Dropdown(["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "Bb", "B"], label="Key", value="E", interactive=True)
974
+ scale = gr.Dropdown(["Major", "Minor"], label="Scale", value="Minor", interactive=True)
975
+ with gr.Row():
976
+ global_prompt = gr.Text(label="Global Prompt", interactive=True, scale=3)
977
+ with gr.Row():
978
+ s = gr.Slider(1, max_textboxes, value=1, step=1, label="Prompts:", interactive=True, scale=2)
979
+ with gr.Row():
980
+ MAX_BATCH_SIZE = gr.Slider(1, 50, value=4, step=1, label="batch size", interactive=True, scale=2)
981
+ #s_mode = gr.Radio(["segmentation", "batch"], value="segmentation", interactive=True, scale=1, label="Generation Mode")
982
+ with gr.Column():
983
+ textboxes = []
984
+ prompts = []
985
+ repeats = []
986
+ calcs = []
987
+ with gr.Row():
988
+ text0 = gr.Text(label="Input Text", interactive=True, scale=4)
989
+ prompts.append(text0)
990
+ drag0 = gr.Number(label="Repeat", value=1, interactive=True, scale=1)
991
+ repeats.append(drag0)
992
+ calc0 = gr.Text(interactive=False, value="00:00 - 00:00", scale=1, label="Time")
993
+ calcs.append(calc0)
994
+ for i in range(max_textboxes):
995
+ with gr.Row(visible=False) as t:
996
+ text = gr.Text(label="Input Text", interactive=True, scale=3)
997
+ repeat = gr.Number(label="Repeat", minimum=1, value=1, interactive=True, scale=1)
998
+ calc = gr.Text(interactive=False, value="00:00 - 00:00", scale=1, label="Time")
999
+ textboxes.append(t)
1000
+ prompts.append(text)
1001
+ repeats.append(repeat)
1002
+ calcs.append(calc)
1003
+ to_calc = gr.Button("Calculate Timings", variant="secondary")
1004
+ with gr.Row():
1005
+ duration = gr.Slider(minimum=1, maximum=300, value=10, step=1, label="Duration", interactive=True)
1006
+ with gr.Row():
1007
+ overlap = gr.Slider(minimum=1, maximum=29, value=12, step=1, label="Overlap", interactive=True)
1008
+ with gr.Row():
1009
+ seed = gr.Number(label="Seed", value=-1, scale=4, precision=0, interactive=True)
1010
+ gr.Button('\U0001f3b2\ufe0f', scale=1).click(fn=lambda: -1, outputs=[seed], queue=False)
1011
+ reuse_seed = gr.Button('\u267b\ufe0f', scale=1)
1012
+
1013
+ with gr.Tab("Audio"):
1014
+ with gr.Row():
1015
+ with gr.Column():
1016
+ input_type = gr.Radio(["file", "mic"], value="file", label="Input Type (optional)", interactive=True)
1017
+ mode = gr.Radio(["melody", "sample"], label="Input Audio Mode (optional)", value="sample", interactive=True)
1018
+ with gr.Row():
1019
+ trim_start = gr.Number(label="Trim Start", value=0, interactive=True)
1020
+ trim_end = gr.Number(label="Trim End", value=0, interactive=True)
1021
+ audio = gr.Audio(source="upload", type="numpy", label="Input Audio (optional)", interactive=True)
1022
+
1023
+ with gr.Tab("Customization"):
1024
+ with gr.Row():
1025
+ with gr.Column():
1026
+ background = gr.ColorPicker(value="#0f0f0f", label="background color", interactive=True, scale=0)
1027
+ bar1 = gr.ColorPicker(value="#84cc16", label="bar color start", interactive=True, scale=0)
1028
+ bar2 = gr.ColorPicker(value="#10b981", label="bar color end", interactive=True, scale=0)
1029
+ with gr.Column():
1030
+ image = gr.Image(label="Background Image", type="filepath", interactive=True, scale=4)
1031
+ with gr.Row():
1032
+ height = gr.Number(label="Height", value=512, interactive=True)
1033
+ width = gr.Number(label="Width", value=768, interactive=True)
1034
+
1035
+ with gr.Tab("Settings"):
1036
+ with gr.Row():
1037
+ channel = gr.Radio(["mono", "stereo", "stereo effect"], label="Output Audio Channels", value="stereo effect", interactive=True, scale=1)
1038
+ sr_select = gr.Dropdown(["11025", "16000", "22050", "24000", "32000", "44100", "48000"], label="Output Audio Sample Rate", value="48000", interactive=True)
1039
+ with gr.Row():
1040
+ model = gr.Radio(["melody", "small", "medium", "large", "custom"], label="Model", value="small", interactive=True, scale=1)
1041
+ with gr.Column():
1042
+ dropdown = gr.Dropdown(choices=get_available_folders(), value=("No models found" if len(get_available_folders()) < 1 else get_available_folders()[0]), label='Custom Model (models folder)', elem_classes='slim-dropdown', interactive=True)
1043
+ ui.create_refresh_button(dropdown, lambda: None, lambda: {'choices': get_available_folders()}, 'refresh-button')
1044
+ with gr.Row():
1045
+ decoder = gr.Radio(["Default", "MultiBand_Diffusion"], label="Decoder", value="MultiBand_Diffusion", interactive=True)
1046
+ with gr.Row():
1047
+ topk = gr.Number(label="Top-k", value=250, interactive=True)
1048
+ topp = gr.Number(label="Top-p", value=0, interactive=True)
1049
+ temperature = gr.Number(label="Temperature", value=1.0, interactive=True)
1050
+ cfg_coef = gr.Number(label="Classifier Free Guidance", value=3.0, interactive=True)
1051
+ with gr.Row():
1052
+ submit = gr.Button("Generate", variant="primary")
1053
+ # Adapted from https://github.com/rkfg/audiocraft/blob/long/app.py, MIT license.
1054
+ _ = gr.Button("Interrupt").click(fn=interrupt, queue=False)
1055
+ with gr.Column() as c:
1056
+ with gr.Tab("Output"):
1057
+ output = gr.Video(label="Generated Music", scale=0)
1058
+ with gr.Row():
1059
+ audio_only = gr.Audio(type="numpy", label="Audio Only", interactive=False)
1060
+ backup_only = gr.Audio(type="numpy", label="Backup Audio", interactive=False, visible=False)
1061
+ send_audio = gr.Button("Send to Input Audio")
1062
+ seed_used = gr.Number(label='Seed used', value=-1, interactive=False)
1063
+ download = gr.File(label="Generated Files", interactive=False)
1064
+ with gr.Tab("Wiki"):
1065
+ gr.Markdown(
1066
+ """
1067
+ - **[Generate (button)]:**
1068
+ Generates the music with the given settings and prompts.
1069
+
1070
+ - **[Interrupt (button)]:**
1071
+ Stops the music generation as soon as it can, providing an incomplete output.
1072
+
1073
+ ---
1074
+
1075
+ ### Generation Tab:
1076
+
1077
+ #### Structure Prompts:
1078
+
1079
+ This feature helps reduce repetetive prompts by allowing you to set global prompts
1080
+ that will be used for all prompt segments.
1081
+
1082
+ - **[Structure Prompts (checkbox)]:**
1083
+ Enable/Disable the structure prompts feature.
1084
+
1085
+ - **[BPM (number)]:**
1086
+ Beats per minute of the generated music.
1087
+
1088
+ - **[Key (dropdown)]:**
1089
+ The key of the generated music.
1090
+
1091
+ - **[Scale (dropdown)]:**
1092
+ The scale of the generated music.
1093
+
1094
+ - **[Global Prompt (text)]:**
1095
+ Here write the prompt that you wish to be used for all prompt segments.
1096
+
1097
+ #### Multi-Prompt:
1098
+
1099
+ This feature allows you to control the music, adding variation to different time segments.
1100
+ You have up to 10 prompt segments. the first prompt will always be 30s long
1101
+ the other prompts will be [30s - overlap].
1102
+ for example if the overlap is 10s, each prompt segment will be 20s.
1103
+
1104
+ - **[Prompt Segments (number)]:**
1105
+ Amount of unique prompt to generate throughout the music generation.
1106
+
1107
+ - **[Prompt/Input Text (prompt)]:**
1108
+ Here describe the music you wish the model to generate.
1109
+
1110
+ - **[Repeat (number)]:**
1111
+ Write how many times this prompt will repeat (instead of wasting another prompt segment on the same prompt).
1112
+
1113
+ - **[Time (text)]:**
1114
+ The time of the prompt segment.
1115
+
1116
+ - **[Calculate Timings (button)]:**
1117
+ Calculates the timings of the prompt segments.
1118
+
1119
+ - **[Duration (number)]:**
1120
+ How long you want the generated music to be (in seconds).
1121
+
1122
+ - **[Overlap (number)]:**
1123
+ How much each new segment will reference the previous segment (in seconds).
1124
+ For example, if you choose 20s: Each new segment after the first one will reference the previous segment 20s
1125
+ and will generate only 10s of new music. The model can only process 30s of music.
1126
+
1127
+ - **[Seed (number)]:**
1128
+ Your generated music id. If you wish to generate the exact same music,
1129
+ place the exact seed with the exact prompts
1130
+ (This way you can also extend specific song that was generated short).
1131
+
1132
+ - **[Random Seed (button)]:**
1133
+ Gives "-1" as a seed, which counts as a random seed.
1134
+
1135
+ - **[Copy Previous Seed (button)]:**
1136
+ Copies the seed from the output seed (if you don't feel like doing it manualy).
1137
+
1138
+ ---
1139
+
1140
+ ### Audio Tab:
1141
+
1142
+ - **[Input Type (selection)]:**
1143
+ `File` mode allows you to upload an audio file to use as input
1144
+ `Mic` mode allows you to use your microphone as input
1145
+
1146
+ - **[Input Audio Mode (selection)]:**
1147
+ `Melody` mode only works with the melody model: it conditions the music generation to reference the melody
1148
+ `Sample` mode works with any model: it gives a music sample to the model to generate its continuation.
1149
+
1150
+ - **[Trim Start and Trim End (numbers)]:**
1151
+ `Trim Start` set how much you'd like to trim the input audio from the start
1152
+ `Trim End` same as the above but from the end
1153
+
1154
+ - **[Input Audio (audio file)]:**
1155
+ Input here the audio you wish to use with "melody" or "sample" mode.
1156
+
1157
+ ---
1158
+
1159
+ ### Customization Tab:
1160
+
1161
+ - **[Background Color (color)]:**
1162
+ Works only if you don't upload image. Color of the background of the waveform.
1163
+
1164
+ - **[Bar Color Start (color)]:**
1165
+ First color of the waveform bars.
1166
+
1167
+ - **[Bar Color End (color)]:**
1168
+ Second color of the waveform bars.
1169
+
1170
+ - **[Background Image (image)]:**
1171
+ Background image that you wish to be attached to the generated video along with the waveform.
1172
+
1173
+ - **[Height and Width (numbers)]:**
1174
+ Output video resolution, only works with image.
1175
+ (minimum height and width is 256).
1176
+
1177
+ ---
1178
+
1179
+ ### Settings Tab:
1180
+
1181
+ - **[Output Audio Channels (selection)]:**
1182
+ With this you can select the amount of channels that you wish for your output audio.
1183
+ `mono` is a straightforward single channel audio
1184
+ `stereo` is a dual channel audio but it will sound more or less like mono
1185
+ `stereo effect` this one is also dual channel but uses tricks to simulate a stereo audio.
1186
+
1187
+ - **[Output Audio Sample Rate (dropdown)]:**
1188
+ The output audio sample rate, the model default is 32000.
1189
+
1190
+ - **[Model (selection)]:**
1191
+ Here you can choose which model you wish to use:
1192
+ `melody` model is based on the medium model with a unique feature that lets you use melody conditioning
1193
+ `small` model is trained on 300M parameters
1194
+ `medium` model is trained on 1.5B parameters
1195
+ `large` model is trained on 3.3B parameters
1196
+ `custom` model runs the custom model that you provided.
1197
+
1198
+ - **[Custom Model (selection)]:**
1199
+ This dropdown will show you models that are placed in the `models` folder
1200
+ you must select `custom` in the model options in order to use it.
1201
+
1202
+ - **[Refresh (button)]:**
1203
+ Refreshes the dropdown list for custom model.
1204
+
1205
+ - **[Decoder (selection)]:**
1206
+ Choose here the decoder that you wish to use:
1207
+ `Default` is the default decoder
1208
+ `MultiBand_Diffusion` is a decoder that uses diffusion to generate the audio.
1209
+
1210
+ - **[Top-k (number)]:**
1211
+ is a parameter used in text generation models, including music generation models. It determines the number of most likely next tokens to consider at each step of the generation process. The model ranks all possible tokens based on their predicted probabilities, and then selects the top-k tokens from the ranked list. The model then samples from this reduced set of tokens to determine the next token in the generated sequence. A smaller value of k results in a more focused and deterministic output, while a larger value of k allows for more diversity in the generated music.
1212
+
1213
+ - **[Top-p (number)]:**
1214
+ also known as nucleus sampling or probabilistic sampling, is another method used for token selection during text generation. Instead of specifying a fixed number like top-k, top-p considers the cumulative probability distribution of the ranked tokens. It selects the smallest possible set of tokens whose cumulative probability exceeds a certain threshold (usually denoted as p). The model then samples from this set to choose the next token. This approach ensures that the generated output maintains a balance between diversity and coherence, as it allows for a varying number of tokens to be considered based on their probabilities.
1215
+
1216
+ - **[Temperature (number)]:**
1217
+ is a parameter that controls the randomness of the generated output. It is applied during the sampling process, where a higher temperature value results in more random and diverse outputs, while a lower temperature value leads to more deterministic and focused outputs. In the context of music generation, a higher temperature can introduce more variability and creativity into the generated music, but it may also lead to less coherent or structured compositions. On the other hand, a lower temperature can produce more repetitive and predictable music.
1218
+
1219
+ - **[Classifier Free Guidance (number)]:**
1220
+ refers to a technique used in some music generation models where a separate classifier network is trained to provide guidance or control over the generated music. This classifier is trained on labeled data to recognize specific musical characteristics or styles. During the generation process, the output of the generator model is evaluated by the classifier, and the generator is encouraged to produce music that aligns with the desired characteristics or style. This approach allows for more fine-grained control over the generated music, enabling users to specify certain attributes they want the model to capture.
1221
+ """
1222
+ )
1223
+ with gr.Tab("AudioGen"):
1224
+ gr.Markdown(
1225
+ """
1226
+ ### AudioGen
1227
+ """
1228
+ )
1229
+ with gr.Row():
1230
+ with gr.Column():
1231
+ with gr.Tab("Generation"):
1232
+ with gr.Accordion("Structure Prompts", open=False):
1233
+ with gr.Row():
1234
+ struc_prompts_a = gr.Checkbox(label="Enable", value=True, interactive=True, container=False)
1235
+ global_prompt_a = gr.Text(label="Global Prompt", interactive=True, scale=3)
1236
+ with gr.Row():
1237
+ s_a = gr.Slider(1, max_textboxes, value=1, step=1, label="Prompts:", interactive=True, scale=2)
1238
+ with gr.Column():
1239
+ textboxes_a = []
1240
+ prompts_a = []
1241
+ repeats_a = []
1242
+ calcs_a = []
1243
+ with gr.Row():
1244
+ text0_a = gr.Text(label="Input Text", interactive=True, scale=4)
1245
+ prompts_a.append(text0_a)
1246
+ drag0_a = gr.Number(label="Repeat", value=1, interactive=True, scale=1)
1247
+ repeats_a.append(drag0_a)
1248
+ calc0_a = gr.Text(interactive=False, value="00:00 - 00:00", scale=1, label="Time")
1249
+ calcs_a.append(calc0_a)
1250
+ for i in range(max_textboxes):
1251
+ with gr.Row(visible=False) as t_a:
1252
+ text_a = gr.Text(label="Input Text", interactive=True, scale=3)
1253
+ repeat_a = gr.Number(label="Repeat", minimum=1, value=1, interactive=True, scale=1)
1254
+ calc_a = gr.Text(interactive=False, value="00:00 - 00:00", scale=1, label="Time")
1255
+ textboxes_a.append(t_a)
1256
+ prompts_a.append(text_a)
1257
+ repeats_a.append(repeat_a)
1258
+ calcs_a.append(calc_a)
1259
+ to_calc_a = gr.Button("Calculate Timings", variant="secondary")
1260
+ with gr.Row():
1261
+ duration_a = gr.Slider(minimum=1, maximum=300, value=10, step=1, label="Duration", interactive=True)
1262
+ with gr.Row():
1263
+ overlap_a = gr.Slider(minimum=1, maximum=9, value=2, step=1, label="Overlap", interactive=True)
1264
+ with gr.Row():
1265
+ seed_a = gr.Number(label="Seed", value=-1, scale=4, precision=0, interactive=True)
1266
+ gr.Button('\U0001f3b2\ufe0f', scale=1).click(fn=lambda: -1, outputs=[seed_a], queue=False)
1267
+ reuse_seed_a = gr.Button('\u267b\ufe0f', scale=1)
1268
+
1269
+ with gr.Tab("Audio"):
1270
+ with gr.Row():
1271
+ with gr.Column():
1272
+ input_type_a = gr.Radio(["file", "mic"], value="file", label="Input Type (optional)", interactive=True)
1273
+ mode_a = gr.Radio(["sample"], label="Input Audio Mode (optional)", value="sample", interactive=False, visible=False)
1274
+ with gr.Row():
1275
+ trim_start_a = gr.Number(label="Trim Start", value=0, interactive=True)
1276
+ trim_end_a = gr.Number(label="Trim End", value=0, interactive=True)
1277
+ audio_a = gr.Audio(source="upload", type="numpy", label="Input Audio (optional)", interactive=True)
1278
+
1279
+ with gr.Tab("Customization"):
1280
+ with gr.Row():
1281
+ with gr.Column():
1282
+ background_a = gr.ColorPicker(value="#0f0f0f", label="background color", interactive=True, scale=0)
1283
+ bar1_a = gr.ColorPicker(value="#84cc16", label="bar color start", interactive=True, scale=0)
1284
+ bar2_a = gr.ColorPicker(value="#10b981", label="bar color end", interactive=True, scale=0)
1285
+ with gr.Column():
1286
+ image_a = gr.Image(label="Background Image", type="filepath", interactive=True, scale=4)
1287
+ with gr.Row():
1288
+ height_a = gr.Number(label="Height", value=512, interactive=True)
1289
+ width_a = gr.Number(label="Width", value=768, interactive=True)
1290
+
1291
+ with gr.Tab("Settings"):
1292
+ with gr.Row():
1293
+ channel_a = gr.Radio(["mono", "stereo", "stereo effect"], label="Output Audio Channels", value="stereo effect", interactive=True, scale=1)
1294
+ sr_select_a = gr.Dropdown(["11025", "16000", "22050", "24000", "32000", "44100", "48000"], label="Output Audio Sample Rate", value="48000", interactive=True)
1295
+ with gr.Row():
1296
+ model_a = gr.Radio(["medium"], label="Model", value="medium", interactive=False, visible=False)
1297
+ decoder_a = gr.Radio(["Default"], label="Decoder", value="Default", interactive=False, visible=False)
1298
+ with gr.Row():
1299
+ topk_a = gr.Number(label="Top-k", value=250, interactive=True)
1300
+ topp_a = gr.Number(label="Top-p", value=0, interactive=True)
1301
+ temperature_a = gr.Number(label="Temperature", value=1.0, interactive=True)
1302
+ cfg_coef_a = gr.Number(label="Classifier Free Guidance", value=3.0, interactive=True)
1303
+ with gr.Row():
1304
+ submit_a = gr.Button("Generate", variant="primary")
1305
+ _ = gr.Button("Interrupt").click(fn=interrupt, queue=False)
1306
+ with gr.Column():
1307
+ with gr.Tab("Output"):
1308
+ output_a = gr.Video(label="Generated Audio", scale=0)
1309
+ with gr.Row():
1310
+ audio_only_a = gr.Audio(type="numpy", label="Audio Only", interactive=False)
1311
+ backup_only_a = gr.Audio(type="numpy", label="Backup Audio", interactive=False, visible=False)
1312
+ send_audio_a = gr.Button("Send to Input Audio")
1313
+ seed_used_a = gr.Number(label='Seed used', value=-1, interactive=False)
1314
+ download_a = gr.File(label="Generated Files", interactive=False)
1315
+ with gr.Tab("Wiki"):
1316
+ gr.Markdown(
1317
+ """
1318
+ - **[Generate (button)]:**
1319
+ Generates the audio with the given settings and prompts.
1320
+
1321
+ - **[Interrupt (button)]:**
1322
+ Stops the audio generation as soon as it can, providing an incomplete output.
1323
+
1324
+ ---
1325
+
1326
+ ### Generation Tab:
1327
+
1328
+ #### Structure Prompts:
1329
+
1330
+ This feature helps reduce repetetive prompts by allowing you to set global prompts
1331
+ that will be used for all prompt segments.
1332
+
1333
+ - **[Structure Prompts (checkbox)]:**
1334
+ Enable/Disable the structure prompts feature.
1335
+
1336
+ - **[Global Prompt (text)]:**
1337
+ Here write the prompt that you wish to be used for all prompt segments.
1338
+
1339
+ #### Multi-Prompt:
1340
+
1341
+ This feature allows you to control the audio, adding variation to different time segments.
1342
+ You have up to 10 prompt segments. the first prompt will always be 10s long
1343
+ the other prompts will be [10s - overlap].
1344
+ for example if the overlap is 2s, each prompt segment will be 8s.
1345
+
1346
+ - **[Prompt Segments (number)]:**
1347
+ Amount of unique prompt to generate throughout the audio generation.
1348
+
1349
+ - **[Prompt/Input Text (prompt)]:**
1350
+ Here describe the audio you wish the model to generate.
1351
+
1352
+ - **[Repeat (number)]:**
1353
+ Write how many times this prompt will repeat (instead of wasting another prompt segment on the same prompt).
1354
+
1355
+ - **[Time (text)]:**
1356
+ The time of the prompt segment.
1357
+
1358
+ - **[Calculate Timings (button)]:**
1359
+ Calculates the timings of the prompt segments.
1360
+
1361
+ - **[Duration (number)]:**
1362
+ How long you want the generated audio to be (in seconds).
1363
+
1364
+ - **[Overlap (number)]:**
1365
+ How much each new segment will reference the previous segment (in seconds).
1366
+ For example, if you choose 2s: Each new segment after the first one will reference the previous segment 2s
1367
+ and will generate only 8s of new audio. The model can only process 10s of music.
1368
+
1369
+ - **[Seed (number)]:**
1370
+ Your generated audio id. If you wish to generate the exact same audio,
1371
+ place the exact seed with the exact prompts
1372
+ (This way you can also extend specific song that was generated short).
1373
+
1374
+ - **[Random Seed (button)]:**
1375
+ Gives "-1" as a seed, which counts as a random seed.
1376
+
1377
+ - **[Copy Previous Seed (button)]:**
1378
+ Copies the seed from the output seed (if you don't feel like doing it manualy).
1379
+
1380
+ ---
1381
+
1382
+ ### Audio Tab:
1383
+
1384
+ - **[Input Type (selection)]:**
1385
+ `File` mode allows you to upload an audio file to use as input
1386
+ `Mic` mode allows you to use your microphone as input
1387
+
1388
+ - **[Trim Start and Trim End (numbers)]:**
1389
+ `Trim Start` set how much you'd like to trim the input audio from the start
1390
+ `Trim End` same as the above but from the end
1391
+
1392
+ - **[Input Audio (audio file)]:**
1393
+ Input here the audio you wish to use.
1394
+
1395
+ ---
1396
+
1397
+ ### Customization Tab:
1398
+
1399
+ - **[Background Color (color)]:**
1400
+ Works only if you don't upload image. Color of the background of the waveform.
1401
+
1402
+ - **[Bar Color Start (color)]:**
1403
+ First color of the waveform bars.
1404
+
1405
+ - **[Bar Color End (color)]:**
1406
+ Second color of the waveform bars.
1407
+
1408
+ - **[Background Image (image)]:**
1409
+ Background image that you wish to be attached to the generated video along with the waveform.
1410
+
1411
+ - **[Height and Width (numbers)]:**
1412
+ Output video resolution, only works with image.
1413
+ (minimum height and width is 256).
1414
+
1415
+ ---
1416
+
1417
+ ### Settings Tab:
1418
+
1419
+ - **[Output Audio Channels (selection)]:**
1420
+ With this you can select the amount of channels that you wish for your output audio.
1421
+ `mono` is a straightforward single channel audio
1422
+ `stereo` is a dual channel audio but it will sound more or less like mono
1423
+ `stereo effect` this one is also dual channel but uses tricks to simulate a stereo audio.
1424
+
1425
+ - **[Output Audio Sample Rate (dropdown)]:**
1426
+ The output audio sample rate, the model default is 32000.
1427
+
1428
+ - **[Top-k (number)]:**
1429
+ is a parameter used in text generation models, including music generation models. It determines the number of most likely next tokens to consider at each step of the generation process. The model ranks all possible tokens based on their predicted probabilities, and then selects the top-k tokens from the ranked list. The model then samples from this reduced set of tokens to determine the next token in the generated sequence. A smaller value of k results in a more focused and deterministic output, while a larger value of k allows for more diversity in the generated music.
1430
+
1431
+ - **[Top-p (number)]:**
1432
+ also known as nucleus sampling or probabilistic sampling, is another method used for token selection during text generation. Instead of specifying a fixed number like top-k, top-p considers the cumulative probability distribution of the ranked tokens. It selects the smallest possible set of tokens whose cumulative probability exceeds a certain threshold (usually denoted as p). The model then samples from this set to choose the next token. This approach ensures that the generated output maintains a balance between diversity and coherence, as it allows for a varying number of tokens to be considered based on their probabilities.
1433
+
1434
+ - **[Temperature (number)]:**
1435
+ is a parameter that controls the randomness of the generated output. It is applied during the sampling process, where a higher temperature value results in more random and diverse outputs, while a lower temperature value leads to more deterministic and focused outputs. In the context of music generation, a higher temperature can introduce more variability and creativity into the generated music, but it may also lead to less coherent or structured compositions. On the other hand, a lower temperature can produce more repetitive and predictable music.
1436
+
1437
+ - **[Classifier Free Guidance (number)]:**
1438
+ refers to a technique used in some music generation models where a separate classifier network is trained to provide guidance or control over the generated music. This classifier is trained on labeled data to recognize specific musical characteristics or styles. During the generation process, the output of the generator model is evaluated by the classifier, and the generator is encouraged to produce music that aligns with the desired characteristics or style. This approach allows for more fine-grained control over the generated music, enabling users to specify certain attributes they want the model to capture.
1439
+ """
1440
+ )
1441
+ with gr.Tab("Audio Info"):
1442
+ gr.Markdown(
1443
+ """
1444
+ ### Audio Info
1445
+ """
1446
+ )
1447
+ with gr.Row():
1448
+ with gr.Column():
1449
+ in_audio = gr.File(type="file", label="Input Any Audio", interactive=True)
1450
+ with gr.Row():
1451
+ send_gen = gr.Button("Send to MusicGen", variant="primary")
1452
+ send_gen_a = gr.Button("Send to AudioGen", variant="primary")
1453
+ with gr.Column():
1454
+ info = gr.Textbox(label="Audio Info", lines=10, interactive=False)
1455
+ with gr.Tab("Changelog"):
1456
+ gr.Markdown(
1457
+ """
1458
+ ## Changelog:
1459
+
1460
+ ### v2.0.1
1461
+
1462
+ - Changed custom model loading to support the official trained models
1463
+
1464
+ - Additional changes from the main facebookresearch repo
1465
+
1466
+
1467
+
1468
+ ### v2.0.0a
1469
+
1470
+ - Forgot to move all the update to app.py from temp2.py... oops
1471
+
1472
+
1473
+
1474
+ ### v2.0.0
1475
+
1476
+ - Changed name from MusicGen+ to AudioCraft Plus
1477
+
1478
+ - Complete overhaul of the repo "backend" with the latest changes from the main facebookresearch repo
1479
+
1480
+ - Added a new decoder: MultiBand_Diffusion
1481
+
1482
+ - Added AudioGen: a new tab for generating audio
1483
+
1484
+
1485
+
1486
+ ### v1.2.8c
1487
+
1488
+ - Implemented Reverse compatibility for audio info tab with previous versions
1489
+
1490
+
1491
+
1492
+ ### v1.2.8b
1493
+
1494
+ - Fixed the error when loading default models
1495
+
1496
+
1497
+
1498
+ ### v1.2.8a
1499
+
1500
+ - Adapted Audio info tab to work with the new structure prompts feature
1501
+
1502
+ - Now custom models actually work, make sure you select the correct base model
1503
+
1504
+
1505
+
1506
+ ### v1.2.8
1507
+
1508
+ - Now you will also recieve json file with metadata of generated audio
1509
+
1510
+ - Added error messages in Audio Info tab
1511
+
1512
+ - Added structure prompts: you can select bpm, key and global prompt for all prompts
1513
+
1514
+ - Added time display next to each prompt, can be calculated with "Calculate Timings" button
1515
+
1516
+
1517
+
1518
+ ### v1.2.7
1519
+
1520
+ - When sending generated audio to Input Audio, it will send a backup audio with default settings
1521
+ (best for continuos generation)
1522
+
1523
+ - Added Metadata to generated audio (Thanks to AlexHK ♥)
1524
+
1525
+ - Added Audio Info tab that will display the metadata of the input audio
1526
+
1527
+ - Added "send to Text2Audio" button in Audio Info tab
1528
+
1529
+ - Generated audio is now stored in the "output" folder (Thanks to AlexHK ♥)
1530
+
1531
+ - Added an output area with generated files and download buttons
1532
+
1533
+ - Enhanced Stereo effect (Thanks to AlexHK ♥)
1534
+
1535
+
1536
+
1537
+ ### v1.2.6
1538
+
1539
+ - Added option to generate in stereo (instead of only mono)
1540
+
1541
+ - Added dropdown for selecting output sample rate (model default is 32000)
1542
+
1543
+
1544
+
1545
+ ### v1.2.5a
1546
+
1547
+ - Added file cleaner (This comes from the main facebookresearch repo)
1548
+
1549
+ - Reorganized a little, moved audio to a seperate tab
1550
+
1551
+
1552
+
1553
+ ### v1.2.5
1554
+
1555
+ - Gave a unique lime theme to the webui
1556
+
1557
+ - Added additional output for audio only
1558
+
1559
+ - Added button to send generated audio to Input Audio
1560
+
1561
+ - Added option to trim Input Audio
1562
+
1563
+
1564
+
1565
+ ### v1.2.4
1566
+
1567
+ - Added mic input (This comes from the main facebookresearch repo)
1568
+
1569
+
1570
+
1571
+ ### v1.2.3
1572
+
1573
+ - Added option to change video size to fit the image you upload
1574
+
1575
+
1576
+
1577
+ ### v1.2.2
1578
+
1579
+ - Added Wiki, Changelog and About tabs
1580
+
1581
+
1582
+
1583
+ ### v1.2.1
1584
+
1585
+ - Added tabs and organized the entire interface
1586
+
1587
+ - Added option to attach image to the output video
1588
+
1589
+ - Added option to load fine-tuned models (Yet to be tested)
1590
+
1591
+
1592
+
1593
+ ### v1.2.0
1594
+
1595
+ - Added Multi-Prompt
1596
+
1597
+
1598
+
1599
+ ### v1.1.3
1600
+
1601
+ - Added customization options for generated waveform
1602
+
1603
+
1604
+
1605
+ ### v1.1.2
1606
+
1607
+ - Removed sample length limit: now you can input audio of any length as music sample
1608
+
1609
+
1610
+
1611
+ ### v1.1.1
1612
+
1613
+ - Improved music sample audio quality when using music continuation
1614
+
1615
+
1616
+
1617
+ ### v1.1.0
1618
+
1619
+ - Rebuilt the repo on top of the latest structure of the main MusicGen repo
1620
+
1621
+ - Improved Music continuation feature
1622
+
1623
+
1624
+
1625
+ ### v1.0.0 - Stable Version
1626
+
1627
+ - Added Music continuation
1628
+ """
1629
+ )
1630
+ with gr.Tab("About"):
1631
+ gen_type = gr.Text(value="music", interactive=False, visible=False)
1632
+ gen_type_a = gr.Text(value="audio", interactive=False, visible=False)
1633
+ gr.Markdown(
1634
+ """
1635
+ This is your private demo for [MusicGen](https://github.com/facebookresearch/audiocraft), a simple and controllable model for music generation
1636
+ presented at: ["Simple and Controllable Music Generation"](https://huggingface.co/papers/2306.05284)
1637
+
1638
+ ## MusicGen+ is an extended version of the original MusicGen by facebookresearch.
1639
+
1640
+ ### Repo: https://github.com/GrandaddyShmax/audiocraft_plus/tree/plus
1641
+
1642
+ ---
1643
+
1644
+ ### This project was possible thanks to:
1645
+
1646
+ #### GrandaddyShmax - https://github.com/GrandaddyShmax
1647
+
1648
+ #### Camenduru - https://github.com/camenduru
1649
+
1650
+ #### rkfg - https://github.com/rkfg
1651
+
1652
+ #### oobabooga - https://github.com/oobabooga
1653
+
1654
+ #### AlexHK - https://github.com/alanhk147
1655
+ """
1656
+ )
1657
+
1658
+ send_gen.click(info_to_params, inputs=[in_audio], outputs=[decoder, struc_prompts, global_prompt, bpm, key, scale, model, dropdown, s, prompts[0], prompts[1], prompts[2], prompts[3], prompts[4], prompts[5], prompts[6], prompts[7], prompts[8], prompts[9], repeats[0], repeats[1], repeats[2], repeats[3], repeats[4], repeats[5], repeats[6], repeats[7], repeats[8], repeats[9], mode, duration, topk, topp, temperature, cfg_coef, seed, overlap, channel, sr_select], queue=False)
1659
+ reuse_seed.click(fn=lambda x: x, inputs=[seed_used], outputs=[seed], queue=False)
1660
+ send_audio.click(fn=lambda x: x, inputs=[backup_only], outputs=[audio], queue=False)
1661
+ submit.click(predict_full, inputs=[gen_type, model, decoder, dropdown, s, struc_prompts, bpm, key, scale, global_prompt, prompts[0], prompts[1], prompts[2], prompts[3], prompts[4], prompts[5], prompts[6], prompts[7], prompts[8], prompts[9], repeats[0], repeats[1], repeats[2], repeats[3], repeats[4], repeats[5], repeats[6], repeats[7], repeats[8], repeats[9], audio, mode, trim_start, trim_end, duration, topk, topp, temperature, cfg_coef, seed, overlap, image, height, width, background, bar1, bar2, channel, sr_select], outputs=[output, audio_only, backup_only, download, seed_used])
1662
+ input_type.change(toggle_audio_src, input_type, [audio], queue=False, show_progress=False)
1663
+ to_calc.click(calc_time, inputs=[gen_type, s, duration, overlap, repeats[0], repeats[1], repeats[2], repeats[3], repeats[4], repeats[5], repeats[6], repeats[7], repeats[8], repeats[9]], outputs=[calcs[0], calcs[1], calcs[2], calcs[3], calcs[4], calcs[5], calcs[6], calcs[7], calcs[8], calcs[9]], queue=False)
1664
+
1665
+ send_gen_a.click(info_to_params_a, inputs=[in_audio], outputs=[decoder_a, struc_prompts_a, global_prompt_a, s_a, prompts_a[0], prompts_a[1], prompts_a[2], prompts_a[3], prompts_a[4], prompts_a[5], prompts_a[6], prompts_a[7], prompts_a[8], prompts_a[9], repeats_a[0], repeats_a[1], repeats_a[2], repeats_a[3], repeats_a[4], repeats_a[5], repeats_a[6], repeats_a[7], repeats_a[8], repeats_a[9], duration_a, topk_a, topp_a, temperature_a, cfg_coef_a, seed_a, overlap_a, channel_a, sr_select_a], queue=False)
1666
+ reuse_seed_a.click(fn=lambda x: x, inputs=[seed_used_a], outputs=[seed_a], queue=False)
1667
+ send_audio_a.click(fn=lambda x: x, inputs=[backup_only_a], outputs=[audio_a], queue=False)
1668
+ submit_a.click(predict_full, inputs=[gen_type_a, model_a, decoder_a, dropdown, s_a, struc_prompts_a, bpm, key, scale, global_prompt_a, prompts_a[0], prompts_a[1], prompts_a[2], prompts_a[3], prompts_a[4], prompts_a[5], prompts_a[6], prompts_a[7], prompts_a[8], prompts_a[9], repeats_a[0], repeats_a[1], repeats_a[2], repeats_a[3], repeats_a[4], repeats_a[5], repeats_a[6], repeats_a[7], repeats_a[8], repeats_a[9], audio_a, mode_a, trim_start_a, trim_end_a, duration_a, topk_a, topp_a, temperature_a, cfg_coef_a, seed_a, overlap_a, image_a, height_a, width_a, background_a, bar1_a, bar2_a, channel_a, sr_select_a], outputs=[output_a, audio_only_a, backup_only_a, download_a, seed_used_a])
1669
+ input_type_a.change(toggle_audio_src, input_type_a, [audio_a], queue=False, show_progress=False)
1670
+ to_calc_a.click(calc_time, inputs=[gen_type_a, s_a, duration_a, overlap_a, repeats_a[0], repeats_a[1], repeats_a[2], repeats_a[3], repeats_a[4], repeats_a[5], repeats_a[6], repeats_a[7], repeats_a[8], repeats_a[9]], outputs=[calcs_a[0], calcs_a[1], calcs_a[2], calcs_a[3], calcs_a[4], calcs_a[5], calcs_a[6], calcs_a[7], calcs_a[8], calcs_a[9]], queue=False)
1671
+
1672
+ in_audio.change(get_audio_info, in_audio, outputs=[info])
1673
+
1674
+ def variable_outputs(k):
1675
+ k = int(k) - 1
1676
+ return [gr.Textbox.update(visible=True)]*k + [gr.Textbox.update(visible=False)]*(max_textboxes-k)
1677
+ def get_size(image):
1678
+ if image is not None:
1679
+ img = Image.open(image)
1680
+ img_height = img.height
1681
+ img_width = img.width
1682
+ if (img_height%2) != 0:
1683
+ img_height = img_height + 1
1684
+ if (img_width%2) != 0:
1685
+ img_width = img_width + 1
1686
+ return img_height, img_width
1687
+ else:
1688
+ return 512, 768
1689
+
1690
+ image.change(get_size, image, outputs=[height, width])
1691
+ image_a.change(get_size, image_a, outputs=[height_a, width_a])
1692
+ s.change(variable_outputs, s, textboxes)
1693
+ s_a.change(variable_outputs, s_a, textboxes_a)
1694
+ interface.queue().launch(**launch_kwargs)
1695
+
1696
+
1697
+ def ui_batched(launch_kwargs):
1698
+ with gr.Blocks() as demo:
1699
+ gr.Markdown(
1700
+ """
1701
+ # MusicGen
1702
+
1703
+ This is the demo for [MusicGen](https://github.com/facebookresearch/audiocraft),
1704
+ a simple and controllable model for music generation
1705
+ presented at: ["Simple and Controllable Music Generation"](https://huggingface.co/papers/2306.05284).
1706
+ <br/>
1707
+ <a href="https://huggingface.co/spaces/facebook/MusicGen?duplicate=true"
1708
+ style="display: inline-block;margin-top: .5em;margin-right: .25em;" target="_blank">
1709
+ <img style="margin-bottom: 0em;display: inline;margin-top: -.25em;"
1710
+ src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a>
1711
+ for longer sequences, more control and no queue.</p>
1712
+ """
1713
+ )
1714
+ with gr.Row():
1715
+ with gr.Column():
1716
+ with gr.Row():
1717
+ text = gr.Text(label="Describe your music", lines=2, interactive=True)
1718
+ with gr.Column():
1719
+ radio = gr.Radio(["file", "mic"], value="file",
1720
+ label="Condition on a melody (optional) File or Mic")
1721
+ melody = gr.Audio(source="upload", type="numpy", label="File",
1722
+ interactive=True, elem_id="melody-input")
1723
+ with gr.Row():
1724
+ submit = gr.Button("Generate")
1725
+ with gr.Column():
1726
+ output = gr.Video(label="Generated Music")
1727
+ audio_output = gr.Audio(label="Generated Music (wav)", type='filepath')
1728
+ submit.click(predict_batched, inputs=[text, melody],
1729
+ outputs=[output, audio_output], batch=True, max_batch_size=MAX_BATCH_SIZE)
1730
+ radio.change(toggle_audio_src, radio, [melody], queue=False, show_progress=False)
1731
+ gr.Examples(
1732
+ fn=predict_batched,
1733
+ examples=[
1734
+ [
1735
+ "An 80s driving pop song with heavy drums and synth pads in the background",
1736
+ "./assets/bach.mp3",
1737
+ ],
1738
+ [
1739
+ "A cheerful country song with acoustic guitars",
1740
+ "./assets/bolero_ravel.mp3",
1741
+ ],
1742
+ [
1743
+ "90s rock song with electric guitar and heavy drums",
1744
+ None,
1745
+ ],
1746
+ [
1747
+ "a light and cheerly EDM track, with syncopated drums, aery pads, and strong emotions bpm: 130",
1748
+ "./assets/bach.mp3",
1749
+ ],
1750
+ [
1751
+ "lofi slow bpm electro chill with organic samples",
1752
+ None,
1753
+ ],
1754
+ ],
1755
+ inputs=[text, melody],
1756
+ outputs=[output]
1757
+ )
1758
+ gr.Markdown("""
1759
+ ### More details
1760
+
1761
+ The model will generate 12 seconds of audio based on the description you provided.
1762
+ You can optionally provide a reference audio from which a broad melody will be extracted.
1763
+ The model will then try to follow both the description and melody provided.
1764
+ All samples are generated with the `melody` model.
1765
+
1766
+ You can also use your own GPU or a Google Colab by following the instructions on our repo.
1767
+
1768
+ See [github.com/facebookresearch/audiocraft](https://github.com/facebookresearch/audiocraft)
1769
+ for more details.
1770
+ """)
1771
+
1772
+ demo.queue(max_size=8 * 4).launch(**launch_kwargs)
1773
+
1774
+
1775
+ if __name__ == "__main__":
1776
+ parser = argparse.ArgumentParser()
1777
+ parser.add_argument(
1778
+ '--listen',
1779
+ type=str,
1780
+ default='0.0.0.0' if 'SPACE_ID' in os.environ else '127.0.0.1',
1781
+ help='IP to listen on for connections to Gradio',
1782
+ )
1783
+ parser.add_argument(
1784
+ '--username', type=str, default='', help='Username for authentication'
1785
+ )
1786
+ parser.add_argument(
1787
+ '--password', type=str, default='', help='Password for authentication'
1788
+ )
1789
+ parser.add_argument(
1790
+ '--server_port',
1791
+ type=int,
1792
+ default=0,
1793
+ help='Port to run the server listener on',
1794
+ )
1795
+ parser.add_argument(
1796
+ '--inbrowser', action='store_true', help='Open in browser'
1797
+ )
1798
+ parser.add_argument(
1799
+ '--share', action='store_true', help='Share the gradio UI'
1800
+ )
1801
+ parser.add_argument(
1802
+ '--unload_model', action='store_true', help='Unload the model after every generation to save GPU memory'
1803
+ )
1804
+
1805
+ parser.add_argument(
1806
+ '--unload_to_cpu', action='store_true', help='Move the model to main RAM after every generation to save GPU memory but reload faster than after full unload (see above)'
1807
+ )
1808
+
1809
+ parser.add_argument(
1810
+ '--cache', action='store_true', help='Cache models in RAM to quickly switch between them'
1811
+ )
1812
+
1813
+ args = parser.parse_args()
1814
+ UNLOAD_MODEL = args.unload_model
1815
+ MOVE_TO_CPU = args.unload_to_cpu
1816
+ if args.cache:
1817
+ MODELS = {}
1818
+
1819
+ launch_kwargs = {}
1820
+ launch_kwargs['server_name'] = args.listen
1821
+
1822
+ if args.username and args.password:
1823
+ launch_kwargs['auth'] = (args.username, args.password)
1824
+ if args.server_port:
1825
+ launch_kwargs['server_port'] = args.server_port
1826
+ if args.inbrowser:
1827
+ launch_kwargs['inbrowser'] = args.inbrowser
1828
+ if args.share:
1829
+ launch_kwargs['share'] = args.share
1830
+
1831
+ # Show the interface
1832
+ if IS_BATCHED:
1833
+ global USE_DIFFUSION
1834
+ USE_DIFFUSION = False
1835
+ ui_batched(launch_kwargs)
1836
+ else:
1837
+ ui_full(launch_kwargs)
requirements.txt ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # please make sure you have already a pytorch install that is cuda enabled!
2
+ av
3
+ einops
4
+ flashy>=0.0.1
5
+ hydra-core>=1.1
6
+ hydra_colorlog
7
+ julius
8
+ num2words
9
+ numpy
10
+ sentencepiece
11
+ spacy==3.5.2
12
+ torch>=2.0.0
13
+ torchaudio>=2.0.0
14
+ huggingface_hub
15
+ tqdm
16
+ transformers>=4.31.0 # need Encodec there.
17
+ xformers
18
+ demucs
19
+ librosa
20
+ gradio
21
+ torchmetrics
22
+ encodec
23
+ pytaglib
24
+ protobuf