hjimjim
commited on
Commit
·
081442b
1
Parent(s):
3b38d19
model upload: reconstruct
Browse files- VAE.py +140 -0
- app.py +188 -2
- model.pth +3 -0
- requirements.txt +6 -0
- vae_model_all.pth +3 -0
VAE.py
ADDED
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
import torch.nn.functional as F
|
4 |
+
import torch.optim as optim
|
5 |
+
|
6 |
+
class VAE(nn.Module):
|
7 |
+
def __init__(self, input_dim, hidden_dim, latent_dim, num_styles=2):
|
8 |
+
super(VAE, self).__init__()
|
9 |
+
self.input_dim = input_dim
|
10 |
+
self.latent_dim = latent_dim
|
11 |
+
self.hidden_dim = hidden_dim
|
12 |
+
|
13 |
+
self.encode = Encoder(self.input_dim, self.hidden_dim, self.latent_dim)
|
14 |
+
self.decode = Decoder(self.latent_dim, self.hidden_dim, self.input_dim)
|
15 |
+
self.style_classifier = StyleClassifier(self.latent_dim, num_styles)
|
16 |
+
|
17 |
+
def reparameterize(self, mu, logvar):
|
18 |
+
std = torch.exp(0.5 * logvar)
|
19 |
+
eps = torch.randn_like(std)
|
20 |
+
return mu + eps * std
|
21 |
+
|
22 |
+
def forward(self, x, right=None, left=None, check=False):
|
23 |
+
mu, logvar, output = self.encode(x)
|
24 |
+
z = self.reparameterize(mu, logvar)
|
25 |
+
style_pred = self.style_classifier(z)
|
26 |
+
decod = self.decode(z, output)
|
27 |
+
return decod, mu, logvar, style_pred
|
28 |
+
|
29 |
+
class Encoder(nn.Module):
|
30 |
+
def __init__(self, input_dim, hidden_dim, latent_dim):
|
31 |
+
super(Encoder, self).__init__()
|
32 |
+
self.hidden_dim = hidden_dim
|
33 |
+
|
34 |
+
self.gru_piano_right = nn.GRU(input_dim, hidden_dim, batch_first=True)
|
35 |
+
self.gru_piano_left = nn.GRU(input_dim, hidden_dim, batch_first=True)
|
36 |
+
|
37 |
+
self.dense_layer = nn.Linear(hidden_dim * 2, hidden_dim, bias = True)
|
38 |
+
|
39 |
+
self.fc_mu = nn.Linear(hidden_dim, latent_dim, bias = True)
|
40 |
+
self.fc_logvar = nn.Linear(hidden_dim, latent_dim, bias = True)
|
41 |
+
|
42 |
+
def forward(self, x):
|
43 |
+
input_list = torch.chunk(x, 2, dim=1)
|
44 |
+
right_input = input_list[0] # torch.Size([Batch Size, Sequence length, input length])
|
45 |
+
left_input = input_list[1]
|
46 |
+
|
47 |
+
# initialize hidden state
|
48 |
+
h0 = torch.zeros(1, right_input.size(0), self.hidden_dim, device=right_input.device)
|
49 |
+
|
50 |
+
# Forward pass through GRU for each instrument
|
51 |
+
o_r, h_r = self.gru_piano_right(right_input, h0)
|
52 |
+
o_l, h_l = self.gru_piano_left(left_input, h0)
|
53 |
+
|
54 |
+
output = torch.cat((o_r, o_l), dim=1)
|
55 |
+
h = torch.cat((h_r[-1,], h_l[-1,]), dim=1)
|
56 |
+
|
57 |
+
h = self.dense_layer(h)
|
58 |
+
h = F.relu(h)
|
59 |
+
mu = self.fc_mu(h)
|
60 |
+
mu = F.relu(mu)
|
61 |
+
logvar = self.fc_logvar(h)
|
62 |
+
logvar = F.relu(logvar) + 1e-4
|
63 |
+
return mu, logvar, output
|
64 |
+
|
65 |
+
|
66 |
+
class Decoder(nn.Module):
|
67 |
+
def __init__(self, latent_dim, hidden_dim, output_dim):
|
68 |
+
super(Decoder, self).__init__()
|
69 |
+
self.latent_dim = latent_dim
|
70 |
+
self.output_dim = output_dim
|
71 |
+
|
72 |
+
self.latent_to_hidden = nn.Linear(latent_dim, latent_dim, bias = True)
|
73 |
+
|
74 |
+
self.piano_right_layer = nn.Linear(latent_dim, hidden_dim, bias = True)
|
75 |
+
self.piano_left_layer = nn.Linear(latent_dim, hidden_dim, bias = True)
|
76 |
+
|
77 |
+
self.r_layer = nn.Linear(hidden_dim, output_dim, bias = True)
|
78 |
+
self.l_layer = nn.Linear(hidden_dim, output_dim, bias = True)
|
79 |
+
|
80 |
+
self.gru_piano_right_cell = nn.GRUCell(output_dim, hidden_dim)
|
81 |
+
self.gru_piano_left_cell = nn.GRUCell(output_dim, hidden_dim)
|
82 |
+
|
83 |
+
|
84 |
+
self.fr_layer = nn.Linear(hidden_dim, output_dim, bias = True)
|
85 |
+
self.fl_layer = nn.Linear(hidden_dim , output_dim, bias = True)
|
86 |
+
|
87 |
+
def forward(self, z, output):
|
88 |
+
|
89 |
+
h = self.latent_to_hidden(z)
|
90 |
+
h = F.relu(h)
|
91 |
+
|
92 |
+
right = torch.split(output, 150, dim=1)[0]
|
93 |
+
left = torch.split(output, 150, dim=1)[1]
|
94 |
+
|
95 |
+
right = right.permute(1, 0, 2)
|
96 |
+
left = left.permute(1, 0, 2)
|
97 |
+
|
98 |
+
right = self.r_layer(right)
|
99 |
+
right = F.tanh(right)
|
100 |
+
left = self.l_layer(left)
|
101 |
+
left = F.tanh(left)
|
102 |
+
|
103 |
+
|
104 |
+
piano_hidden = self.piano_right_layer(h)
|
105 |
+
left_hidden = self.piano_left_layer(h)
|
106 |
+
|
107 |
+
right_outputs = []
|
108 |
+
left_outputs = []
|
109 |
+
|
110 |
+
for t in range(right.size(0)):
|
111 |
+
piano_hidden = self.gru_piano_right_cell(right[t] , piano_hidden)
|
112 |
+
left_hidden = self.gru_piano_left_cell(left[t], left_hidden)
|
113 |
+
|
114 |
+
right_outputs.append(piano_hidden.unsqueeze(1))
|
115 |
+
left_outputs.append(left_hidden.unsqueeze(1))
|
116 |
+
|
117 |
+
# print(right_outputs[0].shape)
|
118 |
+
right_outputs = torch.cat(right_outputs, dim=1)
|
119 |
+
left_outputs = torch.cat(left_outputs, dim=1)
|
120 |
+
|
121 |
+
right_outputs = self.fr_layer(right_outputs)
|
122 |
+
left_outputs = self.fl_layer(left_outputs)
|
123 |
+
|
124 |
+
right_outputs = F.sigmoid(right_outputs)
|
125 |
+
left_outputs = F.sigmoid(left_outputs)
|
126 |
+
|
127 |
+
output = torch.cat((right_outputs, left_outputs), dim=1)
|
128 |
+
|
129 |
+
return output
|
130 |
+
|
131 |
+
class StyleClassifier(nn.Module):
|
132 |
+
def __init__(self, latent_dim, num_styles):
|
133 |
+
super(StyleClassifier, self).__init__()
|
134 |
+
self.fc1 = nn.Linear(latent_dim, 128)
|
135 |
+
self.fc2 = nn.Linear(128, num_styles)
|
136 |
+
|
137 |
+
def forward(self, z):
|
138 |
+
x = F.relu(self.fc1(z))
|
139 |
+
x = self.fc2(x)
|
140 |
+
return F.softmax(x, dim=-1)
|
app.py
CHANGED
@@ -1,4 +1,190 @@
|
|
1 |
import streamlit as st
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
|
3 |
-
x = st.slider('Select a value')
|
4 |
-
st.write(x, 'squared is', x * x)
|
|
|
1 |
import streamlit as st
|
2 |
+
import torch
|
3 |
+
import numpy as np
|
4 |
+
import matplotlib.pyplot as plt
|
5 |
+
from pydub import AudioSegment
|
6 |
+
import pretty_midi as pm
|
7 |
+
from VAE import VAE
|
8 |
+
from midi2audio import FluidSynth
|
9 |
+
import pretty_midi as pm
|
10 |
+
|
11 |
+
|
12 |
+
# Define device
|
13 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
14 |
+
|
15 |
+
# Load VAE model
|
16 |
+
@st.cache_resource
|
17 |
+
def load_model():
|
18 |
+
vae = VAE(input_dim=76, hidden_dim=512, latent_dim=256)
|
19 |
+
vae.load_state_dict(torch.load("vae_model_all.pth", map_location=device))
|
20 |
+
vae = vae.to(device)
|
21 |
+
vae.eval()
|
22 |
+
return vae
|
23 |
+
|
24 |
+
# Function to process the uploaded MIDI file
|
25 |
+
def process_midi(file):
|
26 |
+
try:
|
27 |
+
mid = pm.PrettyMIDI(file)
|
28 |
+
fs = 10
|
29 |
+
hand_dict = {"right": None, "left": None}
|
30 |
+
pitch_list = []
|
31 |
+
|
32 |
+
for inst in mid.instruments:
|
33 |
+
if inst.program // 8 > 0:
|
34 |
+
continue
|
35 |
+
|
36 |
+
piano_roll = inst.get_piano_roll(times=np.arange(0, mid.get_end_time(), 1.0 / fs))
|
37 |
+
if np.sum(piano_roll) == 0:
|
38 |
+
continue
|
39 |
+
hand_pitch = np.where(piano_roll)
|
40 |
+
pitch_list.append(np.average(hand_pitch[0]))
|
41 |
+
|
42 |
+
if len(pitch_list) == 0:
|
43 |
+
st.error("No valid piano data found.")
|
44 |
+
return None, None
|
45 |
+
elif len(pitch_list) == 1:
|
46 |
+
hand_dict['right'] = mid.instruments[np.argmax(pitch_list)].get_piano_roll(times=np.arange(0, mid.get_end_time(), 1.0 / fs))
|
47 |
+
hand_dict['left'] = np.zeros_like(hand_dict['right'])
|
48 |
+
else:
|
49 |
+
hand_dict['right'] = mid.instruments[np.argmax(pitch_list)].get_piano_roll(times=np.arange(0, mid.get_end_time(), 1.0 / fs))
|
50 |
+
hand_dict['left'] = mid.instruments[np.argmin(pitch_list)].get_piano_roll(times=np.arange(0, mid.get_end_time(), 1.0 / fs))
|
51 |
+
|
52 |
+
pitch_start, pitch_stop, duration = 24, 100, 150
|
53 |
+
right_hand = hand_dict['right'][pitch_start:pitch_stop, 26 : 26 + duration]
|
54 |
+
left_hand = hand_dict['left'][pitch_start:pitch_stop, 26 : 26 + duration]
|
55 |
+
|
56 |
+
if np.sum(right_hand) == 0 or np.sum(left_hand) == 0:
|
57 |
+
st.error("Invalid data detected in MIDI file.")
|
58 |
+
return None, None
|
59 |
+
|
60 |
+
return right_hand, left_hand
|
61 |
+
except Exception as e:
|
62 |
+
st.error(f"Error processing MIDI: {e}")
|
63 |
+
return None, None
|
64 |
+
|
65 |
+
# Run the VAE model for reconstruction
|
66 |
+
def reconstruct(right, left, model):
|
67 |
+
right_tensor = torch.tensor(right, dtype=torch.float32).to(device)
|
68 |
+
left_tensor = torch.tensor(left, dtype=torch.float32).to(device)
|
69 |
+
|
70 |
+
input_tensor = torch.cat([right_tensor, left_tensor], dim=0)
|
71 |
+
input_tensor = input_tensor.unsqueeze(0)
|
72 |
+
|
73 |
+
print(input_tensor.shape)
|
74 |
+
with torch.no_grad():
|
75 |
+
recon_data, _, _, _ = model(input_tensor)
|
76 |
+
|
77 |
+
return recon_data.squeeze(0).cpu().numpy()
|
78 |
+
|
79 |
+
|
80 |
+
|
81 |
+
def midi_to_wav(midi_file, wav_file="output.wav", sound_font_path="soundfont.sf2", volume_increase_db=17):
|
82 |
+
fs = FluidSynth(sound_font_path)
|
83 |
+
fs.midi_to_audio(midi_file, wav_file)
|
84 |
+
|
85 |
+
audio = AudioSegment.from_wav(wav_file)
|
86 |
+
louder_audio = audio + volume_increase_db
|
87 |
+
|
88 |
+
louder_audio.export(wav_file, format="wav")
|
89 |
+
|
90 |
+
return wav_file
|
91 |
+
|
92 |
+
# Create a MIDI stream from piano roll data
|
93 |
+
def create_midi_from_piano_roll(right_hand, left_hand, fs=8):
|
94 |
+
pm_obj = pm.PrettyMIDI()
|
95 |
+
|
96 |
+
for hand_data in [right_hand, left_hand]:
|
97 |
+
instrument = pm.Instrument(program=0) # Acoustic Grand Piano
|
98 |
+
pm_obj.instruments.append(instrument)
|
99 |
+
|
100 |
+
for pitch, series in enumerate(hand_data):
|
101 |
+
start_time = None
|
102 |
+
threshold = 0.92 # Threshold for detecting note onset
|
103 |
+
|
104 |
+
for j in range(len(series) - 1):
|
105 |
+
if series[j] < threshold and series[j + 1] >= threshold:
|
106 |
+
start_time = j / fs
|
107 |
+
elif series[j] >= threshold and series[j + 1] < threshold and start_time is not None:
|
108 |
+
end_time = (j + 1) / fs
|
109 |
+
|
110 |
+
if start_time is not None and end_time is not None:
|
111 |
+
note = pm.Note(
|
112 |
+
velocity=100,
|
113 |
+
pitch=pitch + 24,
|
114 |
+
start=start_time,
|
115 |
+
end=end_time
|
116 |
+
)
|
117 |
+
instrument.notes.append(note)
|
118 |
+
start_time = None
|
119 |
+
|
120 |
+
if start_time is not None:
|
121 |
+
end_time = len(series) / fs
|
122 |
+
note = pm.Note(
|
123 |
+
velocity=100,
|
124 |
+
pitch=pitch + 24,
|
125 |
+
start=start_time,
|
126 |
+
end=end_time
|
127 |
+
)
|
128 |
+
instrument.notes.append(note)
|
129 |
+
|
130 |
+
return pm_obj
|
131 |
+
|
132 |
+
|
133 |
+
# Function to convert reconstructed data to MIDI files
|
134 |
+
def convert_to_midi(right_hand, left_hand, file_name="output.mid", fs=8):
|
135 |
+
midi_data = create_midi_from_piano_roll(right_hand, left_hand, fs=fs)
|
136 |
+
midi_data.write(file_name)
|
137 |
+
|
138 |
+
print(f"MIDI file saved to {file_name}")
|
139 |
+
return file_name
|
140 |
+
|
141 |
+
|
142 |
+
# Streamlit interface
|
143 |
+
st.title("GRU-VAE Reconstruction Demo")
|
144 |
+
model = load_model()
|
145 |
+
|
146 |
+
# File upload
|
147 |
+
uploaded_file = st.file_uploader("Upload a MIDI file", type=["mid", "midi"])
|
148 |
+
|
149 |
+
if uploaded_file is not None:
|
150 |
+
st.write("Processing MIDI file...")
|
151 |
+
right_hand, left_hand = process_midi(uploaded_file)
|
152 |
+
|
153 |
+
if right_hand is not None and left_hand is not None:
|
154 |
+
# Display original data
|
155 |
+
st.write("Original MIDI Data:")
|
156 |
+
fig, axs = plt.subplots(1, 2, figsize=(10, 4))
|
157 |
+
axs[0].imshow(right_hand, aspect='auto', cmap='gray')
|
158 |
+
axs[0].set_title("Right Hand")
|
159 |
+
axs[1].imshow(left_hand, aspect='auto', cmap='gray')
|
160 |
+
axs[1].set_title("Left Hand")
|
161 |
+
st.pyplot(fig)
|
162 |
+
|
163 |
+
# Reconstruction
|
164 |
+
recon_data = reconstruct(right_hand.T, left_hand.T, model)
|
165 |
+
recon_right = recon_data[:150].T
|
166 |
+
recon_left = recon_data[150:].T
|
167 |
+
|
168 |
+
# Display reconstructed data
|
169 |
+
st.write("Reconstructed MIDI Data:")
|
170 |
+
fig, axs = plt.subplots(1, 2, figsize=(10, 4))
|
171 |
+
axs[0].imshow(recon_right, aspect='auto', cmap='gray')
|
172 |
+
axs[0].set_title("Right Hand (Reconstructed)")
|
173 |
+
axs[1].imshow(recon_left, aspect='auto', cmap='gray')
|
174 |
+
axs[1].set_title("Left Hand (Reconstructed)")
|
175 |
+
st.pyplot(fig)
|
176 |
+
|
177 |
+
# Convert to MIDI and then to WAV for playback
|
178 |
+
original_midi = convert_to_midi(right_hand, left_hand, "original_output.mid", fs=8)
|
179 |
+
recon_midi = convert_to_midi(recon_right, recon_left, "reconstructed_output.mid", fs=8)
|
180 |
+
|
181 |
+
# Save and play audio
|
182 |
+
original_wav_path = midi_to_wav(original_midi, "original_output.wav")
|
183 |
+
recon_wav_path = midi_to_wav(recon_midi, "reconstructed_output.wav")
|
184 |
+
|
185 |
+
st.write("Original MIDI Playback:")
|
186 |
+
st.audio(original_wav_path, format='audio/wav')
|
187 |
+
|
188 |
+
st.write("Reconstructed MIDI Playback:")
|
189 |
+
st.audio(recon_wav_path, format='audio/wav')
|
190 |
|
|
|
|
model.pth
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:e4803ba1d3b9c224f953c8ffdcf812cb06d779b1875510dd095b6dba70a89f4d
|
3 |
+
size 19734966
|
requirements.txt
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
streamlit==1.16.0
|
2 |
+
torch==1.11.0
|
3 |
+
pretty_midi
|
4 |
+
midi2audio
|
5 |
+
scipy
|
6 |
+
pydub
|
vae_model_all.pth
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:6dc7a37ff6c61c8df10571a6cc008f5e110c5306526625315f09b4a94bd1fea7
|
3 |
+
size 19734966
|