radames commited on
Commit
17e0c31
1 Parent(s): 3ae65e0

share button

Browse files
Files changed (4) hide show
  1. README.md +1 -1
  2. app.py +95 -153
  3. app_batched.py +76 -15
  4. share_btn.py +119 -0
README.md CHANGED
@@ -1,5 +1,5 @@
1
  ---
2
- title: MusicGen
3
  python_version: '3.9'
4
  tags:
5
  - music generation
 
1
  ---
2
+ title: MusicGen Continuation
3
  python_version: '3.9'
4
  tags:
5
  - music generation
app.py CHANGED
@@ -7,15 +7,14 @@ LICENSE file in the root directory of this source tree.
7
  """
8
 
9
  from tempfile import NamedTemporaryFile
10
- import argparse
11
  import torch
12
  import gradio as gr
13
- import os
14
  from audiocraft.models import MusicGen
 
15
  from audiocraft.data.audio import audio_write
16
 
 
17
  MODEL = None
18
- IS_SHARED_SPACE = "musicgen/MusicGen" in os.environ['SPACE_ID']
19
 
20
 
21
  def load_model(version):
@@ -57,160 +56,103 @@ def predict(model, text, melody, duration, topk, topp, temperature, cfg_coef):
57
 
58
  output = output.detach().cpu().float()[0]
59
  with NamedTemporaryFile("wb", suffix=".wav", delete=False) as file:
60
- audio_write(
61
- file.name, output, MODEL.sample_rate, strategy="loudness",
62
- loudness_headroom_db=16, loudness_compressor=True, add_suffix=False)
63
  waveform_video = gr.make_waveform(file.name)
64
  return waveform_video
65
 
66
-
67
- def ui(**kwargs):
68
- with gr.Blocks() as interface:
69
- gr.Markdown(
70
- """
71
- # MusicGen
72
- This is your private demo for [MusicGen](https://github.com/facebookresearch/audiocraft), a simple and controllable model for music generation
73
- presented at: ["Simple and Controllable Music Generation"](https://huggingface.co/papers/2306.05284)
74
- """
75
- )
76
- if IS_SHARED_SPACE:
77
- gr.Markdown("""
78
- This Space doesn't work in this shared UI ⚠
79
-
80
- <a href="https://huggingface.co/spaces/musicgen/MusicGen?duplicate=true" style="display: inline-block;margin-top: .5em;margin-right: .25em;" target="_blank">
81
- <img style="margin-bottom: 0em;display: inline;margin-top: -.25em;" src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a>
82
- to use it privately, or use the <a href="https://huggingface.co/spaces/facebook/MusicGen">public demo</a>
83
- """)
84
- with gr.Row():
85
- with gr.Column():
86
- with gr.Row():
87
- text = gr.Text(label="Input Text", interactive=True)
88
- melody = gr.Audio(source="upload", type="numpy", label="Melody Condition (optional)", interactive=True)
89
- with gr.Row():
90
- submit = gr.Button("Submit")
91
- with gr.Row():
92
- model = gr.Radio(["melody", "medium", "small", "large"], label="Model", value="melody", interactive=True)
93
- with gr.Row():
94
- duration = gr.Slider(minimum=1, maximum=30, value=10, label="Duration", interactive=True)
95
- with gr.Row():
96
- topk = gr.Number(label="Top-k", value=250, interactive=True)
97
- topp = gr.Number(label="Top-p", value=0, interactive=True)
98
- temperature = gr.Number(label="Temperature", value=1.0, interactive=True)
99
- cfg_coef = gr.Number(label="Classifier Free Guidance", value=3.0, interactive=True)
100
- with gr.Column():
101
- output = gr.Video(label="Generated Music")
102
- submit.click(predict, inputs=[model, text, melody, duration, topk, topp, temperature, cfg_coef], outputs=[output])
103
- gr.Examples(
104
- fn=predict,
105
- examples=[
106
- [
107
- "An 80s driving pop song with heavy drums and synth pads in the background",
108
- "./assets/bach.mp3",
109
- "melody"
110
- ],
111
- [
112
- "A cheerful country song with acoustic guitars",
113
- "./assets/bolero_ravel.mp3",
114
- "melody"
115
- ],
116
- [
117
- "90s rock song with electric guitar and heavy drums",
118
- None,
119
- "medium"
120
- ],
121
- [
122
- "a light and cheerly EDM track, with syncopated drums, aery pads, and strong emotions",
123
- "./assets/bach.mp3",
124
- "melody"
125
- ],
126
- [
127
- "lofi slow bpm electro chill with organic samples",
128
- None,
129
- "medium",
130
- ],
131
- ],
132
- inputs=[text, melody, model],
133
- outputs=[output]
134
- )
135
- gr.Markdown(
136
- """
137
- ### More details
138
-
139
- The model will generate a short music extract based on the description you provided.
140
- You can generate up to 30 seconds of audio.
141
-
142
- We present 4 model variations:
143
- 1. Melody -- a music generation model capable of generating music condition on text and melody inputs. **Note**, you can also use text only.
144
- 2. Small -- a 300M transformer decoder conditioned on text only.
145
- 3. Medium -- a 1.5B transformer decoder conditioned on text only.
146
- 4. Large -- a 3.3B transformer decoder conditioned on text only (might OOM for the longest sequences.)
147
-
148
- When using `melody`, ou can optionaly provide a reference audio from
149
- which a broad melody will be extracted. The model will then try to follow both the description and melody provided.
150
-
151
- You can also use your own GPU or a Google Colab by following the instructions on our repo.
152
- See [github.com/facebookresearch/audiocraft](https://github.com/facebookresearch/audiocraft)
153
- for more details.
154
- """
155
- )
156
-
157
- # Show the interface
158
- launch_kwargs = {}
159
- username = kwargs.get('username')
160
- password = kwargs.get('password')
161
- server_port = kwargs.get('server_port', 0)
162
- inbrowser = kwargs.get('inbrowser', False)
163
- share = kwargs.get('share', False)
164
- server_name = kwargs.get('listen')
165
-
166
- launch_kwargs['server_name'] = server_name
167
-
168
- if username and password:
169
- launch_kwargs['auth'] = (username, password)
170
- if server_port > 0:
171
- launch_kwargs['server_port'] = server_port
172
- if inbrowser:
173
- launch_kwargs['inbrowser'] = inbrowser
174
- if share:
175
- launch_kwargs['share'] = share
176
-
177
- interface.queue().launch(**launch_kwargs, max_threads=1)
178
-
179
-
180
- if __name__ == "__main__":
181
- parser = argparse.ArgumentParser()
182
- parser.add_argument(
183
- '--listen',
184
- type=str,
185
- default='127.0.0.1',
186
- help='IP to listen on for connections to Gradio',
187
- )
188
- parser.add_argument(
189
- '--username', type=str, default='', help='Username for authentication'
190
- )
191
- parser.add_argument(
192
- '--password', type=str, default='', help='Password for authentication'
193
- )
194
- parser.add_argument(
195
- '--server_port',
196
- type=int,
197
- default=0,
198
- help='Port to run the server listener on',
199
  )
200
- parser.add_argument(
201
- '--inbrowser', action='store_true', help='Open in browser'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202
  )
203
- parser.add_argument(
204
- '--share', action='store_true', help='Share the gradio UI'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
205
  )
206
 
207
- args = parser.parse_args()
208
-
209
- ui(
210
- username=args.username,
211
- password=args.password,
212
- inbrowser=args.inbrowser,
213
- server_port=args.server_port,
214
- share=args.share,
215
- listen=args.listen
216
- )
 
7
  """
8
 
9
  from tempfile import NamedTemporaryFile
 
10
  import torch
11
  import gradio as gr
 
12
  from audiocraft.models import MusicGen
13
+
14
  from audiocraft.data.audio import audio_write
15
 
16
+
17
  MODEL = None
 
18
 
19
 
20
  def load_model(version):
 
56
 
57
  output = output.detach().cpu().float()[0]
58
  with NamedTemporaryFile("wb", suffix=".wav", delete=False) as file:
59
+ audio_write(file.name, output, MODEL.sample_rate, strategy="loudness", add_suffix=False)
 
 
60
  waveform_video = gr.make_waveform(file.name)
61
  return waveform_video
62
 
63
+ def toggle(choice):
64
+ if choice == "mic":
65
+ return gr.update(source="microphone", value=None, label="Microphone")
66
+ else:
67
+ return gr.update(source="upload", value=None, label="File")
68
+
69
+ with gr.Blocks() as demo:
70
+ gr.Markdown(
71
+ """
72
+ # MusicGen
73
+
74
+ This is the demo for [MusicGen](https://github.com/facebookresearch/audiocraft), a simple and controllable model for music generation
75
+ presented at: ["Simple and Controllable Music Generation"](https://huggingface.co/papers/2306.05284).
76
+ <br/>
77
+ <a href="https://huggingface.co/spaces/musicgen/MusicGen?duplicate=true" style="display: inline-block;margin-top: .5em;margin-right: .25em;" target="_blank">
78
+ <img style="margin-bottom: 0em;display: inline;margin-top: -.25em;" src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a>
79
+ for longer sequences, more control and no queue.</p>
80
+ """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
  )
82
+ with gr.Row():
83
+ with gr.Column():
84
+ with gr.Row():
85
+ text = gr.Text(label="Input Text", interactive=True)
86
+ with gr.Column():
87
+ radio = gr.Radio(["file", "mic"], value="file", label="Melody Condition (optional) File or Mic")
88
+ melody = gr.Audio(source="upload", type="numpy", label="File", interactive=True)
89
+ with gr.Row():
90
+ submit = gr.Button("Submit")
91
+ with gr.Row():
92
+ model = gr.Radio(["melody", "medium", "small", "large"], label="Model", value="melody", interactive=True)
93
+ with gr.Row():
94
+ duration = gr.Slider(minimum=1, maximum=30, value=10, label="Duration", interactive=True)
95
+ with gr.Row():
96
+ topk = gr.Number(label="Top-k", value=250, interactive=True)
97
+ topp = gr.Number(label="Top-p", value=0, interactive=True)
98
+ temperature = gr.Number(label="Temperature", value=1.0, interactive=True)
99
+ cfg_coef = gr.Number(label="Classifier Free Guidance", value=3.0, interactive=True)
100
+ with gr.Column():
101
+ output = gr.Video(label="Generated Music")
102
+ submit.click(predict, inputs=[model, text, melody, duration, topk, topp, temperature, cfg_coef], outputs=[output])
103
+ radio.change(toggle, radio, [melody], queue=False, show_progress=False)
104
+ gr.Examples(
105
+ fn=predict,
106
+ examples=[
107
+ [
108
+ "An 80s driving pop song with heavy drums and synth pads in the background",
109
+ "./assets/bach.mp3",
110
+ "melody"
111
+ ],
112
+ [
113
+ "A cheerful country song with acoustic guitars",
114
+ "./assets/bolero_ravel.mp3",
115
+ "melody"
116
+ ],
117
+ [
118
+ "90s rock song with electric guitar and heavy drums",
119
+ None,
120
+ "medium"
121
+ ],
122
+ [
123
+ "a light and cheerly EDM track, with syncopated drums, aery pads, and strong emotions",
124
+ "./assets/bach.mp3",
125
+ "melody"
126
+ ],
127
+ [
128
+ "lofi slow bpm electro chill with organic samples",
129
+ None,
130
+ "medium",
131
+ ],
132
+ ],
133
+ inputs=[text, melody, model],
134
+ outputs=[output]
135
  )
136
+ gr.Markdown(
137
+ """
138
+ ### More details
139
+
140
+ The model will generate a short music extract based on the description you provided.
141
+ You can generate up to 30 seconds of audio.
142
+
143
+ We present 4 model variations:
144
+ 1. Melody -- a music generation model capable of generating music condition on text and melody inputs. **Note**, you can also use text only.
145
+ 2. Small -- a 300M transformer decoder conditioned on text only.
146
+ 3. Medium -- a 1.5B transformer decoder conditioned on text only.
147
+ 4. Large -- a 3.3B transformer decoder conditioned on text only (might OOM for the longest sequences.)
148
+
149
+ When using `melody`, ou can optionaly provide a reference audio from
150
+ which a broad melody will be extracted. The model will then try to follow both the description and melody provided.
151
+
152
+ You can also use your own GPU or a Google Colab by following the instructions on our repo.
153
+ See [github.com/facebookresearch/audiocraft](https://github.com/facebookresearch/audiocraft)
154
+ for more details.
155
+ """
156
  )
157
 
158
+ demo.launch()
 
 
 
 
 
 
 
 
 
app_batched.py CHANGED
@@ -9,6 +9,8 @@ LICENSE file in the root directory of this source tree.
9
  from tempfile import NamedTemporaryFile
10
  import torch
11
  import gradio as gr
 
 
12
  from audiocraft.data.audio_utils import convert_audio
13
  from audiocraft.data.audio import audio_write
14
  from audiocraft.models import MusicGen
@@ -39,10 +41,13 @@ def predict(texts, melodies):
39
  if melody is None:
40
  processed_melodies.append(None)
41
  else:
42
- sr, melody = melody[0], torch.from_numpy(melody[1]).to(MODEL.device).float().t()
 
 
 
43
  if melody.dim() == 1:
44
  melody = melody[None]
45
- melody = melody[..., :int(sr * duration)]
46
  melody = convert_audio(melody, sr, target_sr, target_ac)
47
  processed_melodies.append(melody)
48
 
@@ -50,7 +55,7 @@ def predict(texts, melodies):
50
  descriptions=texts,
51
  melody_wavs=processed_melodies,
52
  melody_sample_rate=target_sr,
53
- progress=False
54
  )
55
 
56
  outputs = outputs.detach().cpu().float()
@@ -58,14 +63,25 @@ def predict(texts, melodies):
58
  for output in outputs:
59
  with NamedTemporaryFile("wb", suffix=".wav", delete=False) as file:
60
  audio_write(
61
- file.name, output, MODEL.sample_rate, strategy="loudness",
62
- loudness_headroom_db=16, loudness_compressor=True, add_suffix=False)
 
 
 
 
63
  waveform_video = gr.make_waveform(file.name)
64
  out_files.append(waveform_video)
65
- return [out_files]
 
66
 
 
 
 
 
 
67
 
68
- with gr.Blocks() as demo:
 
69
  gr.Markdown(
70
  """
71
  # MusicGen
@@ -81,13 +97,56 @@ with gr.Blocks() as demo:
81
  with gr.Row():
82
  with gr.Column():
83
  with gr.Row():
84
- text = gr.Text(label="Describe your music", lines=2, interactive=True)
85
- melody = gr.Audio(source="upload", type="numpy", label="Condition on a melody (optional)", interactive=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  with gr.Row():
87
  submit = gr.Button("Generate")
88
  with gr.Column():
89
- output = gr.Video(label="Generated Music")
90
- submit.click(predict, inputs=[text, melody], outputs=[output], batch=True, max_batch_size=12)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
  gr.Examples(
92
  fn=predict,
93
  examples=[
@@ -113,9 +172,10 @@ with gr.Blocks() as demo:
113
  ],
114
  ],
115
  inputs=[text, melody],
116
- outputs=[output]
117
  )
118
- gr.Markdown("""
 
119
  ### More details
120
 
121
  The model will generate 12 seconds of audio based on the description you provided.
@@ -127,6 +187,7 @@ with gr.Blocks() as demo:
127
 
128
  See [github.com/facebookresearch/audiocraft](https://github.com/facebookresearch/audiocraft)
129
  for more details.
130
- """)
 
131
 
132
- demo.queue(max_size=60).launch()
 
9
  from tempfile import NamedTemporaryFile
10
  import torch
11
  import gradio as gr
12
+ from share_btn import community_icon_html, loading_icon_html, share_js, css
13
+
14
  from audiocraft.data.audio_utils import convert_audio
15
  from audiocraft.data.audio import audio_write
16
  from audiocraft.models import MusicGen
 
41
  if melody is None:
42
  processed_melodies.append(None)
43
  else:
44
+ sr, melody = (
45
+ melody[0],
46
+ torch.from_numpy(melody[1]).to(MODEL.device).float().t(),
47
+ )
48
  if melody.dim() == 1:
49
  melody = melody[None]
50
+ melody = melody[..., : int(sr * duration)]
51
  melody = convert_audio(melody, sr, target_sr, target_ac)
52
  processed_melodies.append(melody)
53
 
 
55
  descriptions=texts,
56
  melody_wavs=processed_melodies,
57
  melody_sample_rate=target_sr,
58
+ progress=False,
59
  )
60
 
61
  outputs = outputs.detach().cpu().float()
 
63
  for output in outputs:
64
  with NamedTemporaryFile("wb", suffix=".wav", delete=False) as file:
65
  audio_write(
66
+ file.name,
67
+ output,
68
+ MODEL.sample_rate,
69
+ strategy="loudness",
70
+ add_suffix=False,
71
+ )
72
  waveform_video = gr.make_waveform(file.name)
73
  out_files.append(waveform_video)
74
+ return [out_files, melodies]
75
+
76
 
77
+ def toggle(choice):
78
+ if choice == "mic":
79
+ return gr.update(source="microphone", value=None, label="Microphone")
80
+ else:
81
+ return gr.update(source="upload", value=None, label="File")
82
 
83
+
84
+ with gr.Blocks(css=css) as demo:
85
  gr.Markdown(
86
  """
87
  # MusicGen
 
97
  with gr.Row():
98
  with gr.Column():
99
  with gr.Row():
100
+ text = gr.Text(
101
+ label="Describe your music",
102
+ lines=2,
103
+ interactive=True,
104
+ elem_id="text-input",
105
+ )
106
+ with gr.Column():
107
+ radio = gr.Radio(
108
+ ["file", "mic"],
109
+ value="file",
110
+ label="Melody Condition (optional) File or Mic",
111
+ )
112
+ melody = gr.Audio(
113
+ source="upload",
114
+ type="numpy",
115
+ label="File",
116
+ interactive=True,
117
+ elem_id="melody-input",
118
+ )
119
  with gr.Row():
120
  submit = gr.Button("Generate")
121
  with gr.Column():
122
+ output = gr.Video(label="Generated Music", elem_id="generated-video")
123
+ output_melody = gr.Audio(label="Melody ", elem_id="melody-output")
124
+ with gr.Row(visible=False) as share_row:
125
+ with gr.Group(elem_id="share-btn-container"):
126
+ community_icon = gr.HTML(community_icon_html)
127
+ loading_icon = gr.HTML(loading_icon_html)
128
+ share_button = gr.Button("Share to community", elem_id="share-btn")
129
+ share_button.click(None, [], [], _js=share_js)
130
+ submit.click(
131
+ lambda x: gr.update(visible=False),
132
+ None,
133
+ [share_row],
134
+ queue=False,
135
+ show_progress=False,
136
+ ).then(
137
+ predict,
138
+ inputs=[text, melody],
139
+ outputs=[output, output_melody],
140
+ batch=True,
141
+ max_batch_size=12,
142
+ ).then(
143
+ lambda x: gr.update(visible=True),
144
+ None,
145
+ [share_row],
146
+ queue=False,
147
+ show_progress=False,
148
+ )
149
+ radio.change(toggle, radio, [melody], queue=False, show_progress=False)
150
  gr.Examples(
151
  fn=predict,
152
  examples=[
 
172
  ],
173
  ],
174
  inputs=[text, melody],
175
+ outputs=[output],
176
  )
177
+ gr.Markdown(
178
+ """
179
  ### More details
180
 
181
  The model will generate 12 seconds of audio based on the description you provided.
 
187
 
188
  See [github.com/facebookresearch/audiocraft](https://github.com/facebookresearch/audiocraft)
189
  for more details.
190
+ """
191
+ )
192
 
193
+ demo.queue(max_size=15).launch()
share_btn.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ community_icon_html = """<svg id="share-btn-share-icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32">
2
+ <path d="M20.6081 3C21.7684 3 22.8053 3.49196 23.5284 4.38415C23.9756 4.93678 24.4428 5.82749 24.4808 7.16133C24.9674 7.01707 25.4353 6.93643 25.8725 6.93643C26.9833 6.93643 27.9865 7.37587 28.696 8.17411C29.6075 9.19872 30.0124 10.4579 29.8361 11.7177C29.7523 12.3177 29.5581 12.8555 29.2678 13.3534C29.8798 13.8646 30.3306 14.5763 30.5485 15.4322C30.719 16.1032 30.8939 17.5006 29.9808 18.9403C30.0389 19.0342 30.0934 19.1319 30.1442 19.2318C30.6932 20.3074 30.7283 21.5229 30.2439 22.6548C29.5093 24.3704 27.6841 25.7219 24.1397 27.1727C21.9347 28.0753 19.9174 28.6523 19.8994 28.6575C16.9842 29.4379 14.3477 29.8345 12.0653 29.8345C7.87017 29.8345 4.8668 28.508 3.13831 25.8921C0.356375 21.6797 0.754104 17.8269 4.35369 14.1131C6.34591 12.058 7.67023 9.02782 7.94613 8.36275C8.50224 6.39343 9.97271 4.20438 12.4172 4.20438H12.4179C12.6236 4.20438 12.8314 4.2214 13.0364 4.25468C14.107 4.42854 15.0428 5.06476 15.7115 6.02205C16.4331 5.09583 17.134 4.359 17.7682 3.94323C18.7242 3.31737 19.6794 3 20.6081 3ZM20.6081 5.95917C20.2427 5.95917 19.7963 6.1197 19.3039 6.44225C17.7754 7.44319 14.8258 12.6772 13.7458 14.7131C13.3839 15.3952 12.7655 15.6837 12.2086 15.6837C11.1036 15.6837 10.2408 14.5497 12.1076 13.1085C14.9146 10.9402 13.9299 7.39584 12.5898 7.1776C12.5311 7.16799 12.4731 7.16355 12.4172 7.16355C11.1989 7.16355 10.6615 9.33114 10.6615 9.33114C10.6615 9.33114 9.0863 13.4148 6.38031 16.206C3.67434 18.998 3.5346 21.2388 5.50675 24.2246C6.85185 26.2606 9.42666 26.8753 12.0653 26.8753C14.8021 26.8753 17.6077 26.2139 19.1799 25.793C19.2574 25.7723 28.8193 22.984 27.6081 20.6107C27.4046 20.212 27.0693 20.0522 26.6471 20.0522C24.9416 20.0522 21.8393 22.6726 20.5057 22.6726C20.2076 22.6726 19.9976 22.5416 19.9116 22.222C19.3433 20.1173 28.552 19.2325 27.7758 16.1839C27.639 15.6445 27.2677 15.4256 26.746 15.4263C24.4923 15.4263 19.4358 19.5181 18.3759 19.5181C18.2949 19.5181 18.2368 19.4937 18.2053 19.4419C17.6743 18.557 17.9653 17.9394 21.7082 15.6009C25.4511 13.2617 28.0783 11.8545 26.5841 10.1752C26.4121 9.98141 26.1684 9.8956 25.8725 9.8956C23.6001 9.89634 18.2311 14.9403 18.2311 14.9403C18.2311 14.9403 16.7821 16.496 15.9057 16.496C15.7043 16.496 15.533 16.4139 15.4169 16.2112C14.7956 15.1296 21.1879 10.1286 21.5484 8.06535C21.7928 6.66715 21.3771 5.95917 20.6081 5.95917Z" fill="#FF9D00"></path>
3
+ <path d="M5.50686 24.2246C3.53472 21.2387 3.67446 18.9979 6.38043 16.206C9.08641 13.4147 10.6615 9.33111 10.6615 9.33111C10.6615 9.33111 11.2499 6.95933 12.59 7.17757C13.93 7.39581 14.9139 10.9401 12.1069 13.1084C9.29997 15.276 12.6659 16.7489 13.7459 14.713C14.8258 12.6772 17.7747 7.44316 19.304 6.44221C20.8326 5.44128 21.9089 6.00204 21.5484 8.06532C21.188 10.1286 14.795 15.1295 15.4171 16.2118C16.0391 17.2934 18.2312 14.9402 18.2312 14.9402C18.2312 14.9402 25.0907 8.49588 26.5842 10.1752C28.0776 11.8545 25.4512 13.2616 21.7082 15.6008C17.9646 17.9393 17.6744 18.557 18.2054 19.4418C18.7372 20.3266 26.9998 13.1351 27.7759 16.1838C28.5513 19.2324 19.3434 20.1173 19.9117 22.2219C20.48 24.3274 26.3979 18.2382 27.6082 20.6107C28.8193 22.9839 19.2574 25.7722 19.18 25.7929C16.0914 26.62 8.24723 28.3726 5.50686 24.2246Z" fill="#FFD21E"></path>
4
+ </svg>"""
5
+
6
+ loading_icon_html = """<svg id="share-btn-loading-icon" style="display:none;" class="animate-spin" style="color: #ffffff;" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" fill="none" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24"><circle style="opacity: 0.25;" cx="12" cy="12" r="10" stroke="white" stroke-width="4"></circle><path style="opacity: 0.75;" fill="white" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>"""
7
+
8
+ css = """
9
+ /* share button */
10
+ #share-btn-container {
11
+ display: flex;
12
+ padding-left: 0.5rem !important;
13
+ padding-right: 0.5rem !important;
14
+ background-color: #000000;
15
+ justify-content: center;
16
+ align-items: center;
17
+ border-radius: 9999px !important;
18
+ width: 13rem;
19
+ margin-top: 10px;
20
+ margin-left: auto;
21
+ flex: unset !important;
22
+ }
23
+ #share-btn {
24
+ all: initial;
25
+ color: #ffffff;
26
+ font-weight: 600;
27
+ cursor: pointer;
28
+ font-family: 'IBM Plex Sans', sans-serif;
29
+ margin-left: 0.5rem !important;
30
+ padding-top: 0.25rem !important;
31
+ padding-bottom: 0.25rem !important;
32
+ right:0;
33
+ }
34
+ #share-btn * {
35
+ all: unset !important;
36
+ }
37
+ #share-btn-container div:nth-child(-n+2){
38
+ width: auto !important;
39
+ min-height: 0px !important;
40
+ }
41
+ #share-btn-container .wrap {
42
+ display: none !important;
43
+ }
44
+ """
45
+
46
+ share_js = """async () => {
47
+ async function uploadFile(file){
48
+ const UPLOAD_URL = 'https://huggingface.co/uploads';
49
+ const response = await fetch(UPLOAD_URL, {
50
+ method: 'POST',
51
+ headers: {
52
+ 'Content-Type': file.type,
53
+ 'X-Requested-With': 'XMLHttpRequest',
54
+ },
55
+ body: file, /// <- File inherits from Blob
56
+ });
57
+ if(response.headers.get('Content-Type').includes('application/json')){
58
+ const data = await response.json();
59
+ return data;
60
+ }
61
+ const url = await response.text();
62
+ return url;
63
+ }
64
+ async function getInputMediaFile(mediaEl){
65
+ const res = await fetch(mediaEl.src);
66
+ const blob = await res.blob();
67
+ const contentType = res.headers.get("content-type");
68
+ const ext = contentType.split("/")[1];
69
+ const videoId = Date.now()
70
+ const fileName = `MusicGen-${videoId}.${ext}`;
71
+ return new File([blob], fileName, { type: contentType });
72
+ }
73
+ const gradioEl = document.querySelector("gradio-app").shadowRoot || document.querySelector('body > gradio-app');
74
+ const prompt = gradioEl.querySelector('#text-input textarea').value;
75
+ const melody = gradioEl.querySelector('#melody-output audio');
76
+ const generated = gradioEl.querySelector('#generated-video video');
77
+
78
+ const titleTxt = `MusicGen: ${prompt.slice(0, 50)}...`;
79
+
80
+ const shareBtnEl = gradioEl.querySelector('#share-btn');
81
+ const shareIconEl = gradioEl.querySelector('#share-btn-share-icon');
82
+ const loadingIconEl = gradioEl.querySelector('#share-btn-loading-icon');
83
+ if(!generated){
84
+ return;
85
+ };
86
+ shareBtnEl.style.pointerEvents = 'none';
87
+ shareIconEl.style.display = 'none';
88
+ loadingIconEl.style.removeProperty('display');
89
+
90
+ const generatedFile= await getInputMediaFile(generated)
91
+ const generatedURL = await uploadFile(generatedFile);
92
+ let melodyURL = null;
93
+
94
+ if(melody){
95
+ const melodyFile = await getInputMediaFile(melody)
96
+ melodyURL = await uploadFile(melodyFile);
97
+ }
98
+
99
+ const descriptionMd = `
100
+ ### Text
101
+ ${prompt}
102
+
103
+ ### Generated Song
104
+ ${generatedURL}
105
+
106
+ ${(melodyURL && (typeof melodyURL === 'string'))? `
107
+ ### Melody
108
+ <audio controls src="${melodyURL}"></audio>` : ``}
109
+ `;
110
+ const params = new URLSearchParams({
111
+ title: titleTxt,
112
+ description: descriptionMd,
113
+ });
114
+ const paramsStr = params.toString();
115
+ window.open(`https://huggingface.co/spaces/facebook/MusicGen/discussions/new?${paramsStr}`, '_blank');
116
+ shareBtnEl.style.removeProperty('pointer-events');
117
+ shareIconEl.style.removeProperty('display');
118
+ loadingIconEl.style.display = 'none';
119
+ }"""