File size: 28,038 Bytes
590092f
8e10a53
5325fcc
6ec60d5
f187760
6ec60d5
e6925a5
1ed8069
81338d0
5325fcc
6ec60d5
f187760
f80309c
5325fcc
5238467
 
c72eb33
1897b6f
5325fcc
 
0b90fab
f80309c
1897b6f
dca097b
 
 
 
 
 
 
 
 
e8ee3b3
 
dca097b
5238467
f80309c
f187760
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dca097b
f187760
 
e8ee3b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f80309c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b90fab
 
efa2898
0b90fab
 
 
 
efa2898
0b90fab
 
efa2898
0b90fab
 
 
 
 
 
 
 
 
 
 
 
 
c72eb33
0b90fab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
efa2898
0b90fab
efa2898
0b90fab
efa2898
0b90fab
efa2898
0b90fab
 
9fa775a
efa2898
 
 
 
 
ebe56d9
efa2898
 
 
 
 
 
 
 
 
 
 
 
0b90fab
 
efa2898
 
 
 
 
 
 
 
 
 
0b90fab
7f6755b
efa2898
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f6755b
efa2898
 
 
 
 
 
 
054d10f
efa2898
 
 
 
 
 
 
 
 
 
 
 
 
0b90fab
 
efa2898
 
 
 
 
 
 
 
 
 
 
 
 
e7e9ea1
 
efa2898
 
 
 
e7e9ea1
efa2898
e7e9ea1
6e65b60
9fa775a
590092f
9fa775a
7f6755b
e7e9ea1
 
 
 
 
 
 
 
7f6755b
e7e9ea1
 
 
 
 
 
59743f4
e7e9ea1
 
 
f80309c
 
 
e7e9ea1
f80309c
e7e9ea1
 
 
 
59743f4
e7e9ea1
 
 
f80309c
 
 
e7e9ea1
f80309c
590092f
054d10f
 
e7e9ea1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
054d10f
e7e9ea1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9fa775a
 
 
dd54b0a
e7e9ea1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9fa775a
e7e9ea1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
590092f
e7e9ea1
 
 
 
 
 
 
 
 
 
 
 
7f6755b
e7e9ea1
 
38c73b8
e7e9ea1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae140bb
e7e9ea1
 
ae140bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e8ee3b3
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
import spaces  # <--- IMPORTANT: Add this import
import argparse
import logging
import os
from pathlib import Path
import subprocess as sp

#sp.run(["pip", "install", "torch==2.6.0", "torchvision==0.21.0", "torchaudio==2.6.0", "--index-url https://download.pytorch.org/whl/cu124"])
sp.run(["bash", "demos/torch.sh"])
import sys
import time
import typing as tp
from tempfile import NamedTemporaryFile, gettempdir
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
import multiprocessing as mp
import warnings

os.putenv("HF_HUB_ENABLE_HF_TRANSFER","1")
os.environ["SAFETENSORS_FAST_GPU"] = "1"

torch.backends.cuda.matmul.allow_tf32 = False
torch.backends.cuda.matmul.allow_bf16_reduced_precision_reduction = False
torch.backends.cuda.matmul.allow_fp16_reduced_precision_reduction = False
torch.backends.cudnn.allow_tf32 = False
torch.backends.cudnn.deterministic = False
torch.backends.cudnn.benchmark = False
torch.backends.cuda.preferred_blas_library="cublas"
torch.backends.cuda.preferred_linalg_library="cusolver"
torch.set_float32_matmul_precision("highest")

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()


# We'll load a model globally to be shared by our new UI tab
# This simplifies things by avoiding the Predictor class for this specific feature.
print("Loading model for segmented generation...")
MODEL = MusicGen.get_pretrained("facebook/musicgen-melody", device='cuda')
print("Model loaded.")

