Spaces:
Runtime error
Runtime error
Duplicate from fffiloni/img-to-music
Browse filesCo-authored-by: Sylvain Filoni <[email protected]>
- .gitattributes +33 -0
- README.md +13 -0
- app.py +333 -0
- constants.py +9 -0
- requirements.txt +8 -0
- share_btn.py +104 -0
- style.css +51 -0
- utils.py +36 -0
.gitattributes
ADDED
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
6 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
7 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
8 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
9 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
10 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
11 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
12 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
13 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
14 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
15 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
16 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
17 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
18 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
19 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
20 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
21 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
22 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
23 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
24 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
25 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
26 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
27 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
28 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
29 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
30 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
31 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
32 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
33 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
README.md
ADDED
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
title: Img To Music
|
3 |
+
emoji: 🌅🎶
|
4 |
+
colorFrom: green
|
5 |
+
colorTo: purple
|
6 |
+
sdk: gradio
|
7 |
+
sdk_version: 3.28.3
|
8 |
+
app_file: app.py
|
9 |
+
pinned: true
|
10 |
+
duplicated_from: fffiloni/img-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,333 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import openai
|
3 |
+
import numpy as np
|
4 |
+
import time
|
5 |
+
import base64
|
6 |
+
import ffmpeg
|
7 |
+
from sentence_transformers import SentenceTransformer
|
8 |
+
from audio2numpy import open_audio
|
9 |
+
import httpx
|
10 |
+
import json
|
11 |
+
import os
|
12 |
+
import requests
|
13 |
+
import urllib
|
14 |
+
import pydub
|
15 |
+
from os import path
|
16 |
+
from pydub import AudioSegment
|
17 |
+
import re
|
18 |
+
|
19 |
+
MUBERT_LICENSE = os.environ.get('MUBERT_LICENSE')
|
20 |
+
MUBERT_TOKEN = os.environ.get('MUBERT_TOKEN')
|
21 |
+
|
22 |
+
#img_to_text = gr.Blocks.load(name="spaces/pharma/CLIP-Interrogator")
|
23 |
+
img_to_text = gr.Blocks.load(name="spaces/fffiloni/CLIP-Interrogator-2")
|
24 |
+
|
25 |
+
from share_btn import community_icon_html, loading_icon_html, share_js
|
26 |
+
from utils import get_tags_for_prompts, get_mubert_tags_embeddings
|
27 |
+
|
28 |
+
minilm = SentenceTransformer('all-MiniLM-L6-v2')
|
29 |
+
mubert_tags_embeddings = get_mubert_tags_embeddings(minilm)
|
30 |
+
|
31 |
+
##————————————————————————————————————
|
32 |
+
|
33 |
+
MUBERT_LICENSE = os.environ.get('MUBERT_LICENSE')
|
34 |
+
MUBERT_TOKEN = os.environ.get('MUBERT_TOKEN')
|
35 |
+
|
36 |
+
##————————————————————————————————————
|
37 |
+
def get_pat_token():
|
38 |
+
r = httpx.post('https://api-b2b.mubert.com/v2/GetServiceAccess',
|
39 |
+
json={
|
40 |
+
"method": "GetServiceAccess",
|
41 |
+
"params": {
|
42 |
+
"email":"[email protected]",
|
43 |
+
"phone":"+11234567890",
|
44 |
+
"license": MUBERT_LICENSE,
|
45 |
+
"token": MUBERT_TOKEN,
|
46 |
+
|
47 |
+
}
|
48 |
+
})
|
49 |
+
|
50 |
+
rdata = json.loads(r.text)
|
51 |
+
assert rdata['status'] == 1, "probably incorrect e-mail"
|
52 |
+
pat = rdata['data']['pat']
|
53 |
+
#print(f"pat: {pat}")
|
54 |
+
return pat
|
55 |
+
|
56 |
+
def get_music(pat, prompt, track_duration, gen_intensity, gen_mode):
|
57 |
+
|
58 |
+
if len(prompt) > 200:
|
59 |
+
prompt = prompt[:200]
|
60 |
+
|
61 |
+
r = httpx.post('https://api-b2b.mubert.com/v2/TTMRecordTrack',
|
62 |
+
json={
|
63 |
+
"method": "TTMRecordTrack",
|
64 |
+
"params":
|
65 |
+
{
|
66 |
+
"text": prompt,
|
67 |
+
"pat": pat,
|
68 |
+
"mode":gen_mode,
|
69 |
+
"duration":track_duration,
|
70 |
+
"intensity": gen_intensity,
|
71 |
+
"format": "wav"
|
72 |
+
}
|
73 |
+
})
|
74 |
+
|
75 |
+
rdata = json.loads(r.text)
|
76 |
+
|
77 |
+
#print(f"rdata: {rdata}")
|
78 |
+
assert rdata['status'] == 1, rdata['error']['text']
|
79 |
+
track = rdata['data']['tasks'][0]['download_link']
|
80 |
+
print(track)
|
81 |
+
|
82 |
+
local_file_path = "sample.wav"
|
83 |
+
|
84 |
+
# Download the MP3 file from the URL
|
85 |
+
headers = {
|
86 |
+
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7; rv:93.0) Gecko/20100101 Firefox/93.0'}
|
87 |
+
|
88 |
+
retries = 3
|
89 |
+
delay = 5 # in seconds
|
90 |
+
while retries > 0:
|
91 |
+
response = requests.get(track, headers=headers)
|
92 |
+
if response.status_code == 200:
|
93 |
+
break
|
94 |
+
retries -= 1
|
95 |
+
time.sleep(delay)
|
96 |
+
response = requests.get(track, headers=headers)
|
97 |
+
print(f"{response}")
|
98 |
+
# Save the downloaded content to a local file
|
99 |
+
with open(local_file_path, 'wb') as f:
|
100 |
+
f.write(response.content)
|
101 |
+
return "sample.wav", track
|
102 |
+
|
103 |
+
|
104 |
+
def get_results(text_prompt,track_duration,gen_intensity,gen_mode):
|
105 |
+
pat_token = get_pat_token()
|
106 |
+
music = get_music(pat_token, text_prompt, track_duration, gen_intensity, gen_mode)
|
107 |
+
return pat_token, music[0], music[1]
|
108 |
+
|
109 |
+
def get_prompts(uploaded_image, track_duration, gen_intensity, gen_mode, openai_api_key):
|
110 |
+
print("calling clip interrogator")
|
111 |
+
#prompt = img_to_text(uploaded_image, "ViT-L (best for Stable Diffusion 1.*)", "fast", fn_index=1)[0]
|
112 |
+
|
113 |
+
prompt = img_to_text(uploaded_image, 'best', 4, fn_index=1)[0]
|
114 |
+
print(prompt)
|
115 |
+
clean_prompt = clean_text(prompt)
|
116 |
+
print(f"prompt cleaned: {clean_prompt}")
|
117 |
+
musical_prompt = 'You did not use any OpenAI API key to pimp your result :)'
|
118 |
+
if openai_api_key is not None:
|
119 |
+
gpt_adaptation = try_api(prompt, openai_api_key)
|
120 |
+
if gpt_adaptation[0] != "oups":
|
121 |
+
musical_prompt = gpt_adaptation[0]
|
122 |
+
print(f"musical adapt: {musical_prompt}")
|
123 |
+
music_result = get_results(musical_prompt, track_duration, gen_intensity, gen_mode)
|
124 |
+
else:
|
125 |
+
music_result = get_results(clean_prompt, track_duration, gen_intensity, gen_mode)
|
126 |
+
else:
|
127 |
+
music_result = get_results(clean_prompt, track_duration, gen_intensity, gen_mode)
|
128 |
+
|
129 |
+
show_prompts = f"""
|
130 |
+
CLIP Interrogator Caption: '{prompt}'
|
131 |
+
—
|
132 |
+
OpenAI Musical Adaptation: '{musical_prompt}'
|
133 |
+
—
|
134 |
+
Audio file link: {music_result[2]}
|
135 |
+
"""
|
136 |
+
#wave_file = convert_mp3_to_wav(music_result[1])
|
137 |
+
|
138 |
+
time.sleep(1)
|
139 |
+
return gr.Textbox.update(value=show_prompts, visible=True), music_result[1], gr.update(visible=True), gr.update(visible=True), gr.update(visible=True)
|
140 |
+
|
141 |
+
def try_api(message, openai_api_key):
|
142 |
+
|
143 |
+
try:
|
144 |
+
response = call_api(message, openai_api_key)
|
145 |
+
return response, "<span class='openai_clear'>no error</span>"
|
146 |
+
except openai.error.Timeout as e:
|
147 |
+
#Handle timeout error, e.g. retry or log
|
148 |
+
#print(f"OpenAI API request timed out: {e}")
|
149 |
+
return "oups", f"<span class='openai_error'>OpenAI API request timed out: <br />{e}</span>"
|
150 |
+
except openai.error.APIError as e:
|
151 |
+
#Handle API error, e.g. retry or log
|
152 |
+
#print(f"OpenAI API returned an API Error: {e}")
|
153 |
+
return "oups", f"<span class='openai_error'>OpenAI API returned an API Error: <br />{e}</span>"
|
154 |
+
except openai.error.APIConnectionError as e:
|
155 |
+
#Handle connection error, e.g. check network or log
|
156 |
+
#print(f"OpenAI API request failed to connect: {e}")
|
157 |
+
return "oups", f"<span class='openai_error'>OpenAI API request failed to connect: <br />{e}</span>"
|
158 |
+
except openai.error.InvalidRequestError as e:
|
159 |
+
#Handle invalid request error, e.g. validate parameters or log
|
160 |
+
#print(f"OpenAI API request was invalid: {e}")
|
161 |
+
return "oups", f"<span class='openai_error'>OpenAI API request was invalid: <br />{e}</span>"
|
162 |
+
except openai.error.AuthenticationError as e:
|
163 |
+
#Handle authentication error, e.g. check credentials or log
|
164 |
+
#print(f"OpenAI API request was not authorized: {e}")
|
165 |
+
return "oups", f"<span class='openai_error'>OpenAI API request was not authorized: <br />{e}</span>"
|
166 |
+
except openai.error.PermissionError as e:
|
167 |
+
#Handle permission error, e.g. check scope or log
|
168 |
+
#print(f"OpenAI API request was not permitted: {e}")
|
169 |
+
return "oups", f"<span class='openai_error'>OpenAI API request was not permitted: <br />{e}</span>"
|
170 |
+
except openai.error.RateLimitError as e:
|
171 |
+
#Handle rate limit error, e.g. wait or log
|
172 |
+
#print(f"OpenAI API request exceeded rate limit: {e}")
|
173 |
+
return "oups", f"<span class='openai_error'>OpenAI API request exceeded rate limit: <br />{e}</span>"
|
174 |
+
|
175 |
+
def call_api(message, openai_api_key):
|
176 |
+
|
177 |
+
instruction = "Convert in less than 200 characters this image caption to a very concise musical description with musical terms, as if you wanted to describe a musical ambiance, stricly in English"
|
178 |
+
|
179 |
+
print("starting open ai")
|
180 |
+
augmented_prompt = f"{instruction}: '{message}'."
|
181 |
+
openai.api_key = openai_api_key
|
182 |
+
|
183 |
+
response = openai.Completion.create(
|
184 |
+
model="text-davinci-003",
|
185 |
+
prompt=augmented_prompt,
|
186 |
+
temperature=0.5,
|
187 |
+
max_tokens=2048,
|
188 |
+
top_p=1,
|
189 |
+
frequency_penalty=0,
|
190 |
+
presence_penalty=0.6
|
191 |
+
)
|
192 |
+
|
193 |
+
#print(response)
|
194 |
+
|
195 |
+
#return str(response.choices[0].text).split("\n",2)[2]
|
196 |
+
return str(response.choices[0].text).lstrip('\n')
|
197 |
+
|
198 |
+
|
199 |
+
def get_track_by_tags(tags, pat, duration, gen_intensity, gen_mode, maxit=20):
|
200 |
+
|
201 |
+
r = httpx.post('https://api-b2b.mubert.com/v2/RecordTrackTTM',
|
202 |
+
json={
|
203 |
+
"method": "RecordTrackTTM",
|
204 |
+
"params": {
|
205 |
+
"pat": pat,
|
206 |
+
"duration": duration,
|
207 |
+
"format": "wav",
|
208 |
+
"intensity":gen_intensity,
|
209 |
+
"tags": tags,
|
210 |
+
"mode": gen_mode
|
211 |
+
}
|
212 |
+
})
|
213 |
+
|
214 |
+
rdata = json.loads(r.text)
|
215 |
+
print(rdata)
|
216 |
+
#assert rdata['status'] == 1, rdata['error']['text']
|
217 |
+
trackurl = rdata['data']['tasks'][0]
|
218 |
+
|
219 |
+
print('Generating track ', end='')
|
220 |
+
for i in range(maxit):
|
221 |
+
r = httpx.get(trackurl)
|
222 |
+
if r.status_code == 200:
|
223 |
+
return trackurl
|
224 |
+
time.sleep(1)
|
225 |
+
|
226 |
+
|
227 |
+
def generate_track_by_prompt(pat, prompt, duration, gen_intensity, gen_mode):
|
228 |
+
try:
|
229 |
+
_, tags = get_tags_for_prompts(minilm, mubert_tags_embeddings, prompt)[0]
|
230 |
+
result = get_track_by_tags(tags, pat, int(duration), gen_intensity, gen_mode)
|
231 |
+
print(result)
|
232 |
+
return result, ",".join(tags), "Success"
|
233 |
+
except Exception as e:
|
234 |
+
return None, "", str(e)
|
235 |
+
|
236 |
+
def convert_mp3_to_wav(mp3_filepath):
|
237 |
+
|
238 |
+
wave_file="file.wav"
|
239 |
+
|
240 |
+
sound = AudioSegment.from_mp3(mp3_filepath)
|
241 |
+
sound.export(wave_file, format="wav")
|
242 |
+
|
243 |
+
return wave_file
|
244 |
+
|
245 |
+
def remove_emoji(text):
|
246 |
+
emoji_pattern = re.compile("["
|
247 |
+
u"\U0001F600-\U0001F64F" # emoticons
|
248 |
+
u"\U0001F300-\U0001F5FF" # symbols & pictographs
|
249 |
+
u"\U0001F680-\U0001F6FF" # transport & map symbols
|
250 |
+
u"\U0001F1E0-\U0001F1FF" # flags (iOS)
|
251 |
+
"]+", flags=re.UNICODE)
|
252 |
+
return emoji_pattern.sub(r'', text)
|
253 |
+
|
254 |
+
def remove_nonalphanumeric(text):
|
255 |
+
return re.sub(r'[^a-zA-Z0-9\s]', '', text)
|
256 |
+
|
257 |
+
def clean_text(text):
|
258 |
+
clean_text = remove_nonalphanumeric(text)
|
259 |
+
clean_text = remove_emoji(clean_text)
|
260 |
+
clean_text = re.sub(r'\d+', '', clean_text) # Remove any number
|
261 |
+
return clean_text
|
262 |
+
|
263 |
+
article = """
|
264 |
+
|
265 |
+
<div class="footer">
|
266 |
+
<p>
|
267 |
+
|
268 |
+
Follow <a href="https://twitter.com/fffiloni" target="_blank">Sylvain Filoni</a> for future updates 🤗
|
269 |
+
</p>
|
270 |
+
</div>
|
271 |
+
|
272 |
+
<div id="may-like-container" style="display: flex;justify-content: center;flex-direction: column;align-items: center;margin-bottom: 30px;">
|
273 |
+
<p style="font-size: 0.8em;margin-bottom: 4px;">You may also like: </p>
|
274 |
+
<div id="may-like" style="display: flex;flex-wrap: wrap;align-items: center;height: 20px;">
|
275 |
+
<svg height="20" width="122" style="margin-left:4px;margin-bottom: 6px;">
|
276 |
+
<a href="https://huggingface.co/spaces/fffiloni/spectrogram-to-music" target="_blank">
|
277 |
+
<image href="https://img.shields.io/badge/🤗 Spaces-Riffusion-blue" src="https://img.shields.io/badge/🤗 Spaces-Riffusion-blue.png" height="20"/>
|
278 |
+
</a>
|
279 |
+
</svg>
|
280 |
+
</div>
|
281 |
+
</div>
|
282 |
+
|
283 |
+
|
284 |
+
"""
|
285 |
+
|
286 |
+
with gr.Blocks(css="style.css") as demo:
|
287 |
+
with gr.Column(elem_id="col-container"):
|
288 |
+
|
289 |
+
gr.HTML("""<div style="text-align: center; max-width: 700px; margin: 0 auto;">
|
290 |
+
<div
|
291 |
+
style="
|
292 |
+
display: inline-flex;
|
293 |
+
align-items: center;
|
294 |
+
gap: 0.8rem;
|
295 |
+
font-size: 1.75rem;
|
296 |
+
"
|
297 |
+
>
|
298 |
+
<h1 style="font-weight: 900; margin-bottom: 7px; margin-top: 5px;">
|
299 |
+
Image to Music
|
300 |
+
</h1>
|
301 |
+
</div>
|
302 |
+
<p style="margin-bottom: 10px; font-size: 94%">
|
303 |
+
Sends an image in to <a href="https://huggingface.co/spaces/pharma/CLIP-Interrogator" target="_blank">CLIP Interrogator</a>
|
304 |
+
to generate a text prompt which is then run through
|
305 |
+
<a href="https://huggingface.co/Mubert" target="_blank">Mubert</a> text-to-music to generate music from the input image!
|
306 |
+
</p>
|
307 |
+
</div>""")
|
308 |
+
|
309 |
+
input_img = gr.Image(type="filepath", elem_id="input-img")
|
310 |
+
prompts_out = gr.Textbox(label="Text Captions", visible=False, elem_id="prompts_out", info="If player do not work, try to copy/paste the link in a new browser window")
|
311 |
+
music_output = gr.Audio(label="Result", type="filepath", elem_id="music-output").style(height="5rem")
|
312 |
+
#music_url = gr.Textbox(max_lines=1, info="If player do not work, try to copy/paste the link in a new browser window")
|
313 |
+
#text_status = gr.Textbox(label="status")
|
314 |
+
with gr.Group(elem_id="share-btn-container"):
|
315 |
+
community_icon = gr.HTML(community_icon_html, visible=False)
|
316 |
+
loading_icon = gr.HTML(loading_icon_html, visible=False)
|
317 |
+
share_button = gr.Button("Share to community", elem_id="share-btn", visible=False)
|
318 |
+
|
319 |
+
with gr.Accordion(label="Music Generation Options", open=False):
|
320 |
+
openai_api_key = gr.Textbox(type="password", label="🔐 Your OpenAI API Key (optional)", placeholder="sk-123abc...", info="You can use your OpenAI key to adapt CLIP Interrogator caption to a musical translation.")
|
321 |
+
track_duration = gr.Slider(minimum=20, maximum=120, value=55, ustep=5, label="Track duration", elem_id="duration-inp")
|
322 |
+
with gr.Row():
|
323 |
+
gen_intensity = gr.Dropdown(choices=["low", "medium", "high"], value="medium", label="Intensity")
|
324 |
+
gen_mode = gr.Radio(label="mode", choices=["track", "loop"], value="loop")
|
325 |
+
|
326 |
+
generate = gr.Button("Generate Music from Image")
|
327 |
+
|
328 |
+
gr.HTML(article)
|
329 |
+
|
330 |
+
generate.click(get_prompts, inputs=[input_img,track_duration,gen_intensity,gen_mode, openai_api_key], outputs=[prompts_out, music_output, share_button, community_icon, loading_icon], api_name="i2m")
|
331 |
+
share_button.click(None, [], [], _js=share_js)
|
332 |
+
|
333 |
+
demo.queue(max_size=32).launch()
|
constants.py
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import os
|
3 |
+
|
4 |
+
MUBERT_LICENSE = os.environ.get('MUBERT_LICENSE')
|
5 |
+
MUBERT_TOKEN = os.environ.get('MUBERT_TOKEN')
|
6 |
+
|
7 |
+
MUBERT_MODE = "loop"
|
8 |
+
MUBERT_TAGS_STRING = 'tribal,action,kids,neo-classic,run 130,pumped,jazz / funk,ethnic,dubtechno,reggae,acid jazz,liquidfunk,funk,witch house,tech house,underground,artists,mystical,disco,sensorium,r&b,agender,psychedelic trance / psytrance,peaceful,run 140,piano,run 160,setting,meditation,christmas,ambient,horror,cinematic,electro house,idm,bass,minimal,underscore,drums,glitchy,beautiful,technology,tribal house,country pop,jazz & funk,documentary,space,classical,valentines,chillstep,experimental,trap,new jack swing,drama,post-rock,tense,corporate,neutral,happy,analog,funky,spiritual,sberzvuk special,chill hop,dramatic,catchy,holidays,fitness 90,optimistic,orchestra,acid techno,energizing,romantic,minimal house,breaks,hyper pop,warm up,dreamy,dark,urban,microfunk,dub,nu disco,vogue,keys,hardcore,aggressive,indie,electro funk,beauty,relaxing,trance,pop,hiphop,soft,acoustic,chillrave / ethno-house,deep techno,angry,dance,fun,dubstep,tropical,latin pop,heroic,world music,inspirational,uplifting,atmosphere,art,epic,advertising,chillout,scary,spooky,slow ballad,saxophone,summer,erotic,jazzy,energy 100,kara mar,xmas,atmospheric,indie pop,hip-hop,yoga,reggaeton,lounge,travel,running,folk,chillrave & ethno-house,detective,darkambient,chill,fantasy,minimal techno,special,night,tropical house,downtempo,lullaby,meditative,upbeat,glitch hop,fitness,neurofunk,sexual,indie rock,future pop,jazz,cyberpunk,melancholic,happy hardcore,family / kids,synths,electric guitar,comedy,psychedelic trance & psytrance,edm,psychedelic rock,calm,zen,bells,podcast,melodic house,ethnic percussion,nature,heavy,bassline,indie dance,techno,drumnbass,synth pop,vaporwave,sad,8-bit,chillgressive,deep,orchestral,futuristic,hardtechno,nostalgic,big room,sci-fi,tutorial,joyful,pads,minimal 170,drill,ethnic 108,amusing,sleepy ambient,psychill,italo disco,lofi,house,acoustic guitar,bassline house,rock,k-pop,synthwave,deep house,electronica,gabber,nightlife,sport & fitness,road trip,celebration,electro,disco house,electronic'
|
9 |
+
MUBERT_TAGS = np.array(MUBERT_TAGS_STRING.split(','))
|
requirements.txt
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
httpx
|
2 |
+
sentence-transformers
|
3 |
+
ffmpeg
|
4 |
+
audio2numpy
|
5 |
+
openai
|
6 |
+
pydub
|
7 |
+
ffmpeg
|
8 |
+
requests
|
share_btn.py
ADDED
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 = `img-to-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 inputImgEl = gradioEl.querySelector('#input-img img');
|
60 |
+
const prompts = gradioEl.querySelector('#prompts_out textarea').value;
|
61 |
+
const outputMusic = gradioEl.querySelector('#music-output audio');
|
62 |
+
const outputMusic_src = gradioEl.querySelector('#music-output audio').src;
|
63 |
+
const outputMusic_name = outputMusic_src.split('/').pop();
|
64 |
+
let titleTxt = outputMusic_name;
|
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 inputFile = await getInputImgFile(inputImgEl);
|
78 |
+
const urlInputImg = await uploadFile(inputFile);
|
79 |
+
const musicFile = await getOutputMusicFile(outputMusic);
|
80 |
+
const dataOutputMusic = await uploadFile(musicFile);
|
81 |
+
|
82 |
+
const descriptionMd = `#### Input img:
|
83 |
+
<img src='${urlInputImg}' style='max-height: 350px;'>
|
84 |
+
|
85 |
+
#### Prompts out:
|
86 |
+
${prompts}
|
87 |
+
|
88 |
+
#### Music:
|
89 |
+
|
90 |
+
<audio controls>
|
91 |
+
<source src="${dataOutputMusic}" type="audio/wav">
|
92 |
+
Your browser does not support the audio element.
|
93 |
+
</audio>
|
94 |
+
`;
|
95 |
+
const params = new URLSearchParams({
|
96 |
+
title: titleTxt,
|
97 |
+
description: descriptionMd,
|
98 |
+
});
|
99 |
+
const paramsStr = params.toString();
|
100 |
+
window.open(`https://huggingface.co/spaces/fffiloni/img-to-music/discussions/new?${paramsStr}`, '_blank');
|
101 |
+
shareBtnEl.style.removeProperty('pointer-events');
|
102 |
+
shareIconEl.style.removeProperty('display');
|
103 |
+
loadingIconEl.style.display = 'none';
|
104 |
+
}"""
|
style.css
ADDED
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#col-container {max-width: 510px; margin-left: auto; margin-right: auto;}
|
2 |
+
a {text-decoration-line: underline; font-weight: 600;}
|
3 |
+
div#music-output .h-full {
|
4 |
+
min-height: 5rem;
|
5 |
+
}
|
6 |
+
.footer {
|
7 |
+
margin-bottom: 45px;
|
8 |
+
margin-top: 10px;
|
9 |
+
text-align: center;
|
10 |
+
border-bottom: 1px solid #e5e5e5;
|
11 |
+
}
|
12 |
+
.footer>p {
|
13 |
+
font-size: .8rem;
|
14 |
+
display: inline-block;
|
15 |
+
padding: 0 10px;
|
16 |
+
transform: translateY(10px);
|
17 |
+
background: white;
|
18 |
+
}
|
19 |
+
.dark .footer {
|
20 |
+
border-color: #303030;
|
21 |
+
}
|
22 |
+
.dark .footer>p {
|
23 |
+
background: #0b0f19;
|
24 |
+
}
|
25 |
+
.animate-spin {
|
26 |
+
animation: spin 1s linear infinite;
|
27 |
+
}
|
28 |
+
@keyframes spin {
|
29 |
+
from {
|
30 |
+
transform: rotate(0deg);
|
31 |
+
}
|
32 |
+
to {
|
33 |
+
transform: rotate(360deg);
|
34 |
+
}
|
35 |
+
}
|
36 |
+
#share-btn-container {
|
37 |
+
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;
|
38 |
+
}
|
39 |
+
#share-btn {
|
40 |
+
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;
|
41 |
+
}
|
42 |
+
#share-btn * {
|
43 |
+
all: unset;
|
44 |
+
}
|
45 |
+
#share-btn-container div:nth-child(-n+2){
|
46 |
+
width: auto !important;
|
47 |
+
min-height: 0px !important;
|
48 |
+
}
|
49 |
+
#share-btn-container .wrap {
|
50 |
+
display: none !important;
|
51 |
+
}
|
utils.py
ADDED
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
import numpy as np
|
3 |
+
import httpx
|
4 |
+
import os
|
5 |
+
|
6 |
+
from constants import MUBERT_TAGS, MUBERT_MODE, MUBERT_LICENSE
|
7 |
+
|
8 |
+
def get_mubert_tags_embeddings(w2v_model):
|
9 |
+
return w2v_model.encode(MUBERT_TAGS)
|
10 |
+
|
11 |
+
|
12 |
+
|
13 |
+
|
14 |
+
|
15 |
+
def find_similar(em, embeddings, method='cosine'):
|
16 |
+
scores = []
|
17 |
+
for ref in embeddings:
|
18 |
+
if method == 'cosine':
|
19 |
+
scores.append(1 - np.dot(ref, em) / (np.linalg.norm(ref) * np.linalg.norm(em)))
|
20 |
+
if method == 'norm':
|
21 |
+
scores.append(np.linalg.norm(ref - em))
|
22 |
+
return np.array(scores), np.argsort(scores)
|
23 |
+
|
24 |
+
|
25 |
+
def get_tags_for_prompts(w2v_model, mubert_tags_embeddings, prompts, top_n=3, debug=False):
|
26 |
+
prompts_embeddings = w2v_model.encode(prompts)
|
27 |
+
ret = []
|
28 |
+
for i, pe in enumerate(prompts_embeddings):
|
29 |
+
scores, idxs = find_similar(pe, mubert_tags_embeddings)
|
30 |
+
top_tags = MUBERT_TAGS[idxs[:top_n]]
|
31 |
+
top_prob = 1 - scores[idxs[:top_n]]
|
32 |
+
if debug:
|
33 |
+
print(f"Prompt: {prompts[i]}\nTags: {', '.join(top_tags)}\nScores: {top_prob}\n\n\n")
|
34 |
+
ret.append((prompts[i], list(top_tags)))
|
35 |
+
print("ret: " + ret)
|
36 |
+
return ret
|