File size: 8,290 Bytes
9c7e38e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
"""
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,
    }