@spaces.GPU(duration=90)
def predict_segment(prompt, seed, current_segment, duration_per_segment):
    """
    This is the core prediction function for our new UI tab.
    It calls the generate_segment method we created earlier.
    """
    print(f"Requesting to generate segment {current_segment} with seed {seed}.")
    # Convert duration to token length for the model
    # Note: The actual frame rate might differ, but this is a close approximation.
    max_segment_len = int(duration_per_segment * 50) 

    # If the seed is -1 or None, it means we should start with a random seed.
    # The generate_segment function handles the logic of creating a new seed for segment 1.
    seed_to_use = None if seed == -1 else int(seed)

    # Call the method we added to the LMModel
    # Note the path: MODEL.lm.generate_segment
    full_codes, updated_seed = MODEL.lm.generate_segment(
        segment=int(current_segment),
        seed=seed_to_use,
        prompt_text=prompt,
        max_segment_len=max_segment_len,
        # You can pass other generation params here if you add them to the UI
        temp=1.0, 
        top_k=250,
        cfg_coef=3.0,
    )

    # Decode the *entire* audio generated so far to a waveform
    audio_wav = MODEL.compression_model.decode(full_codes.to('cuda'))
    audio_wav = audio_wav.detach().cpu()

    # Save the waveform to a temporary file for the Gradio Audio component
    with NamedTemporaryFile("wb", suffix=".wav", delete=False) as file:
        audio_write(
            file.name, audio_wav[0], MODEL.sample_rate, strategy="loudness",
            loudness_headroom_db=16, loudness_compressor=True, add_suffix=False
        )
        file_cleaner.add(file.name)

    # We must return values for all the outputs of the button's .click() event:
    # 1. The audio file path for the gr.Audio component.
    # 2. The updated seed for the gr.Number component.
    # 3. The next segment number (current + 1) for the gr.Number state.
    # 4. A new label for the button to guide the user.
    return file.name, updated_seed, current_segment + 1, gr.update(value=f"Generate Segment {current_segment + 1}")


def reset_segmented_ui():
    """Resets the UI state for starting a new song."""
    return None, -1, 1, gr.update(value="Generate Segment 1")


def ui_segmented():
    """Builds the Gradio UI for the new 'Long / Segmented Generation' tab."""
    with gr.Blocks() as interface:
        gr.Markdown("## Long / Segmented Generation\nGenerate music longer than the time limit by creating it in segments. The state is saved to a file after each segment.")
        
        with gr.Row():
            prompt = gr.Text(label="Prompt", placeholder="e.g., An epic cinematic orchestral score")
            # The Seed field is critical for linking segments. We use -1 to signify a random start.
            seed = gr.Number(value=-1, label="Seed (-1 for random start)")
        
        duration = gr.Slider(label="Duration PER Segment (seconds)", minimum=10, maximum=90, value=30, step=5)
        
        # This hidden Number component will keep track of which segment we're on
        current_segment = gr.Number(value=1, visible=False)
        
        with gr.Row():
            run_button = gr.Button("Generate Segment 1")
            reset_button = gr.Button("Reset & Start New Song")
        
        audio_output = gr.Audio(label="Full Generated Music So Far", type='filepath')

        # --- Wire up the buttons ---
        run_button.click(
            fn=predict_segment,
            inputs=[prompt, seed, current_segment, duration],
            # The outputs update the audio player, the seed box, the hidden segment counter, and the button label
            outputs=[audio_output, seed, current_segment, run_button]
        )

        reset_button.click(
            fn=reset_segmented_ui,
            inputs=[],
            outputs=[audio_output, seed, current_segment, run_button]
        )
    return interface

    
def convert_wav_to_mp4(wav_path, output_path=None):
    """Converts a WAV file to a waveform MP4 video using ffmpeg."""
    if output_path is None:
        # Create output path in the same directory as the input
        output_path = Path(wav_path).with_suffix(".mp4")
    try:
        command = [
            "ffmpeg",
            "-y",  # Overwrite output file if it exists
            "-i", str(wav_path),
            "-filter_complex",
            "[0:a]showwaves=s=1280x202:mode=line,format=yuv420p[v]",  # Waveform filter
            "-map", "[v]",
            "-map", "0:a",
            "-c:v", "libx264",  # Video codec
            "-c:a", "aac",       # Audio codec
            "-preset", "fast", # Important, don't do veryslow.
            str(output_path),
        ]
        process = sp.run(command, capture_output=True, text=True, check=True)
        return str(output_path)
    except sp.CalledProcessError as e:
        print(f"Error in ffmpeg conversion: {e}")
        print(f"ffmpeg stdout: {e.stdout}")
        print(f"ffmpeg stderr: {e.stderr}")
        raise  # Re-raise the exception to be caught by Gradio

