Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1 +1,128 @@
|
|
| 1 |
-
#!/usr/bin/env python3
|
| 2 |
L = (dim - 1) * tau + 1
|
| 3 |
win = sliding_window_view(x, L)[:, ::tau]
|
| 4 |
return win[:, ::-1].copy()
|
| 5 |
"""
|
| 6 |
Returns list of raw PCA mode signals (time domain) of length same as input.
|
| 7 |
Each mode is a reconstructed time series from one singular vector.
|
| 8 |
"""
|
| 9 |
# Delay-embed
|
| 10 |
X = embed(x, dim, tau)
|
| 11 |
# Normalise rows
|
| 12 |
a = np.linalg.norm(X, axis=1) + 1e-9
|
| 13 |
Xv = X / a[:, None]
|
| 14 |
|
| 15 |
# Randomized SVD
|
| 16 |
U, S, Vt = randomized_svd(Xv, n_components=k, n_iter=5, random_state=0)
|
| 17 |
W = Vt # shape (k, dim)
|
| 18 |
|
| 19 |
# Project each mode back to original space
|
| 20 |
Y = Xv @ W.T # activations (T x k)
|
| 21 |
|
| 22 |
raw_modes = []
|
| 23 |
for i in range(k):
|
| 24 |
# Reconstruct this mode alone
|
| 25 |
mode_embedded = Y[:, i:i+1] @ W[i:i+1, :] # (T, dim)
|
| 26 |
mode_signal = np.real(mode_embedded[:, 0]) * a
|
| 27 |
raw_modes.append(mode_signal)
|
| 28 |
|
| 29 |
return raw_modes
|
| 30 |
if file is None:
|
| 31 |
raise gr.Error("Please upload an audio file.")
|
| 32 |
|
| 33 |
# Load and preprocess
|
| 34 |
try:
|
| 35 |
sig, fs = sf.read(file)
|
| 36 |
except Exception as e:
|
| 37 |
raise gr.Error(f"Failed to read: {e}")
|
| 38 |
|
| 39 |
if sig.ndim > 1:
|
| 40 |
sig = np.mean(sig, axis=1)
|
| 41 |
|
| 42 |
# Resample to 16 kHz for speed/consistency
|
| 43 |
target_sr = 16000
|
| 44 |
if fs != target_sr:
|
| 45 |
sig = signal.resample_poly(sig, target_sr, fs)
|
| 46 |
fs = target_sr
|
| 47 |
|
| 48 |
# Normalise
|
| 49 |
sig = sig / (np.max(np.abs(sig)) + 1e-9)
|
| 50 |
|
| 51 |
duration = len(sig) / fs
|
| 52 |
gr.Info(f"Processing {duration:.1f} sec song with dim={dim}, tau={tau}, k={k} ...")
|
| 53 |
|
| 54 |
# Extract raw modes
|
| 55 |
try:
|
| 56 |
raw_modes = extract_raw_modes(sig, dim=dim, tau=tau, k=k)
|
| 57 |
except Exception as e:
|
| 58 |
raise gr.Error(f"Extraction failed: {e}")
|
| 59 |
|
| 60 |
# Create ZIP with raw mode WAVs
|
| 61 |
temp_dir = tempfile.mkdtemp()
|
| 62 |
for i, mode in enumerate(raw_modes):
|
| 63 |
sf.write(os.path.join(temp_dir, f"raw_mode_{i:02d}.wav"), mode, fs)
|
| 64 |
|
| 65 |
zip_path = os.path.join(tempfile.gettempdir(), "raw_modes.zip")
|
| 66 |
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
|
| 67 |
for fname in os.listdir(temp_dir):
|
| 68 |
zf.write(os.path.join(temp_dir, fname), arcname=fname)
|
| 69 |
|
| 70 |
# Also preview the first raw mode (optional)
|
| 71 |
preview_audio = (fs, raw_modes[0])
|
| 72 |
return preview_audio, zip_path
|
| 73 |
gr.Markdown("""
|
| 74 |
# 🔧 Fast Raw Mode Extractor (GN‑v7, PCA only)
|
| 75 |
Upload your song → get raw Koopman/PCA modes as WAV files.
|
| 76 |
**No ICA, no plots – just the raw modes.**
|
| 77 |
These are the `raw_mode_XX.wav` files from the original GN‑v7.
|
| 78 |
""")
|
| 79 |
with gr.Row():
|
| 80 |
with gr.Column():
|
| 81 |
audio_in = gr.Audio(type="filepath", label="Your song (any length)")
|
| 82 |
dim_slider = gr.Slider(16, 64, value=32, step=2, label="Embedding dim (lower = faster)")
|
| 83 |
tau_slider = gr.Slider(1, 8, value=3, step=1, label="Delay tau")
|
| 84 |
k_slider = gr.Slider(2, 16, value=8, step=1, label="Number of raw modes (k)")
|
| 85 |
run_btn = gr.Button("Extract Raw Modes", variant="primary")
|
| 86 |
with gr.Column():
|
| 87 |
preview = gr.Audio(label="Preview of first raw mode", type="numpy")
|
| 88 |
zip_output = gr.File(label="📦 Download all raw modes (ZIP)")
|
| 89 |
|
| 90 |
run_btn.click(
|
| 91 |
fn=process_to_raw_modes,
|
| 92 |
inputs=[audio_in, dim_slider, tau_slider, k_slider],
|
| 93 |
outputs=[preview, zip_output]
|
| 94 |
)
|
| 95 |
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
L = (dim - 1) * tau + 1
|
| 2 |
win = sliding_window_view(x, L)[:, ::tau]
|
| 3 |
return win[:, ::-1].copy()
|
| 4 |
"""
|
| 5 |
Returns list of raw PCA mode signals (time domain) of length same as input.
|
| 6 |
Each mode is a reconstructed time series from one singular vector.
|
| 7 |
"""
|
| 8 |
# Delay-embed
|
| 9 |
X = embed(x, dim, tau)
|
| 10 |
# Normalise rows
|
| 11 |
a = np.linalg.norm(X, axis=1) + 1e-9
|
| 12 |
Xv = X / a[:, None]
|
| 13 |
|
| 14 |
# Randomized SVD
|
| 15 |
U, S, Vt = randomized_svd(Xv, n_components=k, n_iter=5, random_state=0)
|
| 16 |
W = Vt # shape (k, dim)
|
| 17 |
|
| 18 |
# Project each mode back to original space
|
| 19 |
Y = Xv @ W.T # activations (T x k)
|
| 20 |
|
| 21 |
raw_modes = []
|
| 22 |
for i in range(k):
|
| 23 |
# Reconstruct this mode alone
|
| 24 |
mode_embedded = Y[:, i:i+1] @ W[i:i+1, :] # (T, dim)
|
| 25 |
mode_signal = np.real(mode_embedded[:, 0]) * a
|
| 26 |
raw_modes.append(mode_signal)
|
| 27 |
|
| 28 |
return raw_modes
|
| 29 |
if file is None:
|
| 30 |
raise gr.Error("Please upload an audio file.")
|
| 31 |
|
| 32 |
# Load and preprocess
|
| 33 |
try:
|
| 34 |
sig, fs = sf.read(file)
|
| 35 |
except Exception as e:
|
| 36 |
raise gr.Error(f"Failed to read: {e}")
|
| 37 |
|
| 38 |
if sig.ndim > 1:
|
| 39 |
sig = np.mean(sig, axis=1)
|
| 40 |
|
| 41 |
# Resample to 16 kHz for speed/consistency
|
| 42 |
target_sr = 16000
|
| 43 |
if fs != target_sr:
|
| 44 |
sig = signal.resample_poly(sig, target_sr, fs)
|
| 45 |
fs = target_sr
|
| 46 |
|
| 47 |
# Normalise
|
| 48 |
sig = sig / (np.max(np.abs(sig)) + 1e-9)
|
| 49 |
|
| 50 |
duration = len(sig) / fs
|
| 51 |
gr.Info(f"Processing {duration:.1f} sec song with dim={dim}, tau={tau}, k={k} ...")
|
| 52 |
|
| 53 |
# Extract raw modes
|
| 54 |
try:
|
| 55 |
raw_modes = extract_raw_modes(sig, dim=dim, tau=tau, k=k)
|
| 56 |
except Exception as e:
|
| 57 |
raise gr.Error(f"Extraction failed: {e}")
|
| 58 |
|
| 59 |
# Create ZIP with raw mode WAVs
|
| 60 |
temp_dir = tempfile.mkdtemp()
|
| 61 |
for i, mode in enumerate(raw_modes):
|
| 62 |
sf.write(os.path.join(temp_dir, f"raw_mode_{i:02d}.wav"), mode, fs)
|
| 63 |
|
| 64 |
zip_path = os.path.join(tempfile.gettempdir(), "raw_modes.zip")
|
| 65 |
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
|
| 66 |
for fname in os.listdir(temp_dir):
|
| 67 |
zf.write(os.path.join(temp_dir, fname), arcname=fname)
|
| 68 |
|
| 69 |
# Also preview the first raw mode (optional)
|
| 70 |
preview_audio = (fs, raw_modes[0])
|
| 71 |
return preview_audio, zip_path
|
| 72 |
gr.Markdown("""
|
| 73 |
# 🔧 Fast Raw Mode Extractor (GN‑v7, PCA only)
|
| 74 |
Upload your song → get raw Koopman/PCA modes as WAV files.
|
| 75 |
**No ICA, no plots – just the raw modes.**
|
| 76 |
These are the `raw_mode_XX.wav` files from the original GN‑v7.
|
| 77 |
""")
|
| 78 |
with gr.Row():
|
| 79 |
with gr.Column():
|
| 80 |
audio_in = gr.Audio(type="filepath", label="Your song (any length)")
|
| 81 |
dim_slider = gr.Slider(16, 64, value=32, step=2, label="Embedding dim (lower = faster)")
|
| 82 |
tau_slider = gr.Slider(1, 8, value=3, step=1, label="Delay tau")
|
| 83 |
k_slider = gr.Slider(2, 16, value=8, step=1, label="Number of raw modes (k)")
|
| 84 |
run_btn = gr.Button("Extract Raw Modes", variant="primary")
|
| 85 |
with gr.Column():
|
| 86 |
preview = gr.Audio(label="Preview of first raw mode", type="numpy")
|
| 87 |
zip_output = gr.File(label="📦 Download all raw modes (ZIP)")
|
| 88 |
|
| 89 |
run_btn.click(
|
| 90 |
fn=process_to_raw_modes,
|
| 91 |
inputs=[audio_in, dim_slider, tau_slider, k_slider],
|
| 92 |
outputs=[preview, zip_output]
|
| 93 |
)
|
| 94 |
demo.launch()
|
| 95 |
+
#!/usr/bin/env python3
|
| 96 |
+
"""
|
| 97 |
+
GN‑v7 – Fast Raw Mode Extractor
|
| 98 |
+
================================
|
| 99 |
+
Extract raw Koopman (PCA) modes from any audio file.
|
| 100 |
+
No ICA, no plots – just the raw modes as WAV files.
|
| 101 |
+
"""
|
| 102 |
+
|
| 103 |
+
import os
|
| 104 |
+
import shutil
|
| 105 |
+
import tempfile
|
| 106 |
+
import zipfile
|
| 107 |
+
from typing import List
|
| 108 |
+
|
| 109 |
+
import gradio as gr
|
| 110 |
+
import numpy as np
|
| 111 |
+
from numpy.lib.stride_tricks import sliding_window_view
|
| 112 |
+
import scipy.signal as signal
|
| 113 |
+
from sklearn.utils.extmath import randomized_svd
|
| 114 |
+
import soundfile as sf
|
| 115 |
+
|
| 116 |
+
# ----------------------------------------------------------------------
|
| 117 |
+
# Fast embedding
|
| 118 |
+
# ----------------------------------------------------------------------
|
| 119 |
+
def embed(x: np.ndarray, dim: int, tau: int) -> np.ndarray:
|
| 120 |
+
L = (dim - 1) * tau + 1
|
| 121 |
+
win = sliding_window_view(x, L)[:, ::tau]
|
| 122 |
+
return win[:, ::-1].copy()
|
| 123 |
+
|
| 124 |
+
# ----------------------------------------------------------------------
|
| 125 |
+
# Fast raw mode extraction using randomized SVD
|
| 126 |
+
# ----------------------------------------------------------------------
|
| 127 |
+
def extract_raw_modes(x: np.ndarray, dim: int = 32, tau: int = 3, k: int = 8) -> List[np.ndarray]:
|
| 128 |
+
"""
|
| 129 |
+
Returns list of raw PCA mode signals (time domain) of length same as input.
|
| 130 |
+
Each mode is a reconstructed time series from one singular vector.
|
| 131 |
+
"""
|
| 132 |
+
X = embed(x, dim, tau)
|
| 133 |
+
a = np.linalg.norm(X, axis=1) + 1e-9
|
| 134 |
+
Xv = X / a[:, None]
|
| 135 |
+
|
| 136 |
+
U, S, Vt = randomized_svd(Xv, n_components=k, n_iter=5, random_state=0)
|
| 137 |
+
W = Vt # shape (k, dim)
|
| 138 |
+
|
| 139 |
+
Y = Xv @ W.T # activations (T x k)
|
| 140 |
+
|
| 141 |
+
raw_modes = []
|
| 142 |
+
for i in range(k):
|
| 143 |
+
mode_embedded = Y[:, i:i+1] @ W[i:i+1, :] # (T, dim)
|
| 144 |
+
mode_signal = np.real(mode_embedded[:, 0]) * a
|
| 145 |
+
raw_modes.append(mode_signal)
|
| 146 |
+
|
| 147 |
+
return raw_modes
|
| 148 |
+
|
| 149 |
+
# ----------------------------------------------------------------------
|
| 150 |
+
# Gradio interface
|
| 151 |
+
# ----------------------------------------------------------------------
|
| 152 |
+
def process_to_raw_modes(file, dim: int, tau: int, k: int):
|
| 153 |
+
if file is None:
|
| 154 |
+
raise gr.Error("Please upload an audio file.")
|
| 155 |
+
|
| 156 |
+
try:
|
| 157 |
+
sig, fs = sf.read(file)
|
| 158 |
+
except Exception as e:
|
| 159 |
+
raise gr.Error(f"Failed to read: {e}")
|
| 160 |
+
|
| 161 |
+
if sig.ndim > 1:
|
| 162 |
+
sig = np.mean(sig, axis=1)
|
| 163 |
+
|
| 164 |
+
target_sr = 16000
|
| 165 |
+
if fs != target_sr:
|
| 166 |
+
sig = signal.resample_poly(sig, target_sr, fs)
|
| 167 |
+
fs = target_sr
|
| 168 |
+
|
| 169 |
+
sig = sig / (np.max(np.abs(sig)) + 1e-9)
|
| 170 |
+
|
| 171 |
+
duration = len(sig) / fs
|
| 172 |
+
gr.Info(f"Processing {duration:.1f} sec song with dim={dim}, tau={tau}, k={k} ...")
|
| 173 |
+
|
| 174 |
+
try:
|
| 175 |
+
raw_modes = extract_raw_modes(sig, dim=dim, tau=tau, k=k)
|
| 176 |
+
except Exception as e:
|
| 177 |
+
raise gr.Error(f"Extraction failed: {e}")
|
| 178 |
+
|
| 179 |
+
temp_dir = tempfile.mkdtemp()
|
| 180 |
+
try:
|
| 181 |
+
for i, mode in enumerate(raw_modes):
|
| 182 |
+
sf.write(os.path.join(temp_dir, f"raw_mode_{i:02d}.wav"), mode, fs)
|
| 183 |
+
|
| 184 |
+
zip_path = os.path.join(tempfile.gettempdir(), "raw_modes.zip")
|
| 185 |
+
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
|
| 186 |
+
for fname in os.listdir(temp_dir):
|
| 187 |
+
zf.write(os.path.join(temp_dir, fname), arcname=fname)
|
| 188 |
+
finally:
|
| 189 |
+
shutil.rmtree(temp_dir, ignore_errors=True)
|
| 190 |
+
|
| 191 |
+
preview_audio = (fs, raw_modes[0])
|
| 192 |
+
return preview_audio, zip_path
|
| 193 |
+
|
| 194 |
+
# ----------------------------------------------------------------------
|
| 195 |
+
# UI
|
| 196 |
+
# ----------------------------------------------------------------------
|
| 197 |
+
with gr.Blocks(title="Fast Raw Mode Extractor", theme=gr.themes.Soft()) as demo:
|
| 198 |
+
gr.Markdown("""
|
| 199 |
+
# 🔧 Fast Raw Mode Extractor (GN‑v7, PCA only)
|
| 200 |
+
Upload your song → get raw Koopman/PCA modes as WAV files.
|
| 201 |
+
**No ICA, no plots – just the raw modes.**
|
| 202 |
+
These are the `raw_mode_XX.wav` files from the original GN‑v7.
|
| 203 |
+
""")
|
| 204 |
+
with gr.Row():
|
| 205 |
+
with gr.Column():
|
| 206 |
+
audio_in = gr.Audio(type="filepath", label="Your song (any length)")
|
| 207 |
+
dim_slider = gr.Slider(16, 64, value=32, step=2, label="Embedding dim (lower = faster)")
|
| 208 |
+
tau_slider = gr.Slider(1, 8, value=3, step=1, label="Delay tau")
|
| 209 |
+
k_slider = gr.Slider(2, 16, value=8, step=1, label="Number of raw modes (k)")
|
| 210 |
+
run_btn = gr.Button("Extract Raw Modes", variant="primary")
|
| 211 |
+
with gr.Column():
|
| 212 |
+
preview = gr.Audio(label="Preview of first raw mode", type="numpy")
|
| 213 |
+
zip_output = gr.File(label="📦 Download all raw modes (ZIP)")
|
| 214 |
+
|
| 215 |
+
run_btn.click(
|
| 216 |
+
fn=process_to_raw_modes,
|
| 217 |
+
inputs=[audio_in, dim_slider, tau_slider, k_slider],
|
| 218 |
+
outputs=[preview, zip_output]
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
if __name__ == "__main__":
|
| 222 |
+
demo.launch(ssr_mode=False, server_name="0.0.0.0", server_port=7860)
|