merve HF staff fffiloni commited on
Commit
55f4a27
0 Parent(s):

Duplicate from fffiloni/img-to-music

Browse files

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

Files changed (8) hide show
  1. .gitattributes +33 -0
  2. README.md +13 -0
  3. app.py +158 -0
  4. constants.py +9 -0
  5. requirements.txt +8 -0
  6. share_btn.py +100 -0
  7. style.css +51 -0
  8. utils.py +50 -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.16.0
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,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ import base64
3
+ import gradio as gr
4
+ from sentence_transformers import SentenceTransformer
5
+
6
+ import httpx
7
+ import json
8
+
9
+ import os
10
+ import requests
11
+ import urllib
12
+
13
+ from os import path
14
+ from pydub import AudioSegment
15
+
16
+ #img_to_text = gr.Blocks.load(name="spaces/pharma/CLIP-Interrogator")
17
+ img_to_text = gr.Blocks.load(name="spaces/fffiloni/CLIP-Interrogator-2")
18
+
19
+ from share_btn import community_icon_html, loading_icon_html, share_js
20
+
21
+ def get_prompts(uploaded_image, track_duration, gen_intensity, gen_mode):
22
+ print("calling clip interrogator")
23
+ #prompt = img_to_text(uploaded_image, "ViT-L (best for Stable Diffusion 1.*)", "fast", fn_index=1)[0]
24
+ prompt = img_to_text(uploaded_image, 'fast', 4, fn_index=1)[0]
25
+ print(prompt)
26
+ music_result = generate_track_by_prompt(prompt, track_duration, gen_intensity, gen_mode)
27
+ print(music_result)
28
+ return music_result[0], gr.update(visible=True), gr.update(visible=True), gr.update(visible=True)
29
+
30
+ from utils import get_tags_for_prompts, get_mubert_tags_embeddings, get_pat
31
+
32
+ minilm = SentenceTransformer('all-MiniLM-L6-v2')
33
+ mubert_tags_embeddings = get_mubert_tags_embeddings(minilm)
34
+
35
+
36
+ def get_track_by_tags(tags, pat, duration, gen_intensity, gen_mode, maxit=20):
37
+
38
+ r = httpx.post('https://api-b2b.mubert.com/v2/RecordTrackTTM',
39
+ json={
40
+ "method": "RecordTrackTTM",
41
+ "params": {
42
+ "pat": pat,
43
+ "duration": duration,
44
+ "format": "wav",
45
+ "intensity":gen_intensity,
46
+ "tags": tags,
47
+ "mode": gen_mode
48
+ }
49
+ })
50
+
51
+ rdata = json.loads(r.text)
52
+ assert rdata['status'] == 1, rdata['error']['text']
53
+ trackurl = rdata['data']['tasks'][0]['download_link']
54
+
55
+ print('Generating track ', end='')
56
+ for i in range(maxit):
57
+ r = httpx.get(trackurl)
58
+ if r.status_code == 200:
59
+ return trackurl
60
+ time.sleep(1)
61
+
62
+
63
+ def generate_track_by_prompt(prompt, duration, gen_intensity, gen_mode):
64
+ try:
65
+ pat = get_pat("prodia@prodia.com")
66
+ _, tags = get_tags_for_prompts(minilm, mubert_tags_embeddings, [prompt, ])[0]
67
+ result = get_track_by_tags(tags, pat, int(duration), gen_intensity, gen_mode)
68
+ print(result)
69
+ return result, ",".join(tags), "Success"
70
+ except Exception as e:
71
+ return None, "", str(e)
72
+
73
+ def convert_mp3_to_wav(mp3_filepath):
74
+
75
+ url = mp3_filepath
76
+ save_as = "file.mp3"
77
+
78
+ data = urllib.request.urlopen(url)
79
+
80
+ f = open(save_as,'wb')
81
+ f.write(data.read())
82
+ f.close()
83
+
84
+ wave_file="file.wav"
85
+
86
+ sound = AudioSegment.from_mp3(save_as)
87
+ sound.export(wave_file, format="wav")
88
+
89
+ return wave_file
90
+
91
+ article = """
92
+
93
+ <div class="footer">
94
+ <p>
95
+
96
+ Follow <a href="https://twitter.com/fffiloni" target="_blank">Sylvain Filoni</a> for future updates 🤗
97
+ </p>
98
+ </div>
99
+
100
+ <div id="may-like-container" style="display: flex;justify-content: center;flex-direction: column;align-items: center;margin-bottom: 30px;">
101
+ <p style="font-size: 0.8em;margin-bottom: 4px;">You may also like: </p>
102
+ <div id="may-like" style="display: flex;flex-wrap: wrap;align-items: center;height: 20px;">
103
+ <svg height="20" width="122" style="margin-left:4px;margin-bottom: 6px;">
104
+ <a href="https://huggingface.co/spaces/fffiloni/spectrogram-to-music" target="_blank">
105
+ <image href="https://img.shields.io/badge/🤗 Spaces-Riffusion-blue" src="https://img.shields.io/badge/🤗 Spaces-Riffusion-blue.png" height="20"/>
106
+ </a>
107
+ </svg>
108
+ </div>
109
+ </div>
110
+
111
+
112
+ """
113
+
114
+ with gr.Blocks(css="style.css") as demo:
115
+ with gr.Column(elem_id="col-container"):
116
+
117
+ gr.HTML("""<div style="text-align: center; max-width: 700px; margin: 0 auto;">
118
+ <div
119
+ style="
120
+ display: inline-flex;
121
+ align-items: center;
122
+ gap: 0.8rem;
123
+ font-size: 1.75rem;
124
+ "
125
+ >
126
+ <h1 style="font-weight: 900; margin-bottom: 7px; margin-top: 5px;">
127
+ Image to Music
128
+ </h1>
129
+ </div>
130
+ <p style="margin-bottom: 10px; font-size: 94%">
131
+ Sends an image in to <a href="https://huggingface.co/spaces/pharma/CLIP-Interrogator" target="_blank">CLIP Interrogator</a>
132
+ to generate a text prompt which is then run through
133
+ <a href="https://huggingface.co/Mubert" target="_blank">Mubert</a> text-to-music to generate music from the input image!
134
+ </p>
135
+ </div>""")
136
+
137
+ input_img = gr.Image(type="filepath", elem_id="input-img")
138
+ music_output = gr.Audio(label="Result", type="filepath", elem_id="music-output").style(height="5rem")
139
+
140
+ with gr.Group(elem_id="share-btn-container"):
141
+ community_icon = gr.HTML(community_icon_html, visible=False)
142
+ loading_icon = gr.HTML(loading_icon_html, visible=False)
143
+ share_button = gr.Button("Share to community", elem_id="share-btn", visible=False)
144
+
145
+ with gr.Accordion(label="Music Generation Options", open=False):
146
+ track_duration = gr.Slider(minimum=20, maximum=120, value=30, step=5, label="Track duration", elem_id="duration-inp")
147
+ with gr.Row():
148
+ gen_intensity = gr.Dropdown(choices=["low", "medium", "high"], value="medium", label="Intensity")
149
+ gen_mode = gr.Radio(label="mode", choices=["track", "loop"], value="track")
150
+
151
+ generate = gr.Button("Generate Music from Image")
152
+
153
+ gr.HTML(article)
154
+
155
+ generate.click(get_prompts, inputs=[input_img,track_duration,gen_intensity,gen_mode], outputs=[music_output, share_button, community_icon, loading_icon], api_name="i2m")
156
+ share_button.click(None, [], [], _js=share_js)
157
+
158
+ demo.queue(max_size=32, concurrency_count=20).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
+
6
+ pydub
7
+ ffmpeg
8
+ requests
share_btn.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 outputMusic = gradioEl.querySelector('#music-output audio');
61
+ const outputMusic_src = gradioEl.querySelector('#music-output audio').src;
62
+ const outputMusic_name = outputMusic_src.split('/').pop();
63
+ let titleTxt = outputMusic_name;
64
+ //if(titleTxt.length > 100){
65
+ // titleTxt = titleTxt.slice(0, 100) + ' ...';
66
+ //}
67
+ const shareBtnEl = gradioEl.querySelector('#share-btn');
68
+ const shareIconEl = gradioEl.querySelector('#share-btn-share-icon');
69
+ const loadingIconEl = gradioEl.querySelector('#share-btn-loading-icon');
70
+ if(!outputMusic){
71
+ return;
72
+ };
73
+ shareBtnEl.style.pointerEvents = 'none';
74
+ shareIconEl.style.display = 'none';
75
+ loadingIconEl.style.removeProperty('display');
76
+ const inputFile = await getInputImgFile(inputImgEl);
77
+ const urlInputImg = await uploadFile(inputFile);
78
+ const musicFile = await getOutputMusicFile(outputMusic);
79
+ const dataOutputMusic = await uploadFile(musicFile);
80
+
81
+ const descriptionMd = `#### Input img:
82
+ <img src='${urlInputImg}' style='max-height: 350px;'>
83
+
84
+ #### Music:
85
+
86
+ <audio controls>
87
+ <source src="${dataOutputMusic}" type="audio/wav">
88
+ Your browser does not support the audio element.
89
+ </audio>
90
+ `;
91
+ const params = new URLSearchParams({
92
+ title: titleTxt,
93
+ description: descriptionMd,
94
+ });
95
+ const paramsStr = params.toString();
96
+ window.open(`https://huggingface.co/spaces/fffiloni/img-to-music/discussions/new?${paramsStr}`, '_blank');
97
+ shareBtnEl.style.removeProperty('pointer-events');
98
+ shareIconEl.style.removeProperty('display');
99
+ loadingIconEl.style.display = 'none';
100
+ }"""
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,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, MUBERT_TOKEN
7
+
8
+ def get_mubert_tags_embeddings(w2v_model):
9
+ return w2v_model.encode(MUBERT_TAGS)
10
+
11
+
12
+ def get_pat(email: str):
13
+ r = httpx.post('https://api-b2b.mubert.com/v2/GetServiceAccess',
14
+ json={
15
+ "method": "GetServiceAccess",
16
+ "params": {
17
+ "email": email,
18
+ "license": MUBERT_LICENSE,
19
+ "token": MUBERT_TOKEN,
20
+ "mode": MUBERT_MODE,
21
+ }
22
+ })
23
+
24
+ rdata = json.loads(r.text)
25
+ assert rdata['status'] == 1, "probably incorrect e-mail"
26
+ pat = rdata['data']['pat']
27
+ return pat
28
+
29
+
30
+ def find_similar(em, embeddings, method='cosine'):
31
+ scores = []
32
+ for ref in embeddings:
33
+ if method == 'cosine':
34
+ scores.append(1 - np.dot(ref, em) / (np.linalg.norm(ref) * np.linalg.norm(em)))
35
+ if method == 'norm':
36
+ scores.append(np.linalg.norm(ref - em))
37
+ return np.array(scores), np.argsort(scores)
38
+
39
+
40
+ def get_tags_for_prompts(w2v_model, mubert_tags_embeddings, prompts, top_n=3, debug=False):
41
+ prompts_embeddings = w2v_model.encode(prompts)
42
+ ret = []
43
+ for i, pe in enumerate(prompts_embeddings):
44
+ scores, idxs = find_similar(pe, mubert_tags_embeddings)
45
+ top_tags = MUBERT_TAGS[idxs[:top_n]]
46
+ top_prob = 1 - scores[idxs[:top_n]]
47
+ if debug:
48
+ print(f"Prompt: {prompts[i]}\nTags: {', '.join(top_tags)}\nScores: {top_prob}\n\n\n")
49
+ ret.append((prompts[i], list(top_tags)))
50
+ return ret