def model_worker(model_name: str, task_queue: mp.Queue, result_queue: mp.Queue):
    """
    Persistent worker process (used when NOT running as a daemon).
    """
    try:
        device = 'cuda' if torch.cuda.is_available() else 'cpu'
        model = MusicGen.get_pretrained(model_name, device=device)
        mbd = MultiBandDiffusion.get_mbd_musicgen(device=device)
        while True:
            task = task_queue.get()
            if task is None:
                break
            task_id, text, melody, duration, use_diffusion, gen_params = task
            try:
                model.set_generation_params(duration=duration, **gen_params)
                target_sr = model.sample_rate
                target_ac = 1
                processed_melody = None
                if melody:
                    sr, melody_data = melody
                    melody_tensor = torch.from_numpy(melody_data).to(device).float().t()
                    if melody_tensor.ndim == 1:
                        melody_tensor = melody_tensor.unsqueeze(0)
                    melody_tensor = melody_tensor[..., :int(sr * duration)]
                    #processed_melody = convert_audio(melody_tensor, sr, target_sr, target_ac)
                if processed_melody is not None:
                    output, tokens = model.generate_with_chroma(
                        descriptions=[text],
                        melody_wavs=[processed_melody],
                        melody_sample_rate=target_sr,
                        progress=True,
                        return_tokens=True
                    )
                else:
                    output, tokens = model.generate([text], progress=True, return_tokens=True)
                output = output.detach().cpu()
                if use_diffusion:
                    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_diffusion = outputs_diffusion.detach().cpu()
                    result_queue.put((task_id, (output, outputs_diffusion)))
                else:
                    result_queue.put((task_id, (output, None)))
            except Exception as e:
                result_queue.put((task_id, e))
    except Exception as e:
        result_queue.put((-1, e))

