File size: 25,160 Bytes
6ec60d5
 
5238467
6ec60d5
 
5238467
6457900
 
5238467
8e10a53
6ec60d5
5325fcc
6ec60d5
f187760
6ec60d5
5325fcc
6ec60d5
 
f187760
6ec60d5
023bae0
6ec60d5
5325fcc
5238467
 
6ec60d5
 
1897b6f
5325fcc
 
1897b6f
5238467
6ec60d5
5325fcc
 
 
 
283cd1d
6457900
5325fcc
6ec60d5
 
5238467
6ec60d5
 
5325fcc
6ec60d5
 
 
5238467
 
6ec60d5
 
5325fcc
6ec60d5
5238467
 
6457900
049b1c4
6457900
5238467
56d7528
f187760
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ec60d5
 
 
 
 
 
 
 
 
 
5325fcc
5238467
6ec60d5
 
5325fcc
 
6ec60d5
5238467
 
5325fcc
 
 
 
 
 
 
 
6ec60d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5238467
5325fcc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ec60d5
5325fcc
 
6ec60d5
 
 
 
 
5325fcc
 
f187760
5325fcc
 
 
6ec60d5
f187760
5325fcc
6ec60d5
 
023bae0
6ec60d5
 
 
5325fcc
6ec60d5
5325fcc
6ec60d5
 
297d013
 
 
 
 
 
 
 
 
023bae0
ac60278
049b1c4
5325fcc
6457900
5325fcc
 
 
 
 
 
 
 
 
2e0c668
6ec60d5
5325fcc
 
 
 
 
 
6ec60d5
5238467
5325fcc
 
6457900
5325fcc
 
 
6457900
 
 
5238467
5325fcc
56d7528
5325fcc
 
f66088a
 
5325fcc
f66088a
 
5238467
f187760
6b3bb53
 
ac60278
6b3bb53
ac60278
f187760
 
5325fcc
ac60278
 
 
 
 
 
f66088a
 
 
 
 
 
 
 
6ec60d5
8e10a53
78747f6
8e10a53
912106c
 
107538b
 
78747f6
 
e0231b7
9ffd6b8
ac60278
ae6f193
023bae0
 
 
2cca5ed
ac60278
0a1e7c4
2cca5ed
8e10a53
 
 
 
 
049b1c4
6b3bb53
049b1c4
2b4ee56
049b1c4
 
2cca5ed
912106c
2cca5ed
 
297d013
 
049b1c4
297d013
2cca5ed
 
049b1c4
2cca5ed
 
 
 
 
 
 
 
 
07ea31c
78747f6
07ea31c
 
8e10a53
dbee739
f66088a
78747f6
5325fcc
 
297d013
38a916f
 
 
297d013
 
 
 
 
 
 
 
 
 
 
 
 
f66088a
297d013
38a916f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f66088a
 
297d013
f66088a
38a916f
5325fcc
8e10a53
297d013
 
8e10a53
e2ea31a
 
07ea31c
5325fcc
 
8e10a53
 
e2ea31a
8e10a53
07ea31c
5325fcc
 
8e10a53
 
07ea31c
8e10a53
 
 
 
3c56658
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e10a53
23fe483
5325fcc
 
 
 
 
 
 
 
 
 
 
 
4cf6900
 
 
f187760
 
 
23fe483
5325fcc
 
f187760
5325fcc
 
 
 
 
 
 
 
 
 
 
 
 
 
8e10a53
 
 
5238467
6457900
8e10a53
 
6ec60d5
 
 
 
 
8e10a53
2b4ee56
6ec60d5
f187760
 
 
 
6ec60d5
 
 
 
 
 
 
6b3bb53
f187760
2b4ee56
f187760
 
6ec60d5
8679470
6ec60d5
 
5325fcc
f187760
5325fcc
6b3bb53
6ec60d5
 
 
 
67f93cb
6ec60d5
67f93cb
 
6ec60d5
 
67f93cb
6ec60d5
67f93cb
 
6ec60d5
 
 
 
 
 
 
 
8679470
5325fcc
 
 
 
 
6ec60d5
5325fcc
6ec60d5
5325fcc
 
 
 
 
 
 
 
 
6ec60d5
5325fcc
 
