Download backend/api/midi_utils.py from peter288/django: direct link, hf CLI and curl.
- Browser
- Download file 1.32 kB
-
https://huggingface.co/spaces/peter288/django/resolve/main/backend/api/midi_utils.py
- Command line
-
hf download hf://spaces/peter288/django/backend/api/midi_utils.py
-
curl -L -o midi_utils.py https://huggingface.co/spaces/peter288/django/resolve/main/backend/api/midi_utils.py
1.32 kB
| import mido | |
| from io import BytesIO | |
| def process_midi(midi_bytes: bytes) -> BytesIO: | |
| """ | |
| Processes a MIDI file by transposing all notes up by one semitone. | |
| Args: | |
| midi_bytes: The raw bytes of the input MIDI file. | |
| Returns: | |
| A BytesIO buffer containing the processed MIDI data. | |
| """ | |
| # Create an in-memory file-like object from the input bytes | |
| with BytesIO(midi_bytes) as input_buffer: | |
| mid = mido.MidiFile(file=input_buffer) | |
| # Iterate over all tracks in the MIDI file | |
| for i, track in enumerate(mid.tracks): | |
| # Iterate over all messages in the track | |
| for msg in track: | |
| # Check if the message is a note_on or note_off event | |
| if msg.type in ['note_on', 'note_off']: | |
| # Transpose the note by +1 semitone | |
| # We add a check to ensure the note doesn't go above 127 | |
| if msg.note < 127: | |
| msg.note += 1 | |
| # Save the processed MIDI data to an in-memory output buffer | |
| output_buffer = BytesIO() | |
| mid.save(file=output_buffer) | |
| # Reset the buffer's position to the beginning | |
| output_buffer.seek(0) | |
| return output_buffer |