hephaestusonfire commited on
Commit
a461ba0
Β·
verified Β·
1 Parent(s): f28fd47

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -110
app.py CHANGED
@@ -1,15 +1,17 @@
1
  """
2
  Gradio app for classical music generation with a grid-based Transformer.
3
- Completely native, production-safe engine featuring an synchronized
4
- multi-track algorithmic synthesis engine to bypass cross-platform FluidSynth errors.
5
  """
6
 
7
  import os
8
  import json
9
  import tempfile
 
10
  import gradio as gr
11
  import numpy as np
12
- import mido
 
13
  from scipy.io import wavfile
14
 
15
  import config
@@ -73,6 +75,16 @@ CUSTOM_DAW_CSS = """
73
  .matrix-btn.selected.woodwinds { background-color: #6ed29b !important; box-shadow: inset 0 0 4px #fff !important; }
74
  .matrix-btn.selected.brass { background-color: #fbbf24 !important; box-shadow: inset 0 0 4px #fff !important; }
75
  .matrix-btn.selected.perc { background-color: #fc814a !important; box-shadow: inset 0 0 4px #fff !important; }
 
 
 
 
 
 
 
 
 
 
76
  """
77
 
78
  # Client-side Web Audio synthesis framework
@@ -121,6 +133,7 @@ function() {
121
  }
122
  });
123
 
 
124
  let targetTextBox = document.getElementById('js_communicator').querySelector('input, textarea');
125
  targetTextBox.value = family + "," + row + "," + col;
126
  targetTextBox.dispatchEvent(new Event('input', { bubbles: true }));