6ec60d5
 
 
23fe483
8e10a53
 
 
 
 
 
6ec60d5
8e10a53
5238467
8e10a53
 
 
 
 
5238467
8e10a53
 
 
 
 
1897b6f
8e10a53
 
 
 
 
 
 
 
5238467
6ec60d5
56d7528
 
6ec60d5
 
 
 
 
 
 
 
 
5325fcc
 
6ec60d5
 
5325fcc
 
6ec60d5
 
 
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
# 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 logging
import os
from pathlib import Path
import subprocess as sp
import sys
from tempfile import NamedTemporaryFile
import time
import typing as tp
import warnings
import spaces

from einops import rearrange
import torch
import gradio as gr

from audiocraft.data.audio_utils import convert_audio
from audiocraft.data.audio import audio_write
from audiocraft.models.encodec import InterleaveStereoCompressionModel
from audiocraft.models import MusicGen, MultiBandDiffusion


MODEL = None  # Last used model
SPACE_ID = os.environ.get('SPACE_ID', '')
IS_BATCHED = "facebook/MusicGen" in SPACE_ID or 'musicgen-internal/musicgen_dev' in SPACE_ID
print(IS_BATCHED)
MAX_BATCH_SIZE = 12
BATCHED_DURATION = 30
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 _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')
        out = gr.make_waveform(*args, **kwargs)
        print("Make a video took", time.time() - be)
        return out


def load_model(version='facebook/musicgen-melody'):
    global MODEL
    print("Loading model", version)
    if MODEL is None or MODEL.name != version:
        del MODEL
        MODEL = None  # in case loading would crash
        MODEL = MusicGen.get_pretrained(version)


def load_diffusion():
    global MBD
    if MBD is None:
        print("loading MBD")
        MBD = MultiBandDiffusion.get_mbd_musicgen()


def _do_predictions(texts, melodies, duration, progress=False, gradio_progress=None, **gen_kwargs):
    MODEL.set_generation_params(duration=duration, **gen_kwargs)
    print("new batch", len(texts), texts, [None if m is None else (m[0], m[1].shape) for m in melodies])
    be = time.time()
    processed_melodies = []
    target_sr = 32000
    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)

    try:
        if any(m is not None for m in processed_melodies):
            outputs = MODEL.generate_with_chroma(
                descriptions=texts,
                melody_wavs=processed_melodies,
                melody_sample_rate=target_sr,
                progress=progress,
                return_tokens=USE_DIFFUSION
            )
        else:
            outputs = MODEL.generate(texts, progress=progress, return_tokens=USE_DIFFUSION)
    except RuntimeError as e:
        raise gr.Error("Error while generating " + e.args[0])
    if USE_DIFFUSION:
        if gradio_progress is not None:
            gradio_progress(1, desc='Running MultiBandDiffusion...')
        tokens = outputs[1]
        if isinstance(MODEL.compression_model, InterleaveStereoCompressionModel):
            left, right = MODEL.compression_model.get_left_right_codes(tokens)
            tokens = torch.cat([left, right])
        outputs_diffusion = MBD.tokens_to_wav(tokens)
        if isinstance(MODEL.compression_model, InterleaveStereoCompressionModel):
            assert outputs_diffusion.shape[1] == 1  # output is mono
            outputs_diffusion = rearrange(outputs_diffusion, '(s b) c t -> b (s c) t', s=2)
        outputs = torch.cat([outputs[0], outputs_diffusion], dim=0)
    outputs = outputs.detach().cpu().float()
    pending_videos = []
    out_wavs = []
    for output in outputs:
        with NamedTemporaryFile("wb", suffix=".wav", delete=False) as file:
            audio_write(
                file.name, output, MODEL.sample_rate, strategy="loudness",
                loudness_headroom_db=16, loudness_compressor=True, add_suffix=False)
            pending_videos.append(pool.submit(make_waveform, file.name))
            out_wavs.append(file.name)
            file_cleaner.add(file.name)
    out_videos = [pending_video.result() for pending_video in pending_videos]
    for video in out_videos:
        file_cleaner.add(video)
    print("batch finished", len(texts), time.time() - be)
    print("Tempfiles currently stored: ", len(file_cleaner.files))
    return out_videos, out_wavs


