Update README.md
Browse files
README.md
CHANGED
|
@@ -1 +1,68 @@
|
|
| 1 |
-
https://github.com/xingjianll/symbolic-music-generation/
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
https://github.com/xingjianll/symbolic-music-generation/
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
```python
|
| 5 |
+
from miditok import PerTok, TokenizerConfig
|
| 6 |
+
from transformers import AutoModelForCausalLM, GenerationConfig
|
| 7 |
+
import torch
|
| 8 |
+
import io
|
| 9 |
+
import mido
|
| 10 |
+
import rtmidi
|
| 11 |
+
|
| 12 |
+
# Load tokenizer config and tokenizer
|
| 13 |
+
config = TokenizerConfig(
|
| 14 |
+
num_velocities=8,
|
| 15 |
+
use_velocities=True,
|
| 16 |
+
use_chords=False,
|
| 17 |
+
use_rests=True,
|
| 18 |
+
use_tempos=True,
|
| 19 |
+
use_time_signatures=False,
|
| 20 |
+
use_sustain_pedals=False,
|
| 21 |
+
use_pitch_bends=False,
|
| 22 |
+
use_pitch_intervals=False,
|
| 23 |
+
use_programs=False,
|
| 24 |
+
use_pitchdrum_tokens=False,
|
| 25 |
+
ticks_per_quarter=320,
|
| 26 |
+
use_microtiming=False,
|
| 27 |
+
max_microtiming_shift=0.125
|
| 28 |
+
)
|
| 29 |
+
tokenizer = PerTok(config)
|
| 30 |
+
tokenizer.from_pretrained("xingjianll/midi-tokenizer")
|
| 31 |
+
|
| 32 |
+
# Load model and generation config
|
| 33 |
+
model = AutoModelForCausalLM.from_pretrained("xingjianll/midi-gpt2")
|
| 34 |
+
gen_config = GenerationConfig.from_pretrained("xingjianll/midi-gpt2")
|
| 35 |
+
model.eval()
|
| 36 |
+
|
| 37 |
+
# Generate token sequence
|
| 38 |
+
with torch.no_grad():
|
| 39 |
+
input_ids = torch.tensor([[tokenizer["BOS_None"]]], dtype=torch.long)
|
| 40 |
+
output = model.generate(
|
| 41 |
+
input_ids=input_ids,
|
| 42 |
+
generation_config=gen_config
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
# Decode tokens to MIDI bytes
|
| 46 |
+
generated_ids = output[0].tolist()
|
| 47 |
+
midi_bytes = tokenizer.decode([generated_ids]).dumps_midi()
|
| 48 |
+
midi_file = io.BytesIO(midi_bytes)
|
| 49 |
+
|
| 50 |
+
# Optionally save to disk
|
| 51 |
+
# with open("output.mid", "wb") as f:
|
| 52 |
+
# f.write(midi_bytes)
|
| 53 |
+
|
| 54 |
+
# Setup MIDI output to GarageBand
|
| 55 |
+
midiout = rtmidi.MidiOut()
|
| 56 |
+
available_ports = midiout.get_ports()
|
| 57 |
+
print("Available MIDI ports:", available_ports)
|
| 58 |
+
|
| 59 |
+
# Choose GarageBand's virtual port
|
| 60 |
+
port = mido.open_output('GarageBand Virtual In')
|
| 61 |
+
|
| 62 |
+
# Play MIDI via GarageBand
|
| 63 |
+
midi = mido.MidiFile(file=midi_file)
|
| 64 |
+
for msg in midi.play():
|
| 65 |
+
print(msg)
|
| 66 |
+
port.send(msg)
|
| 67 |
+
|
| 68 |
+
```
|