Here's a thorough review of the provided Python script, which generates a MIDI file based on user input, with suggestions for improvement, explanations, and a refactored version of the code.
Review
Strengths:
- Readability: The script is generally easy to follow, with clear variable names and a logical structure.
- User Interaction: The script engages the user effectively to gather necessary inputs.
- Use of Libraries: Appropriately utilizes
mido for MIDI operations, re for regular expressions, and pandas for data manipulation.
Weaknesses and Suggestions:
-
Undefined Function:
- Issue: The function
calculate_timing_values is called but not defined anywhere in the script.
- Fix: Define this function with the necessary logic to calculate timing values based on BPM, beats per bar, note type, and positions.
-
Error Handling:
- Issue: The script lacks input validation and error handling (e.g., non-integer inputs for BPM, beats per bar, note type, or invalid instrument note types).
- Fix: Implement try-except blocks to handle potential errors, ensuring the script doesn't crash unexpectedly.
-
Code Organization:
- Issue: The entire logic is in a single block.
- Fix: Break down the script into functions, each responsible for a specific task (e.g., input gathering, MIDI file creation, timing value calculation).
-
Magic Numbers:
- Issue: The velocity value (127) is hardcoded.
- Fix: Consider making it a configurable variable or a constant with a descriptive name.
-
Type Hints and Docstrings:
- Issue: Missing type hints for function parameters and return types, as well as docstrings for explaining what functions do.
- Fix: Add type hints and docstrings to enhance code readability and usability.
-
Potential Logic Issue:
- Observation: The timing for
note_off messages is set based on the calculated timing values without considering the duration between note_on and note_off. Ensure this logic aligns with the intended MIDI output.
Refactored Code
Below is a refactored version of the script, addressing the mentioned weaknesses. Note that the calculate_timing_values function is still a placeholder, as its exact implementation depends on the specific timing logic required.
Next Steps:
- Test Thoroughly: Validate the script with various inputs to ensure it behaves as expected.
- Consider Additional Features: Depending on your requirements, you might want to add more functionality, such as supporting multiple instrument tracks or enhancing user input validation.
import re
import pandas as pd
from mido import Message, MidiFile, MidiTrack
def load_instrument_note_map(file_path: str) -> dict:
"""Loads instrument note types to MIDI note numbers from an Excel file."""
df = pd.read_excel(file_path).iloc[1:]
return {row[1]: row[0] for _, row in df.iterrows()}
def gather_user_input() -> tuple:
"""Collects necessary inputs from the user."""
while True:
try:
bpm = int(input("Enter the BPM: "))
beats_per_bar = int(input("Enter the number of beats per bar: "))
note_type = int(input("Enter the note type that gets the beat (e.g., 4 for quarter notes): "))
return bpm, beats_per_bar, note_type
except ValueError:
print("Invalid input. Please enter integer values.")
def calculate_timing_values(bpm: int, beats_per_bar: int, note_type: int, positions: list) -> list:
"""Calculates timing values in ticks for each note position based on BPM, beats per bar, and note type."""
# Calculate ticks per beat based on a standard MIDI resolution of 480 ticks per quarter note
ticks_per_beat = 480
seconds_per_beat = 60 / bpm
ticks_per_note = ticks_per_beat * (4 / note_type) # Adjust for note type (e.g., quarter, eighth)
timing_values = []
for position in positions:
# Calculate the timing in ticks for each note position, assuming the first note starts at time 0
note_timing = int(position * ticks_per_note)
timing_values.append(note_timing)
return timing_values
def create_midi_file(note_map: dict, bpm: int, beats_per_bar: int, note_type: int) -> MidiFile:
"""Creates a MIDI file based on user inputs and instrument note map."""
midi_file = MidiFile(ticks_per_beat=480) # Set MIDI file ticks per beat
midi_track = MidiTrack()
velocity = 127 # Consider making this configurable
while True:
instrument_note_type = input("Enter the instrument note type (or 'q' to quit): ")
if instrument_note_type.lower() == 'q':
break
if instrument_note_type not in note_map:
print("Invalid instrument note type. Please try again.")
continue
midi_note_number = note_map[instrument_note_type]
while True:
positions_str = input("Enter the positions you want to select (e.g., 1 3 5), separated by spaces or commas: ")
try:
positions = list(map(int, re.split(r'[\s,]+', positions_str)))
if all(pos > 0 for pos in positions): # Ensure positions are positive integers
break
else:
print("Positions must be positive integers.")
except ValueError:
print("Invalid input. Please enter numbers separated by spaces or commas.")
timing_values = calculate_timing_values(bpm, beats_per_bar, note_type, positions)
note_on = Message("note_on", note=midi_note_number, velocity=velocity, time=0)
midi_track.append(note_on)
for timing_value in timing_values:
note_off = Message("note_off", note=midi_note_number, velocity=velocity, time=timing_value)
midi_track.append(note_off)
# Add a note_off message for the last note with a delay to ensure it sounds completely
note_off = Message("note_off", note=midi_note_number, velocity=velocity, time=timing_values[-1] if timing_values else 0)
midi_track.append(note_off)
midi_file.tracks.append(midi_track)
return midi_file
def main():
note_map = load_instrument_note_map("instrument notes.xlsx")
bpm, beats_per_bar, note_type = gather_user_input()
midi_file = create_midi_file(note_map, bpm, beats_per_bar, note_type)
midi_filename = input("Enter the name of the MIDI file: ")
if not midi_filename.endswith('.mid'):
midi_filename += '.mid'
midi_file.save(midi_filename)
print(f"MIDI file saved as {midi_filename}")
if __name__ == "__main__":
main()