@spaces.GPU(duration=420)
def predict_batched(texts, melodies):
    max_text_length = 512
    texts = [text[:max_text_length] for text in texts]
    load_model('facebook/musicgen-stereo-melody')
    res = _do_predictions(texts, melodies, BATCHED_DURATION)
    return res


def check(model, model_path, decoder, text, melody, duration, topk, topp, temperature, cfg_coef, output_hint):
    if temperature < 0:
        raise gr.Error("Temperature must not be negative.")
    if topk < 0:
        raise gr.Error("Topk must not be negative.")
    if topp < 0:
        raise gr.Error("Topp must not be negative.")


@spaces.GPU(duration=420)
def predict_full(model, model_path, decoder, text, melody, duration, topk, topp, temperature, cfg_coef, output_hint, progress=gr.Progress()):
    global INTERRUPTING
    global USE_DIFFUSION
    INTERRUPTING = False
    progress(0, desc="Loading model...")
    model_path = model_path.strip()
    if model_path:
        if not Path(model_path).exists():
            raise gr.Error(f"Model path {model_path} doesn't exist.")
        if not Path(model_path).is_dir():
            raise gr.Error(f"Model path {model_path} must be a folder containing "
                           "state_dict.bin and compression_state_dict_.bin.")
        model = model_path

    topk = int(topk)
    if decoder == "MultiBand_Diffusion":
        USE_DIFFUSION = True
        progress(0, desc="Loading diffusion model...")
        load_diffusion()
    else:
        USE_DIFFUSION = False
    load_model(model)

    max_generated = 0

    def _progress(generated, to_generate):
        nonlocal max_generated
        max_generated = max(generated, max_generated)
        progress((min(max_generated, to_generate), to_generate))
        if INTERRUPTING:
            raise gr.Error("Interrupted.")
    MODEL.set_custom_progress_callback(_progress)

    videos, wavs = _do_predictions(
        [text], [melody], duration, progress=True,
        top_k=topk, top_p=topp, temperature=temperature, cfg_coef=cfg_coef,
        gradio_progress=progress)
    information = "To download the output, right-click and click on Save as..."

    if USE_DIFFUSION:
        return videos[0], wavs[0], information, videos[1], wavs[1]
    return videos[0], wavs[0], information, None, None


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 toggle_diffusion(choice):
    if choice == "MultiBand_Diffusion":
        return [gr.update(visible = True)] * 2
    else:
        return [gr.update(visible = False)] * 2


def show_information(choice):
    return [gr.update(visible = True)]


def hide_information(choice):
    return [gr.update(visible = False)]


