Spaces:
Sleeping
Sleeping
Download utils/midi_utils.py from hephaestusonfire/Music_Generator: direct link, hf CLI and curl.
- Browser
- Download file 8.29 kB
-
https://huggingface.co/spaces/hephaestusonfire/Music_Generator/resolve/main/utils/midi_utils.py
- Command line
-
hf download hf://spaces/hephaestusonfire/Music_Generator/utils/midi_utils.py
-
curl -L -o midi_utils.py https://huggingface.co/spaces/hephaestusonfire/Music_Generator/resolve/main/utils/midi_utils.py
8.29 kB
| """ | |
| MIDI utilities: convert between grid representation and PrettyMIDI. | |
| """ | |
| from typing import Dict, Tuple, Optional | |
| import numpy as np | |
| import pretty_midi | |
| import config | |
| # Fixed MIDI pitches for one octave, center around middle range. | |
| # You can adjust these if you want a different register. | |
| # Example: C4 (60) to B4 (71) → 12 pitches. | |
| MELODIC_BASE_PITCH: int = 60 # MIDI note for C4 | |
| # Percussion: General MIDI standard channel 9 (index 9), with typical drum notes. | |
| PERCUSSION_CHANNEL: int = 9 | |
| PERC_KICK_PITCH: int = 36 # Bass Drum 1 | |
| PERC_SNARE_PITCH: int = 38 # Acoustic Snare | |
| PERC_HIHAT_PITCH: int = 42 # Closed Hi-Hat | |
| def create_pretty_midi_from_grids( | |
| strings_grid: np.ndarray, | |
| woodwinds_grid: np.ndarray, | |
| brass_grid: np.ndarray, | |
| perc_grid: np.ndarray, | |
| velocity: int = 80, | |
| ) -> pretty_midi.PrettyMIDI: | |
| """ | |
| Convert per-family grids to a PrettyMIDI object. | |
| Args: | |
| strings_grid: [bars, STEPS_PER_BAR, 12] binary array. | |
| woodwinds_grid: [bars, STEPS_PER_BAR, 12] binary array. | |
| brass_grid: [bars, STEPS_PER_BAR, 12] binary array. | |
| perc_grid: [bars, STEPS_PER_BAR, 3] binary array (Kick, Snare, Hi-hat). | |
| velocity: MIDI velocity for melodic notes. | |
| Returns: | |
| pm: PrettyMIDI object with 4 instrument tracks. | |
| """ | |
| # Basic checks | |
| bars, steps_per_bar, n_pitch_strings = strings_grid.shape | |
| assert steps_per_bar == config.STEPS_PER_BAR | |
| assert n_pitch_strings == config.PITCHES_MELODIC | |
| # Percussion shape check | |
| bars_p, steps_per_bar_p, n_perc = perc_grid.shape | |
| assert bars_p == bars | |
| assert steps_per_bar_p == config.STEPS_PER_BAR | |
| assert n_perc == config.PITCHES_PERC | |
| pm = pretty_midi.PrettyMIDI() | |
| # Create instrument tracks | |
| strings_inst = pretty_midi.Instrument( | |
| program=pretty_midi.instrument_name_to_program("Violin") | |
| ) | |
| woodwinds_inst = pretty_midi.Instrument( | |
| program=pretty_midi.instrument_name_to_program("Clarinet") | |
| ) | |
| brass_inst = pretty_midi.Instrument( | |
| program=pretty_midi.instrument_name_to_program("Trumpet") | |
| ) | |
| # Percussion uses channel 9; PrettyMIDI uses program but channel is set internally. | |
| perc_inst = pretty_midi.Instrument(program=0, is_drum=True) | |
| # Duration per step | |
| step_duration = config.SECONDS_PER_STEP | |
| # Helper to convert (bar_idx, step_idx, pitch_idx) to start/end times | |
| def cell_times(bar_idx: int, step_idx: int) -> Tuple[float, float]: | |
| start = (bar_idx * config.STEPS_PER_BAR + step_idx) * step_duration | |
| end = start + step_duration # simple: one-step duration | |
| return start, end | |
| # Melodic families | |
| def add_melodic_notes(grid: np.ndarray, instrument: pretty_midi.Instrument) -> None: | |
| """ | |
| Add notes to a melodic instrument from a [bars, steps, pitches] grid. | |
| Each active cell becomes a note of one-step duration. | |
| """ | |
| for b in range(bars): | |
| for s in range(config.STEPS_PER_BAR): | |
| for p in range(config.PITCHES_MELODIC): | |
| if grid[b, s, p] > 0.5: # treat >0.5 as "on" | |
| start, end = cell_times(b, s) | |
| midi_pitch = MELODIC_BASE_PITCH + p | |
| note = pretty_midi.Note( | |
| velocity=velocity, | |
| pitch=midi_pitch, | |
| start=start, | |
| end=end, | |
| ) | |
| instrument.notes.append(note) | |
| add_melodic_notes(strings_grid, strings_inst) | |
| add_melodic_notes(woodwinds_grid, woodwinds_inst) | |
| add_melodic_notes(brass_grid, brass_inst) | |
| # Percussion | |
| # Map indices 0,1,2 to Kick, Snare, Hi-hat. | |
| PERC_PITCHES = [PERC_KICK_PITCH, PERC_SNARE_PITCH, PERC_HIHAT_PITCH] | |
| for b in range(bars): | |
| for s in range(config.STEPS_PER_BAR): | |
| for k in range(config.PITCHES_PERC): | |
| if perc_grid[b, s, k] > 0.5: | |
| start, end = cell_times(b, s) | |
| pitch = PERC_PITCHES[k] | |
| note = pretty_midi.Note( | |
| velocity=velocity, | |
| pitch=pitch, | |
| start=start, | |
| end=end, | |
| ) | |
| perc_inst.notes.append(note) | |
| # Append instruments to the PrettyMIDI object | |
| pm.instruments.append(strings_inst) | |
| pm.instruments.append(woodwinds_inst) | |
| pm.instruments.append(brass_inst) | |
| pm.instruments.append(perc_inst) | |
| return pm | |
| def save_midi( | |
| pm: pretty_midi.PrettyMIDI, | |
| out_path: str, | |
| ) -> str: | |
| """ | |
| Save PrettyMIDI object to a .mid file. | |
| Args: | |
| pm: PrettyMIDI object. | |
| out_path: Path to write .mid file. | |
| Returns: | |
| out_path: Same path, for convenience. | |
| """ | |
| pm.write(out_path) | |
| return out_path | |
| # ========================= | |
| # Optional: MIDI → grid for debugging | |
| # ========================= | |
| def midi_to_grids( | |
| midi_path: str, | |
| max_bars: Optional[int] = None, | |
| ) -> Dict[str, np.ndarray]: | |
| """ | |
| Very simple debugging helper: convert a MIDI file back into rough grids. | |
| Assumes the file broadly follows the same tempo/grid assumptions. | |
| This is intentionally approximate and mainly for inspection, not training. | |
| Args: | |
| midi_path: Path to a MIDI file. | |
| max_bars: Optional max number of bars to decode. | |
| Returns: | |
| { | |
| "strings": [bars, STEPS_PER_BAR, 12], | |
| "woodwinds": [bars, STEPS_PER_BAR, 12], | |
| "brass": [bars, STEPS_PER_BAR, 12], | |
| "perc": [bars, STEPS_PER_BAR, 3], | |
| } | |
| """ | |
| pm = pretty_midi.PrettyMIDI(midi_path) | |
| # Estimate total length in bars | |
| total_seconds = pm.get_end_time() | |
| bar_duration = config.SECONDS_PER_BAR | |
| total_bars = int(np.ceil(total_seconds / bar_duration)) | |
| if max_bars is not None: | |
| total_bars = min(total_bars, max_bars) | |
| # Initialize empty grids | |
| strings_grid = np.zeros((total_bars, config.STEPS_PER_BAR, config.PITCHES_MELODIC), dtype=np.float32) | |
| woodwinds_grid = np.zeros_like(strings_grid) | |
| brass_grid = np.zeros_like(strings_grid) | |
| perc_grid = np.zeros((total_bars, config.STEPS_PER_BAR, config.PITCHES_PERC), dtype=np.float32) | |
| def time_to_indices(t: float) -> Tuple[int, int]: | |
| """ | |
| Convert time in seconds to (bar_idx, step_idx), clamped to grid. | |
| """ | |
| step_idx_global = int(np.floor(t / config.SECONDS_PER_STEP)) | |
| bar_idx = step_idx_global // config.STEPS_PER_BAR | |
| step_idx = step_idx_global % config.STEPS_PER_BAR | |
| bar_idx = min(bar_idx, total_bars - 1) | |
| return bar_idx, step_idx | |
| # Very naive family routing: you may refine this mapping later. | |
| for inst in pm.instruments: | |
| # Percussion | |
| if inst.is_drum: | |
| for note in inst.notes: | |
| b, s = time_to_indices(note.start) | |
| if note.pitch == PERC_KICK_PITCH: | |
| k = 0 | |
| elif note.pitch == PERC_SNARE_PITCH: | |
| k = 1 | |
| elif note.pitch == PERC_HIHAT_PITCH: | |
| k = 2 | |
| else: | |
| continue | |
| perc_grid[b, s, k] = 1.0 | |
| else: | |
| # Choose family by program range (very rough heuristic). | |
| program = inst.program | |
| # Strings (e.g., Violin, Viola, Cello) | |
| if program in range(40, 49): | |
| target_grid = strings_grid | |
| # Woodwinds | |
| elif program in range(72, 81) or program in range(64, 73): | |
| target_grid = woodwinds_grid | |
| # Brass | |
| elif program in range(56, 65): | |
| target_grid = brass_grid | |
| else: | |
| target_grid = strings_grid # fallback | |
| for note in inst.notes: | |
| b, s = time_to_indices(note.start) | |
| pitch_idx = note.pitch - MELODIC_BASE_PITCH | |
| if 0 <= pitch_idx < config.PITCHES_MELODIC: | |
| target_grid[b, s, pitch_idx] = 1.0 | |
| return { | |
| "strings": strings_grid, | |
| "woodwinds": woodwinds_grid, | |
| "brass": brass_grid, | |
| "perc": perc_grid, | |
| } |