aross3 fffiloni commited on
Commit
96449d4
β€’
0 Parent(s):

Duplicate from fffiloni/spectrogram-to-music

Browse files

Co-authored-by: Sylvain Filoni <fffiloni@users.noreply.huggingface.co>

Files changed (6) hide show
  1. .gitattributes +34 -0
  2. README.md +13 -0
  3. app.py +221 -0
  4. requirements.txt +9 -0
  5. share_btn.py +101 -0
  6. spectro.py +209 -0
.gitattributes ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Riffusion β€’ Spectrogram To Music
3
+ emoji: πŸŒ–
4
+ colorFrom: indigo
5
+ colorTo: red
6
+ sdk: gradio
7
+ sdk_version: 3.13.2
8
+ app_file: app.py
9
+ pinned: false
10
+ duplicated_from: fffiloni/spectrogram-to-music
11
+ ---
12
+
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+
4
+ from PIL import Image
5
+ import numpy as np
6
+ from spectro import wav_bytes_from_spectrogram_image
7
+
8
+ from diffusers import StableDiffusionPipeline
9
+ from diffusers import StableDiffusionImg2ImgPipeline
10
+
11
+ from share_btn import community_icon_html, loading_icon_html, share_js
12
+
13
+ device = "cuda"
14
+ MODEL_ID = "riffusion/riffusion-model-v1"
15
+ pipe = StableDiffusionPipeline.from_pretrained(MODEL_ID, torch_dtype=torch.float16)
16
+ pipe = pipe.to(device)
17
+ pipe2 = StableDiffusionImg2ImgPipeline.from_pretrained(MODEL_ID, torch_dtype=torch.float16)
18
+ pipe2 = pipe2.to(device)
19
+
20
+ spectro_from_wav = gr.Interface.load("spaces/fffiloni/audio-to-spectrogram")
21
+
22
+ def predict(prompt, negative_prompt, audio_input, duration):
23
+ if audio_input == None :
24
+ return classic(prompt, negative_prompt, duration)
25
+ else :
26
+ return style_transfer(prompt, negative_prompt, audio_input)
27
+
28
+ def classic(prompt, negative_prompt, duration):
29
+ if duration == 5:
30
+ width_duration=512
31
+ else :
32
+ width_duration = 512 + ((int(duration)-5) * 128)
33
+ spec = pipe(prompt, negative_prompt=negative_prompt, height=512, width=width_duration).images[0]
34
+ print(spec)
35
+ wav = wav_bytes_from_spectrogram_image(spec)
36
+ with open("output.wav", "wb") as f:
37
+ f.write(wav[0].getbuffer())
38
+ return spec, 'output.wav', gr.update(visible=True), gr.update(visible=True), gr.update(visible=True)
39
+
40
+ def style_transfer(prompt, negative_prompt, audio_input):
41
+ spec = spectro_from_wav(audio_input)
42
+ print(spec)
43
+ # Open the image
44
+ im = Image.open(spec)
45
+
46
+
47
+ # Open the image
48
+ im = image_from_spectrogram(im, 1)
49
+
50
+
51
+ new_spectro = pipe2(prompt=prompt, image=im, strength=0.5, guidance_scale=7).images
52
+ wav = wav_bytes_from_spectrogram_image(new_spectro[0])
53
+ with open("output.wav", "wb") as f:
54
+ f.write(wav[0].getbuffer())
55
+ return new_spectro[0], 'output.wav', gr.update(visible=True), gr.update(visible=True), gr.update(visible=True)
56
+
57
+ def image_from_spectrogram(
58
+ spectrogram: np.ndarray, max_volume: float = 50, power_for_image: float = 0.25
59
+ ) -> Image.Image:
60
+ """
61
+ Compute a spectrogram image from a spectrogram magnitude array.
62
+ """
63
+ # Apply the power curve
64
+ data = np.power(spectrogram, power_for_image)
65
+
66
+ # Rescale to 0-255
67
+ data = data * 255 / max_volume
68
+
69
+ # Invert
70
+ data = 255 - data
71
+
72
+ # Convert to a PIL image
73
+ image = Image.fromarray(data.astype(np.uint8))
74
+
75
+ # Flip Y
76
+ image = image.transpose(Image.FLIP_TOP_BOTTOM)
77
+
78
+ # Convert to RGB
79
+ image = image.convert("RGB")
80
+
81
+ return image
82
+
83
+ title = """
84
+ <div style="text-align: center; max-width: 500px; margin: 0 auto;">
85
+ <div
86
+ style="
87
+ display: inline-flex;
88
+ align-items: center;
89
+ gap: 0.8rem;
90
+ font-size: 1.75rem;
91
+ margin-bottom: 10px;
92
+ line-height: 1em;
93
+ "
94
+ >
95
+ <h1 style="font-weight: 600; margin-bottom: 7px;">
96
+ Riffusion real-time music generation
97
+ </h1>
98
+ </div>
99
+ <p style="margin-bottom: 10px;font-size: 94%;font-weight: 100;line-height: 1.5em;">
100
+ Describe a musical prompt, generate music by getting a spectrogram image & sound.
101
+ </p>
102
+ </div>
103
+ """
104
+
105
+ article = """
106
+ <p style="font-size: 0.8em;line-height: 1.2em;border: 1px solid #374151;border-radius: 8px;padding: 20px;">
107
+ About the model: Riffusion is a latent text-to-image diffusion model capable of generating spectrogram images given any text input. These spectrograms can be converted into audio clips.
108
+ <br />β€”
109
+ <br />The Riffusion model was created by fine-tuning the Stable-Diffusion-v1-5 checkpoint.
110
+ <br />β€”
111
+ <br />The model is intended for research purposes only. Possible research areas and tasks include
112
+ generation of artworks, audio, and use in creative processes, applications in educational or creative tools, research on generative models.
113
+
114
+ </p>
115
+ <div class="footer">
116
+ <p>
117
+ <a href="https://huggingface.co/riffusion/riffusion-model-v1" target="_blank">Riffusion model</a> by Seth Forsgren and Hayk Martiros -
118
+ Demo by πŸ€— <a href="https://twitter.com/fffiloni" target="_blank">Sylvain Filoni</a>
119
+ </p>
120
+ </div>
121
+
122
+ <p style="text-align: center;font-size: 94%">
123
+ Do you need faster results ? You can skip the queue by duplicating this space:
124
+ <span style="display: flex;align-items: center;justify-content: center;height: 30px;">
125
+ <a href="https://huggingface.co/fffiloni/spectrogram-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" alt="Duplicate Space"></a>
126
+ <a href="https://colab.research.google.com/drive/1FhH3HlN8Ps_Pr9OR6Qcfbfz7utDvICl0?usp=sharing" target="_blank"><img src="https://colab.research.google.com/assets/colab-badge.svg" /></a>
127
+ </span>
128
+ </p>
129
+ """
130
+
131
+ css = '''
132
+ #col-container, #col-container-2 {max-width: 510px; margin-left: auto; margin-right: auto;}
133
+ a {text-decoration-line: underline; font-weight: 600;}
134
+ div#record_btn > .mt-6 {
135
+ margin-top: 0!important;
136
+ }
137
+ div#record_btn > .mt-6 button {
138
+ width: 100%;
139
+ height: 40px;
140
+ }
141
+ .footer {
142
+ margin-bottom: 45px;
143
+ margin-top: 10px;
144
+ text-align: center;
145
+ border-bottom: 1px solid #e5e5e5;
146
+ }
147
+ .footer>p {
148
+ font-size: .8rem;
149
+ display: inline-block;
150
+ padding: 0 10px;
151
+ transform: translateY(10px);
152
+ background: white;
153
+ }
154
+ .dark .footer {
155
+ border-color: #303030;
156
+ }
157
+ .dark .footer>p {
158
+ background: #0b0f19;
159
+ }
160
+ .animate-spin {
161
+ animation: spin 1s linear infinite;
162
+ }
163
+ @keyframes spin {
164
+ from {
165
+ transform: rotate(0deg);
166
+ }
167
+ to {
168
+ transform: rotate(360deg);
169
+ }
170
+ }
171
+ #share-btn-container {
172
+ display: flex; padding-left: 0.5rem !important; padding-right: 0.5rem !important; background-color: #000000; justify-content: center; align-items: center; border-radius: 9999px !important; width: 13rem;
173
+ }
174
+ #share-btn {
175
+ all: initial; color: #ffffff;font-weight: 600; cursor:pointer; font-family: 'IBM Plex Sans', sans-serif; margin-left: 0.5rem !important; padding-top: 0.25rem !important; padding-bottom: 0.25rem !important;right:0;
176
+ }
177
+ #share-btn * {
178
+ all: unset;
179
+ }
180
+ #share-btn-container div:nth-child(-n+2){
181
+ width: auto !important;
182
+ min-height: 0px !important;
183
+ }
184
+ #share-btn-container .wrap {
185
+ display: none !important;
186
+ }
187
+
188
+ '''
189
+
190
+
191
+
192
+ with gr.Blocks(css=css) as demo:
193
+
194
+ with gr.Column(elem_id="col-container"):
195
+
196
+ gr.HTML(title)
197
+
198
+ prompt_input = gr.Textbox(placeholder="a cat diva singing in a New York jazz club", label="Musical prompt", elem_id="prompt-in")
199
+ audio_input = gr.Audio(source="upload", type="filepath", visible=False)
200
+ with gr.Row():
201
+ negative_prompt = gr.Textbox(label="Negative prompt")
202
+ duration_input = gr.Slider(label="Duration in seconds", minimum=5, maximum=10, step=1, value=8, elem_id="duration-slider")
203
+
204
+ send_btn = gr.Button(value="Get a new spectrogram ! ", elem_id="submit-btn")
205
+
206
+ with gr.Column(elem_id="col-container-2"):
207
+
208
+ spectrogram_output = gr.Image(label="spectrogram image result", elem_id="img-out")
209
+ sound_output = gr.Audio(type='filepath', label="spectrogram sound", elem_id="music-out")
210
+
211
+ with gr.Group(elem_id="share-btn-container"):
212
+ community_icon = gr.HTML(community_icon_html, visible=False)
213
+ loading_icon = gr.HTML(loading_icon_html, visible=False)
214
+ share_button = gr.Button("Share to community", elem_id="share-btn", visible=False)
215
+
216
+ gr.HTML(article)
217
+
218
+ send_btn.click(predict, inputs=[prompt_input, negative_prompt, audio_input, duration_input], outputs=[spectrogram_output, sound_output, share_button, community_icon, loading_icon])
219
+ share_button.click(None, [], [], _js=share_js)
220
+
221
+ demo.queue(max_size=250).launch(debug=True)
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ --extra-index-url https://download.pytorch.org/whl/cu113
2
+ torch
3
+ torchaudio
4
+ typing
5
+ pydub
6
+ scipy
7
+ diffusers
8
+ transformers
9
+ accelerate
share_btn.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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"
7
+ style="color: #ffffff;
8
+ "
9
+ 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>"""
10
+
11
+ share_js = """async () => {
12
+ async function uploadFile(file){
13
+ const UPLOAD_URL = 'https://huggingface.co/uploads';
14
+ const response = await fetch(UPLOAD_URL, {
15
+ method: 'POST',
16
+ headers: {
17
+ 'Content-Type': file.type,
18
+ 'X-Requested-With': 'XMLHttpRequest',
19
+ },
20
+ body: file, /// <- File inherits from Blob
21
+ });
22
+ const url = await response.text();
23
+ return url;
24
+ }
25
+ async function getInputImgFile(imgEl){
26
+ const res = await fetch(imgEl.src);
27
+ const blob = await res.blob();
28
+ const imgId = Date.now() % 200;
29
+ const isPng = imgEl.src.startsWith(`data:image/png`);
30
+ if(isPng){
31
+ const fileName = `sd-perception-${{imgId}}.png`;
32
+ return new File([blob], fileName, { type: 'image/png' });
33
+ }else{
34
+ const fileName = `sd-perception-${{imgId}}.jpg`;
35
+ return new File([blob], fileName, { type: 'image/jpeg' });
36
+ }
37
+ }
38
+ async function getOutputMusicFile(audioEL){
39
+ const res = await fetch(audioEL.src);
40
+ const blob = await res.blob();
41
+ const audioId = Date.now() % 200;
42
+ const fileName = `spectro-music-${{audioId}}.wav`;
43
+ const musicBlob = new File([blob], fileName, { type: 'audio/wav' });
44
+ console.log(musicBlob);
45
+ return musicBlob;
46
+ }
47
+
48
+ async function audioToBase64(audioFile) {
49
+ return new Promise((resolve, reject) => {
50
+ let reader = new FileReader();
51
+ reader.readAsDataURL(audioFile);
52
+ reader.onload = () => resolve(reader.result);
53
+ reader.onerror = error => reject(error);
54
+
55
+ });
56
+ }
57
+ const gradioEl = document.querySelector('body > gradio-app');
58
+ // const gradioEl = document.querySelector("gradio-app").shadowRoot;
59
+ const inputPromptEl = gradioEl.querySelector('#prompt-in textarea').value;
60
+ const outputImgEl = gradioEl.querySelector('#img-out img');
61
+ const outputMusic = gradioEl.querySelector('#music-out audio');
62
+ const outputMusic_src = gradioEl.querySelector('#music-out audio').src;
63
+
64
+ let titleTxt = inputPromptEl;
65
+ //if(titleTxt.length > 100){
66
+ // titleTxt = titleTxt.slice(0, 100) + ' ...';
67
+ //}
68
+ const shareBtnEl = gradioEl.querySelector('#share-btn');
69
+ const shareIconEl = gradioEl.querySelector('#share-btn-share-icon');
70
+ const loadingIconEl = gradioEl.querySelector('#share-btn-loading-icon');
71
+ if(!outputMusic){
72
+ return;
73
+ };
74
+ shareBtnEl.style.pointerEvents = 'none';
75
+ shareIconEl.style.display = 'none';
76
+ loadingIconEl.style.removeProperty('display');
77
+ const outputImg = await getInputImgFile(outputImgEl);
78
+ const urlOutputImg = await uploadFile(outputImg);
79
+ const musicFile = await getOutputMusicFile(outputMusic);
80
+ const dataOutputMusic = await uploadFile(musicFile);
81
+
82
+ const descriptionMd = `#### Spectrogram Image:
83
+ <img src='${urlOutputImg}' style='max-height: 350px;'>
84
+
85
+ #### Spectrogram Sound:
86
+
87
+ <audio controls>
88
+ <source src="${dataOutputMusic}" type="audio/wav">
89
+ Your browser does not support the audio element.
90
+ </audio>
91
+ `;
92
+ const params = new URLSearchParams({
93
+ title: titleTxt,
94
+ description: descriptionMd,
95
+ });
96
+ const paramsStr = params.toString();
97
+ window.open(`https://huggingface.co/spaces/fffiloni/spectrogram-to-music/discussions/new?${paramsStr}`, '_blank');
98
+ shareBtnEl.style.removeProperty('pointer-events');
99
+ shareIconEl.style.removeProperty('display');
100
+ loadingIconEl.style.display = 'none';
101
+ }"""
spectro.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Audio processing tools to convert between spectrogram images and waveforms.
3
+ """
4
+ import io
5
+ import typing as T
6
+
7
+ import numpy as np
8
+ from PIL import Image
9
+ import pydub
10
+ from scipy.io import wavfile
11
+ import torch
12
+ import torchaudio
13
+
14
+
15
+ def wav_bytes_from_spectrogram_image(image: Image.Image) -> T.Tuple[io.BytesIO, float]:
16
+ """
17
+ Reconstruct a WAV audio clip from a spectrogram image. Also returns the duration in seconds.
18
+ """
19
+
20
+ max_volume = 50
21
+ power_for_image = 0.25
22
+ Sxx = spectrogram_from_image(image, max_volume=max_volume, power_for_image=power_for_image)
23
+
24
+ sample_rate = 44100 # [Hz]
25
+ clip_duration_ms = 5000 # [ms]
26
+
27
+ bins_per_image = 512
28
+ n_mels = 512
29
+
30
+ # FFT parameters
31
+ window_duration_ms = 100 # [ms]
32
+ padded_duration_ms = 400 # [ms]
33
+ step_size_ms = 10 # [ms]
34
+
35
+ # Derived parameters
36
+ num_samples = int(image.width / float(bins_per_image) * clip_duration_ms) * sample_rate
37
+ n_fft = int(padded_duration_ms / 1000.0 * sample_rate)
38
+ hop_length = int(step_size_ms / 1000.0 * sample_rate)
39
+ win_length = int(window_duration_ms / 1000.0 * sample_rate)
40
+
41
+ samples = waveform_from_spectrogram(
42
+ Sxx=Sxx,
43
+ n_fft=n_fft,
44
+ hop_length=hop_length,
45
+ win_length=win_length,
46
+ num_samples=num_samples,
47
+ sample_rate=sample_rate,
48
+ mel_scale=True,
49
+ n_mels=n_mels,
50
+ max_mel_iters=200,
51
+ num_griffin_lim_iters=32,
52
+ )
53
+
54
+ wav_bytes = io.BytesIO()
55
+ wavfile.write(wav_bytes, sample_rate, samples.astype(np.int16))
56
+ wav_bytes.seek(0)
57
+
58
+ duration_s = float(len(samples)) / sample_rate
59
+
60
+ return wav_bytes, duration_s
61
+
62
+
63
+ def spectrogram_from_image(
64
+ image: Image.Image, max_volume: float = 50, power_for_image: float = 0.25
65
+ ) -> np.ndarray:
66
+ """
67
+ Compute a spectrogram magnitude array from a spectrogram image.
68
+
69
+ TODO(hayk): Add image_from_spectrogram and call this out as the reverse.
70
+ """
71
+ # Convert to a numpy array of floats
72
+ data = np.array(image).astype(np.float32)
73
+
74
+ # Flip Y take a single channel
75
+ data = data[::-1, :, 0]
76
+
77
+ # Invert
78
+ data = 255 - data
79
+
80
+ # Rescale to max volume
81
+ data = data * max_volume / 255
82
+
83
+ # Reverse the power curve
84
+ data = np.power(data, 1 / power_for_image)
85
+
86
+ return data
87
+
88
+
89
+ def spectrogram_from_waveform(
90
+ waveform: np.ndarray,
91
+ sample_rate: int,
92
+ n_fft: int,
93
+ hop_length: int,
94
+ win_length: int,
95
+ mel_scale: bool = True,
96
+ n_mels: int = 512,
97
+ ) -> np.ndarray:
98
+ """
99
+ Compute a spectrogram from a waveform.
100
+ """
101
+
102
+ spectrogram_func = torchaudio.transforms.Spectrogram(
103
+ n_fft=n_fft,
104
+ power=None,
105
+ hop_length=hop_length,
106
+ win_length=win_length,
107
+ )
108
+
109
+ waveform_tensor = torch.from_numpy(waveform.astype(np.float32)).reshape(1, -1)
110
+ Sxx_complex = spectrogram_func(waveform_tensor).numpy()[0]
111
+
112
+ Sxx_mag = np.abs(Sxx_complex)
113
+
114
+ if mel_scale:
115
+ mel_scaler = torchaudio.transforms.MelScale(
116
+ n_mels=n_mels,
117
+ sample_rate=sample_rate,
118
+ f_min=0,
119
+ f_max=10000,
120
+ n_stft=n_fft // 2 + 1,
121
+ norm=None,
122
+ mel_scale="htk",
123
+ )
124
+
125
+ Sxx_mag = mel_scaler(torch.from_numpy(Sxx_mag)).numpy()
126
+
127
+ return Sxx_mag
128
+
129
+
130
+ def waveform_from_spectrogram(
131
+ Sxx: np.ndarray,
132
+ n_fft: int,
133
+ hop_length: int,
134
+ win_length: int,
135
+ num_samples: int,
136
+ sample_rate: int,
137
+ mel_scale: bool = True,
138
+ n_mels: int = 512,
139
+ max_mel_iters: int = 200,
140
+ num_griffin_lim_iters: int = 32,
141
+ device: str = "cuda:0",
142
+ ) -> np.ndarray:
143
+ """
144
+ Reconstruct a waveform from a spectrogram.
145
+
146
+ This is an approximate inverse of spectrogram_from_waveform, using the Griffin-Lim algorithm
147
+ to approximate the phase.
148
+ """
149
+ Sxx_torch = torch.from_numpy(Sxx).to(device)
150
+
151
+ # TODO(hayk): Make this a class that caches the two things
152
+
153
+ if mel_scale:
154
+ mel_inv_scaler = torchaudio.transforms.InverseMelScale(
155
+ n_mels=n_mels,
156
+ sample_rate=sample_rate,
157
+ f_min=0,
158
+ f_max=10000,
159
+ n_stft=n_fft // 2 + 1,
160
+ norm=None,
161
+ mel_scale="htk",
162
+ max_iter=max_mel_iters,
163
+ ).to(device)
164
+
165
+ Sxx_torch = mel_inv_scaler(Sxx_torch)
166
+
167
+ griffin_lim = torchaudio.transforms.GriffinLim(
168
+ n_fft=n_fft,
169
+ win_length=win_length,
170
+ hop_length=hop_length,
171
+ power=1.0,
172
+ n_iter=num_griffin_lim_iters,
173
+ ).to(device)
174
+
175
+ waveform = griffin_lim(Sxx_torch).cpu().numpy()
176
+
177
+ return waveform
178
+
179
+
180
+ def mp3_bytes_from_wav_bytes(wav_bytes: io.BytesIO) -> io.BytesIO:
181
+ mp3_bytes = io.BytesIO()
182
+ sound = pydub.AudioSegment.from_wav(wav_bytes)
183
+ sound.export(mp3_bytes, format="mp3")
184
+ mp3_bytes.seek(0)
185
+ return mp3_bytes
186
+
187
+ def image_from_spectrogram(spectrogram: np.ndarray, max_volume: float = 50, power_for_image: float = 0.25) -> Image.Image:
188
+ """
189
+ Compute a spectrogram image from a spectrogram magnitude array.
190
+ """
191
+ # Apply the power curve
192
+ data = np.power(spectrogram, power_for_image)
193
+
194
+ # Rescale to 0-255
195
+ data = data * 255 / max_volume
196
+
197
+ # Invert
198
+ data = 255 - data
199
+
200
+ # Convert to a PIL image
201
+ image = Image.fromarray(data.astype(np.uint8))
202
+
203
+ # Flip Y
204
+ image = image.transpose(Image.FLIP_TOP_BOTTOM)
205
+
206
+ # Convert to RGB
207
+ image = image.convert("RGB")
208
+
209
+ return image