def ui_full(launch_kwargs):
    with gr.Blocks() as interface:
        gr.HTML(
            """
            <h1 style="text-align: center;">Text-to-Music / Music-to-Music</h1>
            <p style="text-align: center;">Generates up to 2 minutes of music freely, without account and without watermark that you can download</p>
            <br/>
            <br/>
            ✨ Powered by <a href="https://github.com/facebookresearch/audiocraft">MusicGen</a>.
            You'd rather create way better quality music with <a href="https://huggingface.co/spaces/enzostvs/ai-jukebox">AI Jukebox</a> or on <a href="https://www.udio.com">Udio</a>.
            If you are looking for sound effect rather than music, I recommend you <i>Tango 2</i> or <i>Stable Audio</i>.
            The generated tracks tend to be very monotone so I advise you to add an original track to force the AI to make variations.
            <br/>
            <br/>
            """ + ("πŸƒβ€β™€οΈ Estimated time: few minutes." if torch.cuda.is_available() else "🐌 Slow process... ~6 hours for 2 minutes of music.") + """
            Your computer must <b><u>not</u></b> enter into standby mode.
            You can duplicate this space on a free account, it's designed to work on CPU, GPU and ZeroGPU.
            <a href="https://huggingface.co/spaces/Fabrice-TIERCELIN/Text-to-Music?duplicate=true"><img src="https://img.shields.io/badge/-Duplicate%20Space-blue?labelColor=white&style=flat&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAP5JREFUOE+lk7FqAkEURY+ltunEgFXS2sZGIbXfEPdLlnxJyDdYB62sbbUKpLbVNhyYFzbrrA74YJlh9r079973psed0cvUD4A+4HoCjsA85X0Dfn/RBLBgBDxnQPfAEJgBY+A9gALA4tcbamSzS4xq4FOQAJgCDwV2CPKV8tZAJcAjMMkUe1vX+U+SMhfAJEHasQIWmXNN3abzDwHUrgcRGmYcgKe0bxrblHEB4E/pndMazNpSZGcsZdBlYJcEL9Afo75molJyM2FxmPgmgPqlWNLGfwZGG6UiyEvLzHYDmoPkDDiNm9JR9uboiONcBXrpY1qmgs21x1QwyZcpvxt9NS09PlsPAAAAAElFTkSuQmCC&logoWidth=14"></a>
            <br/>
            βš–οΈ If you use the standard models, you can use, modify and share the generated musics but not for commercial uses.

            """
        )
        with gr.Row():
            with gr.Column():
                with gr.Row():
                    text = gr.Text(label = "Input Text", placeholder = "Describe your music here", interactive = True, autofocus = True)
                    with gr.Column():
                        radio = gr.Radio(["file", "mic"], value = "file",
                                         label="Condition on a melody (optional) File or Microphone")
                        melody = gr.Audio(source = "upload", type = "numpy", label = "File",
                                          interactive = True, elem_id="melody-input")
                with gr.Row():
                    duration = gr.Slider(label = "Duration", info = "(in seconds)", minimum = 1, maximum = 120, value = 30, interactive = True)
                with gr.Accordion("Advanced options", open = False):
                    with gr.Row():
                        topk = gr.Number(label = "Top-k", info = "Number of tokens shortlisted", value = 250, minimum = 0, interactive = True)
                        topp = gr.Number(label = "Top-p", info = "Percent of tokens shortlisted", value = 0, minimum = 0, interactive = True)
                        temperature = gr.Number(label = "Temperature", info = "lower=Always similar, higher=More creative", value = 1.0, interactive = True)
                        cfg_coef = gr.Number(label = "Classifier-Free Guidance", info = "lower=Audio quality, higher=Follow the prompt", value = 3.0, minimum = 1, interactive = True)
                    with gr.Row():
                        decoder = gr.Radio(["Default", "MultiBand_Diffusion"],
                                       label = "Decoder", value = "Default", interactive = True)
                    with gr.Row():
                        model = gr.Radio(["facebook/musicgen-melody", "facebook/musicgen-medium", "facebook/musicgen-small",
                                          "facebook/musicgen-large", 
                                          "facebook/musicgen-melody-large",
                                          "facebook/musicgen-stereo-small", "facebook/musicgen-stereo-medium",
                                          "facebook/musicgen-stereo-melody", "facebook/musicgen-stereo-large",
                                          "facebook/musicgen-stereo-melody-large"],
                                         label="Model", value="facebook/musicgen-stereo-melody", interactive=True)
                        model_path = gr.Text(label="Model Path (custom models)")
                with gr.Row():
                    submit = gr.Button("πŸš€ Generate", variant = "primary")
                    # Adapted from https://github.com/rkfg/audiocraft/blob/long/app.py, MIT license.
                    _ = gr.Button("Abort all", variant="stop").click(fn=interrupt, queue = False)
            with gr.Column():
                output = gr.Video(label="Generated Music")
                audio_output = gr.Audio(label = "Generated Music (wav)", type='filepath', autoplay = True, show_download_button = True)
                output_hint = gr.Label()
                diffusion_output = gr.Video(label="MultiBand Diffusion Decoder")
                audio_diffusion = gr.Audio(label="MultiBand Diffusion Decoder (wav)", type='filepath')

        submit.click(toggle_diffusion, decoder, [
            diffusion_output,
            audio_diffusion
        ], queue = False, show_progress = False).then(hide_information, decoder, [
            output_hint
        ], queue = False, show_progress = False).then(check, inputs = [
            model,
            model_path,
            decoder,
            text,
            melody,
            duration,
            topk,
            topp,
            temperature,
            cfg_coef,
            output_hint
        ], outputs = [], queue = False, show_progress = False).success(predict_full, inputs = [
            model,
            model_path,
            decoder,
            text,
            melody,
            duration,
            topk,
            topp,
            temperature,
            cfg_coef,
            output_hint
        ], outputs = [
            output,
            audio_output,
            output_hint,
            diffusion_output,
            audio_diffusion
        ], scroll_to_output = True).then(show_information, decoder, [
            output_hint
        ], queue = False, show_progress = False)

        radio.change(toggle_audio_src, radio, [melody], queue = False, show_progress = False)

        gr.Examples(
            fn = predict_full,
            examples = [
                [
                    "An angry propulsive industrial score with distorted synthesizers and tortured vocals.",
                    None,
                    10,
                    "facebook/musicgen-stereo-melody",
                    "Default"
                ],
                [
                    "A monstrous industrial bach hybrid",
                    "./assets/bach.mp3",
                    10,
                    "facebook/musicgen-stereo-melody",
                    "Default"
                ],
            ],
            inputs=[text, melody, duration, model, decoder],
            outputs=[output]
        )
        gr.Markdown(
            """
            ### How to prompt your music

            You can use round brackets to increase the importance of a part:
            ```
            Classical music, violin, harp, (piano)
            ```

            You can use several levels of round brackets to even more increase the importance of a part:
            ```
            Classical music, violin, (harp), ((piano))
            ```

            You can use number instead of several round brackets:
            ```
            Classical music, (violin), (harp:1.5), ((piano))
            ```

            You can do the same thing with square brackets to decrease the importance of a part:
            ```
            Classical music, strings, [violin], [[harp]], [piano:10]
            ```

            ### More details

            The model can generate up to 30 seconds of audio in one pass.

            The model was trained with description from a stock music catalog, descriptions that will work best
            should include some level of details on the instruments present, along with some intended use case
            (e.g. adding "perfect for a commercial" can somehow help).

            Using one of the `melody` model (e.g. `musicgen-melody-*`), you can optionally provide a reference audio
            from which a broad melody will be extracted.
            The model will then try to follow both the description and melody provided.
            For best results, the melody should be 30 seconds long (I know, the samples we provide are not...)

            It is now possible to extend the generation by feeding back the end of the previous chunk of audio.
            This can take a long time, and the model might lose consistency. The model might also
            decide at arbitrary positions that the song ends.

            **WARNING:** Choosing long durations will take a long time to generate (2min might take ~10min).
            An overlap of 12 seconds is kept with the previously generated chunk, and 18 "new" seconds
            are generated each time.

            We present 10 model variations:
            1. facebook/musicgen-melody -- a music generation model capable of generating music condition
                on text and melody inputs. **Note**, you can also use text only.
            2. facebook/musicgen-small -- a 300M transformer decoder conditioned on text only.
            3. facebook/musicgen-medium -- a 1.5B transformer decoder conditioned on text only.
            4. facebook/musicgen-large -- a 3.3B transformer decoder conditioned on text only.
            5. facebook/musicgen-melody-large -- a 3.3B transformer decoder conditioned on and melody.
            6. facebook/musicgen-stereo-*: same as the previous models but fine tuned to output stereo audio.

            We also present two way of decoding the audio tokens
            1. Use the default GAN based compression model. It can suffer from artifacts especially
                for crashes, snares etc.
            2. Use [MultiBand Diffusion](https://arxiv.org/abs/2308.02560). Should improve the audio quality,
                at an extra computational cost. When this is selected, we provide both the GAN based decoded
                audio, and the one obtained with MBD.

            See [github.com/facebookresearch/audiocraft](https://github.com/facebookresearch/audiocraft/blob/main/docs/MUSICGEN.md)
            for more details.
            """
        )

        interface.queue().launch(**launch_kwargs)


