Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,219 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import tempfile
|
3 |
+
import requests
|
4 |
+
import gradio as gr
|
5 |
+
import torch
|
6 |
+
import librosa
|
7 |
+
import numpy as np
|
8 |
+
import subprocess
|
9 |
+
import sys
|
10 |
+
|
11 |
+
def install_dependencies():
|
12 |
+
"""Install required packages"""
|
13 |
+
try:
|
14 |
+
# Clone ss-vq-vae repository
|
15 |
+
if not os.path.exists('ss-vq-vae'):
|
16 |
+
print("Cloning ss-vq-vae repository...")
|
17 |
+
subprocess.run(['git', 'clone', 'https://github.com/cifkao/ss-vq-vae.git'], check=True)
|
18 |
+
|
19 |
+
# Install ss-vq-vae
|
20 |
+
subprocess.run([sys.executable, '-m', 'pip', 'install', './ss-vq-vae/src'], check=True)
|
21 |
+
|
22 |
+
print("Dependencies installed successfully!")
|
23 |
+
|
24 |
+
except Exception as e:
|
25 |
+
print(f"Error installing dependencies: {e}")
|
26 |
+
raise
|
27 |
+
|
28 |
+
# Install dependencies
|
29 |
+
install_dependencies()
|
30 |
+
|
31 |
+
# Import after installation
|
32 |
+
import confugue
|
33 |
+
from ss_vq_vae.models.vqvae_oneshot import Experiment
|
34 |
+
|
35 |
+
def download_model():
|
36 |
+
"""Download model files if they don't exist"""
|
37 |
+
model_dir = 'ss-vq-vae/experiments/model'
|
38 |
+
os.makedirs(model_dir, exist_ok=True)
|
39 |
+
|
40 |
+
model_path = os.path.join(model_dir, 'model_state.pt')
|
41 |
+
if not os.path.exists(model_path):
|
42 |
+
print("Downloading model...")
|
43 |
+
url = 'https://adasp.telecom-paris.fr/rc-ext/demos_companion-pages/vqvae_examples/ssvqvae_model_state.pt'
|
44 |
+
response = requests.get(url)
|
45 |
+
with open(model_path, 'wb') as f:
|
46 |
+
f.write(response.content)
|
47 |
+
print("Model downloaded successfully!")
|
48 |
+
|
49 |
+
# Download and initialize model
|
50 |
+
download_model()
|
51 |
+
logdir = 'ss-vq-vae/experiments/model'
|
52 |
+
cfg = confugue.Configuration.from_yaml_file(os.path.join(logdir, 'config.yaml'))
|
53 |
+
exp = cfg.configure(Experiment, logdir=logdir, device='cpu')
|
54 |
+
exp.model.load_state_dict(torch.load(os.path.join(logdir, 'model_state.pt'), map_location=exp.device))
|
55 |
+
exp.model.train(False)
|
56 |
+
|
57 |
+
# Preset audio URLs
|
58 |
+
INPUT_ROOT = 'https://adasp.telecom-paris.fr/rc-ext/demos_companion-pages/vqvae_examples/'
|
59 |
+
INPUT_URLS = {
|
60 |
+
'Electric Guitar': INPUT_ROOT + 'real/content/UnicornRodeo_Maybe_UnicornRodeo_Maybe_Full_25_ElecGtr2CloseMic3.0148.mp3',
|
61 |
+
'Electric Organ': INPUT_ROOT + 'real/style/AllenStone_Naturally_Allen%20Stone_Naturally_Keys-Organ-Active%20DI.0253.mp3',
|
62 |
+
'Jazz Piano': INPUT_ROOT + 'real/style/MaurizioPagnuttiSextet_AllTheGinIsGone_MaurizioPagnuttiSextet_AllTheGinIsGone_Full_12_PianoMics1.08.mp3',
|
63 |
+
'Synth': INPUT_ROOT + 'real/content/Skelpolu_TogetherAlone_Skelpolu_TogetherAlone_Full_13_Synth.0190.mp3',
|
64 |
+
'Rhodes DI': INPUT_ROOT + 'real/content/Diesel13_ColourMeRed_Diesel13_ColourMeRed_Full_30_RhodesDI.0062.mp3',
|
65 |
+
'Acoustic Guitar Lead': INPUT_ROOT + 'real/style/NikolaStajicFtVlasisKostas_Nalim_Nikola%20Stajic%20ft.%20Vlasis%20Kostas_Nalim_Acoustic%20Guitar-Lead-Ela%20M%20251.0170.mp3',
|
66 |
+
'Bass Amp': INPUT_ROOT + 'real/content/HurrayForTheRiffRaff_LivingInTheCity_Hurray%20for%20the%20Riff%20Raff_Livin%20in%20the%20City_Bass-Amp-M82.0018.mp3',
|
67 |
+
'Bass Bip': INPUT_ROOT + 'real/style/RememberDecember_CUNextTime_RememberDecember_CUNextTime_Full_11_Bass_bip.041.mp3',
|
68 |
+
'SynthFX': INPUT_ROOT + 'real/content/MR0902_JamesElder_MR0902_JamesElder_Full_13_SynthFX1.163.mp3',
|
69 |
+
'Electric Guitar Close': INPUT_ROOT + 'real/style/Fergessen_TheWind_Fergessen_TheWind_Full_17_SlecGtr3a_Close.146.mp3',
|
70 |
+
'Rhodes NBATG': INPUT_ROOT + 'real/content/NickiBluhmAndTheGramblers_GoGoGo_NBATG%20-%20Rhodes%20-%20DI.098.mp3',
|
71 |
+
'Keys DI Grace': INPUT_ROOT + 'real/style/JessicaChildress_SlowDown_SD%20KEYS-DI-GRACE.147.mp3',
|
72 |
+
'Dulcimer': INPUT_ROOT + 'real/content/ButterflyEffect_PreachRightHere_ButterflyEffect_PreachRightHere_Full_16_Dulcimer2.076.mp3',
|
73 |
+
'Strings Section': INPUT_ROOT + 'real/style/AngeloBoltini_ThisTown_AngeloBoltini_ThisTown_Full_47_Strings_SectionMic_Vln2.0181.mp3',
|
74 |
+
'Mellotron': INPUT_ROOT + 'real/content/Triviul_Dorothy_Triviul_Dorothy_Full_07_Mellotron.120.mp3',
|
75 |
+
'Acoustic Guitar CU': INPUT_ROOT + 'real/style/UncleDad_WhoIAm_legend-strings_AC%20GUITAR-3-CU29-SHADOWHILL.R.0106.mp3',
|
76 |
+
'Fiddle': INPUT_ROOT + 'real/content/EndaReilly_CurAnLongAgSeol_EndaReilly_CurAnLongAgSeol_Full_10_Fiddle2.0163.mp3',
|
77 |
+
'Violins': INPUT_ROOT + 'real/style/ScottElliott_AeternumVale_ScottElliott_AeternumVale_Full_41_Violins.0138.mp3',
|
78 |
+
'Upright Bass': INPUT_ROOT + 'real/content/AbletonesBigBand_SongOfIndia_UPRIGHT%20BASS%20-%20ELA%20M%20260%20-%20Neve%2033102.136.mp3',
|
79 |
+
'Taiko': INPUT_ROOT + 'real/style/CarlosGonzalez_APlaceForUs_CarlosGonzalez_APlaceForUs_Full_21_Taiko.0115.mp3',
|
80 |
+
'Guitar 2': INPUT_ROOT + 'real/content/AllHandsLost_Ambitions_AllHandsLost_Ambitions_Full_Guitar%202.0292.mp3',
|
81 |
+
'Alto Sax': INPUT_ROOT + 'real/style/SunshineGarciaBand_ForIAmTheMoon_zip5-outro-uke-shaker_OUTRO%20ALTO-251E-SSL6000E.0290.mp3',
|
82 |
+
'Bass Close Mic': INPUT_ROOT + 'real/content/DonCamilloChoir_MarshMarigoldsSong_DonCamilloChoir_MarshMarigoldsSong_Full_08_BassCloseMic2.000.mp3',
|
83 |
+
'Electric Guitar Distorted': INPUT_ROOT + 'real/style/EnterTheHaggis_TwoBareHands_25.%20Jubilee%20Riots%20-%202%20Bar%20Hands_ELE%20Guitars-Ignater-M81.160.mp3',
|
84 |
+
'Bells': INPUT_ROOT + 'real/content/cryonicPAX_Melancholy_cryonicPAX_Melancholy_Full_10_Bells.0034.mp3',
|
85 |
+
'Bass Mic 647': INPUT_ROOT + 'real/style/KungFu_JoyRide_40.%20Kung%20Fu%20-%20Joy%20ride_Bass-Mic-647.0090.mp3',
|
86 |
+
}
|
87 |
+
|
88 |
+
# Separate content and style options based on URL paths
|
89 |
+
CONTENT_OPTIONS = [key for key in INPUT_URLS.keys() if any(word in INPUT_URLS[key] for word in ['content'])]
|
90 |
+
STYLE_OPTIONS = [key for key in INPUT_URLS.keys() if any(word in INPUT_URLS[key] for word in ['style'])]
|
91 |
+
|
92 |
+
# Add remaining items to both lists if they don't contain 'content' or 'style'
|
93 |
+
for key in INPUT_URLS.keys():
|
94 |
+
if key not in CONTENT_OPTIONS and key not in STYLE_OPTIONS:
|
95 |
+
CONTENT_OPTIONS.append(key)
|
96 |
+
STYLE_OPTIONS.append(key)
|
97 |
+
|
98 |
+
def load_audio_from_url(url, sr=None):
|
99 |
+
"""Load audio from URL by downloading to temporary file"""
|
100 |
+
response = requests.get(url)
|
101 |
+
with tempfile.NamedTemporaryFile(suffix='.mp3', delete=False) as tmp_file:
|
102 |
+
tmp_file.write(response.content)
|
103 |
+
tmp_file_path = tmp_file.name
|
104 |
+
|
105 |
+
audio, _ = librosa.load(tmp_file_path, sr=sr)
|
106 |
+
os.unlink(tmp_file_path)
|
107 |
+
return audio
|
108 |
+
|
109 |
+
def process_timbre_transfer(content_file, content_preset, style_file, style_preset, max_duration=8):
|
110 |
+
"""Process timbre transfer with uploaded files or presets"""
|
111 |
+
try:
|
112 |
+
# Load content audio (musical notes/melody to preserve)
|
113 |
+
if content_file is not None:
|
114 |
+
a_content, _ = librosa.load(content_file, sr=exp.sr)
|
115 |
+
else:
|
116 |
+
if content_preset and content_preset in INPUT_URLS:
|
117 |
+
a_content = load_audio_from_url(INPUT_URLS[content_preset], sr=exp.sr)
|
118 |
+
else:
|
119 |
+
return None, "Please upload a content file or select a content preset"
|
120 |
+
|
121 |
+
# Load style audio (timbre/texture to apply)
|
122 |
+
if style_file is not None:
|
123 |
+
a_style, _ = librosa.load(style_file, sr=exp.sr)
|
124 |
+
else:
|
125 |
+
if style_preset and style_preset in INPUT_URLS:
|
126 |
+
a_style = load_audio_from_url(INPUT_URLS[style_preset], sr=exp.sr)
|
127 |
+
else:
|
128 |
+
return None, "Please upload a style file or select a style preset"
|
129 |
+
|
130 |
+
# Limit duration to prevent memory issues
|
131 |
+
max_samples = int(max_duration * exp.sr)
|
132 |
+
if len(a_content) > max_samples:
|
133 |
+
a_content = a_content[:max_samples]
|
134 |
+
if len(a_style) > max_samples:
|
135 |
+
a_style = a_style[:max_samples]
|
136 |
+
|
137 |
+
# Preprocess: Convert audio to model input format
|
138 |
+
s_content = torch.as_tensor(exp.preprocess(a_content), device=exp.device)[None, :]
|
139 |
+
s_style = torch.as_tensor(exp.preprocess(a_style), device=exp.device)[None, :]
|
140 |
+
l_content, l_style = (torch.as_tensor([x.shape[2]], device=exp.device) for x in [s_content, s_style])
|
141 |
+
|
142 |
+
# Run model: Extract content features, extract style features, then recombine
|
143 |
+
with torch.no_grad():
|
144 |
+
s_output = exp.model(input_c=s_content, input_s=s_style,
|
145 |
+
length_c=l_content, length_s=l_style)
|
146 |
+
|
147 |
+
# Postprocess: Convert model output back to audio waveform
|
148 |
+
a_output = exp.postprocess(s_output.cpu().numpy()[0])
|
149 |
+
|
150 |
+
return (exp.sr, a_output), "Transfer completed successfully!"
|
151 |
+
|
152 |
+
except Exception as e:
|
153 |
+
return None, f"Error: {str(e)}"
|
154 |
+
|
155 |
+
# Create Gradio interface
|
156 |
+
with gr.Blocks(title="VQ-VAE Timbre Transfer", theme=gr.themes.Soft()) as demo:
|
157 |
+
gr.Markdown("""
|
158 |
+
# 🎵 VQ-VAE Timbre Transfer Demo
|
159 |
+
|
160 |
+
Transfer the timbre (tone/texture) from one audio source to another while preserving the musical content.
|
161 |
+
|
162 |
+
**Content**: Musical notes/melody that will be preserved
|
163 |
+
**Style**: Instrument timbre/texture that will be applied
|
164 |
+
|
165 |
+
### How It Works:
|
166 |
+
The model separates musical content from timbre, then recombines them. Some instrument combinations work better than others due to harmonic compatibility and spectral characteristics.
|
167 |
+
|
168 |
+
### Tips:
|
169 |
+
- Harmonic instruments (piano, guitar) often transfer well to each other
|
170 |
+
- Percussive to sustained transfers may sound less natural
|
171 |
+
- Try different combinations - unexpected results can be musically interesting!
|
172 |
+
""")
|
173 |
+
|
174 |
+
with gr.Row():
|
175 |
+
with gr.Column():
|
176 |
+
gr.Markdown("### 🎼 Content Audio")
|
177 |
+
content_file = gr.Audio(label="Upload Content Audio", type="filepath")
|
178 |
+
content_preset = gr.Dropdown(
|
179 |
+
choices=[""] + CONTENT_OPTIONS,
|
180 |
+
label="Or choose preset",
|
181 |
+
value=""
|
182 |
+
)
|
183 |
+
|
184 |
+
with gr.Column():
|
185 |
+
gr.Markdown("### 🎨 Style Audio")
|
186 |
+
style_file = gr.Audio(label="Upload Style Audio", type="filepath")
|
187 |
+
style_preset = gr.Dropdown(
|
188 |
+
choices=[""] + STYLE_OPTIONS,
|
189 |
+
label="Or choose preset",
|
190 |
+
value="Electric Guitar Close"
|
191 |
+
)
|
192 |
+
|
193 |
+
max_duration = gr.Slider(1, 15, value=8, step=1, label="Max Duration (seconds)")
|
194 |
+
|
195 |
+
process_btn = gr.Button("🚀 Transfer Timbre", variant="primary", size="lg")
|
196 |
+
|
197 |
+
with gr.Row():
|
198 |
+
output_audio = gr.Audio(label="🎵 Output Audio", interactive=False)
|
199 |
+
status_msg = gr.Textbox(label="Status", interactive=False, max_lines=3)
|
200 |
+
|
201 |
+
process_btn.click(
|
202 |
+
fn=process_timbre_transfer,
|
203 |
+
inputs=[content_file, content_preset, style_file, style_preset, max_duration],
|
204 |
+
outputs=[output_audio, status_msg]
|
205 |
+
)
|
206 |
+
|
207 |
+
gr.Markdown("""
|
208 |
+
### 🔧 Troubleshooting
|
209 |
+
- **Poor transfer quality?** Try different instrument combinations or adjust max duration
|
210 |
+
- **Audio doesn't load?** Check internet connection or try different presets
|
211 |
+
- **Processing slow?** Reduce max duration or try shorter audio clips
|
212 |
+
|
213 |
+
### 📖 Citation
|
214 |
+
Original work by Ondřej Cífka (InterDigital R&D and Télécom Paris, 2020).
|
215 |
+
Demo by Ali Dulaimi.
|
216 |
+
""")
|
217 |
+
|
218 |
+
if __name__ == "__main__":
|
219 |
+
demo.launch()
|