@@ -131,7 +144,7 @@ function() {
131
  def generate_html_grid(family_id: str, max_rows: int, labels: list, is_perc: bool = False) -> str:
132
  """Generates an embedded raw grid block structure to preserve look and feel."""
133
  html = f"<div class='instrument-container'>"
134
- html += f"<div style='color: var(--primary-500, #63b3ed); font-weight: bold; margin-bottom: 8px;'>{family_id.upper()} TRACKS</div>"
135
 
136
  for r in reversed(range(max_rows)):
137
  html += "<div class='matrix-row-layout'>"
@@ -149,100 +162,7 @@ def generate_html_grid(family_id: str, max_rows: int, labels: list, is_perc: boo
149
  return html
150
 
151
  # ==============================================================================
152
- # Algorithmic Audio Rendering Core (Bypasses System FluidSynth Dependency)
153
- # ==============================================================================
154
-
155
- def render_composition_to_audio(midi_path: str, out_wav_path: str):
156
- """
157
- Algorithmic synthesizer pipeline. Parses MIDI notes directly and builds an
158
- audio track via mathematically precise sine, triangle, and transient waves.
159
- """
160
- try:
161
- mid = mido.MidiFile(midi_path)
162
- sr = 22050
163
- total_time = mid.length
164
- audio_buffer = np.zeros(int(sr * (total_time + 2.0)), dtype=np.float32)
165
-
166
- def add_tone(freq, start_sec, dur_sec, vol=0.15, family="strings"):
167
- start_idx = int(start_sec * sr)
168
- end_idx = start_idx + int(dur_sec * sr)
169
- if start_idx >= len(audio_buffer): return
170
- end_idx = min(end_idx, len(audio_buffer))
171
-
172
- length = end_idx - start_idx
173
- if length <= 0: return
174
-
175
- t = np.arange(0, length) / sr
176
-
177
- # ADSR Volume Envelopes
178
- envelope = np.ones_like(t)
179
- # Attack
180
- attack_len = min(int(0.05 * sr), length)
181
- if attack_len > 0:
182
- envelope[:attack_len] = np.linspace(0, 1, attack_len)
183
- # Decay / Release
184
- decay_len = length - attack_len
185
- if decay_len > 0:
186
- envelope[attack_len:] = np.exp(-np.linspace(0, 3.0, decay_len))
187
-
188
- if family == "perc":
189
- # Synthesize drum waveforms cleanly via mathematical functions
190
- if freq < 100: # Kick
191
- wave = np.sin(2 * np.pi * 55 * np.exp(-t * 30.0) * t) * np.exp(-t * 15.0) * 0.4
192
- elif freq < 500: # Snare
193
- wave = np.random.normal(0, 1, size=len(t)) * np.exp(-t * 20.0) * 0.25
194
- else: # Hi-hat
195
- wave = np.random.normal(0, 1, size=len(t)) * np.exp(-t * 60.0) * 0.15
196
- elif family == "brass":
197
- # Rich, punchy sawtooth simulation profile
198
- wave = (2.0 / np.pi) * (np.sin(2 * np.pi * freq * t) + 0.5 * np.sin(4 * np.pi * freq * t)) * envelope * vol
199
- elif family == "woodwinds":
200
- # Warm, hollow square-like simulation profile
201
- wave = np.sign(np.sin(2 * np.pi * freq * t)) * envelope * vol * 0.6
202
- else:
203
- # Smooth organic triangle wave configuration profiles
204
- wave = (2.0 / np.pi) * np.arcsin(np.sin(2 * np.pi * freq * t)) * envelope * vol
205
-
206
- audio_buffer[start_idx:end_idx] += wave
207
-
208
- # Extract notes and translate event streams into wave synthesis buffers
209
- for track in mid.tracks:
210
- abs_time = 0.0
211
- active_notes = {}
212
- for msg in mid.merge_tracks([track]):
213
- abs_time += msg.time
214
- if msg.type == 'note_on' and msg.velocity > 0:
215
- active_notes[msg.note] = abs_time
216
- elif msg.type in ['note_off', 'note_on'] and msg.note in active_notes:
217
- start_t = active_notes.pop(msg.note)
218
- duration = max(abs_time - start_t, 0.08)
219
-
220
- # Deduce family profile channel tracking from layout velocities
221
- is_drum = (msg.channel == 9)
222
- if is_drum:
223
- fam = "perc"
224
- elif msg.note >= 68:
225
- fam = "woodwinds"
226
- elif msg.note <= 62:
227
- fam = "brass"
228
- else:
229
- fam = "strings"
230
-
231
- frequency = 440.0 * (2.0 ** ((msg.note - 69) / 12.0))
232
- add_tone(frequency, start_t, duration, family=fam)
233
-
234
- # Normalize audio track signal clips to safeguard speakers
235
- max_val = np.max(np.abs(audio_buffer))
236
- if max_val > 0:
237
- audio_buffer = (audio_buffer / max_val) * 0.85
238
-
239
- wavfile.write(out_wav_path, sr, (audio_buffer * 32767).astype(np.int16))
240
- except Exception as e:
241
- print(f"System Synthesizer Engine Failure Context Exception: {e}")
242
- wavfile.write(out_wav_path, 22050, np.zeros(22050, dtype=np.int16))
243
-
244
- # ==============================================================================
245
- # Pipeline Adapters
246
  # ==============================================================================
247
 
248
  def update_matrix_state(communication_token, strings, woodwinds, brass, perc):
@@ -258,7 +178,16 @@ def update_matrix_state(communication_token, strings, woodwinds, brass, perc):
258
 
259
  idx = (r * config.INPUT_STEPS) + c
260
  target_grid[idx] = 1 if target_grid[idx] == 0 else 0
261
- return strings, woodwinds, brass, perc
 
 
 
 
 
 
 
 
 
262
 
263
  def execute_pipeline(strings, woodwinds, brass, perc, length, temp, tk, lead):
264
  """Compiles MIDI layout parameters and synthesizes a high-fidelity output wave track."""
@@ -282,12 +211,30 @@ def execute_pipeline(strings, woodwinds, brass, perc, length, temp, tk, lead):
282
  midi_out_path=midi_path, device="cpu", primary_family=lead
283
  )
284
 
285
- # Trigger pure matrix-buffer audio wave synthesis
286
- render_composition_to_audio(midi_path, audio_path)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
287
  return midi_path, (audio_path if os.path.exists(audio_path) else None)
288
 
289
  # ==============================================================================
290
- # UI Window Context Orchestration
291
  # ==============================================================================
292
 
293
  with gr.Blocks(css=CUSTOM_DAW_CSS, title="Classical Music Grid Generator") as demo:
@@ -297,6 +244,7 @@ with gr.Blocks(css=CUSTOM_DAW_CSS, title="Classical Music Grid Generator") as de
297
  brass_state = gr.State([0] * (config.PITCHES_MELODIC * config.INPUT_STEPS))
298
  perc_state = gr.State([0] * (config.PITCHES_PERC * config.INPUT_STEPS))
299
 
 
300
  js_communicator = gr.Textbox(visible=False, elem_id="js_communicator")
301
 
302
  gr.HTML("""
@@ -328,33 +276,37 @@ with gr.Blocks(css=CUSTOM_DAW_CSS, title="Classical Music Grid Generator") as de
328
  </div>
329
  """)
330
 
 
331
  with gr.Row():
332
- with gr.Column(scale=1):
333
  gr.HTML(generate_html_grid("strings", config.PITCHES_MELODIC, _MELODIC_NOTE_NAMES, is_perc=False))
334
  gr.HTML(generate_html_grid("woodwinds", config.PITCHES_MELODIC, _MELODIC_NOTE_NAMES, is_perc=False))
335
- with gr.Column(scale=1):
336
  gr.HTML(generate_html_grid("brass", config.PITCHES_MELODIC, _MELODIC_NOTE_NAMES, is_perc=False))
337
  gr.HTML(generate_html_grid("perc", config.PITCHES_PERC, _PERC_NOTE_NAMES, is_perc=True))
 
 
 
 
338
 
339
  with gr.Row():
340
  with gr.Column(scale=3):
341
  with gr.Row():
342
- target_minutes = gr.Slider(minimum=1.0, maximum=5.0, value=2.0, step=0.5, label="Target Playback Length (Minutes)")
343
- temperature = gr.Slider(minimum=0.7, maximum=1.3, value=1.0, step=0.05, label="Creativity Temperature")
344
  with gr.Row():
345
- top_k = gr.Slider(minimum=2, maximum=12, value=6, step=1, label="Top-K Distribution Filter")
346
- primary_family = gr.Dropdown(choices=["strings", "woodwinds", "brass"], value="strings", label="Melodic Ensemble Driver Lead")
347
 
348
  generate_button = gr.Button("🎡 Execute Transformer Music Generation Pipeline", variant="primary")
349
 
350
  with gr.Column(scale=2):
351
- audio_output = gr.Audio(label="πŸ”Š Algorithmic Synthesizer Studio Player (Listen Live)", type="filepath")
352
  midi_output = gr.File(label="⬇ Download Output Standard MIDI File (.mid)")
353
 
354
  js_communicator.change(
355
  fn=update_matrix_state,
356
  inputs=[js_communicator, strings_state, woodwinds_state, brass_state, perc_state],
357
- outputs=[strings_state, woodwinds_state, brass_state, perc_state]
358
  )
359
 
360
  generate_button.click(
 
1
  """
2
  Gradio app for classical music generation with a grid-based Transformer.
3
+ Engineered for cross-version stability on Hugging Face Spaces using pure HTML matrix grids,
4
+ a JS communicator selection layer, and an absolute in-memory FluidSynth audio renderer.
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
 
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
+ .hud-container {
80
+ background-color: #0f141c !important;
81
+ border: 1px solid rgba(99, 179, 237, 0.2) !important;
82
+ padding: 12px !important;
83
+ border-radius: 6px !important;
84
+ }
85
+ .hud-container h3, .hud-container p, .hud-container li, .hud-container strong {
86
+ color: #ffffff !important;
87
+ }
88
  """
89
 
90
  # Client-side Web Audio synthesis framework
 
133
  }
134
  });
