Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,15 +1,17 @@
|
|
| 1 |
"""
|
| 2 |
Gradio app for classical music generation with a grid-based Transformer.
|
| 3 |
-
|
| 4 |
-
|
| 5 |
"""
|
| 6 |
|
| 7 |
import os
|
|
|
|
| 8 |
import tempfile
|
| 9 |
-
import math
|
| 10 |
from typing import Tuple
|
| 11 |
import gradio as gr
|
| 12 |
import numpy as np
|
|
|
|
|
|
|
| 13 |
from scipy.io import wavfile
|
| 14 |
|
| 15 |
import config
|
|
@@ -21,168 +23,155 @@ from inference import generate_midi_file
|
|
| 21 |
_MELODIC_NOTE_NAMES = ["C4","C#4","D4","D#4","E4","F4","F#4","G4","G#4","A4","A#4","B4"]
|
| 22 |
_PERC_NOTE_NAMES = ["Kick", "Snare", "Hi-hat"]
|
| 23 |
|
| 24 |
-
#
|
| 25 |
-
|
| 26 |
.instrument-container {
|
| 27 |
background-color: #151b26 !important;
|
| 28 |
border: 1px solid rgba(255, 255, 255, 0.05) !important;
|
| 29 |
padding: 14px !important;
|
| 30 |
border-radius: 8px !important;
|
|
|
|
| 31 |
}
|
| 32 |
-
.
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
}
|
| 38 |
.grid-label {
|
| 39 |
font-family: monospace !important;
|
| 40 |
font-size: 11px !important;
|
| 41 |
font-weight: bold !important;
|
| 42 |
-
color: #
|
|
|
|
| 43 |
text-align: right;
|
| 44 |
-
|
| 45 |
-
|
| 46 |
}
|
| 47 |
-
.
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
margin: 0 !important;
|
| 52 |
-
border-radius: 2px !important;
|
| 53 |
-
font-size: 14px !important;
|
| 54 |
-
font-weight: bold !important;
|
| 55 |
-
cursor: pointer !important;
|
| 56 |
-
background: #111827 !important;
|
| 57 |
-
border: 1px solid rgba(255, 255, 255, 0.02) !important;
|
| 58 |
}
|
| 59 |
-
.
|
| 60 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
}
|
| 62 |
-
.
|
| 63 |
-
background
|
| 64 |
-
border: 1px solid rgba(99, 179, 237, 0.2) !important;
|
| 65 |
-
padding: 12px !important;
|
| 66 |
-
border-radius: 6px !important;
|
| 67 |
}
|
| 68 |
-
.
|
| 69 |
-
|
| 70 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
"""
|
| 72 |
|
| 73 |
-
# Client
|
| 74 |
-
|
| 75 |
-
(
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
if (
|
| 81 |
-
|
| 82 |
-
let now =
|
| 83 |
-
let gainNode =
|
| 84 |
-
gainNode.connect(
|
| 85 |
|
| 86 |
-
if (
|
| 87 |
-
let
|
| 88 |
-
let buffer =
|
| 89 |
let data = buffer.getChannelData(0);
|
| 90 |
-
for
|
| 91 |
-
|
| 92 |
-
let
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
source.connect(filter); filter.connect(gainNode);
|
| 100 |
-
source.start(now); source.stop(now + 0.12);
|
| 101 |
} else {
|
| 102 |
-
let
|
| 103 |
-
let
|
| 104 |
-
|
| 105 |
-
let osc = ctx.createOscillator();
|
| 106 |
-
osc.type = 'triangle';
|
| 107 |
osc.frequency.setValueAtTime(freq, now);
|
| 108 |
-
|
| 109 |
-
gainNode.gain.
|
| 110 |
-
gainNode.gain.exponentialRampToValueAtTime(0.001, now + 0.3);
|
| 111 |
-
|
| 112 |
osc.connect(gainNode);
|
| 113 |
-
osc.start(now); osc.stop(now + 0.
|
| 114 |
}
|
| 115 |
-
}
|
| 116 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
}
|
| 118 |
"""
|
| 119 |
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
end_idx = start_idx + int(dur_sec * sr)
|
| 140 |
-
if start_idx >= len(audio_buffer): return
|
| 141 |
-
end_idx = min(end_idx, len(audio_buffer))
|
| 142 |
-
t = torch.arange(0, (end_idx - start_idx) / sr, 1/sr)[:end_idx - start_idx].numpy()
|
| 143 |
-
|
| 144 |
-
if is_drum:
|
| 145 |
-
# White noise synthesis profile
|
| 146 |
-
wave = np.random.normal(0, 1, size=len(t)) * np.exp(-t * 25.0) * vol
|
| 147 |
-
else:
|
| 148 |
-
# Smooth organic triangle wave configuration profiles
|
| 149 |
-
wave = (2.0 / np.pi) * np.arcsin(np.sin(2 * np.pi * freq * t)) * np.exp(-t * 3.0) * vol
|
| 150 |
-
|
| 151 |
-
audio_buffer[start_idx:end_idx] += wave
|
| 152 |
-
|
| 153 |
-
# Compute active timeline events using global step parsing matrices
|
| 154 |
-
current_time = 0.0
|
| 155 |
-
active_notes = {}
|
| 156 |
-
|
| 157 |
-
for track in mid.tracks:
|
| 158 |
-
current_time = 0.0
|
| 159 |
-
for msg in track:
|
| 160 |
-
current_time += msg.time * (mid.ticks_per_beat * (600000 / 120) / 100000000.0) # Adaptive fallback parser clock alignment index values
|
| 161 |
-
if msg.type == 'note_on' and msg.velocity > 0:
|
| 162 |
-
active_notes[msg.note] = current_time
|
| 163 |
-
elif msg.type in ['note_off', 'note_on'] and msg.note in active_notes:
|
| 164 |
-
start_t = active_notes.pop(msg.note)
|
| 165 |
-
duration = max(current_time - start_t, 0.05)
|
| 166 |
-
is_drum = (msg.channel == 9)
|
| 167 |
-
frequency = 440.0 * (2.0 ** ((msg.note - 69) / 12.0))
|
| 168 |
-
add_tone(frequency, start_t, duration, is_drum=is_drum)
|
| 169 |
-
|
| 170 |
-
# Normalize audio track and execute float bit operations smoothly
|
| 171 |
-
max_val = np.max(np.abs(audio_buffer))
|
| 172 |
-
if max_val > 0:
|
| 173 |
-
audio_buffer = audio_buffer / max_val
|
| 174 |
-
wavfile.write(out_wav_path, sr, (audio_buffer * 32767).astype(np.int16))
|
| 175 |
-
except Exception as e:
|
| 176 |
-
print(f"System Synthesizer Engine Fallback Activated: {e}")
|
| 177 |
-
# Build safety tone buffer mapping configurations inside server errors
|
| 178 |
-
wavfile.write(out_wav_path, 22050, np.zeros(22050, dtype=np.int16))
|
| 179 |
|
| 180 |
# ==============================================================================
|
| 181 |
-
# Pipeline
|
| 182 |
# ==============================================================================
|
| 183 |
|
| 184 |
-
def
|
| 185 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 186 |
tmpdir = tempfile.mkdtemp()
|
| 187 |
midi_path = os.path.join(tmpdir, "generated.mid")
|
| 188 |
audio_path = os.path.join(tmpdir, "generated.wav")
|
|
@@ -202,50 +191,44 @@ def generate(strings, woodwinds, brass, perc, length, temp, tk, lead):
|
|
| 202 |
target_minutes=length, temperature=temp, top_k=int(tk),
|
| 203 |
midi_out_path=midi_path, device="cpu", primary_family=lead
|
| 204 |
)
|
| 205 |
-
|
| 206 |
-
# Process audio generation via our standalone wave synthesis engine
|
| 207 |
-
render_composition_to_audio(midi_path, audio_path)
|
| 208 |
-
return midi_path, (audio_path if os.path.exists(audio_path) else None)
|
| 209 |
-
|
| 210 |
-
# ==============================================================================
|
| 211 |
-
# Interactive Runtime State Logic
|
| 212 |
-
# ==============================================================================
|
| 213 |
-
|
| 214 |
-
def toggle_cell_state(flat_grid, r, c, max_rows, family):
|
| 215 |
-
"""Toggles state values natively, utilizing string assignments to fix highlight breaks."""
|
| 216 |
-
idx = (r * config.INPUT_STEPS) + c
|
| 217 |
-
current_value = flat_grid[idx]
|
| 218 |
-
new_value = 1 if current_value == 0 else 0
|
| 219 |
-
flat_grid[idx] = new_value
|
| 220 |
|
| 221 |
-
#
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 232 |
|
| 233 |
-
|
| 234 |
-
"""Clears a whole family block instantly by resetting button label texts."""
|
| 235 |
-
blank = [0] * (max_rows * config.INPUT_STEPS)
|
| 236 |
-
updates = []
|
| 237 |
-
for r in range(max_rows):
|
| 238 |
-
for c in range(config.INPUT_STEPS):
|
| 239 |
-
updates.append(gr.update(value=""))
|
| 240 |
-
return [blank] + updates
|
| 241 |
|
| 242 |
# ==============================================================================
|
| 243 |
-
# UI
|
| 244 |
# ==============================================================================
|
| 245 |
|
| 246 |
-
with gr.Blocks(title="Classical Music Grid Generator"
|
| 247 |
|
| 248 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 249 |
|
| 250 |
gr.HTML("""
|
| 251 |
<div style="text-align:center; padding:15px 0;">
|
|
@@ -253,7 +236,7 @@ with gr.Blocks(title="Classical Music Grid Generator", css=CSS_ESTHETIC) as demo
|
|
| 253 |
🎼 Classical Music Grid Generator
|
| 254 |
</h1>
|
| 255 |
<p style="color:#8892aa; font-size:14px; max-width:650px; margin:0 auto;">
|
| 256 |
-
Click
|
| 257 |
</p>
|
| 258 |
</div>
|
| 259 |
""")
|
|
@@ -262,153 +245,38 @@ with gr.Blocks(title="Classical Music Grid Generator", css=CSS_ESTHETIC) as demo
|
|
| 262 |
gr.HTML("""
|
| 263 |
<div style="display:grid; grid-template-columns:repeat(auto-fit,minmax(220px,1fr)); gap:12px; padding:6px 0;">
|
| 264 |
<div style="background:rgba(99,179,237,0.06); border:1px solid rgba(99,179,237,0.2); border-radius:8px; padding:12px;">
|
| 265 |
-
<strong style="color:#63b3ed;">1.
|
| 266 |
<p style="color:#8892aa; font-size:12px; margin:4px 0 0; line-height:1.4;">
|
| 267 |
-
Click
|
| 268 |
-
</p>
|
| 269 |
-
</div>
|
| 270 |
-
<div style="background:rgba(110,210,155,0.06); border:1px solid rgba(110,210,155,0.2); border-radius:8px; padding:12px;">
|
| 271 |
-
<strong style="color:#6ed29b;">2. Coordinate Inspection HUD</strong>
|
| 272 |
-
<p style="color:#8892aa; font-size:12px; margin:4px 0 0; line-height:1.4;">
|
| 273 |
-
Look at the live <strong>Active Selection HUD</strong> panel on the right after any click to inspect precisely which note and step index value was changed.
|
| 274 |
</p>
|
| 275 |
</div>
|
| 276 |
<div style="background:rgba(252,129,74,0.06); border:1px solid rgba(252,129,74,0.2); border-radius:8px; padding:12px;">
|
| 277 |
-
<strong style="color:#fc814a;">
|
| 278 |
<p style="color:#8892aa; font-size:12px; margin:4px 0 0; line-height:1.4;">
|
| 279 |
-
Adjust
|
| 280 |
</p>
|
| 281 |
</div>
|
| 282 |
</div>
|
| 283 |
""")
|
| 284 |
|
| 285 |
-
|
| 286 |
-
woodwinds_state = gr.State([0] * (config.PITCHES_MELODIC * config.INPUT_STEPS))
|
| 287 |
-
brass_state = gr.State([0] * (config.PITCHES_MELODIC * config.INPUT_STEPS))
|
| 288 |
-
perc_state = gr.State([0] * (config.PITCHES_PERC * config.INPUT_STEPS))
|
| 289 |
-
|
| 290 |
with gr.Row():
|
| 291 |
-
# --- LEFT PANEL COLUMN: INSTRUMENT MATRIX SLOTS ---
|
| 292 |
-
with gr.Column(scale=4):
|
| 293 |
-
|
| 294 |
-
# --- STRINGS DECK ---
|
| 295 |
-
with gr.Column(elem_classes="instrument-container strings-deck-wrapper"):
|
| 296 |
-
gr.HTML("<div style='color:#63b3ed; font-weight:bold; font-size:13px; margin-bottom:6px;'>🎻 Strings Family (All 3 Bars)</div>")
|
| 297 |
-
s_buttons = []
|
| 298 |
-
for r in reversed(range(config.PITCHES_MELODIC)):
|
| 299 |
-
with gr.Row():
|
| 300 |
-
with gr.Column(min_width=40, scale=0):
|
| 301 |
-
gr.HTML(f"<div class='grid-label'>{_MELODIC_NOTE_NAMES[r]}</div>")
|
| 302 |
-
for c in range(config.INPUT_STEPS):
|
| 303 |
-
cls = "matrix-cell"
|
| 304 |
-
if c > 0 and c % config.STEPS_PER_BAR == 0:
|
| 305 |
-
cls += " bar-line-left"
|
| 306 |
-
btn = gr.Button("", elem_classes=[cls], min_width=15)
|
| 307 |
-
s_buttons.append((btn, r, c))
|
| 308 |
-
s_clear = gr.Button("🗑️ Clear Strings", size="sm", elem_classes=["instrument-margin-button"])
|
| 309 |
-
|
| 310 |
-
# --- WOODWINDS DECK ---
|
| 311 |
-
with gr.Column(elem_classes="instrument-container instrument-margin woodwinds-deck-wrapper"):
|
| 312 |
-
gr.HTML("<div style='color:#6ed29b; font-weight:bold; font-size:13px; margin-bottom:6px;'>🪵 Woodwinds Family (All 3 Bars)</div>")
|
| 313 |
-
w_buttons = []
|
| 314 |
-
for r in reversed(range(config.PITCHES_MELODIC)):
|
| 315 |
-
with gr.Row():
|
| 316 |
-
with gr.Column(min_width=40, scale=0):
|
| 317 |
-
gr.HTML(f"<div class='grid-label'>{_MELODIC_NOTE_NAMES[r]}</div>")
|
| 318 |
-
for c in range(config.INPUT_STEPS):
|
| 319 |
-
cls = "matrix-cell"
|
| 320 |
-
if c > 0 and c % config.STEPS_PER_BAR == 0:
|
| 321 |
-
cls += " bar-line-left"
|
| 322 |
-
btn = gr.Button("", elem_classes=[cls], min_width=15)
|
| 323 |
-
w_buttons.append((btn, r, c))
|
| 324 |
-
w_clear = gr.Button("🗑️ Clear Woodwinds", size="sm", elem_classes=["instrument-margin-button"])
|
| 325 |
-
|
| 326 |
-
# --- BRASS DECK ---
|
| 327 |
-
with gr.Column(elem_classes="instrument-container instrument-margin brass-deck-wrapper"):
|
| 328 |
-
gr.HTML("<div style='color:#fbbf24; font-weight:bold; font-size:13px; margin-bottom:6px;'>🎺 Brass Family (All 3 Bars)</div>")
|
| 329 |
-
b_buttons = []
|
| 330 |
-
for r in reversed(range(config.PITCHES_MELODIC)):
|
| 331 |
-
with gr.Row():
|
| 332 |
-
with gr.Column(min_width=40, scale=0):
|
| 333 |
-
gr.HTML(f"<div class='grid-label'>{_MELODIC_NOTE_NAMES[r]}</div>")
|
| 334 |
-
for c in range(config.INPUT_STEPS):
|
| 335 |
-
cls = "matrix-cell"
|
| 336 |
-
if c > 0 and c % config.STEPS_PER_BAR == 0:
|
| 337 |
-
cls += " bar-line-left"
|
| 338 |
-
btn = gr.Button("", elem_classes=[cls], min_width=15)
|
| 339 |
-
b_buttons.append((btn, r, c))
|
| 340 |
-
b_clear = gr.Button("🗑️ Clear Brass", size="sm", elem_classes=["instrument-margin-button"])
|
| 341 |
-
|
| 342 |
-
# --- PERCUSSION DECK ---
|
| 343 |
-
with gr.Column(elem_classes="instrument-container instrument-margin perc-deck-wrapper"):
|
| 344 |
-
gr.HTML("<div style='color:#fc814a; font-weight:bold; font-size:13px; margin-bottom:6px;'>🥁 Percussion Grid (All 3 Bars)</div>")
|
| 345 |
-
p_buttons = []
|
| 346 |
-
for r in reversed(range(config.PITCHES_PERC)):
|
| 347 |
-
with gr.Row():
|
| 348 |
-
with gr.Column(min_width=40, scale=0):
|
| 349 |
-
gr.HTML(f"<div class='grid-label'>{_PERC_NOTE_NAMES[r]}</div>")
|
| 350 |
-
for c in range(config.INPUT_STEPS):
|
| 351 |
-
cls = "matrix-cell"
|
| 352 |
-
if c > 0 and c % config.STEPS_PER_BAR == 0:
|
| 353 |
-
cls += " bar-line-left"
|
| 354 |
-
btn = gr.Button("", elem_classes=[cls], min_width=15)
|
| 355 |
-
p_buttons.append((btn, r, c))
|
| 356 |
-
p_clear = gr.Button("🗑️ Clear Percussion", size="sm", elem_classes=["instrument-margin-button"])
|
| 357 |
-
|
| 358 |
-
# --- RIGHT PANEL COLUMN: ACTIVE SELECTION INSPECTION HUD ---
|
| 359 |
with gr.Column(scale=1):
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
# ==============================================================================
|
| 366 |
-
|
| 367 |
-
# Strings Action Pipeline Mapping
|
| 368 |
-
for btn, r, c in s_buttons:
|
| 369 |
-
btn.click(
|
| 370 |
-
fn=lambda grid, row=r, col=c: toggle_cell_state(grid, row, col, config.PITCHES_MELODIC, "strings"),
|
| 371 |
-
inputs=[strings_state], outputs=[strings_state, btn, hud_display]
|
| 372 |
-
).then(fn=None, inputs=[gr.State(r), gr.State(0)], outputs=None, js="window.jsAudioEngine")
|
| 373 |
-
s_clear.click(fn=lambda: clear_family_grid(config.PITCHES_MELODIC), inputs=None, outputs=[strings_state] + [b for b,_,_ in s_buttons])
|
| 374 |
-
|
| 375 |
-
# Woodwinds Action Pipeline Mapping
|
| 376 |
-
for btn, r, c in w_buttons:
|
| 377 |
-
btn.click(
|
| 378 |
-
fn=lambda grid, row=r, col=c: toggle_cell_state(grid, row, col, config.PITCHES_MELODIC, "woodwinds"),
|
| 379 |
-
inputs=[woodwinds_state], outputs=[woodwinds_state, btn, hud_display]
|
| 380 |
-
).then(fn=None, inputs=[gr.State(r), gr.State(0)], outputs=None, js="window.jsAudioEngine")
|
| 381 |
-
w_clear.click(fn=lambda: clear_family_grid(config.PITCHES_MELODIC), inputs=None, outputs=[woodwinds_state] + [b for b,_,_ in w_buttons])
|
| 382 |
-
|
| 383 |
-
# Brass Action Pipeline Mapping
|
| 384 |
-
for btn, r, c in b_buttons:
|
| 385 |
-
btn.click(
|
| 386 |
-
fn=lambda grid, row=r, col=c: toggle_cell_state(grid, row, col, config.PITCHES_MELODIC, "brass"),
|
| 387 |
-
inputs=[brass_state], outputs=[brass_state, btn, hud_display]
|
| 388 |
-
).then(fn=None, inputs=[gr.State(r), gr.State(0)], outputs=None, js="window.jsAudioEngine")
|
| 389 |
-
b_clear.click(fn=lambda: clear_family_grid(config.PITCHES_MELODIC), inputs=None, outputs=[brass_state] + [b for b,_,_ in b_buttons])
|
| 390 |
-
|
| 391 |
-
# Percussion Action Pipeline Mapping
|
| 392 |
-
for btn, r, c in p_buttons:
|
| 393 |
-
btn.click(
|
| 394 |
-
fn=lambda grid, row=r, col=c: toggle_cell_state(grid, row, col, config.PITCHES_PERC, "perc"),
|
| 395 |
-
inputs=[perc_state], outputs=[perc_state, btn, hud_display]
|
| 396 |
-
).then(fn=None, inputs=[gr.State(r), gr.State(1)], outputs=None, js="window.jsAudioEngine")
|
| 397 |
-
p_clear.click(fn=lambda: clear_family_grid(config.PITCHES_PERC), inputs=None, outputs=[perc_state] + [b for b,_,_ in p_buttons])
|
| 398 |
|
| 399 |
-
#
|
| 400 |
-
# Global Parameters & Output Management
|
| 401 |
-
# ==============================================================================
|
| 402 |
-
gr.HTML("<div style='margin-top:20px; border-bottom:1px solid rgba(255,255,255,0.08);'></div>")
|
| 403 |
-
|
| 404 |
with gr.Row():
|
| 405 |
with gr.Column(scale=3):
|
| 406 |
with gr.Row():
|
| 407 |
-
target_minutes = gr.Slider(minimum=1.0, maximum=5.0, value=2.0, step=0.5, label="
|
| 408 |
-
temperature = gr.Slider(minimum=0.7, maximum=1.3, value=1.0, step=0.05, label="
|
| 409 |
with gr.Row():
|
| 410 |
-
top_k = gr.Slider(minimum=2, maximum=12, value=6, step=1, label="
|
| 411 |
-
primary_family = gr.Dropdown(choices=["strings", "woodwinds", "brass"], value="strings", label="
|
| 412 |
|
| 413 |
generate_button = gr.Button("🎵 Execute Transformer Music Generation Pipeline", variant="primary")
|
| 414 |
|
|
@@ -416,14 +284,21 @@ with gr.Blocks(title="Classical Music Grid Generator", css=CSS_ESTHETIC) as demo
|
|
| 416 |
audio_output = gr.Audio(label="🔊 Fluidsynth Generated Audio Player (Listen Live)", type="filepath")
|
| 417 |
midi_output = gr.File(label="⬇ Download Output Standard MIDI File (.mid)")
|
| 418 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 419 |
generate_button.click(
|
| 420 |
-
fn=
|
| 421 |
-
inputs=[
|
| 422 |
-
strings_state, woodwinds_state, brass_state, perc_state,
|
| 423 |
-
target_minutes, temperature, top_k, primary_family
|
| 424 |
-
],
|
| 425 |
outputs=[midi_output, audio_output]
|
| 426 |
)
|
| 427 |
|
|
|
|
|
|
|
|
|
|
| 428 |
if __name__ == "__main__":
|
| 429 |
demo.launch()
|
|
|
|
| 1 |
"""
|
| 2 |
Gradio app for classical music generation with a grid-based Transformer.
|
| 3 |
+
Implements custom pure HTML/JS matrix toggling and inline Fluidsynth
|
| 4 |
+
buffer rendering matching standard cross-platform streaming specifications.
|
| 5 |
"""
|
| 6 |
|
| 7 |
import os
|
| 8 |
+
import json
|
| 9 |
import tempfile
|
|
|
|
| 10 |
from typing import Tuple
|
| 11 |
import gradio as gr
|
| 12 |
import numpy as np
|
| 13 |
+
import fluidsynth
|
| 14 |
+
import pretty_midi
|
| 15 |
from scipy.io import wavfile
|
| 16 |
|
| 17 |
import config
|
|
|
|
| 23 |
_MELODIC_NOTE_NAMES = ["C4","C#4","D4","D#4","E4","F4","F#4","G4","G#4","A4","A#4","B4"]
|
| 24 |
_PERC_NOTE_NAMES = ["Kick", "Snare", "Hi-hat"]
|
| 25 |
|
| 26 |
+
# Custom CSS for high-fidelity dark studio layout highlights
|
| 27 |
+
CUSTOM_DAW_CSS = """
|
| 28 |
.instrument-container {
|
| 29 |
background-color: #151b26 !important;
|
| 30 |
border: 1px solid rgba(255, 255, 255, 0.05) !important;
|
| 31 |
padding: 14px !important;
|
| 32 |
border-radius: 8px !important;
|
| 33 |
+
margin-bottom: 15px;
|
| 34 |
}
|
| 35 |
+
.matrix-row-layout {
|
| 36 |
+
display: flex;
|
| 37 |
+
gap: 0px;
|
| 38 |
+
margin-bottom: 2px;
|
| 39 |
+
align-items: center;
|
| 40 |
}
|
| 41 |
.grid-label {
|
| 42 |
font-family: monospace !important;
|
| 43 |
font-size: 11px !important;
|
| 44 |
font-weight: bold !important;
|
| 45 |
+
color: #8892aa !important;
|
| 46 |
+
width: 50px;
|
| 47 |
text-align: right;
|
| 48 |
+
padding-right: 8px;
|
| 49 |
+
box-sizing: border-box;
|
| 50 |
}
|
| 51 |
+
.cells-container {
|
| 52 |
+
display: flex;
|
| 53 |
+
flex: 1;
|
| 54 |
+
gap: 2px;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
}
|
| 56 |
+
.matrix-btn {
|
| 57 |
+
flex: 1;
|
| 58 |
+
height: 24px;
|
| 59 |
+
border: 1px solid rgba(255,255,255,0.03);
|
| 60 |
+
border-radius: 2px;
|
| 61 |
+
cursor: pointer;
|
| 62 |
+
background: #111827;
|
| 63 |
+
transition: all 0.1s;
|
| 64 |
+
padding: 0 !important;
|
| 65 |
}
|
| 66 |
+
.matrix-btn:hover {
|
| 67 |
+
background: rgba(255,255,255,0.08);
|
|
|
|
|
|
|
|
|
|
| 68 |
}
|
| 69 |
+
.matrix-btn.bar-line {
|
| 70 |
+
border-left: 2px solid rgba(255, 255, 255, 0.25);
|
| 71 |
}
|
| 72 |
+
|
| 73 |
+
/* Explicit Color Highlights applied using the custom selection token classes */
|
| 74 |
+
.matrix-btn.selected.strings { background-color: #63b3ed !important; box-shadow: inset 0 0 4px #fff !important; }
|
| 75 |
+
.matrix-btn.selected.woodwinds { background-color: #6ed29b !important; box-shadow: inset 0 0 4px #fff !important; }
|
| 76 |
+
.matrix-btn.selected.brass { background-color: #fbbf24 !important; box-shadow: inset 0 0 4px #fff !important; }
|
| 77 |
+
.matrix-btn.selected.perc { background-color: #fc814a !important; box-shadow: inset 0 0 4px #fff !important; }
|
| 78 |
"""
|
| 79 |
|
| 80 |
+
# Client-side Web Audio synthesis framework
|
| 81 |
+
JS_AUDIO_SYNTH = """
|
| 82 |
+
function() {
|
| 83 |
+
window.AudioContext = window.AudioContext || window.webkitAudioContext;
|
| 84 |
+
let audioCtx = null;
|
| 85 |
+
|
| 86 |
+
function triggerTone(row, isPerc) {
|
| 87 |
+
if (!audioCtx) audioCtx = new AudioContext();
|
| 88 |
+
if (audioCtx.state === 'suspended') audioCtx.resume();
|
| 89 |
+
let now = audioCtx.currentTime;
|
| 90 |
+
let gainNode = audioCtx.createGain();
|
| 91 |
+
gainNode.connect(audioCtx.destination);
|
| 92 |
|
| 93 |
+
if (isPerc) {
|
| 94 |
+
let bufSize = Math.floor(audioCtx.sampleRate * 0.12);
|
| 95 |
+
let buffer = audioCtx.createBuffer(1, bufSize, audioCtx.sampleRate);
|
| 96 |
let data = buffer.getChannelData(0);
|
| 97 |
+
for(let i=0; i<bufSize; i++) data[i] = Math.random() * 2 - 1;
|
| 98 |
+
let src = audioCtx.createBufferSource(); src.buffer = buffer;
|
| 99 |
+
let flt = audioCtx.createBiquadFilter(); flt.type = 'bandpass';
|
| 100 |
+
if (row === 0) { flt.frequency.setValueAtTime(60, now); gainNode.gain.setValueAtTime(0.7, now); }
|
| 101 |
+
else if (row === 1) { flt.frequency.setValueAtTime(1000, now); gainNode.gain.setValueAtTime(0.4, now); }
|
| 102 |
+
else { flt.frequency.setValueAtTime(7000, now); gainNode.gain.setValueAtTime(0.2, now); }
|
| 103 |
+
src.connect(flt); flt.connect(gainNode);
|
| 104 |
+
src.start(now); src.stop(now + 0.12);
|
|
|
|
|
|
|
|
|
|
| 105 |
} else {
|
| 106 |
+
let freq = 440 * Math.pow(2, ((60 + row) - 69) / 12);
|
| 107 |
+
let osc = audioCtx.createOscillator(); osc.type = 'triangle';
|
|
|
|
|
|
|
|
|
|
| 108 |
osc.frequency.setValueAtTime(freq, now);
|
| 109 |
+
gainNode.gain.setValueAtTime(0.2, now);
|
| 110 |
+
gainNode.gain.exponentialRampToValueAtTime(0.001, now + 0.25);
|
|
|
|
|
|
|
| 111 |
osc.connect(gainNode);
|
| 112 |
+
osc.start(now); osc.stop(now + 0.25);
|
| 113 |
}
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
window.toggleStudioCell = function(family, row, col, isPerc) {
|
| 117 |
+
let cellClass = `btn-${family}-${row}-${col}`;
|
| 118 |
+
let buttons = document.querySelectorAll('.' + cellClass);
|
| 119 |
+
buttons.forEach(btn => {
|
| 120 |
+
btn.classList.toggle('selected');
|
| 121 |
+
if (btn.classList.contains('selected')) {
|
| 122 |
+
triggerTone(row, isPerc === 1);
|
| 123 |
+
}
|
| 124 |
+
});
|
| 125 |
+
|
| 126 |
+
// Pass programmatic event parameters smoothly directly into python backend communication arrays
|
| 127 |
+
let targetTextBox = document.getElementById('js_communicator').querySelector('input, textarea');
|
| 128 |
+
targetTextBox.value = family + "," + row + "," + col;
|
| 129 |
+
targetTextBox.dispatchEvent(new Event('input', { bubbles: true }));
|
| 130 |
+
};
|
| 131 |
}
|
| 132 |
"""
|
| 133 |
|
| 134 |
+
def generate_html_grid(family_id: str, max_rows: int, labels: list, is_perc: bool = False) -> str:
|
| 135 |
+
"""Generates an embedded raw grid block structure to preserve look and feel."""
|
| 136 |
+
html = f"<div class='instrument-container'>"
|
| 137 |
+
html += f"<div style='color: var(--primary-500, #63b3ed); font-weight: bold; margin-bottom: 8px;'>{family_id.upper()} TRACKS</div>"
|
| 138 |
+
|
| 139 |
+
for r in reversed(range(max_rows)):
|
| 140 |
+
html += "<div class='matrix-row-layout'>"
|
| 141 |
+
html += f"<div class='grid-label'>{labels[r]}</div>"
|
| 142 |
+
html += "<div class='cells-container'>"
|
| 143 |
+
for c in range(config.INPUT_STEPS):
|
| 144 |
+
is_bar_start = (c > 0 and c % config.STEPS_PER_BAR == 0)
|
| 145 |
+
cls = f"matrix-btn {family_id} btn-{family_id}-{r}-{c}"
|
| 146 |
+
if is_bar_start:
|
| 147 |
+
cls += " bar-line"
|
| 148 |
+
html += f"<button class='{cls}' onclick='toggleStudioCell(\"{family_id}\", {r}, {c}, {1 if is_perc else 0})'></button>"
|
| 149 |
+
html += "</div></div>"
|
| 150 |
+
|
| 151 |
+
html += "</div>"
|
| 152 |
+
return html
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
|
| 154 |
# ==============================================================================
|
| 155 |
+
# Pipeline Adapters & In-Memory Audio Render Logic
|
| 156 |
# ==============================================================================
|
| 157 |
|
| 158 |
+
def update_matrix_state(communication_token, strings, woodwinds, brass, perc):
|
| 159 |
+
"""Parses structural token tracking strings directly into persistent memory states."""
|
| 160 |
+
if not communication_token or "," not in communication_token:
|
| 161 |
+
return strings, woodwinds, brass, perc
|
| 162 |
+
|
| 163 |
+
family, r_str, c_str = communication_token.split(",")
|
| 164 |
+
r, c = int(r_str), int(c_str)
|
| 165 |
+
|
| 166 |
+
state_map = {"strings": strings, "woodwinds": woodwinds, "brass": brass, "perc": perc}
|
| 167 |
+
target_grid = state_map[family]
|
| 168 |
+
|
| 169 |
+
idx = (r * config.INPUT_STEPS) + c
|
| 170 |
+
target_grid[idx] = 1 if target_grid[idx] == 0 else 0
|
| 171 |
+
return strings, woodwinds, brass, perc
|
| 172 |
+
|
| 173 |
+
def execute_pipeline(strings, woodwinds, brass, perc, length, temp, tk, lead):
|
| 174 |
+
"""Compiles MIDI layout parameters and synthesizes a high-fidelity output wave track."""
|
| 175 |
tmpdir = tempfile.mkdtemp()
|
| 176 |
midi_path = os.path.join(tmpdir, "generated.mid")
|
| 177 |
audio_path = os.path.join(tmpdir, "generated.wav")
|
|
|
|
| 191 |
target_minutes=length, temperature=temp, top_k=int(tk),
|
| 192 |
midi_out_path=midi_path, device="cpu", primary_family=lead
|
| 193 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
|
| 195 |
+
# SECURE MEMORY SYNTHESIS ENGINE: Translates tracks cleanly into float arrays
|
| 196 |
+
try:
|
| 197 |
+
pm = pretty_midi.PrettyMIDI(midi_path)
|
| 198 |
+
sample_rate = 22050
|
| 199 |
+
|
| 200 |
+
fs = fluidsynth.Synth()
|
| 201 |
+
sfid = fs.sfload("soundfont.sf2")
|
| 202 |
+
fs.program_select(0, sfid, 0, 0)
|
| 203 |
+
|
| 204 |
+
# Build synthesis samples stream directly from the PrettyMIDI structural object references
|
| 205 |
+
audio_data = pm.fluidsynth(fs=sample_rate)
|
| 206 |
+
|
| 207 |
+
# Normalize and capture float signals safely
|
| 208 |
+
if len(audio_data) > 0:
|
| 209 |
+
audio_data = audio_data / np.max(np.abs(audio_data))
|
| 210 |
+
wavfile.write(audio_path, sample_rate, (audio_data * 32767).astype(np.int16))
|
| 211 |
+
except Exception as e:
|
| 212 |
+
print(f"[Synth Audio Engine Failure Context Exception]: {e}")
|
| 213 |
+
# Return fallback silence array block to maintain pipeline stability
|
| 214 |
+
wavfile.write(audio_path, 22050, np.zeros(22050, dtype=np.int16))
|
| 215 |
|
| 216 |
+
return midi_path, (audio_path if os.path.exists(audio_path) else None)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
|
| 218 |
# ==============================================================================
|
| 219 |
+
# UI Window Context Orchestration
|
| 220 |
# ==============================================================================
|
| 221 |
|
| 222 |
+
with gr.Blocks(css=CUSTOM_DAW_CSS, title="Classical Music Grid Generator") as demo:
|
| 223 |
|
| 224 |
+
# Core Persistent Internal Matrix Arrays Map Definitions
|
| 225 |
+
strings_state = gr.State([0] * (config.PITCHES_MELODIC * config.INPUT_STEPS))
|
| 226 |
+
woodwinds_state = gr.State([0] * (config.PITCHES_MELODIC * config.INPUT_STEPS))
|
| 227 |
+
brass_state = gr.State([0] * (config.PITCHES_MELODIC * config.INPUT_STEPS))
|
| 228 |
+
perc_state = gr.State([0] * (config.PITCHES_PERC * config.INPUT_STEPS))
|
| 229 |
+
|
| 230 |
+
# Hidden communicator text area component following your explicit design parameters
|
| 231 |
+
js_communicator = gr.Textbox(visible=False, elem_id="js_communicator")
|
| 232 |
|
| 233 |
gr.HTML("""
|
| 234 |
<div style="text-align:center; padding:15px 0;">
|
|
|
|
| 236 |
🎼 Classical Music Grid Generator
|
| 237 |
</h1>
|
| 238 |
<p style="color:#8892aa; font-size:14px; max-width:650px; margin:0 auto;">
|
| 239 |
+
Click cells inside the instrument matrix panels to assign note frameworks natively across all three bars.
|
| 240 |
</p>
|
| 241 |
</div>
|
| 242 |
""")
|
|
|
|
| 245 |
gr.HTML("""
|
| 246 |
<div style="display:grid; grid-template-columns:repeat(auto-fit,minmax(220px,1fr)); gap:12px; padding:6px 0;">
|
| 247 |
<div style="background:rgba(99,179,237,0.06); border:1px solid rgba(99,179,237,0.2); border-radius:8px; padding:12px;">
|
| 248 |
+
<strong style="color:#63b3ed;">1. Paint Framework Motifs</strong>
|
| 249 |
<p style="color:#8892aa; font-size:12px; margin:4px 0 0; line-height:1.4;">
|
| 250 |
+
Click grid boxes to toggle note triggers across all 3 bars. Highlights display instantly and remain fixed when clicked.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 251 |
</p>
|
| 252 |
</div>
|
| 253 |
<div style="background:rgba(252,129,74,0.06); border:1px solid rgba(252,129,74,0.2); border-radius:8px; padding:12px;">
|
| 254 |
+
<strong style="color:#fc814a;">2. Compile & Stream Live</strong>
|
| 255 |
<p style="color:#8892aa; font-size:12px; margin:4px 0 0; line-height:1.4;">
|
| 256 |
+
Adjust target duration parameters and lead options, then click generate. Use the inline media layout player to listen live.
|
| 257 |
</p>
|
| 258 |
</div>
|
| 259 |
</div>
|
| 260 |
""")
|
| 261 |
|
| 262 |
+
# Interactive Grid Displays Mapping Sections
|
|
|
|
|
|
|
|
|
|
|
|
|
| 263 |
with gr.Row():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 264 |
with gr.Column(scale=1):
|
| 265 |
+
gr.HTML(generate_html_grid("strings", config.PITCHES_MELODIC, _MELODIC_NOTE_NAMES, is_perc=False))
|
| 266 |
+
gr.HTML(generate_html_grid("woodwinds", config.PITCHES_MELODIC, _MELODIC_NOTE_NAMES, is_perc=False))
|
| 267 |
+
with gr.Column(scale=1):
|
| 268 |
+
gr.HTML(generate_html_grid("brass", config.PITCHES_MELODIC, _MELODIC_NOTE_NAMES, is_perc=False))
|
| 269 |
+
gr.HTML(generate_html_grid("perc", config.PITCHES_PERC, _PERC_NOTE_NAMES, is_perc=True))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 270 |
|
| 271 |
+
# Control Parameters Sliders Deck
|
|
|
|
|
|
|
|
|
|
|
|
|
| 272 |
with gr.Row():
|
| 273 |
with gr.Column(scale=3):
|
| 274 |
with gr.Row():
|
| 275 |
+
target_minutes = gr.Slider(minimum=1.0, maximum=5.0, value=2.0, step=0.5, label="Target Playback Length (Minutes)")
|
| 276 |
+
temperature = gr.Slider(minimum=0.7, maximum=1.3, value=1.0, step=0.05, label="Creativity Temperature")
|
| 277 |
with gr.Row():
|
| 278 |
+
top_k = gr.Slider(minimum=2, maximum=12, value=6, step=1, label="Top-K Distribution Filter")
|
| 279 |
+
primary_family = gr.Dropdown(choices=["strings", "woodwinds", "brass"], value="strings", label="Melodic Ensemble Driver Lead")
|
| 280 |
|
| 281 |
generate_button = gr.Button("🎵 Execute Transformer Music Generation Pipeline", variant="primary")
|
| 282 |
|
|
|
|
| 284 |
audio_output = gr.Audio(label="🔊 Fluidsynth Generated Audio Player (Listen Live)", type="filepath")
|
| 285 |
midi_output = gr.File(label="⬇ Download Output Standard MIDI File (.mid)")
|
| 286 |
|
| 287 |
+
# Context Change Bindings Map Hooks
|
| 288 |
+
js_communicator.change(
|
| 289 |
+
fn=update_matrix_state,
|
| 290 |
+
inputs=[js_communicator, strings_state, woodwinds_state, brass_state, perc_state],
|
| 291 |
+
outputs=[strings_state, woodwinds_state, brass_state, perc_state]
|
| 292 |
+
)
|
| 293 |
+
|
| 294 |
generate_button.click(
|
| 295 |
+
fn=execute_pipeline,
|
| 296 |
+
inputs=[strings_state, woodwinds_state, brass_state, perc_state, target_minutes, temperature, top_k, primary_family],
|
|
|
|
|
|
|
|
|
|
| 297 |
outputs=[midi_output, audio_output]
|
| 298 |
)
|
| 299 |
|
| 300 |
+
# Inject Client Synthesis Contexts on Framework Boot Ingestion Pass
|
| 301 |
+
demo.load(None, js=JS_AUDIO_SYNTH)
|
| 302 |
+
|
| 303 |
if __name__ == "__main__":
|
| 304 |
demo.launch()
|