Download generate.py from dennis-xavier/MidiGen: direct link, hf CLI and curl.
- Browser
- Download file 2.54 kB
-
https://huggingface.co/dennis-xavier/MidiGen/resolve/main/generate.py
- Command line
-
hf download hf://dennis-xavier/MidiGen/generate.py
-
curl -L -o generate.py https://huggingface.co/dennis-xavier/MidiGen/resolve/main/generate.py
2.54 kB
| """Generate a MIDI continuation from a single orchestral harp note.""" | |
| import argparse | |
| from pathlib import Path | |
| import torch | |
| from safetensors.torch import load_file | |
| from symusic import Note, Score, Tempo, Track | |
| from model import BPM, DUR_CEIL_SECONDS, N_DUR_BINS, TICKS_PER_S, TPQ, MidiTransformer, _bin_to_seconds | |
| DRUM_PROGRAMS = (0, 8, 16, 24, 25, 32, 40, 48, 56) | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--weights", type=Path, default=Path(__file__).with_name("model.safetensors")) | |
| parser.add_argument("--output", type=Path, default=Path("harp.mid")) | |
| parser.add_argument("--notes", type=int, default=500, help="Maximum number of continuation notes.") | |
| parser.add_argument("--seed", type=int, default=1337, help="Random seed for sampling.") | |
| args = parser.parse_args() | |
| if args.notes < 1: | |
| parser.error("--notes must be positive") | |
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| model = MidiTransformer() | |
| model.load_state_dict(load_file(str(args.weights)), strict=True) | |
| model.to(device).eval() | |
| # [onset delta in seconds, track, instrument, pitch, duration in seconds] | |
| prompt = torch.tensor([[[0.0, 0.0, 46.0, 60.0, 0.25]]], device=device) | |
| torch.manual_seed(args.seed) | |
| continuation = model.generate(prompt, args.notes, temperature=1.0, top_p=0.95) | |
| score = Score(TPQ) | |
| score.tempos.append(Tempo(0, BPM)) | |
| harp = Track(name="Orchestral harp", program=46) | |
| harp.notes.append(Note(0, round(0.25 * TICKS_PER_S), 60, 80)) | |
| score.tracks.append(harp) | |
| tracks = {(0, 46): score.tracks[0]} | |
| onset = 0.0 | |
| for delta, track_id, instrument, pitch, duration_bin in continuation: | |
| onset += _bin_to_seconds(delta) | |
| key = (track_id, instrument) | |
| is_drum = instrument >= 128 | |
| if key not in tracks: | |
| program = DRUM_PROGRAMS[instrument - 128] if is_drum else instrument | |
| score.tracks.append(Track(name=f"Track {track_id}", program=program, is_drum=is_drum)) | |
| tracks[key] = score.tracks[-1] | |
| midi_pitch = max(0, min(127, pitch - 128 if is_drum else pitch)) | |
| duration = _bin_to_seconds(duration_bin, N_DUR_BINS, DUR_CEIL_SECONDS) | |
| tracks[key].notes.append(Note(round(onset * TICKS_PER_S), max(1, round(duration * TICKS_PER_S)), midi_pitch, 80)) | |
| score.dump_midi(str(args.output)) | |
| print(f"Saved {args.output} with {len(continuation)} generated notes plus the prompt.") | |
| if __name__ == "__main__": | |
| main() | |