135
 
136
+ // Pass programmatic event parameters smoothly directly into python backend communication arrays
137
  let targetTextBox = document.getElementById('js_communicator').querySelector('input, textarea');
138
  targetTextBox.value = family + "," + row + "," + col;
139
  targetTextBox.dispatchEvent(new Event('input', { bubbles: true }));
 
144
  def generate_html_grid(family_id: str, max_rows: int, labels: list, is_perc: bool = False) -> str:
145
  """Generates an embedded raw grid block structure to preserve look and feel."""
146
  html = f"<div class='instrument-container'>"
147
+ html += f"<div style='color: #c9d1e8; font-weight: bold; margin-bottom: 8px;'>{family_id.upper()} TIMELINE</div>"
148
 
149
  for r in reversed(range(max_rows)):
150
  html += "<div class='matrix-row-layout'>"
 
162
  return html
163
 
164
  # ==============================================================================
165
+ # Pipeline Adapters & In-Memory Audio Render Logic
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
  # ==============================================================================
167
 
168
  def update_matrix_state(communication_token, strings, woodwinds, brass, perc):
 
178
 
179
  idx = (r * config.INPUT_STEPS) + c
180
  target_grid[idx] = 1 if target_grid[idx] == 0 else 0
181
+
182
+ # Compute display update formatting metrics
183
+ bar_num = (c // config.STEPS_PER_BAR) + 1
184
+ step_num = (c % config.STEPS_PER_BAR) + 1
185
+ note_name = _PERC_NOTE_NAMES[r] if family == "perc" else _MELODIC_NOTE_NAMES[r]
186
+ status = "πŸ”΄ ACTIVATED" if target_grid[idx] == 1 else "βšͺ DEACTIVATED"
187
+
188
+ hud_info = f"### πŸŽ›οΈ Selection HUD\n* **Family:** {family.upper()}\n* **Note / Track:** `{note_name}`\n* **Location:** Bar {bar_num}, Step {step_num} (Global Index {c})\n* **Status:** {status}"
189
+
190
+ return strings, woodwinds, brass, perc, hud_info
191
 
192
  def execute_pipeline(strings, woodwinds, brass, perc, length, temp, tk, lead):
193
  """Compiles MIDI layout parameters and synthesizes a high-fidelity output wave track."""
 
211
  midi_out_path=midi_path, device="cpu", primary_family=lead
212
  )