def ui_batched(launch_kwargs):
    with gr.Blocks() as demo:
        gr.Markdown(
            """
            # MusicGen

            For Metropolis - from: ["Simple and Controllable Music Generation"](https://huggingface.co/papers/2306.05284).
            <br/>
            <a href="https://huggingface.co/spaces/facebook/MusicGen?duplicate=true"
                style="display: inline-block;margin-top: .5em;margin-right: .25em;" target="_blank">
            <img style="margin-bottom: 0em;display: inline;margin-top: -.25em;"
                src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a>
            for longer sequences, more control and no queue.</p>
            """
        )
        with gr.Row():
            with gr.Column():
                with gr.Row():
                    text = gr.Text(label="Describe your music", lines=2, interactive=True)
                    with gr.Column():
                        radio = gr.Radio(["file", "mic"], value="file",
                                         label="Condition on a melody (optional) File or Microphone")
                        melody = gr.Audio(source="upload", type="numpy", label="File",
                                          interactive=True, elem_id="melody-input")
                with gr.Row():
                    submit = gr.Button("Generate", variant="primary")
            with gr.Column():
                output = gr.Video(label="Generated Music")
                audio_output = gr.Audio(label="Generated Music (wav)", type='filepath')
        submit.click(predict_batched, inputs=[text, melody],
                     outputs=[output, audio_output], batch=True, max_batch_size=MAX_BATCH_SIZE)
        radio.change(toggle_audio_src, radio, [melody], queue=False, show_progress=False)
        gr.Examples(
            fn=predict_batched,
            examples=[
                [
                    "An angry propulsive industrial score with distorted synthesizers and tortured vocals.",
                    None,
                    "facebook/musicgen-stereo-melody",
                    "Default"
                ],
                [
                    "A monstrous industrial bach hybrid",
                    "./assets/bach.mp3",
                    "facebook/musicgen-stereo-melody",
                    "Default"
                ],
            ],
            inputs=[text, melody],
            outputs=[output]
        )
        gr.Markdown("""
        ### More details

        The model will generate 30 seconds of audio.
        The model was trained with description from a stock music catalog, descriptions that will work best
        should include some level of details on the instruments present, along with some intended use case
        (e.g. adding "perfect for a commercial" can somehow help).

        You can optionally provide a reference audio from which a broad melody will be extracted.
        The model will then try to follow both the description and melody provided.
        For best results, the melody should be 30 seconds long (I know, the samples we provide are not...)

        You can access more control (longer generation, more models etc.) by clicking
        the <a href="https://huggingface.co/spaces/facebook/MusicGen?duplicate=true"
                style="display: inline-block;margin-top: .5em;margin-right: .25em;" target="_blank">
            <img style="margin-bottom: 0em;display: inline;margin-top: -.25em;"
                src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a>
        (you will then need a paid GPU from HuggingFace).
        If you have a GPU, you can run the gradio demo locally (click the link to our repo below for more info).
        Finally, you can get a GPU for free from Google
        and run the demo in [a Google Colab.](https://ai.honu.io/red/musicgen-colab).

        See [github.com/facebookresearch/audiocraft](https://github.com/facebookresearch/audiocraft/blob/main/docs/MUSICGEN.md)
        for more details. All samples are generated with the `stereo-melody` model.
        """)

        demo.queue(max_size=8 * 4).launch(**launch_kwargs)


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--listen',
        type=str,
        default='0.0.0.0' if 'SPACE_ID' in os.environ else '127.0.0.1',
        help='IP to listen on for connections to Gradio',
    )
    parser.add_argument(
        '--username', type=str, default='', help='Username for authentication'
    )
    parser.add_argument(
        '--password', type=str, default='', help='Password for authentication'
    )
    parser.add_argument(
        '--server_port',
        type=int,
        default=0,
        help='Port to run the server listener on',
    )
    parser.add_argument(
        '--inbrowser', action='store_true', help='Open in browser'
    )
    parser.add_argument(
        '--share', action='store_true', help='Share the gradio UI'
    )

    args = parser.parse_args()

    launch_kwargs = {}
    launch_kwargs['server_name'] = args.listen

    if args.username and args.password:
        launch_kwargs['auth'] = (args.username, args.password)
    if args.server_port:
        launch_kwargs['server_port'] = args.server_port
    if args.inbrowser:
        launch_kwargs['inbrowser'] = args.inbrowser
    if args.share:
        launch_kwargs['share'] = args.share

    logging.basicConfig(level=logging.INFO, stream=sys.stderr)

    # Show the interface
    if IS_BATCHED:
        global USE_DIFFUSION
        USE_DIFFUSION = False
        ui_batched(launch_kwargs)
    else:
        ui_full(launch_kwargs)