class Predictor:
    def __init__(self, model_name: str, depth: str):
        self.model_name = model_name
        self.is_daemon = mp.current_process().daemon
        if self.is_daemon:
            # Running in a daemonic process (e.g., on Spaces)
            self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
            self.model = MusicGen.get_pretrained(self.model_name, device=self.device, depth=depth)
            self.mbd = MultiBandDiffusion.get_mbd_musicgen(device=self.device)  # Load MBD here too
            self.current_task_id = 0 # Initialize task ID
        else:
            # Running in a non-daemonic process (e.g., locally)
            self.task_queue = mp.Queue()
            self.result_queue = mp.Queue()
            self.process = mp.Process(
                target=model_worker, args=(self.model_name, self.task_queue, self.result_queue)
            )
            self.process.start()
            self.current_task_id = 0
            self._check_initialization()

    def _check_initialization(self):
        """Check if the worker process initialized successfully (only in non-daemon mode)."""
        if not self.is_daemon:
            time.sleep(2)
            try:
                task_id, result = self.result_queue.get(timeout=3)
                if isinstance(result, Exception):
                    if task_id == -1:
                        raise RuntimeError("Model loading failed in worker process.") from result
            except:
                pass

    def predict(self, text, melody, duration, use_diffusion, **gen_params):
        """Submits a prediction task."""
        if self.is_daemon:
             # Directly perform the prediction (single-process mode)
            self.current_task_id +=1
            task_id = self.current_task_id
            try:
                self.model.set_generation_params(duration=duration, **gen_params)
                target_sr = self.model.sample_rate
                target_ac = 1
                processed_melody = None
                if melody:
                    sr, melody_data = melody
                    melody_tensor = torch.from_numpy(melody_data).to(self.device).float().t()
                    if melody_tensor.ndim == 1:
                        melody_tensor = melody_tensor.unsqueeze(0)
                    melody_tensor = melody_tensor[..., :int(sr * duration)]
                    processed_melody = convert_audio(melody_tensor, sr, target_sr, target_ac)
                if processed_melody is not None:
                    output, tokens = self.model.generate_with_chroma(
                        descriptions=[text],
                        melody_wavs=[processed_melody],
                        melody_sample_rate=target_sr,
                        progress=True,
                        return_tokens=True
                    )
                else:
                    output, tokens = self.model.generate([text], progress=True, return_tokens=True)
                output = output.detach().cpu()
                if use_diffusion:
                    if isinstance(self.model.compression_model, InterleaveStereoCompressionModel):
                        left, right = self.model.compression_model.get_left_right_codes(tokens)
                        tokens = torch.cat([left, right])
                    outputs_diffusion = self.mbd.tokens_to_wav(tokens)
                    if isinstance(self.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_diffusion = outputs_diffusion.detach().cpu()
                    return task_id, (output, outputs_diffusion) #Return the task id.
                else:
                  return task_id, (output, None)
            except Exception as e:
                return task_id, e
        else:
            # Use the multiprocessing queue (multi-process mode)
            self.current_task_id += 1
            task = (self.current_task_id, text, melody, duration, use_diffusion, gen_params)
            self.task_queue.put(task)
            return self.current_task_id

    def get_result(self, task_id):
        """Retrieves the result of a prediction task."""
        if self.is_daemon:
            # Results are returned directly by 'predict' in daemon mode
            result_id, result = task_id, task_id #predictor return (task_id, results)
        else:
            # Get result from the queue (multi-process mode)
            while True:
                result_task_id, result = self.result_queue.get()
                if result_task_id == task_id:
                    break  # Found the correct result
        if isinstance(result, Exception):
            raise result
        return result

    def shutdown(self):
        """Shuts down the worker process (if running)."""
        if not self.is_daemon and self.process.is_alive():
            self.task_queue.put(None)
            self.process.join()

_default_model_name = "facebook/musicgen-melody"

@spaces.GPU(duration=90)  # Use the decorator for Spaces
def predict_full(model, model_path, depth, use_mbd, text, melody, duration, topk, topp, temperature, cfg_coef):
    # Initialize Predictor *INSIDE* the function
    predictor = Predictor(model, depth)
    task_id, (wav, diffusion_wav) = predictor.predict( # Unpack directly!
        text=text,
        melody=melody,
        duration=duration,
        use_diffusion=use_mbd,
        top_k=topk,
        top_p=topp,
        temperature=temperature,
        cfg_coef=cfg_coef,
    )
    # Save and return audio files
    wav_paths = []
    video_paths = []
    # Save standard output
    with NamedTemporaryFile("wb", suffix=".wav", delete=False) as file:
        audio_write(
            file.name, wav[0], 44100, strategy="loudness", #hardcoded sample rate
            loudness_headroom_db=16, loudness_compressor=True, add_suffix=False
        )
        wav_paths.append(file.name)
        # Make and clean up video:
        video_path = convert_wav_to_mp4(file.name)
        video_paths.append(video_path)
        file_cleaner.add(file.name)
        file_cleaner.add(video_path)
    # Save MBD output if used
    if diffusion_wav is not None:
        with NamedTemporaryFile("wb", suffix=".wav", delete=False) as file:
            audio_write(
                file.name, diffusion_wav[0], 44100, strategy="loudness", #hardcoded sample rate
                loudness_headroom_db=16, loudness_compressor=True, add_suffix=False
            )
            wav_paths.append(file.name)
            # Make and clean up video:
            video_path = convert_wav_to_mp4(file.name)
            video_paths.append(video_path)
            file_cleaner.add(file.name)
            file_cleaner.add(video_path)
    # Shutdown predictor to prevent hanging processes!
    if not predictor.is_daemon: # Important!
        predictor.shutdown()
    if use_mbd:
         return video_paths[0], wav_paths[0], video_paths[1], wav_paths[1]
    return video_paths[0], wav_paths[0], None, None

def toggle_audio_src(choice):
    if choice == "mic":
        return gr.update(sources="microphone", value=None, label="Microphone")
    else:
        return gr.update(sources="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 ui_full(launch_kwargs):
    with gr.Blocks() as interface:
        gr.Markdown(
            """
            # MusicGen
            This is your private demo for [MusicGen](https://github.com/facebookresearch/audiocraft),
            a simple and controllable model for music generation
            presented at: ["Simple and Controllable Music Generation"](https://huggingface.co/papers/2306.05284)
            """
        )
        with gr.Row():
            with gr.Column():
                with gr.Row():
                    text = gr.Text(label="Input Text", interactive=True)
                    with gr.Column():
                        radio = gr.Radio(["file", "mic"], value="file",
                                         label="Condition on a melody (optional) File or Mic")
                        melody = gr.Audio(sources="upload", type="numpy", label="File",
                                          interactive=True, elem_id="melody-input")
                with gr.Row():
                    submit = gr.Button("Submit")
                    # _ = gr.Button("Interrupt").click(fn=interrupt, queue=False)  # Interrupt is now handled implicitly
                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-melody", interactive=True)
                    model_path = gr.Text(label="Model Path (custom models)", interactive=False, visible=False)  # Keep, but hide
                    depth = gr.Radio(["float32", "bfloat16", "float16"],
                                     label="Model Precision", value="float32", interactive=True)
                    with gr.Row():
                        decoder = gr.Radio(["Default", "MultiBand_Diffusion"],
                                       label="Decoder", value="Default", interactive=True)
                with gr.Row():
                    duration = gr.Slider(minimum=1, maximum=120, value=10, label="Duration", interactive=True)
                with gr.Row():
                    topk = gr.Number(label="Top-k", value=250, interactive=True)
                    topp = gr.Number(label="Top-p", value=0, interactive=True)
                    temperature = gr.Number(label="Temperature", value=1.0, interactive=True)
                    cfg_coef = gr.Number(label="Classifier Free Guidance", value=3.0, interactive=True)
            with gr.Column():
                output = gr.Video(label="Generated Music")
                audio_output = gr.Audio(label="Generated Music (wav)", type='filepath')
                diffusion_output = gr.Video(label="MultiBand Diffusion Decoder", visible=False)
                audio_diffusion = gr.Audio(label="MultiBand Diffusion Decoder (wav)", type='filepath', visible=False)

        submit.click(
            toggle_diffusion, decoder, [diffusion_output, audio_diffusion], queue=False
        ).then(
            predict_full,
            inputs=[model, model_path, depth, decoder, text, melody, duration, topk, topp, temperature, cfg_coef],
            outputs=[output, audio_output, diffusion_output, audio_diffusion]
        )
        radio.change(toggle_audio_src, radio, [melody], queue=False, show_progress=False)

        gr.Examples(
            fn=predict_full,
            examples=[
                [
                    "An 80s driving pop song with heavy drums and synth pads in the background",
                    "./assets/bach.mp3",
                    "facebook/musicgen-melody",
                    "Default"
                ],
                [
                    "A cheerful country song with acoustic guitars",
                    "./assets/bolero_ravel.mp3",
                    "facebook/musicgen-melody",
                    "Default"
                ],
                [
                    "90s rock song with electric guitar and heavy drums",
                    None,
                    "facebook/musicgen-medium",
                    "Default"
                ],
                [
                    "a light and cheerly EDM track, with syncopated drums, aery pads, and strong emotions",
                    "./assets/bach.mp3",
                    "facebook/musicgen-melody",
                    "Default"
                ],
                 [
                    "lofi slow bpm electro chill with organic samples",
                    None,
                    "facebook/musicgen-medium",
                    "Default"
                ],
                [
                    "Punk rock with loud drum and power guitar",
                    None,
                    "facebook/musicgen-medium",
                    "MultiBand_Diffusion"
                ],
            ],
            inputs=[text, melody, model, decoder],
            outputs=[output]
        )
        gr.Markdown(
            """
            ### More details

            The model will generate a short music extract based on the description you provided.
            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 text and melody.
            6. facebook/musicgen-stereo-small -- a 300M transformer decoder conditioned on text only, fine tuned for stereo output.
            7. facebook/musicgen-stereo-medium -- a 1.5B transformer decoder conditioned on text only, fine tuned for stereo output.
            8. facebook/musicgen-stereo-melody -- a 1.5B transformer decoder conditioned on text and melody, fine tuned for stereo output.
            9. facebook/musicgen-stereo-large -- a 3.3B transformer decoder conditioned on text only, fine tuned for stereo output.
           10. facebook/musicgen-stereo-melody-large -- a 3.3B transformer decoder conditioned on text and melody, fine tuned for stereo output.

            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)

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)

    # Build the two interfaces
    original_interface = ui_full({})
    segmented_interface = ui_segmented()

    # Combine them in a tabbed layout
    tabbed_interface = gr.TabbedInterface(
        [original_interface, segmented_interface],
        ["Single Generation", "Long / Segmented Generation"]
    )

    # Launch the final combined app
    tabbed_interface.queue().launch(**launch_kwargs)