213
 
214
+ # SECURE MEMORY SYNTHESIS ENGINE: Bypasses platform-specific subprocess audio drivers
215
+ try:
216
+ pm = pretty_midi.PrettyMIDI(midi_path)
217
+ sample_rate = 22050
218
+
219
+ fs = fluidsynth.Synth()
220
+ # Direct local verification mapping
221
+ sfid = fs.sfload("soundfont.sf2")
222
+ fs.program_select(0, sfid, 0, 0)
223
+
224
+ # Build synthesis samples stream directly via the memory buffer loops to avoid 1s failure loops
225
+ audio_data = pm.fluidsynth(fs=sample_rate)
226
+
227
+ if len(audio_data) > 0:
228
+ audio_data = audio_data / np.max(np.abs(audio_data))
229
+ wavfile.write(audio_path, sample_rate, (audio_data * 32767).astype(np.int16))
230
+ except Exception as e:
231
+ print(f"[Synth Audio Engine Failure Context Exception]: {e}")
232
+ wavfile.write(audio_path, 22050, np.zeros(22050, dtype=np.int16))
233
+
234
  return midi_path, (audio_path if os.path.exists(audio_path) else None)
235
 
236
  # ==============================================================================
237
+ # UI Blocks Composition Window
238
  # ==============================================================================
239
 
240
  with gr.Blocks(css=CUSTOM_DAW_CSS, title="Classical Music Grid Generator") as demo:
 
244
  brass_state = gr.State([0] * (config.PITCHES_MELODIC * config.INPUT_STEPS))
245
  perc_state = gr.State([0] * (config.PITCHES_PERC * config.INPUT_STEPS))
246
 
247
+ # Hidden communicator text area component following your design parameters
248
  js_communicator = gr.Textbox(visible=False, elem_id="js_communicator")
249
 
250
  gr.HTML("""
 
276
  </div>
277
  """)
278
 
279
+ # Interactive Grid Displays Mapping Sections
280
  with gr.Row():
281
+ with gr.Column(scale=4):
282
  gr.HTML(generate_html_grid("strings", config.PITCHES_MELODIC, _MELODIC_NOTE_NAMES, is_perc=False))
283
  gr.HTML(generate_html_grid("woodwinds", config.PITCHES_MELODIC, _MELODIC_NOTE_NAMES, is_perc=False))
 
284
  gr.HTML(generate_html_grid("brass", config.PITCHES_MELODIC, _MELODIC_NOTE_NAMES, is_perc=False))
285
  gr.HTML(generate_html_grid("perc", config.PITCHES_PERC, _PERC_NOTE_NAMES, is_perc=True))
286
+
287
+ with gr.Column(scale=1):
288
+ with gr.Column(elem_classes="hud-container"):
289
+ hud_display = gr.Markdown("### πŸŽ›οΈ Selection HUD\n*Click any block in the orchestration grids to inspect active coordinate parameters.*")
290
 
291
  with gr.Row():
292
  with gr.Column(scale=3):
293
  with gr.Row():
294
+ target_minutes = gr.Slider(minimum=1.0, maximum=5.0, value=2.0, step=0.5, label="πŸ• Target Length (Minutes)")
295
+ temperature = gr.Slider(minimum=0.7, maximum=1.3, value=1.0, step=0.05, label="🌑️ Creativity Temperature")
296
  with gr.Row():
297
+ top_k = gr.Slider(minimum=2, maximum=12, value=6, step=1, label="🎲 Top-K Distribution Filter")
298
+ primary_family = gr.Dropdown(choices=["strings", "woodwinds", "brass"], value="strings", label="🎼 Primary Orchestration Lead")
299
 
300
  generate_button = gr.Button("🎡 Execute Transformer Music Generation Pipeline", variant="primary")
301
 
302
  with gr.Column(scale=2):
303
+ audio_output = gr.Audio(label="πŸ”Š Fluidsynth Generated Audio Player (Listen Live)", type="filepath")
304
  midi_output = gr.File(label="⬇ Download Output Standard MIDI File (.mid)")
305
 
306
  js_communicator.change(
307
  fn=update_matrix_state,
308
  inputs=[js_communicator, strings_state, woodwinds_state, brass_state, perc_state],
309
+ outputs=[strings_state, woodwinds_state, brass_state, perc_state, hud_display]
310
  )
311
 
312
  generate_button.click(